home security projects for arduino - cjoint.com · introduction. our kit allows you to connect pir...

124

Upload: ngodiep

Post on 14-Jul-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

HomeSecurityProjectsforArduino

TimRustige

HomeSecurityProjectsforArduino

©TimRustige

Firstedition:June2015

PublishedbyTRComputersLimited.

AllTrademarks&RegisteredTrademarksareherebyacknowledged.

TheelectronicdesignoftheArduinoboardsisopensource(CreativeCommonsCC-SA-BYLicense)theArduinoname,logoandthegraphicsdesignofitsboardsareaprotectedtrademarkofArduinoLLC.

RaspberryPiandtheRaspberryPilogoareregisteredtrademarksoftheRaspberryPiFoundation.

Allrightsreserved.Nopartofthisbookoranyofthesoftwarefeaturedmaybereproducedortranslatedinanyformwithoutthepriorwrittenconsentoftheauthor.

Disclaimer:Whilsteveryefforthasbeenmadetoensurealltheinformationcontainedinthisbookisaccurate,theauthor&publishercanacceptnoliabilityforanyconsequentiallossordamage,howevercaused,arisingasaresultofusingtheinformationcontained.

TableofContentsIntroduction.

ConnectingaPIRmoduletotheArduino.

SetuptheArduinosoftware.

SetupPythononyourPC

PythononWindowsPCs.

SettingupaspareGmailaccount.

Pythonscriptwithemailfunction.

HowtograbanimagefromawebcaminPython.

Captureaphoto&emailitasanattachment.

ConnectamagneticdoorsensortotheArduino

SetuptheArduinosoftwarefordoorsensor.

SetupPythonwithdoorsensoronyourPC

PythondoorsensorexampleonWindowsPCs.

Pythondooralarmscriptwithemailfunction.

HowtograbanimagefromawebcaminPython.

Captureaphoto&emailitasanattachment.

Part2–GoingWireless

HowtoconnecttheNRF24L01+toArduino

CablingdiagramforArduinoUnoR3wirelessPIR

CablingdiagramforanArduinoNanowirelessPIR.

InstallingManiacBug’sRF24libraryforArduino.

UploadPIRtransmittercodetotheArduino.

Uploadreceivercodetoa2ndArduino.

SettingupaspareGmailaccount.

PythonscriptwithemailfunctiontorunonyourPC.

ArduinoUnoR3wirelessmagneticdoorsensor

ArduinoNanowithwirelessmagneticdoorsensor

UploadtransmittercodetotheArduinoformagdoor.

Pythoncodeforwirelessmagneticdoorsensor.

PythoncodeforwirelessPIR&doorsensortoemail.

ConnectaLDRlightsensortotheArduino

Arduinoanaloginputpins.

MakeawirelessArduinoLDRlightsensor.

SketchcodeforwirelessArduinoLDRlightsensor.

PythoncodeforwirelessArduinoLDRlightsensor.

Makeastandalonebatterypoweredbeepingreceiver.

Arduino&NRF24L01receiverportablebeeperSketch.

SettingupArduinoIDEsoftwareonaRaspberryPi.

UsingthePythonscriptsonaRaspberryPi

PythonscripttocapturefromPiCameramodule.

SomethingElse

Usefullinks:

Introduction.

OurkitallowsyoutoconnectPIRmotionsensors&magneticdoorsensorstotheUSBportonyourPCorMac-viaanArduinoboard-andthenreceivealarmphotosonyoursmartphone,whenthey’retriggered.Ourfullprojectkitcontainseverythingyou’llneed:Arduinocompatibleboard,PIRsensor,magneticdoorsensor,PDFinstructions,ArduinosoftwareandPythonsoftware.WealsoshowyouhowtousetheinexpensiveNRF24L01+wirelessboardsforcommunications.

TheArduinocompatibleboardsweusearetheUnoR3&ProNanocloneswithUSBports.Youwriteasmallprogram-calledaSketch-onyourPCandthenuploadittotheArduinoboardusingtheArduinodevelopmentsoftwareonyourPC.TheuploadedprogramthenrunsontheArduinoboardeachtimeyoupoweritup.Ifyouwanttousetheboardforadifferentproject,youjustreprogramitwithanewSketchviatheUSBport.

Theboardshavedigitalandanalogueinput/outputs:thereare13digitalpins,whicharelikeswitchesthatcanbeonoroff.Sowecansetoneofthepinsasaninput&connectaPIRmoduletoit,andalsosetanotherofthepinsasanoutputandconnectanLEDtoit(theLEDweuseisactuallyhard-wiredontotheboard).WecanthenwriteaSketch(theArduinonameforaprogram)thatsensesthePIRmotionsensorhasbeentrippedandturnsontheLEDfor30seconds.

Therearealsosixanaloguepinswhichcandetectaninputvaluebetween0-1023.Theseareusefulifyouwanttoconnectasensorthatmighthavearangeofvalues,likeatemperature,moistureorlightsensor.Towardstheendofthisdocumentweshowyouhowtoreadalightsensor.

TheboardsconnecttothePCusingtheUSBport.TheUSBportsuppliesthe5voltpowerrequiredbytheArduino,andalsotheinterfaceforreprogrammingtheboardwithanewSketch.TheboardcantalkbacktothePCoveraUSBserialinterface,whichallowsustosenda“motiondetected”messagebacktothePCwhenthePIRistriggered.

OnthePCwe’regoingtousetheprogramminglanguagePythontoreadthe“motiondetected”messageandthensendanemailalerttoourphone,usingaGmailaccount.We’reusingPythonbecauseit’savailableforWindows,Mac&LinuxPCs.We’vechosenPython2.7.8,becausesomeofthelibraryfunctionsweneedaren’tyetavailableforthenewerversionPython3.4.1

USBArduinomodelscanbepoweredbyaPC,aUSBmainsadapteroraUSBbatterypack.

ConnectingaPIRmoduletotheArduino.

Here’showtoconnectthePIRmoduletotheUnoR3compatibleboard.IfyouliftthedomeoffthePIRyou’llseethepinsarelabelled.(Don’tworryaboutwirecolours,justmakesureyouattachthethreepointstogethercorrectly.)

Here’showtoconnectthesmallerProNanoboard:GNDtoGND,OUTtoD10&VCCto5V

SetuptheArduinosoftware.

ThelatestversionoftheArduino1.0.6softwaresuiteforWindows,MacOSX&Linuxcanbedownloadedfromhttp://arduino.cc/en/Main/Software

OnceinstalledtoyourWindowsPC,launchthesoftwarefromtheDesktopshortcut.

Itwilllooklikethis:

GotoFile→Open&selectthesketchcalledpir.InsertUSBleadintotheArduino&yourPC.

GotoTools→SerialPort&selecttheserialportthatappearedwhenyouattachedtheArduino.

(makeanoteoftheportnumber,COM8intheredbox,you’llneeditlaterforthePythonscripts)

GotoTools→Board&selecteitherArduinoUnoATmega328(thelargerboard)orArduinoNanow/ATmega328(thesmallerboard).

YoucannowprogramtheArduinobyclickingonthecirclewitharight-pointingarrowinit.

SetupPythononyourPC

Aswementionedintheintroduction,weusethePythonprogramminglanguageonthePCtoreadaserialinputfromtheUSBcableattachedtotheArduino.We’llbelookingoutfora“MotionDetected”messagefromtheArduino&connectedPIRmodule.Whenweseethatmessagewe’llperformanaction.Therearevariousexamplescripts,eachslightlymorecomplex&useful.

We’regoingtousePythonversion2.7.8whichisavailableforWindows,Mac&Linuxhere:

https://www.python.org/download/releases/2.7.8/

Pleasedon’tbetemptedtodownloadthe64bitorthenewer3.4.1version,asthelibrarieswe’reusingwon’tworkwithit.Python2.7.832bitforWindowsXP,Vista7&8.1isalsoontheDVD.

Here’swhatthePythonIDLE(GUI)lookslike:

WealsoneedtoinstallthePySeriallibrarypyserial-2.7.win32.exe(md5)forPython2.x(2.4…2.7)

fromhttps://pypi.python.org/pypi/pyserialforWindowsinstalls.ThisisalsoontheDVD.

PythononWindowsPCs.

LaunchPython2.7→IDLE(PythonGUI)fromWindowsProgrammenu.File→Open→pir1.py

Newwindowopens→selectRun→RunModule

Ifyougetanerror,thenyou’llneedtochangetheserialCOMportnumberinthepir1.pyscripttomatchtheconfigurationonyourPC.YoucandeterminewhichUSBserialCOMportnumberhasbeenallocatedtoyourArduinointhebottomrightoftheArduinoprogrammingsoftwarescreen.

MoveinfrontofthePIRmodule&youshouldseethe“MotionDetected”messageinthePythonShellscreen.

Here’swhatthecontentsofPythonscriptPir1.pylooklikeincaseyouwanttotypeityourself:

importserial

importtime

whileTrue:

ser=serial.Serial(‘COM6‘,9600)

message=ser.read(15)

now=time.ctime()

print(message+(‘‘)+now)

ser.close()

time.sleep(10)

Thefirsttwolinesoftheprogramsetupthetime&USBserialportfunctions.Thenwehavethemainloopoftheprogram,whichcontinuesforever,oruntilyouclosetheIdlePythonGUIwindow.

Thefirstlineofthemainloopsetsuptheserialport,whichyouwillalmostcertainlyhavetochangefromCOM6tosomethingelse,likeCOM8orCOM10,dependingwhatyoufoundwhenyourantheArduinosoftware.

YoucanalsoseewhichCOMporthasbeenallocatedtoyourArduinoboardinWindowsXPunderControlPanel→System→Hardware→DeviceManager→Ports(COM&LPT).

TryinsertingtheUSBdeviceintoadifferentportonyourPCifyoudon’tseeitlisted.

Thenextlinereads15charactersfromtheserialportintothevariable message .Thenextlinereadsthecurrenttime&dateintothevariable now .Thenthevariablesgetprintedtothescreen,theserialportgetsclosed&wewaittensecondswhilethePIRmoduleresets.

Next,we’lladdemailcapabilities..

SettingupaspareGmailaccount.Thesimplestwayofsendingemails&photosasattachmentsfromyourPC,istosetupanewGmailaccountforthePCtouse,evenifyoualreadyhaveanexistingGmailaccount.Foronething,itgetsyou15GBofnewcloudstorageforyouralertphotos&secondlyitremovesthecomplicationofgeneratingapplicationspecificpasswordsforotherappsonyourexistingGmailaccount.

YouneedtocreatethenewGmailaccountinthewebbrowseronyourPCorMac@

https://accounts.google.com/SignUp?service=mail

andnotedownthelogin&passwordforlater.

Next,youneedtosetthenewGmailaccounttoEnable“lesssecureapps”.Whileloggedingoto:

https://www.google.com/settings/u/0/security/lesssecureapps

Nowwehaveaworkingemailaccount,justforthePCtousewhensendingemailsfromPython.AnyphotossentfromthePCwillbebacked-upintheSentfolder&youonlyneeddeleteoldphotosifyougetneartothe15GBlimit.EmailsfromthePCrunningPythoncanbesenttoanyotheremailaddressonyourphoneoradifferentPC.

Pythonscriptwithemailfunction.

First,gotothewebsitegmail.com&createanewaccount,justfortheArduinotouse.DothisevenifyoualreadyhaveaGmailaccountyouuseeveryday.Usethatnewlogin&passwordbelow.

LaunchPython2.7→IDLE(PythonGUI)fromWindowsProgrammenu.File→Open→pir2.py

You’llneedtochangethetextI’vehighlightedinred.importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘hard-to-guess-password‘

SUBJECT=‘Intruder’

TEXT=‘PIRTriggered’

defsend_email():

print(“SendingArduinoEmail”)

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+‘‘+now+‘\n’

printheader

msg=header+‘\n’+TEXT+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘COM6‘,9600)

message=ser.read(15)

now=time.ctime()

print(message+(‘‘)+now)

send_email()

ser.close()

time.sleep(10)

ChangetheTO=emailaddresstotheoneyouwanttoreceivethealert,typicallytheemailaddressyouuseonyoursmartphone.ChangetheGMAIL_USERandGMAIL_PASSvaluestotheonesforthebrandnewgmailaccountyoujustmade.Alsorememberthatyourserialportprobablywon’tbethesameasmyCOM6.

selectRun→RunModule&youshouldreceiveanemailonyourphonewhenthePIRistriggered.

HowtograbanimagefromawebcaminPython.

TocaptureanimagefromawebcaminMicrosoftWindows,weneedtoinstallPythonlibrariesVideoCapture.pyandPIL.YouneedtodownloadVideoCapture-0.9-5.zipfromhttp://videocapture.sourceforge.net/andPythonImagingLibrary1.1.7forPython2.7fromhttp://www.pythonware.com/products/pil/index.htm.

VideoCapture.pycomesasacompressedfilewiththefolders\Lib&\DLLsinside,thecontentsneedtobemanuallycut&pastedintoyourc:\Python27folders\lib&\DLLs

Ifyou’vedownloadedVideoCapture.pyfromtheinternet,don’tcopythefilesfromthefolder“DLLs(for64-bitPython)”-evenifyou’reusing64bitWindows,usethe32bitDLLsinstead.

VideoCapture.py&PILarealsoontheDVD.InstallPIL,asyouwouldanyotherWindowsapplication,oncethefile\DLLs\vidcap.pydhasbeencopiedtofolderc:\Python27\DLLs&thefivefilesinside\Libfoldertoc:\Python27\Libfolder.

Ifyou’reusingWindows8,youmayfindyouneedtofirstcopythosefive\Libfilestoc:\Python27&thencopythemfromtheretothefolderc:\Python27\Lib.

WetestedtheimagecaptureusinganoldSonyPS2EyetoywebcamonWindowsXP,andabrandnewLogitechC270webcamonWindows764bit&Windows8.1.-othermodelsmayormaynotworkcorrectly.(Note:We’reusing32bitversionsofPython&alllibrarieson32&64bitWindows–theyworkfine)

Thescriptvidcaptest.pyshownbelowwillcaptureaphotocalledimage.jpgtothecurrentfolderonyourharddrive,whichishopefullyc:\Python27.(Don’ttryandrunvidcaptest.pyfromtheDVD!)

fromVideoCaptureimportDevice

cam=Device()

cam.setResolution(640,480)

cam.saveSnapshot(‘image.jpg’,timestamp=1,boldfont=0,textpos=‘bc’)

Ifthephotocapturedcorrectly,youcannowmoveontothenextscript.

Captureaphoto&emailitasanattachment.

Onceyou’veconfirmedthatimage.jpggotcapturedcorrectly,youcanusethepir3.pyscriptbelowtocaptureaphotofromthewebcamandemailittoyourphonewhenthePIRistriggered.

Partsofthescriptthatyouneedtoalterarehighlightedinred.

#!/usr/bin/python

importserial

importtime

importsmtplib

fromemail.MIMEMultipartimportMIMEMultipart

fromemail.MIMEBaseimportMIMEBase

fromemail.MIMETextimportMIMEText

fromemailimportEncoders

fromVideoCaptureimportDevice

importos

gmail_user=“[email protected]

gmail_pwd=“hard-to-guess-password”

cam=Device()

defmail(to,subject,text,attach):

msg=MIMEMultipart()

msg[‘From’]=gmail_user

msg[‘To’]=to

msg[‘Subject’]=subject

msg.attach(MIMEText(text))

part=MIMEBase(‘application’,‘octet-stream’)

part.set_payload(open(attach,‘rb’).read())

Encoders.encode_base64(part)

part.add_header(‘Content-Disposition’,

‘attachment;filename=”%s”’%os.path.basename(attach))

msg.attach(part)

mailServer=smtplib.SMTP(“smtp.gmail.com”,587)

mailServer.ehlo()

mailServer.starttls()

mailServer.ehlo()

mailServer.login(gmail_user,gmail_pwd)

mailServer.sendmail(gmail_user,to,msg.as_string())

mailServer.close()

whileTrue:

ser=serial.Serial(‘COM8‘,9600)

message=ser.read(15)

now=time.ctime()

print(message+(‘‘)+now)

cam.setResolution(640,480)

cam.saveSnapshot(‘image3.jpg’,timestamp=1,boldfont=0,textpos=‘bc’)

mail(“[email protected]“,

“PIRmotionalarm”,

“Thisemailwassentwithpython”,

“image.jpg”)

ser.close()

time.sleep(10)

ConnectamagneticdoorsensortotheArduino

Componentsrequired:

MiniBreadboard

1Kresistor(red,black,brown)

10Kresistor(orange,black,brown)

Magneticreedswitch,linkwire&terminalblock.

3xmaletomaleIDCcables(colournotimportant).

ThecolouroftheIDCmaletomaleleadswe’vesuppliedaren’timportant,justmakesureyoujointhecorrectpointstogether.

SetuptheArduinosoftwarefordoorsensor.

ThelatestversionoftheArduino1.0.6softwaresuiteforWindows,MacOSX&Linuxcanbedownloadedfromhttp://arduino.cc/en/Main/Software

OnceinstalledtoyourWindowsPC,launchthesoftwarefromtheDesktopshortcut.

Itwilllooklikethis:

GotoFile→Open&selectthescriptcalleddoor.InserttheUSBleadintotheArduino&yourPC.

GotoTools→SerialPort&selecttheserialportthatappearedwhenyouattachedtheArduino.

(makeanoteoftheportnumber-COM8bottomright-you’llneeditlaterforthePythonscripts)

GotoTools→Board&selecteitherArduinoUnoATmega328(thelargerboard)orArduinoNanoATmega328(thesmallerboard).

YoucannowprogramtheArduinobyclickingonthecirclewitharight-pointingarrowinit.

SetupPythonwithdoorsensoronyourPC

Aswementionedintheintroduction,we’llusethePythonprogramminglanguageonthePC,toreadaserialinputfromtheUSBcableattachedtotheArduino.We’llbelookingoutfora“DoorOPENED”messagefromtheArduino&connecteddoorsensor.Whenweseethatmessagewe’llperformanaction.Therearevariousexamplescripts,eachslightlymorecomplex&useful.

We’regoingtousePythonversion2.7.8whichisavailableforWindows,Mac&Linuxhere:

https://www.python.org/download/releases/2.7.8/

Pleasedon’tbetemptedtodownloadthe64bitorthenewer3.4.1version,asthelibrarieswe’reusingwon’tworkwithit.Python2.7.832bitforWindowsXP,Vista7&8isalsoontheDVD.

WealsoneedtoinstallthePySeriallibrarypyserial-2.7.win32.exe(md5)forPython2.x(2.4…2.7)fromhttps://pypi.python.org/pypi/pyserialforWindowsinstalls.ThisisalsoontheDVD.

Here’swhatthePythonIDLE(GUI)lookslike:

PythondoorsensorexampleonWindowsPCs.

LaunchPython2.7→IDLE(PythonGUI)fromWindowsProgrammenu.File→Open→door1.py

Newwindowopens→selectRun→RunModule

(Ifyougetanerror,thenyou’llneedtochangetheserialCOMportnumberinthedoor1.pyscripttomatchtheconfigurationonyourPC–it’sinredtextinthelistingbelow.YoucandeterminewhichUSBserialCOMportnumberhasbeenallocatedtoyourArduinointhebottomrightoftheArduinoprogrammingsoftwarescreen.Or,youcanseewhichCOMporthasbeenallocatedtoyourArduinoboardinWindowsXPunderControlPanel→System→Hardware→DeviceManager→PortsCOM&LPT.TryinsertingtheUSBdeviceintoadifferentportonyourPCifyoudon’tseeitlisted.)

Movethemagnetawayfromthewireddoorsensorandyoushouldseethe“DoorOPENED”messageinthePythonShellscreen.Moveitback&youshouldsee“Doorclosed”.

Contents&explanationofPythonscriptDoor1.py,incaseyouwanttotypeityourself:

importserial

importtime

ODS=“C”

whileTrue:

ser=serial.Serial(‘COM8‘,9600)

message=ser.read(10)

DS=message[5]

now=time.ctime()

ser.close()

while(ODS!=DS):

ifDS==“C”:

print“Doorclosed”+now

elifDS==“O”:

print“DoorOPENED”+now

else:

DS=ODS

break

time.sleep(0.1)

ODS=DS

Thefirsttwolinesoftheprogramgiveusaccesstothetime&USBserialportfunctionsinPython.Thevariable ODS standsfor“OLDDOORSTATE”andthestartingvalueis“C”forclosed.

ThemainWhilelooprepeatedlyreads10charactersfromtheUSB/serialportintothevariable message .The5thcharacterofthe message variablegetsloadedinto DS &shouldeitherread“C”forclosedor“O”foropen(itwilloccasionallyreadsomethingelse,butweignoreanythingthatisn’t“O”or“C”).Wegetthecurrentdate&timeintothevariable now .Thenweclosetheserialport.

Thesecondaryloopcomparesthedoorstatewejustreadin(either“C”or“O”)totheolddoorstate,&ifthey’redifferent,itmeanssomeonehasopenedorclosedthedoor…Sothescriptprints“DoorOPENED”&thetime&datetothescreen,or“Doorclosed”.IfthevalueinDSisn’t“O”or“C”(whichitoccasionallywillbeduetoerrorsreadingtheUSB/serialport)thenwesetDSbacktotheolddoorstateODS.

Wethendropbackouttothemainloopandsleepfor0.1ofasecond.Lastly,whateverisheldinthevariableDSnowgetsshiftedintoODS(theOldDoorState).

Pythondooralarmscriptwithemailfunction.

First,gotothewebsitegmail.com&createanewaccount,justfortheArduinotouse.DothisevenifyoualreadyhaveaGmailaccountyouuseeveryday.Enterthosenewaccountdetailsbelow.

RunPython2.7→IDLE(PythonGUI)fromWindowsProgrammenu.File→Open→door2.py

You’llneedtochangethetextI’vehighlightedinred.importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘password’

NOW=”“

ODS=“C”

message=”“

defsend_email():

print(“SendingEmail”)

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:’+message+‘‘+NOW+‘\n’

printheader

msg=header+‘\n’+message+‘\n’+NOW+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘COM8‘,9600)

message=ser.read(11)

DS=message[5]

NOW=time.ctime()

ser.close()

while(ODS!=DS):

ifDS==“C”:

print“Doorclosed”+NOW

send_email()

elifDS==“O”:

print“DoorOPENED”+NOW

send_email()

else:

DS=ODS

break

time.sleep(0.1)

ODS=DS

ChangetheTO=emailaddresstotheoneyouwanttoreceivethealert,typicallytheemailaddressyouuseonyoursmartphone.ChangetheGMAIL_USERandGMAIL_PASSvaluestotheonesforthebrandnewgmailaccountyoujustmade.AlsorememberthatyourserialportwillprobablynotbethesameasmyCOM8.

selectRun→RunModule&youshouldreceiveanemailonyourphonewhenthedoorsensoristriggered.

Next,I’llshowyouhowtograbaphotofromawebcam,whenthedoorsensoristriggered.

HowtograbanimagefromawebcaminPython.

TocaptureanimagefromawebcaminMicrosoftWindows,weneedtoinstallPythonlibrariesVideoCapture.pyandPIL.YouneedtodownloadVideoCapture-0.9-5.zipfromhttp://videocapture.sourceforge.net/andPythonImagingLibrary1.1.7forPython2.7fromhttp://www.pythonware.com/products/pil/index.htm.

VideoCapture.pyfilesinsidethefolders\Lib&\DLLsneedtobemanuallycut&pastedintoyourc:\Python27folders\lib&\DLLs

Don’tcopythefilesfromthefolder“DLLs(for64-bitPython)”ifyou’vedownloadedVideoCapture.pyfromtheinternet,evenifyou’reusing64bitWindows.

VideoCapture.py&PILarealsoontheDVD.InstallPIL,asyouwouldanyotherWindowsapplication,oncethefile\DLLs\vidcap.pydhasbeencopiedtofolderc:\Python27\DLLs&thefivefilesinside\Libfoldertoc:\Python27\Libfolder.

Ifyou’reusingWindows8,youmayfindyouneedtofirstcopythosefive\Libfilestoc:\Python27&thencopythemfromtheretothefolderc:\Python27\Lib.

WetestedtheimagecaptureusinganoldSonyPS2EyetoywebcamonWindowsXP,andabrandnewLogitechC270webcamonWindows764bit&Windows8.1.-othermodelsmayormaynotworkcorrectly.(Note:We’reusing32bitversionsofPython&alllibrarieson32&64bitWindows–theyworkfine)

Thescriptvidcaptest.pyshownbelowwillcaptureaphotocalledimage.jpgtothecurrentfolderonyourharddrive,whichishopefullyc:\Python27.(Don’ttryandrunvidcaptest.pyfromtheDVD!)

fromVideoCaptureimportDevice

cam=Device()

cam.setResolution(640,480)

cam.saveSnapshot(‘image.jpg’,timestamp=1,boldfont=0,textpos=‘bc’)

Ifthephotocapturedcorrectly,youcannowmoveontothenextscript.

Captureaphoto&emailitasanattachment.

Onceyou’veconfirmedthatimage.jpggotcapturedcorrectly,youcanusethedoor3.pyscriptbelowtocaptureaphotofromthewebcamandemailittoyourphonewhenthedoorisopened.Youshouldhavealreadycreatedanewgmail.comaccountsolelyforusewiththeArduino.

Partsofthescriptthatyouneedtoalterarehighlightedinred.

#!/usr/bin/python

importserial

importtime

importsmtplib

fromemail.MIMEMultipartimportMIMEMultipart

fromemail.MIMEBaseimportMIMEBase

fromemail.MIMETextimportMIMEText

fromemailimportEncoders

fromVideoCaptureimportDevice

importos

gmail_user=“[email protected]

gmail_pwd=“hard-to-guess-password”

cam=Device()

NOW=”“

ODS=“C”

message=”“

defmail(to,subject,text,attach):

msg=MIMEMultipart()

msg[‘From’]=gmail_user

msg[‘To’]=to

msg[‘Subject’]=subject

msg.attach(MIMEText(text))

part=MIMEBase(‘application’,‘octet-stream’)

part.set_payload(open(attach,‘rb’).read())

Encoders.encode_base64(part)

part.add_header(‘Content-Disposition’,

‘attachment;filename=”%s”’%os.path.basename(attach))

msg.attach(part)

mailServer=smtplib.SMTP(“smtp.gmail.com”,587)

mailServer.ehlo()

mailServer.starttls()

mailServer.ehlo()

mailServer.login(gmail_user,gmail_pwd)

mailServer.sendmail(gmail_user,to,msg.as_string())

mailServer.close()

whileTrue:

ser=serial.Serial(‘COM9‘,9600)

message=ser.read(11)

DS=message[5]

NOW=time.ctime()

ser.close()

while(ODS!=DS):

ifDS==“C”:

print“Doorclosed”+NOW

cam.setResolution(640,480)

cam.saveSnapshot(‘image3.jpg’,timestamp=1,boldfont=0,textpos=‘bc’)

mail(“[email protected]“,

“DoorClosed”,

“DoorClosed”+NOW,

“image3.jpg”)

elifDS==“O”:

print“DoorOPENED”+NOW

cam.setResolution(640,480)

cam.saveSnapshot(‘image3.jpg’,timestamp=1,boldfont=0,textpos=‘bc’)

mail(“[email protected]“,

“DoorOPENED”,

“DoorOPENED”+NOW,

“image3.jpg”)

else:

DS=ODS

break

time.sleep(0.1)

ODS=DS

Part2–GoingWirelessWhiletheexamplesalreadygivenworkgreatwithanArduinoconnectedtotheUSBportonyourPC,MacorRaspberryPi.Youmightwanttohaveanumberofdifferentsensors,invariousplacesaroundyourhome,reportingbackwirelesslytotheArduinoattachedtoyourPC.

AstheArduinoUnoR3andNanocloneboardscanbeboughtfromChinaforaround£3/$5each,wecanmakecompletewirelessPIRsensorsforaround£10/$15each.We’regoingtousetheinexpensiveNRF24L01+boards,whichcostaround£1/$1.50eachoneBay,tocommunicatewirelessly.Tryandbuytheonespicturedasweknowtheyworkcorrectly.

TheNRF24L01+boardstransmitandreceiveinthesamelicence-free2.4GHzbandusedbyWiFi,butaren’tWiFicompatible.YoucanstillgetinterferencefromotherWiFidevicesthough,sodon’tsetupyourprojectnexttoyourWiFirouter.

TheoperatingrangeofthestandardboardswithanantennaprintedonthePCBisaround20metres,butthereisalsoaslightlymoreexpensiveversionwithanexternalantenna,thatcanmanage100metres.

Here’swhatafullyassembledwirelessPIRsensorlookslike.PoweredbyaUSBbatterypack.

Here’swhatafullyassembledmagneticdoorsensorlookslike.

HowtoconnecttheNRF24L01+toArduino

Signal RFModulepin WireColour ArduinoPin

GND 1 Brown GND

VCC 2 Red 3.3V

CE 3 Orange 9

CSN 4 Yellow 10

SCK 5 Green 13

MOSI 6 Blue 11

MISO 7 Violet 12

Topview:

Bottomview:

CablingdiagramforArduinoUnoR3wirelessPIR

Thelinkcablesarestandard20cmlong40waymaletofemaleDuPontbreadboardcablesavailablefromeBay.Thebrown,red,orange,yellow,green,blue,violetcablesareallnexttoeachotherinthe40waycableweused,andcanbeseparatedintoa7wirebunch.

RemembertheNRF24L01+boardsarepoweredby3.3V,not5V.TheredwirefromtheNRF24L01+connectsto3V3ontheArduino.

Here’saFritzingwiringdiagramforanArduinoUnoR3board:

CablingdiagramforanArduinoNanowirelessPIR.

Thelinkcablesarestandard20cmlong40waymaletofemaleDuPontbreadboardcablesavailablefromeBay.Thebrown,red,orange,yellow,green,blue,violetcablesareallnexttoeachotherinthe40waycableweused,andcanbeseparatedintoa7wirebunch.

Here’saFritzingwiringdiagramforanArduinoNanoUSBboardonaminibreadboard:

InstallingManiacBug’sRF24libraryforArduino.

TomakeitsimplefortheArduinototalktotheNRF24L01+module,weneedtoinstallManiacBug’sRF24library.

Gotothewebpagehttps://github.com/maniacbug/RF24andclickontheDownloadZIPbuttonontheright-handsideofthepage.RenamethefileRF24-master.ziptoRF24.zip.OpenthezipfileandextracttheRF24-Masterfolder.RenametheextractedfolderRF24-MastertoRF24.

StartupyouArduinoIDEsoftware&gotoSketch→ImportLibrary→AddLibraryandselecttheunzipped&renamedRF24folder.OnthelatestArduino1.6.4onWindowsyougotoSketch→IncludeLibrary→Add.ZIPLibrary→selecttheextractedRF24folder(notthezipfile).

UploadPIRtransmittercodetotheArduino.OnceyouhavetheRF24libraryinstalledandallthewiresconnectedup,itjustremainstouploadthefiletransmitpir.inototheArduino(Weshowedyouhowtodothisintheearlierexamples).

//Importneededlibraries

#include<SPI.h>

#include<nRF24L01.h>

#include<RF24.h>

//DeclareConstantsandPinNumbers

#defineCE_PIN9

#defineCSN_PIN10

//Definethetransmitpipe

constuint64_tpipe=0xE8E8F0F0E1LL;

//CreateRadio

RF24radio(CE_PIN,CSN_PIN);

//Declarevariables

intswitchPin=7;

intvalue=0;

intmsg[1];

//setup

voidsetup(){

pinMode(switchPin,INPUT);

Serial.begin(9600);

}

//MainLoop

voidloop(){

//readPIRstatus

value=digitalRead(switchPin);

if(HIGH==value){

//printmotiondetectedtoserialterminal

Serial.println(“Motiondetected”);

//Preparetheradiomoduletotransmit

radio.begin();

radio.openWritingPipe(pipe);

radio.powerDown();

delay(1000);

radio.powerUp();

//Sendcodeforthesensor,use0000throughto8888

StringtheMessage=“4444“;

intmessageSize=theMessage.length();

for(inti=0;i<messageSize;i++){

intcharToSend[1];

charToSend[0]=theMessage.charAt(i);

radio.write(charToSend,1);

}

//terminatemessageisa9

msg[0]=9;

radio.write(msg,1);

//killpowertoradio

radio.powerDown();

delay(2000);

}

}

OncethetransmittersketchhasbeenuploadedtotheArduino,itwillrunwheneveryouconnectpower.Weuseda5VUSBpowerbanktopowerourfirsttransmitternode.

WhenanyonemovesinfrontofthePIR,theArduinoprints“MotionDetected”totheSerialMonitor,sendsa4444codemessageoverthewirelessmodule,andterminatesthemessagebysendinganumber9.IfyouhaveseveralArduinossetupwithPIRmodulesyoucanreusethesametransmitterprogramineachArduino,butjustchangethetransmitstringto3333or5555,soyoucandistinguishbetweenthematthereceiver.Don’tusethestring9999though,asitwillconfusethesoftware.

TotestthetransmitterwiththeArduinoconnectedtotheUSBportonyourPC,openuptheTools→SerialMonitoroptionintheArduinoIDEsoftwareandyoushouldseea“MotionDetected”messageeachtimeyoumovenearthePIRmodule.

Tofurthertestthetransmitter,weneeda2ndArduinorunningthereceivercodeattachedtoourPC.

Connectupa2ndArduinowithaNRF24L01,justlikewedidforthetransmitterunit,butthistimethere’snoneedtoattachaPIRsensor.We’llthenprogramthe2ndArduinowiththereceivercode.

Uploadreceivercodetoa2ndArduino.OnceyouhavetheRF24libraryinstalledandthetransmittersetup,itjustremainstouploadthereceivercodetoa2ndArduino.(Wealreadyshowedyouhowtodothisintheearliernon-wirelessexamples)Fileiscalledreceiver.inoonourDVD.

//setuprequiredlibraries

#include<nRF24L01.h>

#include<RF24.h>

#include<RF24_config.h>

#include<SPI.h>

//setupvariablesandradio

intmsg[1];

RF24radio(9,10);

constuint64_tpipe=0xE8E8F0F0E1LL;

intlastmsg=1;

StringtheMessage=””;

//setupradio

voidsetup(void){

Serial.begin(9600);

radio.begin();

radio.openReadingPipe(1,pipe);

radio.startListening();

}

//mainloop

voidloop(void){

if(radio.available()){

booldone=false;

done=radio.read(msg,1);

chartheChar=msg[0];

if(msg[0]!=9){

theMessage.concat(theChar);

}

else{

Serial.println(theMessage);

theMessage=””;

}

}

}

IfyouhavethereceiverArduinoconnectedbyaUSBporttoyourPC,youcanopentheserialmonitor(Tools→SerialMonitor)&seemessagescomingfromthetransmitterwhenthePIRmoduleistriggered.Ifyou’vesetupseveralArduinos&PIRsastransmitters,thenyou’llseemessageslike3333,4444,or5555dependingwhichPIRhasbeentriggered.

Occasionallyyou’llseethemessagereceivedas444insteadof4444,butwestillhaveenoughinformationtoknowwhichsensorhasbeentriggered(see“SomethingElse”chapterneartheendofthebookformoreonthis).Inthenextexamplei’llshowyouhowtosendanemailalerttoyourphone,viathereceiverArduinoconnectedtoaPC,whenthePIRhasbeentriggered.

SettingupaspareGmailaccount.Thesimplestwayofsendingemails&photosasattachmentsfromyourPC,istosetupanewGmailaccountforthePCtouse,evenifyoualreadyhaveanexistingGmailaccount.Foronething,itgetsyou15GBofnewcloudstorageforyouralarmalerts&secondlyitremovesthecomplicationofgeneratingapplicationspecificpasswordsforotherappsonyourexistingGmailaccount.

YouneedtocreatethenewGmailaccountinthewebbrowseronyourPCorMac@

https://accounts.google.com/SignUp?service=mail

andnotedownthelogin&passwordforlater.

Next,youneedtosetthenewGmailaccounttoEnable“lesssecureapps”.Whileloggedingoto:

https://www.google.com/settings/u/0/security/lesssecureapps

Nowwehaveaworkingemailaccount,justforthePCtousewhensendingemailsfromPython.EmailsfromthePCrunningPythoncanbesenttoanyotheremailaddressonyourphoneoradifferentPC.

PythonscriptwithemailfunctiontorunonyourPC.

First,gotothewebsitegmail.com&createanewaccount,justfortheArduinotouse.DothisevenifyoualreadyhaveaGmailaccountyouuseeveryday.Makesureyouenabled“lesssecureapps”accesstothegmailaccount.Usethatnewlogin&passwordbelow.

LaunchPython2.7→IDLE(PythonGUI)fromWindowsProgrammenu.File→Open→wirelesspir.py

You’llneedtochangethetextI’vehighlightedinred.importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘hard-to-guess-password‘

SUBJECT=‘Intruder’

TEXT=‘PIRTriggered’

defsend_email():

print(“SendingArduinoEmail”)

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+‘‘+now+‘\n’

printheader

msg=header+‘\n’+TEXT+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘COM6‘,9600)

message=ser.read(4)

now=time.ctime()

print(message+(‘‘)+now)

send_email()

ser.close()

time.sleep(10)

ChangetheTO=emailaddresstotheoneyouwanttoreceivethealert,typicallytheemailaddressyouuseonyoursmartphone.ChangetheGMAIL_USERandGMAIL_PASSvaluestotheonesforthebrandnewgmailaccountyoujustmade.Yourserialportprobablywon’tbeonCOM6.

selectRun→RunModule&youshouldreceiveanemailonyourphonewhenthePIRistriggered.

ArduinoUnoR3wirelessmagneticdoorsensor

ThelinkcablestotheNRF24L01+arestandard20cmlong40waymaletofemaleDuPontbreadboardcablesavailablefromeBay.Thebrown,red,orange,yellow,green,blue,violetcablesareallnexttoeachotherinthe40waycableweused,andcanbeseparatedintoa7wirebunch.

Theminibreadboardusedforthemagneticdoorcircuitusesa1k(brown,black,red)&a10k(brown,black,orange)resistortoprovideastablepullup/downvoltagedividercircuit.

Here’saFritzingwiringdiagramforanArduinoUnoR3board:

ArduinoNanowithwirelessmagneticdoorsensor

ThelinkcablestotheNRF24L01+arestandard20cmlong40waymaletofemaleDuPontbreadboardcablesavailablefromeBay.Thebrown,red,orange,yellow,green,blue,violetcablesareallnexttoeachotherinthe40waycableweused,andcanbeseparatedintoa7wirebunch.

Theminibreadboardusedforthemagneticdoorcircuitusesa1k&a10kresistortoprovideastablepullup/downvoltagedividercircuit.

Here’saFritzingwiringdiagramforanArduinoNanoUSBboard:

UploadtransmittercodetotheArduinoformagdoor.OnceyouhavetheRF24libraryinstalledandallthewiresconnectedup,itjustremainstouploadthewirelessmagdoortransmittercodetotheArduinooverUSB.(we’veshowedyouhowinpreviousexamples).Here’sthemagdooralarmtransmittersketch,calledtransmitdoor.ino

//Importneededlibraries

#include<SPI.h>

#include<nRF24L01.h>

#include<RF24.h>

//DeclareConstantsandPinNumbers

#defineCE_PIN9

#defineCSN_PIN10

//Definethetransmitpipe

constuint64_tpipe=0xE8E8F0F0E1LL;

//CreateRadio

RF24radio(CE_PIN,CSN_PIN);

//Declarevariables-dsisdoorstateandodsisolddoorstate

intswitchPin=7;

intds=0;

intmsg[1];

intods=0;

//setup

voidsetup(){

pinMode(switchPin,INPUT);

Serial.begin(9600);

}

//MainLoop

voidloop(){

//readDoorstatus

ds=digitalRead(switchPin);

if(HIGH==ds&&ds!=ods){

//printdooropenedtoserialterminal

Serial.println(“DoorOpened”);

StringtheMessage=“5555”;

//Preparetheradiomoduletotransmit

radio.begin();

radio.openWritingPipe(pipe);

radio.powerDown();

delay(1000);

radio.powerUp();

//Sendcodeforthesensor,use0000throughto8888

intmessageSize=theMessage.length();

for(inti=0;i<messageSize;i++){

intcharToSend[1];

charToSend[0]=theMessage.charAt(i);

radio.write(charToSend,1);

}

//terminatemessageisa9

msg[0]=9;

radio.write(msg,1);

//killpowertoradio

radio.powerDown();

delay(2000);

ods=ds;

}

elseif(HIGH!=ds&&ds!=ods){

Serial.println(“DoorClosed”);

StringtheMessage=“6666”;

//Preparetheradiomoduletotransmit

radio.begin();

radio.openWritingPipe(pipe);

radio.powerDown();

delay(1000);

radio.powerUp();

//Sendcodeforthesensor,use0000throughto8888

intmessageSize=theMessage.length();

for(inti=0;i<messageSize;i++){

intcharToSend[1];

charToSend[0]=theMessage.charAt(i);

radio.write(charToSend,1);

}

//terminatemessageisa9

msg[0]=9;

radio.write(msg,1);

//killpowertoradio

radio.powerDown();

delay(2000);

ods=ds;

}

else{

ods=ds;

}

}

Ifthedoorisopenedthetransmitternodesendsa5555codeovertheNRF24L01+link,andwhenthedoorisclosedagainthetransmittersendsa6666code.Thevariablesds(doorstate)andods(olddoorstate)keeptrackofwhetherthemagneticdoorsensorreads0or1,andifthatstatehasjustchanged.

OntheArduinoreceiverside,wecanusethesamesketchweusedforthePIRreceiver(aswe’restilljustreceiving4digitcodes).WejustneedadifferentPythonscriptrunningonthePC/Mactointerpretthefactthedoorhasbeenopenedorclosed.

Pythoncodeforwirelessmagneticdoorsensor.RunthiscodeonyourPCorMacrunningPython2.7.8IDLE.importserial

importtime

whileTrue:

ser=serial.Serial(‘COM8’,9600)

code=ser.read(4)

now=time.ctime()

ifcode==“4444”:

message=“PIRtriggered”

elifcode==“5555”:

message=“DoorOpened”

elifcode==“6666”:

message=“DoorClosed”

else:

message=“SomethingElse”

print(message+(‘‘)+now)

ser.close()

time.sleep(1)

We’vetestedthecodeabovewithanArduinoNanocloneattachedtoaPIRsensor,adifferentArduinoNanocloneattachedtoamagneticdoorsensor,andaArduinoUnoR3clonerunningtheNRF24L01+receivercodeattachedtoaPC.

Thenextexamplebringsthemagneticdoorsensor&PIRsensorreceivercodestogetherinascriptthatsendsanemailfromyourPCwhenthey’retriggered.

PythoncodeforwirelessPIR&doorsensortoemail.Runthecodewirelessdoor.pyonyourPCorMacrunningPython2.7.8IDLE.

importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘hard-to-guess-password’

NOW=”“

message=”“

defsend_email():

print(“SendingEmail”)

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:’+message+‘‘+NOW+‘\n’

printheader

msg=header+‘\n’+message+‘\n’+NOW+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘COM8’,9600)

code=ser.read(4)

NOW=time.ctime()

ifcode==“4444”:

message=“PIRtriggered”

elifcode==“5555”:

message=“DoorOpened”

elifcode==“6666”:

message=“DoorClosed”

else:

message=“SomethingElse”

print(message+(‘‘)+NOW)

print(code)

send_email()

ser.close()

time.sleep(1)

ConnectaLDRlightsensortotheArduino

Componentsrequired:

MiniBreadboard

10Kresistor(brown,black,orange)

LDR–lightdependentresistor

3xmaletomaleIDCconnectingcables

TheLDR(lightdependentresistor)variesitsresistancedependinghowmuchlightisfallingonitsface.WecanreadthisvalueontheArduino&useittoimproviseawardrobe,cupboardordraweralarm.Ifthecupboardisopened,morelightwillbedetectedandthatcantriggeranemailtoourphone.

Here’showit’sconnected:(thecoloursofthewiresyouuseisn’timportant,justthepositions)

Arduinoanaloginputpins.

ThedigitalinputpinsontheArduinodetectwhetherapinishighorlow,orifyouprefersetto1or0.Anyofthedigitalpinswillonlyeverreadhighorlow,butifwewanttoreadfromasensorthatcanhaveawiderangeofpossiblevaluesweuseananalogueinputpin.Therearesixdifferentanaloginputpinsavailable.

Examplesofsensorsyoucanattachtotheanalogpinsare:lightsensors,humiditysensors,temperaturesensors,gassensors,alcoholsensors&waterlevelsensors.ThesensorsconnectedtoananaloginputontheArduinowillgiveavaluebetween0and1023.

YoucanusetheArduinoSketchesandPythonscriptswe’veprovidedbelowtoreadanyanalogsensorconnectedtoanArduino&getittosendthevaluetoaPC.JustGoogleyoursensortypeandseewhatsupportingresistorsetcarerecommendedforconnectingittoanArduino.

UploadthesketchLDR2totheArduino&thenopenTools→SerialMonitortoseethevaluesscrollupthescreen.Coverthesensorwithyourfinger&you’llseethevaluegobelow200.

//sketchtoreadlightvaluefromLDRsensor-over200islight

//printsvaluetotheserialterminal

intsensorPin=A0;//selecttheinputpinfortheLDRsensor

intsensorValue=0;//variabletostorethevaluecomingfromthesensor

voidsetup(){

Serial.begin(9600);

}

voidloop(){

//readthevaluefromthesensor:

sensorValue=analogRead(sensorPin);

Serial.println(sensorValue);

delay(500);

}

Asavaluebelow200canbeconsiderdarkness,wecanuseatriggervalueofmorethan200tosendanemailsayingourdrawerorcupboarddoorhasbeenopened.Usethesketchabovetofigureoutthetriggervalueneededforyourparticularsituation.Inthenextexamplewe’llconnecttheLDRsensorcircuittoanArduinoNano&NRF24L01+boardtomakeawirelesssensorversion.

MakeawirelessArduinoLDRlightsensor.

Here’stheFritzingwiringdiagramshowinghowtoconnectanArduinoNanototheNRF24L01+boardandthelightdependentresistorcircuit.(Youdon’tneedtousethesamecolourwiresasus,justconnectthecorrectpointstogether).

TheideabehindthisprojectisthatyoucanplacetheArduino(poweredbyaUSBbatterypack)insideadrawer,cupboardorwardrobe,anditwillwirelesslysendatriggercodetoyourPC,whichinturnwillemailyourphonewhenthelightlevelincreases&emailyouagainwhenitgoesbacktodarkness.

SketchcodeforwirelessArduinoLDRlightsensor.

UploadthefollowingSketchtoyourArduinoboard(calledtransmitldr.inoonourDVD/Server).

//Importneededlibraries

#include<SPI.h>

#include<nRF24L01.h>

#include<RF24.h>

//DeclareConstantsandPinNumbers

#defineCE_PIN9

#defineCSN_PIN10

//Definethetransmitpipe

constuint64_tpipe=0xE8E8F0F0E1LL;

//CreateRadio

RF24radio(CE_PIN,CSN_PIN);

//Declarevariables

//dsisdrawerstateandodsisolddrawerstate

intds=0;

intmsg[1];

intods=0;

intsensorPin=A0;//selecttheinputpinfortheLDRsensor

//setup

voidsetup(){

Serial.begin(9600);

}

//MainLoop

voidloop(){

//readDrawerstatus

ds=analogRead(sensorPin);

if(ds>200&&ods<=200){

//printdooropenedtoserialterminal

Serial.println(“DrawerOpened”);

Serial.println(ds);

Serial.println(ods);

StringtheMessage=“7777”;

//Preparetheradiomoduletotransmit

radio.begin();

radio.openWritingPipe(pipe);

radio.powerDown();

delay(1000);

radio.powerUp();

//Sendcodeforthesensor,use0000throughto8888

intmessageSize=theMessage.length();

for(inti=0;i<messageSize;i++){

intcharToSend[1];

charToSend[0]=theMessage.charAt(i);

radio.write(charToSend,1);

}

//terminatemessageisa9

msg[0]=9;

radio.write(msg,1);

//killpowertoradio

radio.powerDown();

delay(500);

ods=ds;

}

elseif(ds<200&&ods>=200){

Serial.println(“DrawerClosed”);

Serial.println(ds);

Serial.println(ods);

StringtheMessage=“8888”;

//Preparetheradiomoduletotransmit

radio.begin();

radio.openWritingPipe(pipe);

radio.powerDown();

delay(1000);

radio.powerUp();

//Sendcodeforthesensor,use0000throughto8888

intmessageSize=theMessage.length();

for(inti=0;i<messageSize;i++){

intcharToSend[1];

charToSend[0]=theMessage.charAt(i);

radio.write(charToSend,1);

}

//terminatemessageisa9

msg[0]=9;

radio.write(msg,1);

//killpowertoradio

radio.powerDown();

delay(500);

ods=ds;

}

else{

ods=ds;

}

}

WhentheSketchisrunningonyourArduino,opentheTools→SerialMonitorscreen,andyou’llseethemessage“DrawerOpened”appearwhenthelightlevelgoesabove200,alongwiththecontentsoftheDS&ODSvariables(I’velefttheminfortroubleshootingpurposes)theradiomodulethentransmitscode7777.

Whenthelightleveldropsbelow200,you’llseethe“DrawerClosed”message,alongwiththeDS&ODSvalues.Theradiomodulethensendsthe8888code.

Weusethe2ndArduino&NRF24L01+boardreceiversetupfromthepreviousexperimentstoreceivethecodesonourPCorMac.NextI’llshowyouthePythoncodetorunonthePC.

PythoncodeforwirelessArduinoLDRlightsensor.

RunthePythonexamplewirelessldr.pyonyourPCorMacrunningPython2.7.8IDLE.Itdetectsthe7777or8888codescomingovertheUSBconnectionfromthereceiverArduino&sendsanemailalert.

Remembertochangetheitemshighlightedinredtosuityoursetup.

importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘hard-to-guess-password’

NOW=”“

ODS=“C”

message=”“

defsend_email():

print(“SendingEmail”)

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:’+message+‘‘+NOW+‘\n’

printheader

msg=header+‘\n’+message+‘\n’+NOW+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘COM8‘,9600)

code=ser.read(4)

NOW=time.ctime()

ifcode==“7777”:

message=“DrawerOpened”

elifcode==“8888”:

message=“DrawerClosed”

else:

message=“SomethingElse”

print(message+(‘‘)+NOW)

print(code)

send_email()

ser.close()

time.sleep(1)

Makeastandalonebatterypoweredbeepingreceiver.

Ifyourwirelesstransmitterisoutsidesomewhere&youdon’thaveaccesstoaPCtoattachyourreceiverto,thenitcanbehandytohaveabatterypoweredArduinoreceiverthatcangiveyouanindicationthatthealarmhasbeentriggered.

Inthisexamplewe’llusea5voltbeepertosoundforhalfasecondwhenavalidcode4digitalarmcodeisreceived.

Here’showtowireeverythingtogether:

Arduino&NRF24L01receiverportablebeeperSketch.

Uploadsketchreceiverbeep.inotoyourArduino.Thesketchexpectsthebeeper+sidetobeconnectedtodigitalpin7&thebeeper’s-toGND.

//setuprequiredlibraries

#include<nRF24L01.h>

#include<RF24.h>

#include<RF24_config.h>

#include<SPI.h>

//setupvariablesandradio

intbeepPin=7;

intmsg[1];

RF24radio(9,10);

constuint64_tpipe=0xE8E8F0F0E1LL;

intlastmsg=1;

StringtheMessage=””;

//setupradio

voidsetup(void){

Serial.begin(9600);

pinMode(beepPin,OUTPUT);

radio.begin();

radio.openReadingPipe(1,pipe);

radio.startListening();

}

//mainloop

voidloop(void){

if(radio.available()){

booldone=false;

done=radio.read(msg,1);

chartheChar=msg[0];

if(msg[0]!=9){

theMessage.concat(theChar);

}

else{

Serial.println(theMessage);

digitalWrite(beepPin,HIGH);

delay(500);

digitalWrite(beepPin,LOW);

theMessage=””;

}

}

}

YoucannowruntheArduinoreceiverunitfromaportableUSBpowerwithoutbeingattachedtoaPC.Whenavalid4digitcodeisreceivedthebeeperwillsoundforhalfasecond-delay(500).

Youcouldchangethesketcharoundsothatdifferent4digitcodesgivedifferentdurationbeeps.

SettingupArduinoIDEsoftwareonaRaspberryPi.

Althoughwe’vesaidyouneedtoconnecttheArduinototheUSBportonaPCorMac,it’salsopossibletoconnecttheArduinoboardtoaRaspberryPi’sUSBport.

IfyouwanttoprogramtheArduinoboardsfromtheRaspberryPi,ratherthanaPCorMac,thenyouneedtoinstalltheArduinosoftware.OpentheTerminalonyourPi&typein:

sudoapt-getupdate

sudoapt-getinstallarduino

CurrentlythatinstallsArduinoIDE1.0.1,whichworksfine(currentPC/Macversionis1.6),butthenyoualsoneedtomanuallyinstalltheRF24library.

DownloadManiacBug’sRF24libraryfromhttps://github.com/maniacbug/RF24byclickingontheDownloadZIPbuttonnearthelower-rightsideofthepage.UnzipthefoldertoyourDesktopandrenamethefolderRF24-masterasRF24.QuittheArduinosoftwareifit’salreadyrunning.

MovetheRF24librarytothecorrectlocationonthePi,with:

sudocp/home/pi/Desktop/RF24*/usr/share/arduino/libraries-r

ThenstarttheArduinosoftwareatMenu→Electronics→ArduinoIDEandgotoSketch→ImportLibraryandyoushouldseeRF24listed.

NextyouneedtodownloadourArduinoSketches&Unzipthem

wgethttp://www.securipi.co.uk/arduino-sketches.zip

Unpackthemwith

unziparduino-sketches.zip

YoucannowuploadanyoftheArduinosketchestoyourUnoorNanoboard.Forexamplereceiverbeep.ino

GotoFile→OpenandselecttheSketchtouploadtotheboard.

GotoTools→BoardandselecteitherUnoorArduinoNanow/ATmega328

ThenTools→SerialPortandselect/dev/ttyUSB0

ThenclicktheBlueRightArrowicon(underneathEdit)touploadyourSketch.

UsingthePythonscriptsonaRaspberryPi

YoucanusetheRaspberryPidesktoporcommandlinetorunourPython2scripts.(don’tusePython3).

YouneedPython2.7.3installedtorunthesescripts,thedefaultonmyPi.Checkyourversionwith:

python-V

DownloadthemtoyourPi’scommandlinewith

wgethttp://www.securipi.co.uk/arduinopython.zip

Unpackthemwith

unziparduinopython.zip

Seealistofthemwith

ls-al

ShowtheUSBserialportsinyourPiwith

ls-l/dev/ttyUSB*

LetsassumeyourArduinoison/dev/ttyUSB0.

Editwirelesstest.pyusingnanoandreplacethereferencetoCOM8with/dev/ttyUSB0

nanowirelesstest.py

Savethefile(CTRL-O)&exit(CTRL-X)nano.

RunthePythonscript

pythonwirelesstest.py

Makethesamechangestopythonscriptswirelesspir.py,wirelessdoor.py&wirelessldr.py

IfyounoticethetimeontheRaspberryPiisincorrect,changeitwith

sudodpkg-reconfiguretzdata

PythonscripttocapturefromPiCameramodule.

Thisscriptisinourdownloadaswirelesspirpi2.py.Makesureyouchangetheemailaddresseshighlightedinred.Launchitwith

pythonwirelesspirpi2.py

Makesureyou’veenabled“lesssecureapps”intheGmailsettingstoo.#!/usr/bin/python

#makeanewgmailacountandenterthecorrectdetailsbelow

#changetheemailaddresseswe’veusedtomatchyoursender&recipient

#thisscriptworkswithRaspberryPiCamerapluggedintoaRaspberryPi

importserial

importtime

importsmtplib

fromemail.MIMEMultipartimportMIMEMultipart

fromemail.MIMEBaseimportMIMEBase

fromemail.MIMETextimportMIMEText

fromemailimportEncoders

importos

gmail_user=“[email protected]

gmail_pwd=“hard-to-guess-password-goes-here”

defmail(to,subject,text,attach):

msg=MIMEMultipart()

msg[‘From’]=gmail_user

msg[‘To’]=to

msg[‘Subject’]=subject

msg.attach(MIMEText(text))

part=MIMEBase(‘application’,‘octet-stream’)

part.set_payload(open(attach,‘rb’).read())

Encoders.encode_base64(part)

part.add_header(‘Content-Disposition’,

‘attachment;filename=”%s”’%os.path.basename(attach))

msg.attach(part)

mailServer=smtplib.SMTP(“smtp.gmail.com”,587)

mailServer.ehlo()

mailServer.starttls()

mailServer.ehlo()

mailServer.login(gmail_user,gmail_pwd)

mailServer.sendmail(gmail_user,to,msg.as_string())

mailServer.close()

whileTrue:

ser=serial.Serial(‘/dev/ttyUSB0’,9600)

message=ser.read(4)

now=time.ctime()

print(message+(‘‘)+now)

os.system(‘raspistill-oimage.jpg-hf’)

mail(“[email protected]“,

“PIRmotionalarm”,

“ThisisanemailsentwithPythonfromyourRaspberryPi”,

“image.jpg”)

os.system(‘rmimage.jpg’)

ser.close()

time.sleep(10)

SomethingElse

Isaidearlierintheinstructionsthatsometimesafourdigitcode(like5555)mightbereceivedasonlythreedigits(like555)atthereceiver,andthatwecouldaccountforthatinthesoftwareifyoufindyou’rereceivinglotsof“SomethingElse”messages.

Allweneedtodoisonlyusethe1stdigitofthe4digitmessage,whichinthisexamplewillbe5.SolookatthePythoncodeexamplesthatrunonyourPC,andanylinethatlookslike

elifcode==“5555”:

Canbechangedto

elifcode[0]==“5”:

Here’safullexample.Youstillneedtomodifytheitemsinredtext.Thelinesingreenhavebeenmodified.

importserial

importtime

importsmtplib

TO=‘[email protected]

GMAIL_USER=‘[email protected]

GMAIL_PASS=‘hard-to-guess-password-goes-here’

NOW=”“

message=”“

defsend_email():

print(“SendingEmail”)

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:’+message+‘‘+NOW+‘\n’

printheader

msg=header+‘\n’+message+‘\n’+NOW+‘\n\n’

smtpserver.sendmail(GMAIL_USER,TO,msg)

smtpserver.close()

whileTrue:

ser=serial.Serial(‘/dev/ttyUSB0‘,9600)

code=ser.read(4)

NOW=time.ctime()

ifcode[0]==“4”:

message=“PIRtriggered”

elifcode[0]==“5”:

message=“DoorOpened”

elifcode[0]==“6”:

message=“DoorClosed”

else:

message=“SomethingElse”

print(message+(‘‘)+NOW)

print(code)

print(code[0])

send_email()

ser.close()

time.sleep(1)

Usefullinks:

https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo