Connecting The PIR With Arduino In Python

Introduction

  • In this article, I am going to explain about connecting the PIR with Arduino In Python.The output will be displayed on both sides in Python and the Arduino. It will send the message of what we have given to print in the input.
Parts Of List
 
Hardware Requirement
  • Arduino Uno
  • PIR Sensor
  • IR Sensor
  • Bread Board
  • Hook Up wires 
Software Requirement
  • Arduino IDE
  • Python 3.5.2 
PIR Sensor
 
 
Figure 1: PIR Sensor
  • It is used to detect human movement around approximately 10m from the sensor.
  • The actual range is between 5m to 12m.
  • It is of high sensitivity and low noise.
Programming
 
Arduino Programming
  1. int pirPin = 2;  
  2.   
  3. int minSecsBetweenEmails = 60; // 1 min  
  4.   
  5. long lastSend = -minSecsBetweenEmails * 1000l;  
  6.   
  7. void setup()  
  8. {  
  9.   pinMode(pirPin, INPUT);  
  10.   Serial.begin(9600);  
  11. }  
  12.   
  13. void loop()  
  14. {  
  15.   long now = millis();  
  16.   if (digitalRead(pirPin) == HIGH)  
  17.   {  
  18.     if (now > (lastSend + minSecsBetweenEmails * 1000l))  
  19.     {  
  20.       Serial.println("MOVEMENT");  
  21.       lastSend = now;  
  22.     }  
  23.     else  
  24.     {  
  25.       Serial.println("Too soon");  
  26.     }  
  27.   }  
  28.   delay(500);  
  29. }  
Explanation
  • In the Arduino part, it has been explained about the distance of the person at the time, it will have the output at the Serial monitor.
  • The output will be displayed as "Too Soon".
Python Program
  1. import time  
  2. import serial  
  3. import smtplib  
  4.   
  5. TO = '[email protected]'  
  6. GMAIL_USER = '[email protected]'  
  7. GMAIL_PASS = 'putyourpasswordhere'  
  8.   
  9. SUBJECT = 'Intrusion!!'  
  10. TEXT = 'Your PIR sensor detected movement'  
  11.     
  12. ser = serial.Serial('COM4', 9600)  
  13.   
  14. def send_email():  
  15.     print("Sending Email")  
  16.     smtpserver = smtplib.SMTP("smtp.gmail.com",587)  
  17.     smtpserver.ehlo()  
  18.     smtpserver.starttls()  
  19.     smtpserver.ehlo  
  20.     smtpserver.login(GMAIL_USER, GMAIL_PASS)  
  21.     header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER  
  22.     header = header + '\n' + 'Subject:' + SUBJECT + '\n'  
  23.     print header  
  24.     msg = header + '\n' + TEXT + ' \n\n'  
  25.     smtpserver.sendmail(GMAIL_USER, TO, msg)  
  26.     smtpserver.close()  
  27.       
  28. while True:  
  29.     message = ser.readline()  
  30.     print(message)  
  31.     if message[0] == 'M' :  
  32.         send_email()  
  33.     time.sleep(0.5)  
Explanation
  • In this Python coding, it will be used to connect the PIR sensor and will give the output in Python shield. It will also be displayed as Too Soon.
Output
 
 
Figure 2:Output