STANNUM
Open the simulator

Tutorials / Input

PIR motion sensor

The HC-SR501: it raises its output for a few seconds when something warm moves in front of it.

Parts in the example:
  • PIR sensor
  • Relay
  • LED
The PIR sensor block as it appears on the canvas.

What it is

A passive infrared sensor watches for a change in the heat pattern in front of it — a person walking by — and holds its output HIGH for a while, set by a small trimmer on the module (a few seconds by default). No motion, LOW. It is the sensor of automatic lights and cheap alarms.

In the simulator

The block has a Motion button: click it and the output goes HIGH for the number of seconds chosen in Settings (Time in HIGH, 1 to 60 s, 3 by default), with a countdown shown on the block. Clicking again restarts the countdown, like a person still moving.

Pins

PinWhat it is
Ssignal — HIGH while motion is detected — to a GPIO
3V3power — to a 3V3 symbol
GNDground — to a GND symbol

Wiring

The circuit below is the example Motion alarm — PIR + relay from the lab — open it with Project → Open example… and it comes ready to run.

The wired circuit, as the lab draws it.
PIR sensor pinGoes to
SD27 on the board (GPIO 27)
3V3a 3V3 symbol
GNDa GND symbol

Settings

Double-click the block's title bar to open its card, then the Settings tab. Changes apply to the running simulation right away.

The Settings tab of the PIR sensor.
SettingAcceptsDefaultNotes
Time in HIGH1 to 60 s3 sOn the real sensor this time is a trimpot on the board.

Code

sketch.cpp
#include <Arduino.h>

const int PIR = 27;
const int RELE = 14;
const int LED = 2;

void setup() {
  Serial.begin(115200);
  pinMode(PIR, INPUT);
  pinMode(RELE, OUTPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (digitalRead(PIR) == HIGH) {
    digitalWrite(RELE, HIGH);          // switch the load through the relay
    digitalWrite(LED, !digitalRead(LED));  // fast blink = alarm active
    Serial.println("motion detected!");
  } else {
    digitalWrite(RELE, LOW);
    digitalWrite(LED, LOW);
  }
  delay(150);
}

pinMode(PIR, INPUT) and digitalRead(PIR) == HIGH. While it is HIGH the sketch energizes the relay and toggles the LED on every pass; otherwise both go off. The 150 ms delay sets the blink rate of the warning.

Run it

Press Build and run. The first build of a project takes a while; after that, only what changed is rebuilt.

The simulation running: the canvas reacts and the serial monitor shows what the code prints.

Click Motion: the relay's channel lights, the LED blinks fast and the serial monitor prints “motion detected!” until the countdown ends.

How the simulation models it

Try this

  1. Turn it into an automatic light: lamp on the relay (see the relay guide), off 10 seconds after the last detection.
  2. Count detections per minute and print the rate.

See also