Movement sensor

This tutorial will show how to use the HC-SR501 motion sensor with a Raspberry Pi to detect movement and then light an LED.

Distance sensor wired up with a Raspberry Pi

Setting up the Sensor

We need to set up the sensor. Follow the table below to get the wires connected. It may be helpful to have the GPIO pinout diagram open alongside this table. Open Pinout Diagram

Sensor Pin Raspbrry Pi Pin
VCC 5v Power
OUT GPIO 14
GND Ground (GND)
Pinout table for HC-SR501 motion sensor

Connecting up the LED

Next we need to wire up the LED
LED Raspbrry Pi Pin
Red (+ve) GPIO 02
Black (-ve) Ground (GND)
Pinout table for LED

The Code

The following code will connect up the sensor and the LED. First we need to set up the sensor pin to be a read pin (GPIO.IN) so that we can tell when the pin is high (ie. triggered) or not. Then we set up the LED to turn on when the sensor is triggered.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

LED = 2
SENSOR = 14

GPIO.setup(LED, GPIO.OUT)
GPIO.setup(SENSOR, GPIO.IN)

while True:
if GPIO.input(SENSOR):
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)

time.sleep(0.5)