Interfacing Arduino using python and pyserial library

 

Talking to Arduino using python is quite easy as it has a serial library to communicate with the hardware.

we can easily read and write data using python.

now we are going to build a simple project based on Arduino and python to send an email if there is any movement detected by the PIR sensor

So first we need to install python from its website

https://www.python.org/downloads/

After downloading python we need to install Serial library

https://pypi.python.org/pypi/pyserial

Now we have to design circuit for PIR with Arduino

pir with arduino,

Code for Arduino :

#define pir 6
void setup()
{
pinMode(pir, INPUT);
Serial.begin(9600);}void loop()
{
int a;
a = digitalRead(pir);if (a == 1)
{
Serial.println(“pir sensor activated”);
delay(10);
}}

python code for sending mail:
import smtplib
import serial
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def sendemail():
fromaddr = “##########”
toaddr = “############”
msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “SUBJECT OF THE MAIL”

body = “YOUR MESSAGE HERE”
msg.attach(MIMEText(body, ‘plain’))

server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(‘***username***’, “****password****”)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

ser = serial.Serial(‘COM8’, baudrate=9600, timeout=1) //select comport and baud rate

while 1:
tdata = ser.readline()
if(tdata.__len__() > 0):
print(tdata)
sendemail()