Adding a motion sensor (hc-sr501) to my Raspberry Pi


As part of my “make my home a bit smarter” projects, I wanted to add simple motion detection via motion sensor to a Raspberry Pi. This is the first project with a hc-sr501 motion sensor I tried. The goal is to combine the sensor with an esp8266, but this is another project (as I’m still waiting for most of the parts I ordered from

The whole setup is very straight forward, so this tutorial is very short. Basically it has 3 steps:

  • connecting the hardware
  • writing the script
  • testing the setup

So let’s start!

Connecting the hc-sr501 motion sensor

We need:

  • a Raspberry Pi (I use a B+, but any would do), with Jessie installed and fully configured
  • a hc-sr501 motion sensor
  • 3 jumper wires
  • a power supply for the raspberry pi
  • a network connection (LAN cable in my case)
  • a screw driver to adjust the sensor settings

Depending on where you bought the sensor, there will be a documentation  … or sometimes … not, as in my case. But the setup is pretty simple. I took a picture of the sensor and reverse-engineered-documented the sensor.


As I was travelling when I wrote this tutorial, I had to rely on my iPhone came. I hope the pictures are still ok.


Now connect the jumper wires to the corresponding pins (have a look at the picture).


Finally connect your wires to the Raspberry Pi. I used pin 11 (GPIO17) to connect the data wire, as I use some other GPIO pins already. So feel free to use another GPIO pin.

Hardware setup is done! Start your Pi and let it boot.


Writing the test script

Access your Raspberry Pi via SSH (I have no monitor I could connect directly to the Pi).

Let’s create a test python script. (Python should be installed, if not, please install it.)

Also make sure that the python module RPi.GPIO is installed. If not install it, by:

sudo apt-get install python-dev python-rpi.gpio

Now create the testscript:


and copy the following code that I copied from the Raspberry Pi learning resources:

import RPi.GPIO as GPIO
import time
sensor = 17 #this is the data pin - which might have to be adjusted, depending on your setup
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
previous_state = False
current_state = False
while True:
previous_state = current_state
current_state = GPIO.input(sensor)
if current_state != previous_state:
new_state = "HIGH" if current_state else "LOW"
print("GPIO pin %s is %s" % (sensor, new_state))


Make sure, the sensor pin it the one you selected, or change the value accordingly. Save the script.

Make the script executable by entering:

chmod -x

And run the script as admin.

sudo python

The output should be something like this, if there is some movement in front of the sensor.


If there is a reading, but the sensor seems to react to slow or fast, try to adjust the sensor settings with the screw driver.


Leave a Reply

Your email address will not be published. Required fields are marked *