Try Embedded

Motion alarm

A PIR motion sensor triggers a buzzer and an LED when someone walks by.

Sensors · Beginner

In a real product: Home security system (Smart home): A motion sensor triggers the alarm.

A passive infrared (PIR) sensor sees the heat that people and animals give off. When something warm moves across its view, its output goes HIGH. That is how automatic lights and burglar alarms work.

What you'll learn

  • Reading a PIR sensor's digital output
  • Doing something only on a change of state (motion starts, motion ends)
  • Making a simple alarm with a buzzer and an LED

How it works

The PIR's OUT goes to pin 2. It is HIGH while it detects motion, and drops a few seconds after the motion stops (a real module has trimmers for that hold time and for the sensitivity).

While OUT is HIGH the loop lights the built-in LED and beeps the buzzer on pin 8. The alarm flag remembers the last state, so "Motion detected!" and "All clear" are printed only once each time.

Try this

  • Click the PIR sensor while the simulation runs to make it detect motion.
  • Turn on a relay (a lamp) for 10 seconds after the last motion.
  • Count how many times motion was detected.

sketch.ino

// A PIR motion sensor on pin 2 triggers a buzzer (pin 8) and the built-in LED.
const int PIR = 2;
const int BUZZER = 8;
bool alarm = false;

void setup() {
  pinMode(PIR, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(PIR) == HIGH) {
    if (!alarm) Serial.println("Motion detected!");
    alarm = true;
    digitalWrite(LED_BUILTIN, HIGH);
    tone(BUZZER, 880, 200);
    delay(300);
  } else {
    if (alarm) Serial.println("All clear");
    alarm = false;
    digitalWrite(LED_BUILTIN, LOW);
  }
}

Lessons behind it