Passive Infrared Sensor with Raspberry Pi

Connect the PIR motion sensor to a Raspberry Pi and send alert messages via email

Written By: Marcus Schappi

Dash icon
Difficulty
Easy
Steps icon
Steps
11
A passive infrared (PIR) sensor measures infrared light radiating from objects in its view. These sensors collect incident infrared radiation with the use of a Fresnel lens, on a pyroelectric sensor and can detect human movement as long as it is within the range of the sensor.

In this guide, learn to connect a PIR motion sensor to the Raspberry Pi. Then learn to program the Raspberry Pi with smtplib to send an alert email when such movement is detected.

Complete this guide to start incorporating the PIR motion sensor in your Raspberry Pi projects.

Step 1 Overview

A PIR (passive infrared) sensor also known as an infrared motion sensor is an inexpensive, low-power and durable sensor used for the detection of movement within its range. It includes a pyroelectric sensor and a Fresnel lens. You can see the pyroelectric sensor under the lenses as a round metal can. The curved lenses concentrates infrared radiation toward the sensor.

Through a changing voltage level, it detects changes in the infrared radiation level which is why it is commonly used to detect whether a human has moved in or out of its range. 
There are three pins on the sensor that will be connected up to the Raspberry Pi:

From left to right as shown:
VCC - Voltage common collector
DO - Digital output
GND - Ground

Step 2 Connect red jumper wire to VCC pin

First, connect a red jumper wire to the VCC pin found on the PIR motion sensor. 

Step 3 Connect jumper wire to Digital Output pin

Next, connect another jumper wire this time to the DO pin found on the PIR motion sensor. 

Step 4 Connect black jumper wire to GND pin

Finally, connect a black jumper wire to GND on the PIR motion sensor.

Step 5 Attach jumper wire to 5V on Raspberry Pi

Attach the other end of the red jumper wire to 5V on the Raspberry Pi.

Step 6 Connect DO to GPIO23 on Raspberry Pi

Then connect the jumper wire attached to DO on the PIR motion sensor, to GPIO23 on the Raspberry Pi.

Step 7 Connect GND to GND on Raspberry Pi

Lastly, connect the black jumper wire to a GND pin on the Raspberry Pi.

Step 8 First test

from gpiozero import MotionSensor
import time

pir = MotionSensor(23)

while True:
    if pir.motion_detected:
        print('Motion detected')
        time.sleep(3)

This code uses the GPIO Zero library
Now that the connections are complete, power up the Raspberry Pi, then open up a text editor. In this guide, we are using the nano editor over SSH.

Copy and paste the following code.

Step 9 Sending a message with smtplib

from gpiozero import MotionSensor, LED
import time
import smtplib

pir = MotionSensor(23)

def send_mail():
    print("Sending text")
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login("youremailaddress@gmail.com","yourpassword")
    msg = 'Intruder alert!'
    server.sendmail("youremailaddress@gmail.com","recipientemail@gmail.com",msg)
    server.quit()
    time.sleep(1)
    print("Text sent!")

while True:
    if pir.motion_detected:
        send_mail()
        time.sleep(30)
    else:
        time.sleep(3)
Replace youremailaddress@gmail.com and recipientemail@gmail.com with the sender and recipient email addresses of your choice.
Once you have confirmed that the test code works and the wiring is all good, let's send an email with an alert message using the Raspberry Pi.

smtplib is a module that defines an smtp client session object, it can be used to send an email to any machine with an SMTP or ESMTP listener daemon. We have used it in our next python script to get the Raspberry Pi to send an alert message to a recipient email address. 
First, import the smtplib module with import smtplib
Next, create a new function def send_mail()
When this function is run, a "Sending text" message is first printed to the command line with the print function.

Next, the server to be used is established. Here, we will be using the Gmail SMTP server. If you are using Yahoo or Outlook then use one of these: 'smtp-mail.outlook.com:587' or 'smtp.mail.yahoo.com:587'.

Then, the SMTP connection in put in TLS (Transport Layer Security) mode with server.starttls(). Doing so, all SMTP commands that follow will be encrypted.

Then, enter your login credentials in server.login. Create the message to be sent in msg and then send it to the recipient email address with server.sendmail().

Finally, terminate the SMTP session and close the connection with server.quit

Once the message has been sent, the message "Text sent!" will be displayed. 
Next, update the code in if pir.motion_detected is true, so that the send_mail() function will be called. Next, get it to sleep for 30 seconds. Otherwise, get it to keep checking every 3 seconds for any motion in the environment within its range.

Step 10 Add a subject line

from gpiozero import MotionSensor
import time
import smtplib
from email.mime.text import MIMEText

pir = MotionSensor(23)

def send_mail():
    print("Sending text")
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    fromx = 'youremailaddress@gmail.com'
    to = 'recipientemailaddress@gmail.com'
    server.login("youremailaddress@gmail.com","yourpassword")
    msg = MIMEText('This is a test for the PIR motion sensor!')
    msg['Subject'] = 'Alert Message from Raspberry Pi'
    msg['From'] = fromx
    msg['To'] = to
    server.sendmail(fromx,to,msg.as_string())
    server.quit()
    time.sleep(1)
    print("Text sent!")

while True:
    if pir.motion_detected:
        send_mail()
        time.sleep(10)
    else:
        time.sleep(3)
Although the smtplib.SMTP.sendmail() function does not take a subject parameter, we can use the Python email.message standard library to do so.

Specifically, using Python's email.mime module, we can do just that. MIME stands for Multipurpose Internet Mail Extensions, and it comes in handy if you want to add any images, hyperlinks, or responsive content too.
To import MIMEText, the following was added:

from email.mime.text import MIMEText

Most of the send_mail function remains the same. One change is that we have added fromx and to which will hold the sender and recipient email addresses.

as_string returns the entire message, including the subject flattened as a string.

For more information on how to use the email package, see the documentation here
Replace your existing code with the following and enter your login details as well as sender and recipient email addresses.

Step 11 Conclusion

Enter the following command: sudo python3 programname.py
Place a hand along the PIR motion sensor's line of sight and you should see 'Sending text' printed. Once successfully sent, you should then see 'Text sent!' 
That's it! In the next guide, we will show you how to combine the PIR motion sensor with the Raspberry Pi camera module and get it to capture images, attach it to the email, and send it along with the alert message.