Tuesday, December 24, 2019

Sensing Intruder

#Arduino Code

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 > (lastSend + minSecsBetweenEmails * 1000l))

    {

      Serial.println("MOVEMENT");

      lastSend = now;

    }

    else

    {

      Serial.println("Too soon");

    }

  }

  delay(500);

}

======================================================================

#Python Code

import time
import serial
import smtplib


#IMAP USE ON and APP password(not normal password)required
#Turn off serial monitor of arduino
TO = '*@*.*'  #receiver mail
GMAIL_USER = '@gmail.com' #Gmail password here
GMAIL_PASS = '**************' #APP password here

SUBJECT = 'Intrusion!!'
TEXT = 'Your PIR sensor detected movement'

ser = serial.Serial('COM3', 9600)

def send_email():
  print("Sending Email")
  smtpserver = smtplib.SMTP("smtp.gmail.com",587) #What is different with SMTP_SSL
  #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==b'MOVEMENT\r\n' : #How to use byte?
      send_email()
  time.sleep(0.5)