# Arduino Lesson 17. Email Sending Movement Detector

## Overview

In this lesson you will learn how to use a PIR movement detector with an Arduino and to have the Arduino communicate with a Python program running on your computer to send an email whenever movement is detected by the sensor.  
  
The Arduino is the heart of this project. It 'listens' to the PIR sensor and when motion is detect, instructs the computer via the USB port to send an email.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/535/medium800/learn_arduino_overview.jpg?1396814047)

# Arduino Lesson 17. Email Sending Movement Detector

## Parts

To build the project described in this lesson, you will need the following parts.

You will also need a computer with an Internet connection (so you can send email thru it)!

# Arduino Lesson 17. Email Sending Movement Detector

## Breadboard Layout

The only thing that you are connecting to the Arduino is the PIR sensor, so you could if you prefer simply push the wires attached to the PIR sensor directly into the Arduino board. However, the wires from the sensor, are a bit loose in the Arduino sockets so it is probably better to use the breadboard layout below.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/541/medium800/learn_arduino_breadboard.png?1396814130)

# Arduino Lesson 17. Email Sending Movement Detector

## Arduino Code

The Arduino will send a message over USB Serial connection whenever movement is detected. However, this could have the potential to generate a lot of emails. For this reason the Arduino sends a different message if its too soon to send another email.

```
int pirPin = 7;

int minSecsBetweenEmails = 60; // 1 min

long lastSend = -minSecsBetweenEmails * 1000l;

void setup()
{
  pinMode(pirPin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  long now = millis();
  if (digitalRead(pirPin) == HIGH)
  {
    if (now &gt; (lastSend + minSecsBetweenEmails * 1000l))
    {
      Serial.println("MOVEMENT");
      lastSend = now;
    }
    else
    {
      Serial.println("Too soon");
    }
  }
  delay(500);
}
```

The variable “minSecsBetweenEmails” can be changed to whatever you feel is a reasonable value. Here it is set to 60 seconds, so emails will not be sent at a rate of more than one a minute.

To keep track of when the last request to send an email was sent, a variable “lastSend” is used. This is initialized to a negative number, equal to the negative of the number of milliseconds specified in the “minSecsBetweenEmails” variable. This ensures that the PIR can be triggered immediately that the Arduino sketch starts.

Within the loop, the function “millis()” is used to get the number of milliseconds since the Arduino started and compare it with that last time the alarm was triggered and only if it is more than the specified number of seconds since last time does it send the message “MOVEMENT”. Otherwise even though movement has been detected, it just sends the message “Too soon”.

Before you link things up to your Python program, you can test the Arduino setup by just opening the Serial Monitor on the Arduino IDE.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/542/medium800/learn_arduino_serial_monitor.png?1396814148)

# Arduino Lesson 17. Email Sending Movement Detector

## Installing Python and PySerial

If you are using a Mac or Linux computer, the Python is already installed. If you are using Windows, then you will need to install it. In either case, you will also need to install the PySerial library to allow communication with the Arduino.

## Install Python on Windows

To install Python on Windows, download the installer from [http://www.python.org/getit/](http://www.python.org/getit/ "Link: http://www.python.org/getit/").

**This project was built using Python 2.7.3**

There are some reported problems with PySerial on Windows, using Python 3, so stick to Python 2.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/543/medium800/learn_arduino_pyserial_install_dos_1.png?1396814168)

Once Python is installed, you will find a new Program Group on your Start menu. However, we are going to make a change to Windows to allow you to use Python from the Command Prompt. You will need this to be able to install PySerial.

We are going to add something to the PATH environment variable.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/544/medium800/learn_arduino_Python_inst_win_setting_path.png?1396814197)

To do this, you need to go to the Windows Control panel and find the System Properties control. Then click on the button labelled “Environment Variables” and in the window that pops-up select “Path” in the bottom section (System Variables). Click “Edit” and then at the end of the “Variable Value” without deleting any of the text already there, add the text: _;C:\Python27_

_Don't forget the ";" before the new bit!_

To test that it worked okay, start a new Command Prompt (DOS Prompt) and enter the command “python”. You should see something like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/004/545/medium800/learn_arduino_python_from_dos.png?1396814213)

## Install PySerial
 

Whatever your operating system, download the .tar.gz install package for PySerial 2.6 from [https://pypi.python.org/pypi/pyserial](https://pypi.python.org/pypi/pyserial)

 

This will give you a file called: pyserial-2.6.tar.gz

 

If you are using windows you need to uncompress this into a folder. Unfortunately, it is not a normal zip file, so you may need to download a tool such as 7-zip ([http://www.7-zip.org/](http://www.7-zip.org/)).

 

If you are using a Mac or Linux computer, then open a Terminal session, 'cd' to wherever you downloaded pyserial-2.6.tar.gz and then issue the following command to unpack the installation folder.

```
$ tar -xzf pyserial-2.6.tar.gz 
```

The rest of the procedure is the same whatever your operating system. Use you Comamnd Prompt / Terminal session and “cd” into the pyserial-2.6 folder, then run the command:

```
sudo python setup.py install
```

![](https://cdn-learn.adafruit.com/assets/assets/000/004/546/medium800/learn_arduino_pyserial_install_dos_1.png?1396814230)

# Arduino Lesson 17. Email Sending Movement Detector

## 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.

```
import time
import serial
import smtplib

TO = 'putyour@email.here'
GMAIL_USER = 'putyour@email.here'
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:

```
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.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/547/medium800/learn_arduino_arduino_ide_port.png?1396814256)

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

```
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.

![](https://cdn-learn.adafruit.com/assets/assets/000/004/548/medium800/learn_arduino_trace_message_sending_mac.png?1396814279)

Notice also the “Too soon” messages.

# Arduino Lesson 17. Email Sending Movement Detector

## Other Things to Do

Now that you have a means of sending email from your Arduino, this opens up all sorts of possibilities You could add different types of sensor, and perhaps send yourself hourly temperature reports by email.  
  
The PIR sensor could be used directly with the Arduino to play a warning tone or turn on LEDs.

**About the Author.**

Simon Monk is author of a number of books relating to Open Source Hardware. The following books written by Simon are available from Adafruit: [Programming Arduino](https://www.adafruit.com/products/1019), [30 Arduino Projects for the Evil Genius](https://www.adafruit.com/products/868) and [Programming the Raspberry Pi](https://www.adafruit.com/index.php?main_page=adasearch&q=programming+raspberry+pi).


## Featured Products

### PIR (motion) sensor

[PIR (motion) sensor](https://www.adafruit.com/product/189)
PIR sensors are used to detect motion from pets/humanoids from about 20 feet away (possibly works on zombies, not guaranteed). This one has an adjustable delay before firing (approx 2-4 seconds), adjustable sensitivity **and** we include a 1 foot (30 cm) cable with a socket so you...

In Stock
[Buy Now](https://www.adafruit.com/product/189)
[Related Guides to the Product](https://learn.adafruit.com/products/189/guides)
### Adafruit METRO 328 Fully Assembled - Arduino IDE compatible

[Adafruit METRO 328 Fully Assembled - Arduino IDE compatible](https://www.adafruit.com/product/50)
We sure love the ATmega328 here at Adafruit, and we use them&nbsp;_a lot_&nbsp;for our own projects. The processor has plenty of GPIO, Analog inputs, hardware UART SPI and I2C, timers and PWM galore - just enough for most simple projects. When we need to go small, we use a <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/50)
[Related Guides to the Product](https://learn.adafruit.com/products/50/guides)
### Half Sized Premium Breadboard - 400 Tie Points

[Half Sized Premium Breadboard - 400 Tie Points](https://www.adafruit.com/product/64)
This is a cute, half-size breadboard with&nbsp;400 tie points, good for small projects. It's 3.25" x 2.2" / 8.3cm&nbsp;x 5.5cm&nbsp;with a standard double-strip in the middle and two power rails on both sides.&nbsp;You can pull the power rails off easily to make the breadboard as...

Out of Stock
[Buy Now](https://www.adafruit.com/product/64)
[Related Guides to the Product](https://learn.adafruit.com/products/64/guides)
### Premium Male/Male Jumper Wires - 40 x 6" (150mm)

[Premium Male/Male Jumper Wires - 40 x 6" (150mm)](https://www.adafruit.com/product/758)
Handy for making wire harnesses or jumpering between headers on PCB's. These premium jumper wires are 6" (150mm) long and come in a 'strip' of 40 (4 pieces of each of ten rainbow colors). They have 0.1" male header contacts on either end and fit cleanly next to each other...

Out of Stock
[Buy Now](https://www.adafruit.com/product/758)
[Related Guides to the Product](https://learn.adafruit.com/products/758/guides)
### Programming Arduino By Simon Monk

[Programming Arduino By Simon Monk](https://www.adafruit.com/product/1019)
Using clear, easy-to-follow examples, _Programming Arduino: Getting Started with Sketches_&nbsp;- Third&nbsp;_Edition_ reveals the software side of Arduino and explains how to write well-crafted sketches using the modified C language of Arduino. No prior programming experience is...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/1019)
[Related Guides to the Product](https://learn.adafruit.com/products/1019/guides)

## Related Guides

- [PIR Motion Sensor](https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor.md)
- [Remote controlled door lock using a fingerprint sensor & Adafruit IO](https://learn.adafruit.com/remote-controlled-door-lock-using-a-fingerprint-sensor-and-adafruit-io.md)
- [Character LCDs](https://learn.adafruit.com/character-lcds.md)
- [Digital Circuits 7: MCUs... how do they work?](https://learn.adafruit.com/mcus-how-do-they-work.md)
- [DS1307 Real Time Clock Breakout Board Kit](https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit.md)
- [Wave Shield Voice Changer](https://learn.adafruit.com/wave-shield-voice-changer.md)
- [Adafruit CC3000 WiFi and Xively](https://learn.adafruit.com/adafruit-cc3000-wifi-and-xively.md)
- [Smart Measuring Cup](https://learn.adafruit.com/smart-measuring-cup.md)
- [Arduino Lesson 10. Making Sounds](https://learn.adafruit.com/adafruit-arduino-lesson-10-making-sounds.md)
- [Halloween Pumpkin](https://learn.adafruit.com/halloween-pumpkin.md)
- [Wave Shield](https://learn.adafruit.com/adafruit-wave-shield-audio-shield-for-arduino.md)
- [WiFi Candy Bowl Monitor](https://learn.adafruit.com/wifi-candy-bowl.md)
- [Reverse Geocache Box](https://learn.adafruit.com/reverse-geocache-engagement-box.md)
- [How to Choose a Microcontroller](https://learn.adafruit.com/how-to-choose-a-microcontroller.md)
- [Adafruit Proto Screw Shield](https://learn.adafruit.com/adafruit-proto-screw-shield.md)
- [Program an AVR or Arduino Using Raspberry Pi GPIO](https://learn.adafruit.com/program-an-avr-or-arduino-using-raspberry-pi-gpio-pins.md)
