Arduino - Motion Sensor

by DIYables in Circuits > Arduino

11 Views, 0 Favorites, 0 Comments

Arduino - Motion Sensor

This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://arduinogetstarted.com/tutorials/arduino-motion-sensor

This build uses an HC-SR501 PIR motion sensor with an Arduino Uno to detect movement, the same kind of sensing behind automatic doors, lights, and escalators. The sensor outputs a simple HIGH or LOW signal that the Arduino reads to tell when something warm and moving passes in front of it.

Supplies

Wiring

The HC-SR501 has three pins. Connect GND to the Arduino's GND, VCC to the Arduino's 5V, and the OUTPUT pin to one of the Arduino's digital input pins. If the wiring feels loose, stack a screw terminal shield on the Arduino and land the three wires in its screw terminals instead of pushing jumper wires directly into the headers. Leave the sensor's jumper and two potentiometers at their default setting for now.

How It Works

The sensor reacts only to an object that is both moving and giving off infrared heat, which is why it picks up humans and animals but ignores something like a moving toy vehicle that doesn't emit infrared. The OUTPUT pin goes HIGH when motion is detected and LOW when it isn't. The sensor can't tell if a person is present, only if something moved, so someone sitting still in range reads as no motion, which is why a motion-activated light can turn off while a person is still in the room.

Code

The sketch sets the pin wired to the sensor's OUTPUT as a digital input with pinMode(), then repeatedly checks its state with digitalRead(). A change from LOW to HIGH marks the start of motion, and a change back from HIGH to LOW marks the end. After uploading the code, open the Serial Monitor and wave a hand in front of the sensor to see the detected motion printed out.

arduino-motion-sensor.ino - the sketch from the tutorial, unchanged.

pinStatePrevious = pinStateCurrent; // store old state
pinStateCurrent = digitalRead(PIN_TO_SENSOR); // read new state

if (pinStatePrevious == LOW && pinStateCurrent == HIGH) { // pin state change: LOW -> HIGH
Serial.println("Motion detected!");
}

Things That Go Wrong

The detection range potentiometer sets how far the sensor reaches, roughly 3 meters turned fully clockwise up to 7 meters turned fully anti-clockwise. The time delay potentiometer sets how long OUTPUT stays HIGH after motion, from about 3 seconds anti-clockwise to 5 minutes clockwise. The jumper switches between single trigger, where OUTPUT toggles LOW and HIGH repeatedly while motion continues, and repeatable trigger, where OUTPUT just stays HIGH the whole time. Mixing these settings up looks like a wiring fault but is just the sensor's configuration.

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://arduinogetstarted.com/tutorials/arduino-motion-sensor