How to Build a Motion Detection System Using Raspberry Pi and Twilio WhatsApp API

September 13, 2022
Written by
Mahlomola Moses Mothogoane
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by
Mia Adjei
Twilion

How to Build a Motion Detection System Using Raspberry Pi and Twilio WhatsApp API

Let's say you want to know if there is human movement in your room or house. In this tutorial, you will learn how to build a motion detection system and get notifications when motion is detected in your room via WhatsApp text using the Twilio Programmable Messaging API for WhatsApp. At the end of this tutorial, you will have developed a smart system that will send WhatsApp texts from Raspberry Pi — how awesome!

Prerequisites

To complete this tutorial, you need:

  • A Twilio account.
  • An active WhatsApp account, to test the project. 
  • A Raspberry Pi (ideally a 3B+ or newer) running Raspberry Pi OS (formerly Raspbian), powered by either a USB cable or wall adapter.
  • A PIR infrared motion sensor (HC-SR501).
  • Three female-to-female jumper wires.

The HC-SR501 is one of the most used motion sensors. This sensor has two modes, which are single trigger mode and repeatable mode. You can learn more about the sensor here. In this tutorial, you will be using the repeatable trigger mode.

First time working with Raspberry Pi? Visit this link to learn more about how Raspberry Pi works, from GPIO to programming with it. You can also get your new board here.

Connect the HC-SR501 sensor to the Raspberry Pi

Start building your motion detection system by configuring the sensor's settings.

The following picture from the sensor's description explains how to adjust your sensor.

Diagram explaining IR motion sensor settings

Pick up the sensor and adjust the orange potentiometers, turning both of them fully counter-clockwise. Then, set the jumper set to the repeatable trigger setting. When you are finished, your sensor should look like the photo below:

Motion sensor with orange potentiometers turned fully counter-clockwise, and yellow jumper set set to repeatable trigger mode.

Now, you are ready to connect the jumpers to the sensor and the sensor to the Raspberry Pi.

This motion sensor has three pins, whose names you can find under the white domed lens. If you remove this dome, you will see that the pins are labeled VCC (power), OUT (output), and GND (ground). Take three jumper wires of different colors. For my sensor, I have chosen blue, white, and green jumpers, but you can select the colors you like.

First, connect the jumpers to the sensor:

  1. Connect the VCC of the sensor to the blue jumper.
  2. Connect the OUT of the sensor to the white jumper.
  3. Connect the GND of the sensor to the green jumper.

Second, connect the above connection to the Raspberry Pi:

  1. Connect the blue jumper to the GPIO VCC pin.
  2. Connect the white jumper to the GPIO 23 pin.
  3. Connect the green jumper to the GPIO GND pin.

To learn more about the Raspberry Pi's GPIO pins, take a look at the documentation here.

If you removed the white lens from the sensor, reattach it now.

The final circuit will look like the image below.

Motion sensor connected to Raspberry Pi with jumper cables

Configure your Twilio WhatsApp Sandbox

Now, log into your Twilio Console to configure your Twilio WhatsApp Sandbox settings. Click on the Messaging tab in the left-side navigation menu. Under Messaging, click on Settings and select WhatsApp Sandbox Settings.

Twilio WhatsApp Sandbox settings page

Note that the sandbox allows you to test your application in a developer environment. For production, you can request an upgrade to your account.

To start using the Twilio WhatsApp Sandbox, use your WhatsApp account to send the unique phrase specified on your console (under the Sandbox Participants header) to the WhatsApp number assigned to your sandbox. Mine is “join found-shadow”.

You should receive a message on your WhatsApp as shown below.

WhatsApp messages from Twilio Sandbox

Create the Python script to read the HC-SR501 sensor

At this point, your hardware circuit is ready, and now you just need software.

So now let's write out a script to read data from the HC-SR501 sensor. You can connect to your Raspberry Pi via SSH protocol, but this is not the only way to access Raspberry Pi. If you prefer, you can access the Raspberry Pi's terminal through its Desktop if you have a monitor, keyboard, and mouse connected.

First, install Twilio and RPI.GPO, by running the following commands:

pip install twilio
pip install RPI.GPIO

Create a folder for your script, name it motion_detection, and open it by entering the following commands on your terminal:

mkdir motion_detection
cd motion_detection

Now, in the motion_detection folder, create your Python script, name it motion.py, and open it with nano.

sudo nano motion.py will open your script so you can start coding. If you don't want to use nano, you can use a text editor of your choice.

touch motion.py
sudo nano motion.py

Import your imports in the beginning of your script:

import RPi.GPIO as GPIO
import time
from twilio.rest import Client

In this project, we will use GPIO to access and read the pins on the Raspberry Pi, time to put some delays in our program, and twilio to access the Twilio WhatsApp API.

Now that you have your imports, you can access their functions. We will use pin 23 to read the sensor, and for that, enter the following code:

PIR_SENSOR=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_SENSOR,GPIO.IN)

We are done with setting up GPIOs, so let's dive into the Twilio WhatsApp API. For this, you will need your Account SID and Auth Token, which you can find in the Twilio Console under Account Info.

  • Account SID - Used to identify yourself in API requests.
  • Auth Token - Used to authenticate REST API requests.

Account Info in Twilio Console

Now that you have your account credentials, initialize the Twilio client with the following code, replacing the placeholder text with your values for Account SID and Auth Token, and add your WhatsApp number in E164 format:

account_sid = "your account sid"
auth_token = "your auth token"

client = Client(account_sid,auth_token)
whatsapp_number="your WhatsApp number"

Now you are all set and can make a request to the Twilio WhatsApp API. Twilio makes it easy for us, and we will use the following function to send our message:

def alertUser(x):
    message = client.messages.create(
                                  body='hello buddy, movement is detected in your room!!',
                                  from_='whatsapp:+14155238886',
                                  to=f'whatsapp:{whatsapp_number}'
                              )

There are three properties that we need to pass here.

  • body - This is your message.
  • from_ - This is whatsapp: combined with your sandbox number.
  • to - This is whatsapp: combined with the number for your personal WhatsApp Account.

Now we need to listen to the events from the GPIO pin, checking if the sensor detected any movement. GPIO has made it easy for us — we can just call the built-in function and pass our function (alertUser()) as a callback. Let's do that by entering the following code:

try:
    GPIO.add_event_detect(PIR_SENSOR,GPIO.RISING,callback=alertUser)
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("exited")
finally:
    GPIO.cleanup()

Line 2, from the above code, is calling alertUser() once there is movement detected from the sensor. On lines 3 to 4, we add some delay. In line 5, we listen for a keyboard interrupt to exit the program.

The complete code is as follows:

import RPi.GPIO as GPIO
import time
from twilio.rest import Client

PIR_SENSOR=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_SENSOR,GPIO.IN)


account_sid="<YOUR_ACCOUNT_SID>"
auth_token ="<YOUR_AUTH_TOKEN>" 

client = Client(account_sid, auth_token)
whatsapp_number="<YOUR_WHATSAPP_NUMBER>"

def alertUser(x):
    print("motion")
    message = client.messages.create(
                                  body='hello buddy, movement is detected in your room!!',
                                  from_='whatsapp:+14155238886',
                                  to=f'whatsapp:{whatsapp_number}'
                              )
    
try:
    GPIO.add_event_detect(PIR_SENSOR,GPIO.RISING,callback=alertUser)
    while True:
        print(GPIO.input(PIR_SENSOR))
        time.sleep(1)
except KeyboardInterrupt:
    print("exited")
finally:
    GPIO.cleanup()

Happy days!! Now, we can run the program, using the following command from within the project directory:

python motion.py

After running this command, wave your hand over your sensor, and after some seconds, you should receive a text message on your personal WhatsApp. Here is the output from mine.

Motion detection text messages in WhatsApp

Yes, I did a few tests there…

Now you can put your hardware in your room — just make sure it is connected to the internet so that once motion is detected, you will be notified. Let me know if you have any questions or comments!

Mahlomola Moses Mothogoane is a Developer at Falcorp, a game developer, and a hardware and software developer. Feel free to reach out to me on LinkedIn and Twitter or send me an email at mahlomolamoses@gmail.com.