Python Code

Now, you need to create the Python program. To do this, copy the code below into a file called “movement.py”. On Mac / Linux you can use the “nano” editor, on Windows, it is probably easiest to make the file using the Python editor 'IDLE” which is available from the Python program group on your start menu.

Download: file
import time
import serial
import smtplib

TO = '[email protected]'
GMAIL_USER = '[email protected]'
GMAIL_PASS = 'putyourpasswordhere'

SUBJECT = 'Intrusion!!'
TEXT = 'Your PIR sensor detected movement'
  
ser = serial.Serial('COM4', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print header
    msg = header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()
    
while True:
    message = ser.readline()
    print(message)
    if message[0] == 'M' :
        send_email()
    time.sleep(0.5)

Before you run the Python program, there are some configuration changes that you need to make. These are all up near the top of the file.

The program assumes that the emails are being set from a gmail account. So, if you don't have one, you might like to make yourself one, even if it is just for this project.

Change the email address next to “TO” to the email that you want to receive the notifications. This does not have to be your email address, but probably will be.

Change the email address next to “GMAIL_USER” to the email address of your gmail address and alter the password on the next line to the password you use to retrieve your emails.

If you want to, you can also change the subject line and text of the message to be sent, on the lines that follow.

You will also need to set the serial port of the Arduino by editing the line below:

Download: file
ser = serial.Serial('COM4', 9600)
For Windows, this will be something like “COM4” for Mac and Linux, something like “/dev/tty.usbmodem621”. You can find this by openning the Arduino IDE and in the bottom right corner, it will show you the port that is connected to the Arduino.

When you have made these changes, you can run the program from Command Prompt / Terminal with the command:

Download: file
python movement.py

When a movement is triggered you should get some trace like this and shortly after an email will arrive in your inbox.

Notice also the “Too soon” messages.

This guide was first published on Feb 28, 2013. It was last updated on Feb 28, 2013. This page (Python Code) was last updated on May 04, 2015.