Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi...

606

Transcript of Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi...

Page 1: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 2: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 3: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiMechatronicsProjectsHOTSHOT

Page 4: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TableofContents

RaspberryPiMechatronicsProjectsHOTSHOT

Credits

AbouttheAuthors

AbouttheReviewers

www.PacktPub.com

Supportfiles,eBooks,discountoffers,andmore

Whysubscribe?

FreeaccessforPacktaccountholders

Preface

Whatthisbookcovers

Whatyouneedforthisbook

Whothisbookisfor

Conventions

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

Missionchecklist

Task1

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Classifiedintel

Readerfeedback

Customersupport

Downloadingtheexamplecode

Downloadingthecolorimagesofthisbook

Errata

Piracy

Questions

Page 5: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

1.HelloWorld

AquickintroductiontotheRaspberryPi

FeaturesofaRaspberryPi

WherecanIbuyaRaspberryPi?

RequirementstogetstartedwiththeRaspberryPi

OperatingsystemsontheRaspberryPi

GettingstartedwithRaspbian

DownloadingRaspbian

FlashingimageontotheSDcard

Windows

Linux

Acommand-lineinterface-basedapproach

IdentifyingtheSDcardmountpoint

UnmounttheSDcard

FlashtheSDcard

GUI-basedapproach

SettinguptheRaspberryPi

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

Missionchecklist

Huntingandgathering

Engagethrusters

Objectivecomplete–minidebriefing

SettinguptheGPIO

Engagethrusters

InstallingGPIOlibraries

Objectivecomplete–minidebriefing

GPIOprogrammingusingPython

Engagethrusters

Analternativetoquick2wire–RPi.GPIO

Page 6: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefing

Electricaloutputofourprogram

Engagethrusters

Objectivecomplete–minidebriefing

IntroductiontothePiCrust–aprototypingplatformfortheRaspberryPi

Missionaccomplished

Hotshotchallenge

2.ARaspberryWebIDEExample

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

Missionchecklist

Installation,features,andusageoftheOccidentalisoperatingsystemfromAdafruit

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

SetupofaremoteloginintotheRaspberryPi

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

InstallationoftheRaspberryPiWebIDE

Engagethrusters

Objectivecomplete–minidebriefing

PythondevelopmentontheWebIDE

Prepareforliftoff

QuickintroductiontotheI2Cinterface

ConfiguringtheI2CinterfaceontheRaspberryPi

Engagethrusters

Objectivecomplete–minidebriefing

TestanddebuggingexamplesusingtheWebIDE

Prepareforliftoff

Page 7: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

3.TheArduinoRaspberryPiInterface

Missionbriefing

Whyisitawesome?

WherecanyoubuyanArduino?

YourHotshotobjectives

Missionchecklist

InstallingtheArduinoIDE

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

ProgrammingtheArduinousingtheRaspberryPi

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

RaspberryPiAlaMode

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

TheWeasleyweatherclock

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

ControllingthestepperusingtheArduino

Prepareforliftoff

Engagethrusters

Counterclockwiserotationofthesteppermotor

Objectivecomplete–minidebriefing

Page 8: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ControllingtheRGBLEDStripusingtheArduino

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

I2CCommunicationusingtheArduino(optional)

Prepareforliftoff

Engagethrusters

The7-Segmentdisplay

8x8LEDmatrix

BlinkM

Proximitysensor

Objectivecomplete–minidebriefing

SerialportcommunicationwiththeRaspberryPi

Engagethrusters

PythonprogramfortheWeasleyclock

Arduinoacknowledgementtocontrolsignal

Controlflowfortheweatherclock

Temperaturedata

ControloftheRGBLEDstrip

Controlofstepperviaserialport

Programmingtheweatherforecastposition

8x8matrixcontrol

BlinkMcontrol

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

4.ChristmasLightSequencer

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

Page 9: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InterfacethedevicestotheRaspberryPi

Prepareforliftoff

Engagethrusters

ConnectingmultipleappliancestotheRaspberryPi

Objectivecomplete–minidebriefing

SettingupthedigitallyaddressableRGBmatrix

Prepareforliftoff

WherecanIbuythem?

Engagethrusters

Howdoesitwork?

LightinguptheRGBLEDstrip

AnArduino-basedcontrol

Objectivecomplete–minidebriefing

Interfaceofanaudiodevice

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Installingthewebserver

Prepareforliftoff

Engagethrusters

Objectivecomplete–missiondebriefing

Interfacingthewebserver

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

References

5.InternetofThingsExample–AnE-mailAlertWaterFountain

Missionbriefing

Whyisitawesome?

Yourobjectives

Page 10: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Missionchecklist

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

InstallationoftheFlaskframework

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

ControllingRGBLEDsfromawebpage

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Setupofthee-mailalertsinthefountain

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

6.RaspberryPiasaPersonalAssistant

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

Settingupthee-mailfeedparser

Prepareforliftoff

Engagethrusters

Settinguptheparserforremindersandevents

Prepareforliftoff

Engagethrusters

Designinganenclosuredesignforthepersonalassistant

Prepareforliftoff

Page 11: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters

Settinguptheassemblyforthedishmonitor

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Settingupsensorsforthekeyalertsystem

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenges

References

7.RaspberryPi-basedLineFollowingRobot

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

Missionchecklist

AssemblyofthePiPlateforthelinefollowingrobot

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Sensorselection,interface,anddatainterpretation

Engagethrusters

LightDependentResistors

Infraredemitter/detector

Machine-vision-basedlinefollowingrobot

Sensorselection

Objectivecomplete–missiondebriefing

Implementationoflinefollowinglogicbasedonsensordata

Prepareforliftoff

Engagethrusters

Page 12: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefing

Testingthemotordrivercircuit

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Preparationofthelinefollowingcourse

Prepareforliftoff

Engagethrusters

Useelectricaltapeandbuildatrack

Designingthechassisforthelinefollowingrobot

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Astep-by-stepassemblyoftherobot

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

References

8.ConnectFourDesktopGameusingRaspberryPi

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

Helloworldexamplewiththepygame

Prepareforliftoff

Engagethrusters

Playingsoundsusingthepygamemodule

Buildingmenususingthepygamemodule

Objectivecomplete–minidebriefing

Page 13: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GettingstartedwiththeConnectFourgame(UIandsoundeffects)

Prepareforliftoff

EngageThrusters

Addingamenuforthegame

Addingsoundstothegame

Objectivecomplete–missiondebriefing

InterfacinggameinputsusingthePiFacemodule

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

AbriefdescriptionoftheConnectFourGameAI

Prepareforliftoff

Engagethrusters

Maingameloop

Objectivecomplete–minidebriefing

Marqueedesignandcontrol(optional)

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Setupoftheswitchesusingacardboardbox

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

References

9.TheRaspberryPi-enabledPet/WildlifeMonitor

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

Page 14: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Installingandtestingthepython-twistedframework

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

SettingupandtestingSparkCoretointeractwithappliances

Prepareforliftoff

EngageThrusters

Objectivecomplete–minidebriefing

InstallingandtestingtheGoogleCoderprojectontheRaspberryPi

Prepareforliftoff

Engagethrusters

Objectivecomplete–objectivecomplete

Abriefoverviewofabirdfeederthattriggersacamera

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Alternativesandprojectideastoconsider

Missionaccomplished

Hotshotchallenge

10.RaspberryPiPersonalHealthMonitor

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

Missionchecklist

Settingupawebservertorecordhealthparameters

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

AsimpleexercisetoolusingtheRaspberryPi

Prepareforliftoff

Engagethrusters

Page 15: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Aminiprojectidea

Objectivecomplete–minidebriefing

Settingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointment

Engagethrusters

Settingupareminderfordoctor’sappointments

Objectivecomplete–minidebriefing

Asimpletoolthatremindsapersontotakehis/herpills

Prepareforliftoff

Engagethrusters

Otherprojectideas

Objectivecomplete–minidebriefing

Missionaccomplished

Hotshotchallenge

11.HomeAutomationusingRaspberryPi

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

Asimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheevening

Prepareforliftoff

Softwareprerequisites

Engagethrusters

Objectivecomplete–minidebriefing

Alternativesolutionsandsomeprojectideastoconsider

Acustomarywebserverexample

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

Turningonalawnsprinkleronlywhenthereisnorainforecast!

Prepareforliftoff

Engagethrusters

Page 16: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefing

GainingremoteaccesstoyourRaspberryPitocontrolappliances

Someprojectideastoconsider

Missionaccomplished

12.UsingaRaspberryPiforScienceandEducation

Missionbriefing

Whyisitawesome?

YourHotshotobjectives

ImprovingyourvocabularyusingtheRaspberryPi

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

RaspberryPiandKhanAcademy

Someideastoconsider

BuildingasciencefairexhibitusingtheRaspberryPi

Prepareforliftoff

Engagethrusters

Objectivecomplete–minidebriefing

SomesimpleeducationalexperimentsusingtheRaspberryPi

Hotshotchallenge

13.TipsandTricks

Missionbriefing

Whyisitawesome?

Yourobjectives

Missionchecklist

SettingupRaspberryPiasadevelopmentplatform

#1–SimpletrickforPythondevelopmentviaremotelogin

#2WebdevelopmentusingGoogleCoder

#3AdafruitOccidentalis

#4JavaDevelopmentusingtheRaspberryPi

#5TheThingboxproject

Page 17: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RemotelyloggingintheRaspberryPifromanywhereontheInternet

ProblemsthatmightbeencounteredwhileusingRaspberryPi

SDcardcorruption

Powerissues

DevicespoweredbyUSB

Cooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatform

TheRaspberryPimodelBversusB+,modelAversusA+

Projectideasthatcanbeimplementedoveraweekend

UsefulresourcesfortheRaspberryPi

RaspberryPiFoundation’sforums:

RaspberryPiStackExchange:

Element14’sRaspberryPicommunity:

Missionaccomplished

Index

Page 18: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 19: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiMechatronicsProjectsHOTSHOT

Page 20: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 21: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiMechatronicsProjectsHOTSHOTCopyright©2015PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:February2015

Productionreference:1190215

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

BirminghamB32PB,UK.

ISBN978-1-84969-622-7

www.packtpub.com

Page 22: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 23: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

CreditsAuthors

SaiYamanoor

SrihariYamanoor

Reviewers

GuyScheffer

SreedharVaddi

CheukYu

CommissioningEditor

UshaIyer

AcquisitionEditors

UshaIyer

RebeccaPedley

SamWood

ContentDevelopmentEditor

SusmitaSabot

TechnicalEditor

ParagTopre

CopyEditor

JanbalDharmaraj

ProjectCoordinator

MiltonD’souza

Proofreaders

SimranBhogal

MariaGould

AmeeshaGreen

PaulHindle

Indexer

HemanginiBari

Graphics

SheetalAute

Page 24: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DishaHaria

ProductionCoordinators

AparnaBhagat

ManuJoseph

CoverWork

AparnaBhagat

Page 25: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 26: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AbouttheAuthorsSaiYamanoorisamechatronicsengineerworkingforaprivatestart-upschoolintheSanFranciscoBayAreawherehebuildsdevicesthathelpstudentsachievetheirfullpotential.HecompletedhisdegreeinmechanicalengineeringatCarnegieMellonUniversity,Pittsburgh,PA,andhisundergraduateworkinmechatronicsatSriKrishnaCollegeofEngineeringandTechnology,Coimbatore,India.Hisinterests,deeplyrootedinDIYandopensoftwareandhardwarecultures,includedevelopinggadgetsandappsthatimprovequalityoflife,InternetofThings,crowdfunding,education,andnewtechnologies.Inhissparetime,heplayswithvariousdevicesandarchitecturessuchasRaspberryPi,Arduino,Galileo,Androiddevices,andothers.Saishareshisadventureswithmechatronicsattheaptlynamed“MechatronicsCraze”blogathttp://mechatronicscraze.wordpress.com/.

IwanttothankmyparentsforencouragingmeinallmyendeavorsandformakingmewhatIamtoday.Iamgratefultomybrotherwhohashelpedshapemycareeralltheseyears.IlookforwardtoworkingwithSriharionsimilarprojectsinthefuture.IsincerelythankMr.S.BalajiRaghavendrawhohasbeenagreatsourceofinspirationtomewhilepursuingmyundergraduatedegree.IamalsothankfultoSusmitaSabotandtheentiresupportteamatPacktPublishingwhowerepatientandunderstoodthecircumstancesduringdifficulttimes.

SrihariYamanoorisanaturephotographerandmechanicalengineerwithexperienceworkinginmedicaldevicedesignandCAD/CAM.Hecompletedhismaster’sinscienceaswellasadegreeinengineeringfromStanfordUniversity.Hisworkandinterestsinmedicaldevicesincludewomen’shealth,cancer,orthopedics,andcardiovasculardiseases,aswellasnewerareassuchasdigitalhealthandelectronichealthrecords.HehasseveralthousandsofhoursofCADexperiencebehindhimandisalsocertifiedamongotherthingsasaSolidWorksexpert,simulationprofessional,andaSolidWorksinstructor.Hisinterestsrangefromengineeringandeducationtosocialentrepreneurship,animalwelfare,andcrowdfunding.

Iwouldliketothankmyparents,NarasimhanandYasodaVenakatakrishnan,fortheirsteadfastsupportinmyeducationandeffortsthroughouttheyears,culminatinginprojectssuchasthisbook.Overthecourseoftheyears,manyfriendshavehelpedbothSaiandmegrowinmanyways.Forthisreason,Iwouldliketosayabigwordofthanks,innoparticularorder,toRikaCatherineHirachi,AnnaLiuJao,ShirupaGupta,PatrickNguyen,VishnuPrasadRamachandran,AndrewEib,ChristopherMa,andKarthikPalaniappan.IamsureIammissingsomenames,andforthis,Iapologizeinadvance.Iwouldalsoliketothankmygraciousmentors,Dr.KevinWaldron,Dr.JamesStubbs,RussellSampson,MukundPatel,andasIfondlycallhim,Cyril“Master”,allofwhomhavegivenmeadviceandshownmetheway.Iwouldliketoespeciallythankmyfirstcat,Squeaky,andthefelinesBob,Saxon,andFishbone,thathavefollowedme,forinspiringmeandpushingmetostayontrackandkeepaneyeonthebigpicture.

Page 27: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 28: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AbouttheReviewersSreedharVaddihas4yearsofexperienceinbigdata,4yearsincloudcomputing,and15yearsinJava.Hisexperienceincludesworkinthefieldsofbigdatasecurity,biomedical/healthcare,mobilesecurity,financialservices(wholesale,mortgage,investment,andbrokerage),theWeb(marketplace,crowdsourcing,andadvertising),newsandentertainment,propertyandcasualtyinsurance,softwareproductdevelopment,andscientificresearch.

Hehashands-onexperienceasanarchitectworkingonenterprisemobileapplications,Hadoop,SaaS,PaaS,IaaS,thecloud,richenterpriseapplications,n-tierenterprisesystems,EnterpriseApplicationIntegration(EAI)inweb-enablinglegacysystems,IBMMainframeandSAP,andSOAwebserviceswithJava2andJEE.

HehasalsoworkedinallphasesofSDLC,namelydesigning,developing,performancetesting,andimplementingWeb-2.0,Web-UI,server-side,middleware,andmobileapplications.HehasalsoworkedwithBig5ConsultingandFortune100companies.Hehasledteamsofsizesvaryingfrom2to80acrosstheglobeindifferenttimezones,cultures,anddialects.

HeisanadministratorofJEEcontainers(Geronimo,WebSphere,Weblogic,JBoss,andTomcat)andCDH.Heisalsoatechnicalconsultantatastealthmodestart-upinanimalcareintheclinicaltrialsindustry.Heisadiligentworkerandquicklearnerwithexcellentproblemsolving,presentation,andmentoringskills.

CheukYuispursuingabachelor’sdegreeinelectricalengineeringattheUniversityofCalifornia,LosAngeles(UCLA),withanemphasisoncircuitandsignalprocessing.HeworkedonmultipleembeddedsystemsprojectsusingvariousmicrocontrollerssuchasArduino,Teensy,andRaspberryPi.AsastudentresearcherfortheELFINCubeSatMissionatUCLA,healsohashands-onexperienceworkingonprintedcircuitboards,includingdesigningandtestingavionicsandgroundsupportequipmentboards.Besidesworkandstudy,heisalsoanamateurradiooperatorandastronomer.

Page 29: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 30: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

www.PacktPub.com

Page 31: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

https://www2.packtpub.com/books/subscription/packtlib

DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.

Page 32: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

Page 33: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

Page 34: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 35: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrefaceTheRaspberryPiisaquaintexampleoftechnologicalinnovationsthatcomebyonceeverytwoorthreedecadesandsetoffarevolutionthattoucheseveryaspectofhumanlifefromscientificexplorationtoentertainmenttoeducation.Whatisexcitingthistimearoundisthatthereareseveralsuchinnovationshappeningsimultaneously.Theymightsoundlike,andareinaway,buzzwords,buttheyareinfactreal,andarechangingourlivesinsomanyways,sofewofwhichweareconsciouslyawareof.Wearespeakingofinnovationsinentrepreneurship,suchascrowdsourcingortheemergenceofDIYwithanalmostcult-likefollowingtoinnovationsintechnologythatarecurrent,suchas3DprintingandInternetofEverything,andinnovationsthatareimpendingsuchas4Dprinting,smartmanufacturing,andmuchmore.

TheRaspberryPihasalreadyfoundseveralusesasevidencedbyhundredsofwebsites,projectexamples,andcrowdsourcingcampaigns.PeoplehaveusedthePitobuildrobots,teachprogramming,restoreoldgamingconsoles,streamvideos,collectdata,anddomanyotherthings.ThePiitselfhasgonethroughdesigniterationsandcontinuestospurcompetingsystems.PeoplehavetakenadvantageofthisandhavehookedupthePitomanydifferentecosystems,expandingitsubiquityandutility.

ThepurposeofthisbookistohelpthosewhoareexcitedabouttheRaspberryPiandhaveprojectideasinmind,orwouldsimplyliketogettheirhandsdirtyandpracticeimplementingprojectssothattheycanthenusethatknowledgeforotherendeavors.Wetriedtotakeapracticalapproach,introducingthePiinthefirstcoupleofprojectthatyoucanskipifyouarefamiliarwiththeRaspberryPiandhaveuseditbefore.Wethendiscussprojectsofincreasingcomplexity.WehavealsoattemptedtodiversifytheprojectstodemonstratevarioususesforthePithroughoutthebook.

Page 36: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

WhatthisbookcoversProject1,HelloWorld,willintroducetheRaspberryPiandremindyouofthingsthatyoushouldknowasyouproceedthroughthebook.WewillsetuptheRaspberryPiandblinkanLED.

Project2,ARaspberryWebIDEExample,willtakeyouthroughPythondevelopmentusingabrowser.WewillusetheAdafruitWebIDEandleadyouthroughthedevelopmentprocessusingAdafruitproductsaspropsfortheexamples.

Project3,TheArduinoRaspberryPiInterface,isinspiredbytheHarryPotterseries,andinanefforttoshowourloveforthisseries,wehavecreatedaclocksimilartotheinnovativeandendearingWeasleyclockusingtheRaspberryPiandanArduino.Thisproject,ofcourse,allowstheclocktoreportbackweatherconditions.

Project4,ChristmasLightSequencer,discussesholidaysasthebesttimeforDIYprojects,andifyouareeverstarvedofideas,holidaysarethebesttimetocookupideas.WepickedaChristmas-themedprojecttodemonstratecontrollingappliancesconnectedtoalocalnetworkusingRaspberryPi.

Project5,InternetofThingsExample–AnE-mailAlertWaterFountain,followsthethemeofthepreviousproject.Wewillshowyouhowtocontroladecorativefountainsuchthatanytimeyoureceiveanewe-mail,yourfountain’slightwillflashanalert(thiscanalsobeswitchedtoreceiveTwitteralerts).

Project6,RaspberryPiasaPersonalAssistant,willshowyouhowyoucanusethePiasyourpersonalassistant,remindingyouofchores,settingalarms,anddoingeverythingatyourcommand.

Project7,RaspberryPi-basedLineFollowingRobot,willtakeyouthroughthesimplestofallrobots,thelinefollowingbot,withRaspberryPiatthehelm.Thisprojectwillshowyouthewayforthisandothercomplexroboticsprojectsyouwishtoimplement.

Project8,ConnectFourDesktopGameusingRaspberryPi,followstheinstant-classicthemefortheRaspberryPi,whichincludesgames.Allmannersofgamingapplications,includingtherevivalofarchaicgamestonewonesandmods,arebeingcreatedusingtheRaspberryPi.Wewillimplementthegameusingapushbuttoninterface.

Project9,TheRaspberryPi-enabledPet/WildlifeMonitor,willwalkyouthroughafunexampleofabirdfeedermonitorthatallowsyoutotriggeraphotocaptureeachtimethebirdapproachesthefeeder.Youcanthinkofextendingthistootherpets,orsay,theferalcatsinyourcolony.

Project10,RaspberryPiPersonalHealthMonitor,isaprojectwherewesetupasimplewebservertorecordourpersonalhealthparameters,buildasimpletooltoremindourselvestoremainphysicallyactive,andremindourselvestorefillaprescriptionviae-mailalerts.

Project11,HomeAutomationusingRaspberryPi,isaprojectwherewewillshowyouhowtocontrolappliancesusingatwistednetworkwheretheapplianceisconnectedtoa

Page 37: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

platformsuchasanArduino.TheRaspberryPiactsasaserverthatcontrolsallsuchnodesinthenetwork.

Project12,UsingaRaspberryPiforScienceandEducation,isaprojectpackedwithexamples,includingavocabularylearningtool,awebhostforKhanAcademy,andawindmillgeneratorscienceexhibit.Havefunlearningandteaching!

Project13,TipsandTricks,isaprojectpackedwithtipsandtricksthatwillhelpyouusetheRaspberryPi!

Youcanalsogetthevideos,tipsandtricks,andmanymorethingsrelatedtotheprojectsathttp://diywithpi.com/.

Page 38: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 39: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

WhatyouneedforthisbookTogetstarted,youwillneedtheRaspberryPi,amonitor,akeyboard,apowersource,andpreferably,alaptoporpersonalcomputerrunningonanyOS—Windows,Linux,orApple.Otherhardwareandsoftwarerecommendationsaremadeintheindividualprojects,andyouarewelcometoreplacethemwithwhatyouseefit.AworkingknowledgeofPythonispreferred,butnotrequired.

Page 40: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 41: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

WhothisbookisforThisbookisprimarilyaimedathobbyistsanddo-it-yourselfenthusiastsaswellasthoselookingtoimplementspecificprojectsusinglowcosthardwareandsoftwarecenteredaroundtheRaspberryPi.Basicexposuretoelectronics,programming,andInternetusageisassumed.Wehavetriedtotakeapragmaticapproach,implementingtheprojectsandshowinghowyoucandothisonyourown.

Page 42: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 43: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ConventionsInthisbook,youwillfindseveralheadingsappearingfrequently.Togiveclearinstructionsofhowtocompleteaprocedureortask,weuse:

Page 44: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 45: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingThissectionexplainswhatyouwillbuild,withascreenshotofthecompletedproject.

Page 46: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Thissectionexplainswhytheprojectiscool,unique,exciting,andinteresting.Itdescribeswhatadvantagetheprojectwillgiveyou.

Page 47: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesThissectionexplainstheeightmajortasksrequiredtocompleteyourproject.

Task1Task2Task3Task4Task5Task6Task7Task8

Page 48: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistThissectionexplainsanypre-requisitesfortheproject,suchasresourcesorlibrariesthatneedtobedownloaded,andsoon.

Page 49: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 50: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Task1Thissectionexplainsthetaskthatyouwillperform.

Page 51: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThissectionexplainsanypreliminaryworkthatyoumayneedtodobeforebeginningworkonthetask.

Page 52: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersThissectionliststhestepsrequiredinordertocompletethetask.

Page 53: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingThissectionexplainshowthestepsperformedintheprevioussectionallowsustocompletethetask.Thissectionismandatory.

Page 54: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ClassifiedintelThissectionprovidessomeextrainformationrelevanttothetask.

Youwillalsofindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestyles,andanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Wewillgothroughtheimportantfeaturesofthepygamemodule,whichisnecessarytobuildourarcadegame,includingplayingsoundsandcontrollingthemenu.”

Ablockofcodeissetasfollows:

GPIO.output(25,True)

while1:

GPIO.output(25,False)

sleep(1)

GPIO.output(25,True)

sleep(1)

Anycommand-lineinputoroutputiswrittenasfollows:

#cp/usr/src/asterisk-addons/configs/cdr_mysql.conf.sample

/etc/asterisk/cdr_mysql.conf

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,inmenusordialogboxesforexample,appearinthetextlikethis:“clickingtheNextbuttonmovesyoutothenextscreen”.

NoteWarningsorimportantnotesappearinaboxlikethis.

TipTipsandtricksappearlikethis.

Page 55: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 56: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.

Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitleviathesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.

Page 57: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 58: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 59: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Page 60: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DownloadingthecolorimagesofthisbookWealsoprovideyouaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttp://www.packtpub.com/sites/default/files/downloads/6227OT_ColoredImages.pdf.

Page 61: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedonourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.Anyexistingerratacanbeviewedbyselectingyourtitlefromhttp://www.packtpub.com/support.

Page 62: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.

Page 63: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.

Page 64: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 65: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter1.HelloWorldItisaHotshotcustomtobeginlearninganythingnewwithaHelloWorldexample.Sincewewillbedoingreallycoolthingsinthisbook,wewillsay“HelloWorld”inauniquefashion.Inthisproject,wewillusetheRaspberryPitocauseanLEDlighttoblink.ThisprojectisdirectedtowardsthosewhoarerelativelynewtotheRaspberryPienvironmentasawarm-upexercise.FeelfreetoskipaheadifyouhavealreadydonethiswithyourPi,thoughwesuggestyoulookthroughandmakesureyouhaven’tmissedanything.

Page 66: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AquickintroductiontotheRaspberryPiIfwesearchforthetermRaspberryPiovertheweboropentheRaspberryPiFoundation’swebpage,wewillfindthattheRaspberryPiisacomputerthatisthesizeofacreditcard.

PartsofaRaspberryPi

Page 67: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

FeaturesofaRaspberryPiTheRaspberryPiFoundation(http://www.raspberrypi.org/)initiallyreleasedtheRaspberryPimodelB.ThiswasfollowedbytheRaspberryPimodelA.In2014,theRaspberryPifoundationreleasedvariantsB+andA+.TheRaspberryPimodelsAandA+(costing25USDand20USDrespectively)donotcomewithanEthernetport,aUSBportand256MBRAM.ThemodelA+replacedmodelAwhilethemodelB+replacedmodelB.ThemodelB(price:35USD)camewithanEthernetport,2USBports,and512MBRAM;modelB+,whichsupersedesmodelB,comeswith40pinGPIOheaderasopposedto26intheearliermodels,andhas4USBportsandamicroSDcardslotinsteadoftheSDslot.PertheRaspberryPiFoundationwebsite,modelB+(aswellasmodelA+)consumeslowerpower,hasbetteraudioandabetterformfactor,whichwecertainlyconcurwith.ThemodelA+alsocomeswitha40pinGPIOheaderandamicroSDcardslot.ThemodelsA+andB+haveninemoreGPIOpinsthantheirpredecessors.

NoteTheRaspberryPi2wasreleasedafterwefinishedwritingthebook.Pleaserefertothebook’ssitetofindoutmoreaboutgettingstartedwithmodel2.

TheobjectiveofthisbookistobuildcoolprojectsusingtheRaspberryPi.WewilldiscussthecomponentsofRaspberryPifromthisperspective.IfyouareinterestedinfindingoutmoreabouttheRaspberryPi,theRaspberryPiFoundation’swebpagehaspublishedthetechnicalspecificationsofallthecomponents.

First,wewilldiscussthecomponentsavailableontheRaspberryPiandtheuseofthesecomponentsinourprojects.ThecomponentsoftheRaspberryPiinclude:

2USBports(1USBportavailableinmodelA)Ethernetport(availableonlyinmodelsBandB+)RCAoutputHDMIoutputAudiooutputLowlevelperipherals,whichinclude:

GPIO(GeneralPurposeInputOutput)UART/SerialPort(UniversalAsynchronousReceiverTransmitter)I2C(twowireinterface)SPI(SerialPeripheralInterface)

Page 68: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 69: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

WherecanIbuyaRaspberryPi?Element14andRSComponentsarethemostcommondistributorsoftheRaspberryPiintheUnitedStates.TheRaspberryPimodelAwasroughlypricedat25USD,whileitssuccessormodelA+waspricedat20USD.ThemodelBwaspricedat35USDandthemodelB+ispricedat40USD.TherearealsoaneverincreasingnumberoflocaldistributorssuchasAdafruitandFry’sElectronicsintheUSthatselltheRaspberryPiforamargin.PleasechecktheRaspberryPiFoundationwebsiteandothersourcesformorevendors.

Page 70: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RequirementstogetstartedwiththeRaspberryPiInthissection,wewilldiscusstheitemsrequiredtogetstartedwiththeRaspberryPi.Wewillneedallthesamethingsthatarerequiredtouseacomputer/laptop.Theyare:

DisplayKeyboardMouseWi-FiAdapter/Ethernetcable

NoteItispossibletousetheRaspberryPiviaremoteloginusingasecureshell.ThismightseemdifficulttothosewhoarenewtotheLinuxenvironment.ThesetupoftheRaspberryPiforremoteloginisexplainedinProject13,TipsandTricks.

TheRaspberryPieLinuxwiki(http://elinux.org/RPi_Hub)haslistedperipheralsthathavebeentestedandconfirmedtohaveworkedontheRaspberryPi.Youhavethefreedomtochooseperipheralsaccordingtoyourchoice.

Display:TheRaspberryPiisprovidedwithanHDMIoutputandanRCAoutput.ItispossibletoconnectamonitorthathasanHDMIinput.ItisalsopossibletoconnectmonitorsthathaveaDVIinputwithanHDMItotheDVIcable.Powersupply:SincetheRaspberryPiconsumes700mAforitsoperation,itisrecommendedthatthereaderusespoweredUSBhubstousedevicessuchasWi-FiadaptersasopposedtopluggingindevicessuchastheWi-FiadaptersdirectlytotheUSBportoftheRaspberryPitoavoidthedeviceresettingitself.

OperatingsystemsontheRaspberryPiTheRaspberryPifoundationrecommendsthefollowingoperatingsystemsontheRaspberryPi.Theyare:

RaspbianArchLinuxARMRISCOS

Youarewelcometochooseanyoperatingsystemofyourchoice.Forbeginners,westronglyrecommendtheRaspbianOSforprojects.TheRaspbianisequippedwithtoolstogetstartedeasily.TheRaspberryPi’sfirmwareisimplementedsuchthattheoperatingsystemisloadedfromanSDcard.

Page 71: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GettingstartedwithRaspbianInthissection,wewilldownloadanimagefromtheRaspberryPiFoundation’swebpagetoacomputer,flashanSDcardwiththeimage,andsetuptheoperatingsystemontheRaspberryPi.Wewillalsotrytowriteandexecuteourfirstexample.

DownloadingRaspbianThelatestRaspbianimageishostedontheRaspberryPiFoundation’swebpage(http://www.raspberrypi.org/downloads/).ThelatestimageatthetimeofwritingthisbookwasRaspbianwheezy.Weneedtodownloadtheimageandextractittothefolderofourchoice.

RaspbianwheezyontheRaspberryPiFoundation’swebsite

FlashingimageontotheSDcardWewilldiscussflashingtheSDcardwiththeRaspbianimageonbothWindowsandLinuxmachines.

Windows

Extractthefilestoalocationofyourchoice.TheWin32DiskImagertoolisrequiredtopreparetheSDcardwiththeRaspbianimage.

TipAstandardRaspbianimageisabout1.8GBbig.ItisstronglyrecommendedthatyouuseanSDcardthatisatleastof4GBbig.

Page 72: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TheWin32DiskImagertool

WecanflashtheSDcardinthreesimplesteps(asshownintheprecedingscreenshot):

1. SelecttheSDcardthatneedstobeflashed.2. SelecttheRaspbianimagelocation.3. ClickonWrite.4. ClickonYestoconfirm.

ConfirmoverwritingtheSDcard

5. Itcantakeawhilebeforethewritecycleiscompleted.

Linux

Page 73: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TherearetwoidenticalmethodstoflashanSDcardonaLinuxmachine.Thetwoapproachesinclude:

AGUI-basedapproachAcommand-lineinterface-basedapproach

Acommand-lineinterface-basedapproach

TheSDcardcanbeflashedinthreesimplestepsusingacommand-lineinterface.Thesestepsareasfollows:

1. IdentifytheSDcardmountpoint.2. UnmounttheSDcard.3. FlashtheSDcard.

IdentifyingtheSDcardmountpoint

AssoonasweinserttheSDcardintoaUSBcardreaderoranSDcardslotfoundonalaptop,weneedtoopenaterminalonourLinuxmachine.Weneedtoidentifyourdevice’smountpointonthemachineusingthefollowingcommand:

df–h

Thedevicesenumeratedonthemachinewillbelistedasshowninthefollowingscreenshot:

Storagedevicesidentifiedbytheoperatingsystem

Page 74: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

UnmounttheSDcard

Inthepreviousexample,the/dev/sdb5pathisthestoragedeviceofinterest.Theremaybemorethanonestoragedevicethatmightbeconnectedtoamachine.Weneedtomakesurethatwehaveidentifiedtherightdevice.Oncewehaveidentifiedthedevice,ithastobeunmountedusingthefollowingcommand:

umount/dev/sdb

FlashtheSDcard

Now,wewillflashourSDcardusingthefollowingcommand:

ddbs=4Mif=~/2012-09-18-wheezy-raspbian.imgof=/dev/sdb

Theif=argumentpointstothelocationoftheimageandof=referstotheSDcardmountpoint.ThewriteoperationtakesawhiletocompleteanditisreadyforuseontheRaspberryPiuponcompletion.GUI-basedapproach

OnaDebianLinux-basedoperatingsystem,thereisapackagecalledusb-imagewriter.TheImageWriterpackageperformsthesameoperationsrequiredtoflashanSDcard.

AUSBImageWriteronUbuntu

Page 75: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettinguptheRaspberryPiNowthattheimageisflashed,let’sgetstartedwithsettinguptheRaspberryPiforthefirsttime.WewillhavetoinserttheSDcardslotfoundontheothersideoftheRaspberryPi.

AflashedSDcardintheslot

Whenthekeyboardandthemouseareconnected,wecangetstartedbypoweringuptheRaspberryPi!

OncetheRaspberryPiispoweredup,theoperatingsystembootsuptoRaspi-config.Theraspi-configisthetoolusedtosetupdesktopoptions,keyboardsettings,storagesettings,andsoon.TheRaspi-configscreenisshowninthefollowingscreenshot:

TheRaspi-configscreen

Page 76: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Inthissection,wewilldiscusseachfeatureoftheraspi-configtool:

info:Asthenamesuggests,thissectiongivesthegeneralinformationaboutthetool.expand_rootfs:WhiletheSDcardisflashedwiththeoperatingsystemimage,theSDcardispartitionedjustaboutthesizeoftheimage.Thiscommandaidstoexpandthepartitionsothattheremainingspacecanbeusedforfilestorage.overscan:ThisisanoptionusedwhentheRaspberryPiisconnectedtothetelevision.configure_keyboard:Thisoptionisusedtoconfigurethechange_typeoptionofthekeyboard.change_pass:Thedefaultpasswordisraspberry,andifnecessary,thisoptionletsyouswitchtoastrongerpassword.change_locale:Theoptionletsyouchangethelanguagepreferences.change_timezone:Wecansetourcurrenttimezoneusingthisoption.memory_split:ThisoptionletsussplitthememorybetweentheARMprocessor’sCPUandthegraphicsprocessor.overclock:Thedefaultclockspeedis700MHz.Thisoptionletsyousettheclockspeedto1GHz.ThismightvaryforRaspberryPi2.ssh:Thisoptionenablesthesecureshellserver.ThisisrequiredtoremotelylogintheRaspberryPiandcontroldevicesremotely.ItisenabledbydefaultonRaspbian.boot_behaviour:Thisoptionenablesyoutobootdirectlyintothedesktop.

TipItisimportantthatyouenablethisoptiononasthedefaultoptionbootsintoanormaltext-basedconsole.

update:IftheRaspberryPiisconnectedtotheInternetusinganEthernetcable,theraspi-configtooldownloadsanypackagethatmightbeavailable.

OncewecompletethesetupprocessbyselectingFinish,theRaspberryPirebootsandexpandsthefilesystemifnecessary.

Page 77: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 78: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewillsetuptheGPIO(GeneralPurposeInputOutput)peripheralontheRaspberryPiandwriteourfirstprogramtocauseanLEDtoblink.Attheend,wewillrepeatthesamestepswithaRaspberryPiadd-onboardcalledPiCrust.Thiswillallowyoutogetyourfeetwetandensureyouhavealltherighttoolsgoingforward,andshouldyouneedto,troubleshootanyproblemsyoumightidentify.

Page 79: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Thinkofsaying“HelloWorld”asbothanodtoprogrammingtraditionandadryruntoensureyouarewellequipped!

Page 80: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesTheobjectivesforthismissionarequitesimple,andyettakeusallseveralmilestonesfurther!HerearetheobjectivesoftheHelloWorldmission:

CollectallthenecessarytoolsSetuptheGPIOperipheralIntroduceourselvestotheRaspberryPienvironmentTurnalightemittingdiode(LED)onandoffwitha1seconddelay

Page 81: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistGoovertheprevioussections,andmakesureyouhaveallthetools.DownloadtheGPIOlibraries,andensureyoucanlogintotheRaspberryPiremotely,andyouareallset!

NoteTherearetwodifferentwaystouseaRaspberryPi.Theyare:

ConnectingamonitortotheHDMIportortheRCAjackandakeyboardtotheUSBportoftheRaspberryPi.RemotelyloggingintotheRaspberryPifromthereader’sworkstation.

Ifyouareabeginner,itisbesttousethefirstmethodwhilethesecondmethodcanbeusedifyouarefamiliarwiththeLinuxoperatingsystemandremotelogincapabilities.

OncewecompletethesetupprocessbyselectingFinish,theRaspberryPirebootsandexpandsthefilesystemifnecessary.

Page 82: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 83: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HuntingandgatheringAsstatedbefore,youwillneedtomakesureyouhaveallthetools.So,goahead,huntandgatheraway.Grabatleastoneofeachofthefollowingandmorethanoneofeach,ifyou,likeus,arepronetoaccidents:

AlaptoptodownloadtheRaspberryPiimageandsetupeverythingRaspberryPi—ModelB/B+(preferred),akeyboard,andamousefortheRaspberryPi(optional)SDcardwith4GBmemory(SDcardpreparationwasexplainedearlierinthisproject)USBPowerAdapter(Rated1.0A)andMicroUSBpowercableEthernetcableWi-Fiadapter—(optional)refertotheeLinuxwikiforRaspberryPiforverifiedperipheralsBreadboardJumperwiresDiscreteResistorValuesAworkbench(oracleanworkingsurface—hopefullyyouhaveone)Goodthoughtsandacan-doattitudeLotsofcoffee,tea,orasafebeverageofyourchoice

Page 84: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersYouwillneedallofthetoolslistedintheprevioussectiontogetthroughthisproject.Takeyourtimeandmakesureyouhaveeverythinghandy!

Page 85: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingDoyouhaveallthetools?Readytogo?Thenontothenexttask!

Page 86: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 87: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettinguptheGPIOWeneedtoenabletheGPIOperipheralsinourRaspbianinstallationtogetstarted.Inordertodownloadtherequiredtoolsandsetthingsinmotion,theRaspberryPineedstobeconnectedtotheInternet.

TheGPIOpinisapinthatisavailablefromtheRaspberryPi’sprocessorthatenablesinterfacinginputandoutputdevicestotheRaspberryPi.Inthissection,wewilltalkaboutsettinguptheGPIOforinterfacinganoutputdevice.Thereisa26-pininterface(40inModelB+)availableontheRaspberryPiandabout17ofthose26pinsareGPIOpins(26oftheminModelB+)whiletheothersaremiscellaneouspinssuchaspower.Thepinsaredrivenbya3.3VrailandeachGPIOpinisratedforabout17mAandthetotalcurrentdrawnotexceeding50mA.

Page 88: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersWealsoneedtoknowtheGPIOperipheralsavailabletoconductourexperiment.ThefollowingfigureshowstheGPIOmapsoftheRaspberryPiRev1andRev2:

GPIOmapforModelsA,B,andB+.(ImagepublishedwithpermissionfromRaspi.tv)

TheletterP1showninthefollowingimagecorrespondstoP1-1oftheGPIOmap.P1-1correspondstothefirstpinontheleftinthefrontrow,whileP1-2correspondstothefirstpinontheleftinthebackrow.

TheRaspberryPiGPIOperipheral

Page 89: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Inthisbook,wewillbemostlyusingPythonprogramminglanguage.Pythonisaverysimpleandeasylanguagetolearn.Wemaywanderofftootherprogramminglanguagesfromtimetotime,butwewillmostlysticktoPython.Withthisinmind,let’sgetstarted.

InstallingGPIOlibrariesTherearealotoflibrariesavailabletoaccesstheGPIOperipheral.Theeasiesttoinstallanduseisthequick2wirepythonAPI.TheAPIisusedtocontroltheGPIOperipheralsandI2CdevicesconnectedtotheRaspberryPi.

NoteTherearedifferentlibrariessuchastheRPi.GPIO,Pi4J,andsoon.Weareusingthequick2wireAPIinthisexampleasabeginnermightfinditeasytouse.Youarewelcometouseotherlibrariesofyourchoice.Thequick2wire-gpio-admintoolenablescontrollingtheGPIOpinswithoutrootaccess.

Onedisadvantageofusingthequick2wiremoduleisthatitprovidesaccessonlytoGPIOpins0through7.

Theterminalcanbelocatedintheleftcornerofthedesktopandhasbeenhighlightedinthefollowingscreenshot:

ACommand-lineterminalontheRaspbiandesktop

1. Thequick2wirelibraryinstallationisbasedonapostonthequick2wirewebsite(http://quick2wire.com/articles/how-to-add-quick2wire-as-a-raspbian-software-

Page 90: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

source/).Inordertoinstallthequick2wire-pythonlibrary,therepositoryneedstobeaddedto/etc/apt/sources.list.

Inthecommandline,therepositoryisaddedbyusingthenanotexteditor:

sudonano/etc/apt/sources.list

Thefollowinglinesneedtobeaddedtothefile:

#Quick2WireSoftware

debhttp://dist.quick2wire.com/raspbianwheezymain

deb-srchttp://dist.quick2wire.com/raspbianwheezymain

ThefilecanbesavedbytypingCTRL+X.ThefilecanalsobesavedbypressingYkeywhileexitingtheeditor.Alternatively,thelinescanbeaddedusingagraphicaltexteditorsuchas,leafpadandsavingit:

sudoleafpad/etc/apt/sources.list

2. Inordertoensurethatthepackagesaredownloadedfromthequick2wirerepository,weneedtoauthenticatethepackagesusingakeyavailablefromquick2wire:

wgethttps://raw.githubusercontent.com/quick2wire/quick2wire-software-

users/master/[email protected]

sudoapt-keyadd

[email protected]

3. Thecacheisupdatedandthelatestsoftwarepackagescanbedownloadedasfollows:

sudoapt-getupdate

sudoapt-getupgrade

4. Thequick2wiretoolisinstalledasfollows:

sudoapt-getinstallquick2wire-gpio-admin

sudoapt-getinstallquick2wire-python3-api

Page 91: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingNow,wasn’tthateasy?Let’sgetmorefamiliarwiththeGPIOinput/outputoperations.

Page 92: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 93: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GPIOprogrammingusingPythonInthissection,wewillensurethatthelibraryiscorrectlyinstalledandaddtheusertothegroup.ThiswillenabletheusertousetheGPIOpinswithouthavingrootprivileges.ThiswillbefollowedbythesectionongettingstartedwithGPIOcontrolprogramminginPython.

Page 94: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersInordertogetstartedwithprogrammingintheRaspberryPi,wewilllaunchPythonIDLE3fromthedesktop.

LaunchingIDLE3fromthedesktop

1. Now,wehavetogetstartedwithprogrammingtheLEDblinkingexampleinIDLE3.2. ThisLEDblinkingsamplecodeisasfollows:

fromtimeimportsleep

fromquick2wire.gpioimportpins,Out

withpins.pin(7,direction=Out)asout_pin:

whileTrue:

out_pin.value=1

sleep(1)

out_pin.value=0

sleep(1)

out_pin.unexport()

3. Wewillimportthesleepclassfromthetimemoduleinthefirstline.Thisisrequiredtointroducea1-seconddelaybetweenturningtheLEDonandoffeveryothersecond:

fromtimeimportsleep

4. Wealsoneedthepinclassfromthequick2wireGPIOlibrary:

Page 95: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

fromquick2wire.gpioimportPin

5. Weneedtosettheoutputpinthatwewillbeusingintheexample:

LED_output=Pin(8,Pin.Out)

6. Wecansetthepintothelogicalhigh(3.3V)asfollows:

LED_output=1

7. Wewillsetthepintothelogicallow(0V)asfollows:

LED_output=0

8. Wewillexecutethesamethingusinganinfinitewhileloop:

whileTrue:

LED_output=1

sleep(1)

LED_output=0

sleep(1)

9. ThiswillmaketheLEDblinkwitha1-seconddelay.Weshouldalsonotetheindentontheblinksequence.Theblinksequencehasadifferentindentcomparedtothewhileloop.Hence,thecodethatisatadifferentindentisexecutedinfinitely.

10. Whentheprogramisinterrupted(bypressingCTRL+Conthekeyboard),weneedtounexportthepinsatexit:

out_pin.unexport()

Analternativetoquick2wire–RPi.GPIO1. AnotheralternativeistouseRPi.GPIO(https://pypi.python.org/pypi/RPi.GPIO).It

comesasastandardpackagealongwiththeRaspbianWheezyOS.Let’sperformaquickreviewofthecode:

importRPi.GPIOasGPIO

fromtimeimportsleep

GPIO.setmode(GPIO.BCM)

GPIO.setup(8,GPIO.OUT)

GPIO.output(8,GPIO.LOW)

whileTrue:

GPIO.output(8,GPIO.HIGH)

sleep(1)

GPIO.output(8,GPIO.LOW)

sleep(1)

GPIO.cleanup()

2. Afterimportingtherequiredmodules,wegetstartedwithsettingupthepinnumberingmode.Therearetwotypesofpinnumberingmodes,namely:

TheBCMPinnumberingmode:Thepinnumbersarebaseduponthepin

Page 96: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

numbersoftheBCMchip.TheBoardnumberingmode:ThepinnumbersarebaseduponthepinnumbersoftheRaspberryPiGPIOheader.Inthisexample,wewillsettheBCMnumberingmodeandsetpin8astheoutput:

GPIO.setmode(GPIO.BCM)

GPIO.setup(8,GPIO.OUT)

3. Wecansetthepintologicalhigh(3.3V)asfollows:

GPIO.output(8,GPIO.HIGH)

4. Wecansetthepintologicallow(3.3V)asfollows:

GPIO.output(8,GPIO.LOW)

5. Now,theLEDcanbemadetoblinkwitha1seconddelay:

whileTrue:

GPIO.output(8,GPIO.HIGH)

sleep(1)

GPIO.output(8,GPIO.LOW)

sleep(1)

6. WhentheprogramisinterruptedbytypingCTRL+C,wehavetocleanupandreleaseanyoccupiedGPIOresources:

GPIO.cleanup()

Page 97: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthissection,wefinishedwritingaprogramtomakeanLEDblink.Inthenextsection,wewillputacircuittogetherthatmakesanLEDblink.

Page 98: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 99: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ElectricaloutputofourprogramIntheprevioussection,wewroteaprogramtomakeanLEDblink.Let’slookattheelectricalconnectiontoobservetheoutputofourprogram.WewillconnectaresistorbetweentheGPIOpinandtheanodeoftheLED.WewillconnectthecathodetothegroundpinoftheRaspberryPi.

Page 100: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersWewillconnecttheLEDandtheresistortotheGPIOpinandthegroundpin,asshowninthisimage:

LEDblinkingcircuit

NoteIfwearenotcarefulwiththehandlingoftheRaspberryPiGPIOpins,itmayeithertemporarilyresettheRaspberryPiorsometimesevenpermanentlydamagetheGPIOpin.ThereareseveraltutorialsinbasicelectronicsavailableovertheWeb.Itisimportantthatyoufamiliarizeyourselfwiththebasicsofelectronics.

Onceweconnectthecircuitasshownintheprecedingimage,wewillbeabletoexecutetheprogramandconcludeourexperiment.

Wecanexecutetheprogrambyrunningthemodule,asshowninthefollowingscreenshot:

Page 101: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ExecutingthePythonexample

Page 102: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingThat’sit!WehavewetourfeetbysayingHelloWorldbyblinkinganLED!Onourwaytobiggerandbetterthings,let’sstopandexaminethePiCrustforamoment.

IntroductiontothePiCrust–aprototypingplatformfortheRaspberryPiNowthatourHelloWorldexampleisdone,wewillleaveyouwithonemorething.Throughoutthisbook,wewillreviewsomeadd-onhardwaretoaccesstheGPIOperipheralsontheRaspberryPi.Inthisproject,wewilldiscussthePiCrustboardfortheRaspberryPi.

ThePiCrustboardwasdesignedbyJoeWalnes.ItisaboardthatisstackableontheRaspberryPiandeliminatestheneedforabreadboardtoprototypecircuits.

APiCrustboard

ThePiCrustisanopensourceadd-onhardwareandcostsapproximately$14tobuildoneourselves.Thedesigncanbedownloadedfreeofcostfromhttp://picru.st.

So,itisuptoyoutodecidewhetheryouwanttosimplybuyone,buildone,orasweare

Page 103: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

pronetoencourage,improveuponitandopensourceitforotherstobenefit!

ThemainadvantagebehindPiCrustisthatitisaidsprototyping.ItallowseasyaccesstotheI2Cinterface,SPIinterface,UARTport,andtheGPIOpins.ThefollowingfigureshowsBlinkM—anI2C-drivenRGBLEDmountedontopofthePiCrust.

PiCruststackedontopoftheRaspberryPi

Page 104: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 105: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedNowthatyouhavetraveledthisfarwithus,howdoyoufeel?Doyouneedabreak,ormorecoffee?Beforeyoudoeither,let’sreview.

Inthisproject,wegotstartedwiththeLEDblinkingexampleusingtheRaspberryPi.WediscussedthesetupofGPIOperipheralsandusingtheminanexperiment.YouarewelcometocontinueexperimentswiththeGPIOperipheralswithprojectssuchasLEDsequencing,threebitcounter,andsoon.

Intheforthcomingprojects,wewilllookintoI2Ccommunication,SPIcommunication,andUARTcommunication(serialport).

Page 106: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 107: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeWelldone;youhavetaughtyourPitosay“HelloWorld”!However,wearesureyoucandomore,muchmore.HaveyouwatchedthemovieCloseEncountersoftheThirdKind?Well,ifnot,youshould.However,thisisnotachallengeinitself.Inthemovie,thehumanbeingsattemptatcommunicationwithwhattheybelieveisaliensbybuildingapatternoflightsthataresettomusic.CanyoumakeapatternofLEDsrepeatthatorsomethingsimilar?

Page 108: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 109: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter2.ARaspberryWebIDEExampleInthisproject,wewilllearnhowtodevelopprojectsusingtheWebIDEfromAdafruitIndustries.WewillflashanSDcardwiththeRaspbianOS,installtheOccidentalistool(https://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-3),setuptheweb-baseddevelopmenttool,andtestthesetupusinganexample.

NoteOccidentaliswasinitiallyavailableasaRaspbianOSimagebyAdafruitIndustries.ItcomprisedofthetoolsetthatenabledtogetstartedwithprojectdevelopmentusingtheRaspberryPi.TheOSimagewasdeprecatedandreleasedafterwefinishedwritingthebook.Wehavetakenourbestefforttoupdatethebook.Pleaserefertothisbook’swebsiteformoreinformation.

Page 110: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewilldiscussinstallingatool,Occidentalis,andaWebIDEthatenablesprogramminginthePythonlanguageontheRaspberryPi.WewillalsodiscussoneexamplefromtheAdafruitrepositoryandanotherexampleofdrivinganRGBLED.

Thefollowingtableliststhebillofmaterialsusedinthisproject.Thesearejustexamples,andalternativeproductsthathaveasimilarspecificationmayalsobeused.

Item EstimatedCost

RaspberryPiModelB 35USD

AdafruitCobbler(https://www.adafruit.com/product/914) 7USD

Adafruit7-segmentLEDBackpack(https://www.adafruit.com/product/879) 10USD

Blinkm(https://www.sparkfun.com/products/8579) 13USD

Page 111: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?TheAdafruitWebIDEincombinationwiththeOccidentalisoperatingsystemenablesdevelopmentinthePythonlanguageonaRaspberryPiusingjustawebbrowser.ItalsoenablesaccesstosampleprojectsdevelopedbyAdafruitviaBitbucket,asourcecontroltool.(IfyouarenotfamiliarwithsourcecontroltoolssuchasBitbucket,Git,andsoon,theexamplesinthisprojectareagreatwaytogetstarted!)TheAdafruitWebIDEisatooldevelopedforhobbyistsandcomeswithexamplesfortechniquessuchaspulse-widthmodulation(usedinlightingsystemcontrol)andI2Ccommunication,andalsoprovidesexamplesforcontrollingproductsfromAdafruit.

NoteTheAdafruitWebIDEisnowabetareleaseanditmaynotworksuccessfullyacrossdifferentplatforms.TheAdafruitlearningsystemhasindicatedthatthisdevelopmenttoolwasdirectedtowardsadvancedhobbyists.Wehavetakenourbesteffortstoexplainitassimplyaspossible.

Pulse-widthmodulationisatechniqueusedwidelyinmotorcontrol,lightingsystems,andsoon.Itisatechniquewheretheaveragevoltageappliedtoadeviceisvariedbychangingthewidthofthepulse.Thereareseveraltutorialsonpulse-widthmodulation(https://learn.sparkfun.com/tutorials/pulse-width-modulation)availableallovertheWeb.

I2Ccommunication(https://learn.sparkfun.com/tutorials/i2c)isaformofserialcommunicationinterfaceusedtoconnectmultipleslavedevices(usuallysensors)withamasterdevice(RaspberryPioramicrocontroller)throughacommoninterface.

Page 112: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesInthisproject,wewilldiscussthefollowingfeatures:

BootstrappingyourRaspberryPibyinstallingOccidentalisSetupofremoteloginintotheRaspberryPiInstallationoftheRaspberryPiWebIDEPythondevelopmentontheWebIDETestanddebuggingexamplesusingtheWebIDE

NoteThisprojectshouldnotbeconsideredasanattempttopromoteAdafruitIndustriesortheirproductsdevelopedfortheirplatform.ThisprojectmerelydemonstratessimplificationofdevelopmentontheRaspberryPiusingatoolfromAdafruitIndustries.

Page 113: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistInordertogetstarted,thefirststepistoinstalltheOccidentalisdistro,whichisaderivativeoftheRaspbianoperatingsystem.

Thethingsrequiredtogetstartedareasfollows:

A4GBSDcardflashedwiththeRaspbianOSAnOccidentalisimage.AnEthernetcable

Page 114: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 115: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Installation,features,andusageoftheOccidentalisoperatingsystemfromAdafruitThefirststepisinstallingOccidentalisontheRaspberryPi.

Page 116: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThefirststepistheinstallationoftheAdafruit-Pi-Findertool.Thetoolcanbedownloadedfromhttps://github.com/adafruit/Adafruit-Pi-Finder/releases/latest.ItisavailableforWindows,Linux,andMacplatforms.

Page 117: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. YoucanfinddetailedinstructionsoninstallingtheOccidentalistoolat

https://github.com/adafruit/Adafruit-Pi-Finder.2. Alternatively,astep-by-stepinstructionisalsoavailableonthisbook’swebsite.We

cannotincludethemheresincechangesweremadetoOccidentalisinstallationprocessafterwefinishedwritingthisbook.

Page 118: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingOncetheinstallationiscomplete,wehavetoensurethattheRaspberryPiaswellasthedevelopmentmachineareconnectedtothenetworkviatheEthernetportoraUSBWi-Fidongle.

Page 119: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 120: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SetupofaremoteloginintotheRaspberryPiInthissection,wewillremotelylogintotheRaspberryPiusingasecureshell.SincetheRaspberryPicomeswithsshdenabled,itispossibletologinremotelyusingthelocalname,raspberrypi.local(Duringthebootstrappingprocess,theavahi-daemontoolisinstalledandhence,itispossibletoremotelylogintotheRaspberryPiusingthelocalname,raspberrypi.local).Alternatively,onaWindowsmachine,youcanuseatoolsuchasAdvancedIPScanner(http://www.advanced-ip-scanner.com/)tofindtheIPaddressoftheRaspberryPi.Asnapshotofthistoolisshownlaterinthisproject.

NoteIfyouareusingaWindowsmachine,theBonjourPrintServicesdrivershavetobeinstalledtoremotelyloginusingthelocalname,raspberrypi.local.TheBonjourPrintServicesdriversareavailablefromhttp://support.apple.com/kb/DL999.

Page 121: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheIPaddressoftheRaspberryPicanbeidentifiedusingtoolssuchasAdvancedIPScanner,asshowninthefollowingscreenshot:

AlistofdevicesandIPaddressesconnectedtoanetworksimilartotheRaspberryPi

Page 122: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. OnceweknowtheIPaddress,weuseanSSHclientsuchasPuTTYonWindowsora

command-lineterminalonaLinuxoraMacmachinetoremotelylogintothemachine(inthiscase,weshowthisonaWindowsmachine).

2. OnaWindowsmachine,weeitherusetheIPaddressoftheRaspberryPioritslocalname(raspberrypi.local)andlogintotheRaspberryPi,asshowninthefollowingscreenshot:

3. OnceweentertheIPaddress/localnameinthePuTTywindow,weloginasfollows:

loginas:pi

<username>@<ipaddress>'spassword:raspberry

Alternatively,wecanalsologinusingtheIPaddressoftheRaspberryPiinsteadofthelocalname,raspberrypi.local.

Page 123: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingIftheusernameandpasswordareenteredcorrectly,weshouldbeabletoremotelylogintotheRaspberryPitoinstallthewebserver.

Page 124: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 125: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InstallationoftheRaspberryPiWebIDEWewillgetstartedbyusingaremoteloginclientsuchasPuTTYtoremotelylogintotheRaspberryPiandinstalltheAdafruitWebIDE.InordertogetstartedwithexamplesfromtheAdafruitrepository,weneedaBitbucketaccount,andAdafruitprovidesdetailedinstructionsforthisathttp://learn.adafruit.com/webide/getting-started.

Page 126: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Oncewehaveloggedin,theAdafruitlearningsystem’swebsiterecommends

executingthefollowingtoinstallthewebserver:

curlhttps://raw.githubusercontent.com/adafruit/Adafruit-

WebIDE/master/scripts/install.sh|sudosh

2. Itshouldtakeaboutfiveminutestofinishtheinstallation.Iftheinstallationwassuccessful,weshouldbeabletoseethemessagemarkedinthefollowingscreenshot:

SuccessfulcompletionoftheAdafruitWebIDEinstallation

3. Assumingtheinstallationwassuccessful,weshouldbeabletolaunchtheAdafruitWebIDEusinghttp://raspberrypi.local.

Page 127: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AdafruitWebIDElaunchedforthefirsttime

4. InordertomakeuseoftheexamplesfromAdafruitIndustries,weneedtocreateaBitbucketaccount(itispossibletocreateonewithaGoogleaccount)andintegratetheWebIDEwiththeBitbucketaccount.Theinstructionsforthisareprovidedonthewebpage,asshownintheprecedingscreenshot.

Page 128: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingIftheinstallationwassuccessful,aftercompletionoftheregistration,wearedonewiththistask.Let’smoveonandlearntocodeusingtheWebIDE!

Page 129: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 130: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PythondevelopmentontheWebIDEInthissection,wewillusea7-segmentLEDbackpackandtheAdafruitCobbleralongwitha26-pinribboncable.WewilltestanexamplefromtheAdafruitrepository(https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code).Inthisproject,thenewadd-onhardwarethatwewilldiscussistheAdafruitCobbler.TheCobblerisasmallboardthataidsprototypingcircuitsonabreadboard.TheAdafruitCobblercostsabout7USDwhiletheribboncablecostsabout3USDandthe7-segmentbackpackcostsabout10USD.

NoteTheearliermentionedproductsaremerelyexamplestodemonstratetheAdafruitWebIDE.Therearealternativeprototypingplatformsandproductsavailableforahigherorlowerprice.

TheCobblermountedonabreadboard

Page 131: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInordertogetstartedwiththeprototyping,the26-pinribboncableisusedtoconnecttheGPIOinterfacetotheCobbler,asshowninthefollowingimage.Wehavetoensurethatpin1oftheGPIOheadermatchespin1oftheAdafruitCobbler.(TheCobblercomeswithashroudedheader,andhenceitisfoolproof.However,pin1oftheRaspberryPineedstobematchedcorrectly.)

QuickintroductiontotheI2CinterfaceTheI2CinterfacewasinventedbyPhillipsSemiconductors.Itisaformofserialcommunicationinterfaceusedtoconnectmultipleslavedevices(usuallysensors)withamasterdevice(RaspberryPioramicrocontroller)throughacommoninterface.Eachdevicehasauniqueaddressthatisusedbythemastertoreadorwritedata.ThereareplentyofresourcesavailabletofamiliarizeourselveswiththeI2Cinterface.Wewillmoveontothenextstageofconfiguringtheinterface.

ConfiguringtheI2CinterfaceontheRaspberryPiIntheOccidentalisdistribution,theI2Cdriversareinstalledandenabledbydefault.Hence,wecangetstartedbyconnectingtheAdafruit7-segmentbackpacktotheAdafruitCobbler,asshowninthefollowingimage.(ConnectionsbetweentheCobblerandthe7-segmentbackpackareClockpin,SCL(C)-SCL(B)DataPin-SDA(C)-SDA(B),3V3(C)to+(B)GND(C)to-(B),whereCistheCobblerandBisthebackpack):

Page 132: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

7-segmentbackpackconnectionsonabreadboard

NowthatwehaveconnectedtheRaspberryPi,theAdafruitCobbler,andthe7-segmentbackpack,let’sgetstartedwiththedetectionofthebackpackontheRaspberryPi’sI2Cinterfaceandprogramanexample.

Beforewegetstartedwiththeexample,weneedtodeterminetheI2Cbustowhichthedeviceisconnectedbyusingthefollowingcommand:

sudoi2cdetect–y0

Thecommandoutputsatablethatcontainsthelistofdevicesforthatparticularbus.Sincetherearenodevicesconnectedtobus0,wescanfordevicesonbus1.Inthisexperiment,wearetestingtheAdafruit7-segmentbackpack.Inthefigurethatfollows,the7-segmentbackpackisconnectedtobus1andthedeviceaddressis0x70.Refertothefollowingscreenshot:

Page 133: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Thei2cdetectoutput

Weshouldchangethebusaddressinthecodetodrivethe7-segmentbackpack.Line11intheAdafruit_I2C.pyfileneedstobechangedinthecodeaccordingtothebustowhichthedeviceisconnected.Hence,line11shouldbe:

def__init__(self,address,bus=smbus.SMBus(1),debug=False):

Page 134: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. The7-segmentbackpackisadevicecontrolledviaanI2Cport.AnyI2Cdevicehas

fourpins,namelyclock,data,powersupply,andground.TheI2CdeviceneedstobeconnectedtotheCobbler,asshownintheearlierscreenshot.

2. ThereareseveralexamplesavailablefromAdafruitintheWebIDE.Let’slocatetheex_7segment_clock.pyexample(intheIDE,itislocatedatAdafruit_Raspberry-Pi-Python-Code|ex_7segment_clock.py).Thisisasimpleexampletodisplaythecurrenttimeonthe7-segmentbackpack:

Theex_7segment_clock.pyfilelocationintheWebIDE

3. Let’sdoaquickreviewoftheprogram.WegetstartedbyimportingthedatetimeandAdafruit_7Segmentmodules:

ThesegmentvariableisinitializedasaninstanceofanI2Cdeviceattheaddress0x70.Weenteraninfiniteloopandgetthecurrenttimeusingthedatetimemodule:

now=datetime.datetime.now()

hour=now.hour

minute=now.minute

second=now.second

Sincethe7-segmentLEDbackpackconsistsoffourdigits,wewritethecurrenttimeateachpositionasfollowsalongwithacolon:

#Sethours

segment.writeDigit(0,int(hour/10))#Tens

segment.writeDigit(1,hour%10)#Ones

#Setminutes

segment.writeDigit(3,int(minute/10))#Tens

segment.writeDigit(4,minute%10)#Ones

Page 135: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#Togglecolon

segment.setColon(second%2)#Togglecolonat1Hz

#Waitonesecond

Thisexerciseisrepeatedwithaonesecondinterval.

4. TheprogramisexecutedbyclickingonRunfoundintheIDE.Ifourconnectionswereright,weshouldbeabletoseethecurrenttimeonthe7-segmentdisplay(showninthefollowingfigure).

Page 136: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWewereabletotestanAdafruitproductusingtheirWebIDEinthissection.

A7-segmentbackpackconnectedtotheCobbler

Page 137: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 138: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TestanddebuggingexamplesusingtheWebIDEInthisexample,wewillconnecttheBlinkMtotheRaspberryPi.ABlinkMisanRGBLEDthatcanbeconnectedtoyourRaspberryPiviatheI2Cinterface.Itispossibletoexecutelightscriptsusingtheport.TheconnectionstotheBlinkMaresimilartothatofthe7-segmentbackpack.

BlinkMconnectedtotheCobbler

NoteItisimportanttopayattentionwhileconnectingdevicestotheGPIOheaderoftheRaspberryPi.IftherearedevicesthatdrawalotofcurrentfromtheGPIOpins,itmayresetthePiorpermanentlydamageitintheeventofashortcircuit.Itisassumedthatyouarefamiliarwithbasicelectronicsandcapableofhandlingsuchdevices.

Page 139: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffSimilartothepreviousexperiment,weneedtodeterminethebustowhichthedeviceisconnectedusingthei2cdetectcommand.Asshowninthefollowingscreenshot,thedeviceisconnectedtobus1andthedeviceaddressis0x09:

Blinkmconnectedtobus1

Page 140: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheBlinkMdatasheet

(thingm.com/fileadmin/thingm/downloads/BlinkM_datasheet.pdf)providesstep-by-stepinformationtoexecutethelightscripts.

2. AlistofscriptsavailableontheBlinkMisshowninthefollowingscreenshot:

AlistofscriptsavailableontheBlinkM

3. Let’sseethecodetoexecutealightscript(forexample,scriptnumber6)ontheBlinkMusingtheAdafruitWebIDEinterface.Inordertoexecuteascriptforever,thedatasheetmentionsthatthefollowingcharactersshouldbewrittenattheI2Cdeviceaddressinthefollowingsequence:'p',<scriptno>,0,0.Let’sdiscusshowtoexecutethisusingaPythonscriptontheRaspberryPiinterfacedwiththeBlinkMLED.ThePythonscriptofthisexampleiscalledPlay_blinkm.py:

Page 141: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ThePlay_blinkm.pyfilecanbeexecutedbycreatinganewfileintherepositorythatwascreatedwhenyousignedupforaBitbucketaccount.Whenthefileissaved,thechangesaresavedtoyourBitbucketaccount.Thecodeforthisisgivenasfollows:

#!/usr/bin/python

#python-smbus

importsmbus

#createi2cobject

bus=smbus.SMBus(1)

#refertodatasheetforscriptsequence

#Playscriptbywriting0x70orponthebus

bus.write_byte(0x09,0x70)

#playscriptno:6

bus.write_byte(0x09,0x06)

#playthescriptinfinitely

bus.write_byte(0x09,0x00)

bus.write_byte(0x09,0x00)

Thefirstlineofthiscodeiscalledshebang.ItindicatesthatthescripthastobeexecutedusingPython.Weneedtoimportpython-smbustoexecutethelightscript:

importsmbus

WeneedtocreateanobjectforI2Ccommunication.Weneedtowritethecontrolscriptviabus1.Thisisdonebythefollowinglineofcode:

bus=smbus.SMBus(1)

Inordertoplayascript(scriptnumber6inthiscase)forever,wewrite'p',<scriptno>,0,0ontheI2Cbusasfollows:

bus.write_byte(0x09,0x70)

bus.write_byte(0x09,0x06)

bus.write_byte(0x09,0x00)

bus.write_byte(0x09,0x00)

4. ThiswouldcausetheBlinkMtoexecutescriptnumber6aslongasthedeviceispoweredanduntilanotherinstructionhasbeenissuedtothedevicethroughtheI2Cinterface.

5. Now,itispossibletodebugourprogrambyexecutingitstepbystep.Thishelpsidentifyanyproblemswiththeprogram.Let’sreviewsomeoptionstodebugaprogram.Wecanlaunchtheprogramfortroubleshooting/debuggingbyclickingonDebug.

TheAdafruitWebIDEtoolbar

Thisopensuptwoconsoles,DebugOutputandDebugVariables(shownin

Page 142: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

thefollowingscreenshot).ThewindowDebugOutputprintsanyoutputoftheprogram.Ifweincludedanyprintstatementsinourprogram,theoutputisdisplayedinthiswindow.Thiswindowcanbeusedtoviewanyresults,ensurethataparticularcallbackfunctionwasexecuted,ordeterminewhethertheprogramexecutiongotpastaparticularlineoftheprogram.TheDebugVariableswindowdisplaysthestateofvariablesastheprogramisbeingexecuted.BoththewindowsarehelpfulindeterminingwhetheraPythonscriptwaswrittenasintended.

Debugterminals

WhenwestartdebuggingaPythonscript,thetoolbaratthetoppresentsuswithtwooptions,namelyStepOverandStepIn,asshowninthefollowingscreenshot:

TheAdafruitdebugtoolbar

Inthisexample,itispossibletotesttheexecutionofcommandsbysteppingthrougheachlineofthescript.Thisisreallyusefulwhendevices(forexample,apressuresensor)arenotprovidingtheintendedoutputtoidentifytherootcause.

Page 143: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthissection,weinterfacedandcontrolledanRGBLEDusinganI2CinterfaceanddiscussedsomeoptionsavailablefordebuggingintheAdafruitWebIDE.

TheAdafruitWebIDEcanconsiderablyreducetheturnaroundtimeforanyprojectdevelopmentactivity.

Page 144: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 145: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,weworkedontwosimpleexperimentsusingtheI2CinterfaceontheRaspberryPi.ThetwoexamplesdiscussedusingtheAdafruitWebIDEreflectthefactthatthetoolcanhelpsavetimeforanyelectronicsprojectinvolvingaRaspberryPisinceitcomeswithsomeoftheprerequisitesinstalledalongwithawebinterfacethatjustmakesremotedevelopmenteasier.

WehopethatyouhadfuntakingtheOccidentalisdistributionforatestdriveandfinditusefulinyourprojects.

Page 146: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 147: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisproject,weusedtwodifferenttypesofI2Cdevices,thatis,anLEDbackpackandanRGBLED.ItispossibletoconnectmultipleI2Cdevicestothesameinterface.Howcanthisbeachieved?HowcanweidentifytheaddressesoftheseI2Cinterface-enableddevicesandcontrolthem?

Page 148: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 149: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter3.TheArduinoRaspberryPiInterfaceInthisproject,wewilllookintointerfacingtheRaspberryPitotheArduinomicrocontrollerdevelopmentplatform.Arduino(www.arduino.cc)isapopularmicrocontrollerplatformthatiswidelyusedtoprototypedifferentprojects.WewilldiscussinstallationoftheArduinodevelopmentenvironmentanddiscussanexampleofitsusage.

RaspberryPiandArduinohavebecomepopularplatformsamonghobbyists,anditisbeingwidelyusedbypeoplefromdifferentbackgrounds,includingschoolanduniversitystudents,artists,andengineers.ThisprojectexplainshowtheRaspberryPicanbeusedincombinationwithArduino.

NoteTheRaspberryPicomeswithaGPIOpinsetthatisquitecapableofinterfacingandcontroldevices.WewouldliketodiscusstheArduinoRaspberryPiinterfacebecauseyoumayhaveprojectsthatwereoriginallybuiltusinganArduino,especiallyinscenarioswherearemotefirmwareupdateneedstobeperformedontheArduinoplatformusingtheRaspberryPi.ThisprojectpresentstheoptionsofenhancingthecapabilitiesoftheArduinomicrocontrollerusingaRaspberryPi.

Page 150: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthefirstpartoftheproject,wewilldiscussprogrammingtheArduinoforthefirsttime,andinthesecondhalf,wewilllookintothecontrolofaWeasleyweatherclock.WewillalsolookintotheRaspberryPiAlaMode,stackableadd-onarduinohardware(http://wyolum.com/projects/alamode/).

Page 151: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?ArduinoisanopensourcemicrocontrollerdevelopmentplatformbasedontheAtmelseriesofmicrocontrollers.Ithasbroughtengineers,artists,andstudentstothesametable.Theprogramminginterface(programsarewritteninC/C++usually)issosimpleandthiswasthesolereasonthatmadetheplatformsopopular.Hence,itiswidelyusedforprototypinginproductdevelopment.

Overtheyears,therehavebeenseveralhardwareadd-onsthataidedinhardwaredevelopmentusingtheArduino.Someoftheseadd-onscanbestackedontopoftheArduinodevelopmentplatform,andtheyarecommonlyreferredtoasshields.Thereareshieldsformedicaldevices,interfacingsensors,GPSunits,andactuatorssuchassteppermotors,servomotors,andsoon.TheecosystemofthegadgetsthatarebuiltaroundtheArduinoissovastthatthemicrocontrollerplatformwaslaunchedintothestratospherealongwithaheliumballoon.

WherecanyoubuyanArduino?SincetheArduinoisanopensourcemicrocontrollerboard,therearemanyresellersfortheproduct.ThebasicversionoftheArduinoistheArduinoUnoandcostsabout$29.95.Arduino-relatedproductsaresoldatwebsitessuchasSparkfun,Adafruit,andSeeedStudio.

Page 152: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesInthisproject,wewilldothefollowing:

InstalltheArduinoIDEProgramtheArduinousingtheRaspberryPiRaspberryPiAlaMode(oranyotherArduinodevelopmentboard)IntroductiontoWeasleyWeatherClockandBillofMaterialsControlthestepperusingtheArduinoControltheRGBLEDStripusingtheArduinoI2CCommunicationusingtheArduino(optional)SerialportcommunicationwiththeRaspberryPi

Page 153: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistWeneedaRaspberryPialongwithanSDcardflashedwiththeRaspbianOS,amicroUSBpowercable,displaysetup,andanArduinotogetstarted.Inthelatersectionofthisproject,wewillneedsomeadditionalhardwaresuchasRGBLEDStrips,motors,wires,andsoon.

Page 154: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 155: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InstallingtheArduinoIDEInthissection,wewillinstalltheArduinoIDEontheRaspberryPi.

Page 156: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffAnArduinomicrocontrollerdevelopmentplatform(anyvariantthatcouldbeprogrammedusingtheArduinoIDEisfine)isabsolutelyessentialforthissectionoftheproject.

Page 157: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheIDEcouldbeinstalledbyexecutingthefollowingcommandinthecommand

lineterminal:

sudoapt-getinstallarduino

2. MostArduinoproductscomewithaUSBportandareprogrammedviatheUSBport(theArduinoenumeratesasaserialportdevice).IttakesawhiletodownloadandinstalltheArduinoIDE.Oncetheinstallationisfinished,wecantesttheinstallationbyexecutingthefollowingcommand:

arduino

TheArduinoIDEisshowninthefollowingscreenshot:

TheArduinoIDEinterface

Page 158: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingNowthatwehaveinstalledtheArduinoIDE,let’smoveontothenextsectionandrunanexampletestusingtheArduinodevelopmentplatform.

Page 159: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 160: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ProgrammingtheArduinousingtheRaspberryPiWewillintroduceourselvestotheArduinoIDEwithanLEDblinkingexample.

Page 161: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThereareseveralexamplesfortheArduinoandittakeslessthanaminutetoexecutethefirstprogram.Let’sgetstartedwiththetraditionalLEDblinkingexample.TheLEDblinkingexamplecanbefoundatFile|Examples|01.Basics|Blink.

Page 162: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. WegetstartedbyidentifyingtheArduino’sserialportenumeratedontheRaspberry

Pi.2. TheserialportisidentifiedfromTools|SerialPort.Usuallythereisonlyoneserial

portasshowninthefollowingscreenshot.Ifthereismorethanoneserialportdeviceconnected,itisrecommendedthatyouproceedwithcaution.

3. WecanprogramtheArduinobyclickingontheUploadbutton.

TheArduinoIDEinterface

Page 163: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingIftheArduinoisconnectedandtheserialportwascorrectlyidentified,theprogramshouldbeuploadedsuccessfully.

SketchuploadedusingtheArduinoIDE

MostArduinoproductscomewithanonboardLEDtotesttheLEDblinkingexample.

Page 164: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 165: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiAlaModeInthissection,wewillbrieflydiscusstheRaspberryPiAlaMode’sfeaturesanditssetup.RaspberryPiAlaMode(asshowninthefollowingfigure)isastackableArduinodevelopmentplatformdevelopedspecificallyfortheRaspberryPi.Theboard,whichisreleasedasopensourcehardware,ispricedatabout$45andalsoincludesareal-timeclockandamicroSDcardslotfordatalogging.

RaspberryPiAlaModemodestackedontheRaspberryPi

Page 166: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheattractivefeatureoftheboardisthatitcouldbeprogrammedviatheRaspberryPi’sUARTpinsandhenceeliminatestheneedforaUSBport.TheboardcouldbeeitherpoweredviatheRaspberryPiorthroughtheMicroBUSBportusingawallwarttransformer.Theproduct’swebpage,http://wyolum.com/projects/alamode/alamode-getting-started/,offersasinglestepprocesstostartusingtheboard.

NoteTheRaspberryPiAlaModemodeisjustoneexampleofthestackableArduinohardware.ThereareprobablyothersimilarstackableArduinohardwareavailableinthemarket.Forexample,https://www.kickstarter.com/projects/raspitv/raspio-duino-affordable-arduino-programming-on-ras.

Page 167: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Oncethearchiveisdownloadedfromtheirwebpage,weextractthecontents:

tar–xvzfalamode-setup.tar.gz

2. Oncethefilesareextracted,thesetupisasfollows:

sudo./setup

3. Aftertheinstallationiscomplete,theRaspberryPialamode’sserialportisenumeratedas/dev/ttyS0.

Page 168: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingAftertheinstallationiscomplete,weshouldhavetheRaspberryPiAlaModemodeenumeratedandbereadytostartprogrammingthehardwareadd-onboard.

Page 169: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 170: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TheWeasleyweatherclockWewillbuildaWeasleyweatherclockinthisprojectusinganArduinomicrocontrollerboardandtheRaspberryPi.TheWeasleyWeatherclockisinspiredbytheWeasleyclockseenintheHarryPotterseriesofmovies.AWeasleyclockisusedtoidentifythecurrentlocationofafamilymemberoftheWeasleys(forexample,work,school,andsoon)andalsothesafetyofthefamilymember.Mrs.MollyWeasley(thematriarchoftheWeasleys)usedtheWeasleyclocktokeeptabsonherfamilyandthisclockhashaditsvariantsovertheyears.Thisprojecthappenstobeoneofthem!

TheWeasleyweatherclockisonethatdisplaysthecurrentoutdoortemperatureandtheforecast.Italsowarnsusaboutimpendingdangersduetoconditionssuchastornadoes,blizzards,andsoon.

AWeasleyweatherclockbuiltusingtheArduinoandtheRaspberryPi

Page 171: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThefollowingitems(alongwiththeirapproximatecost)arerequiredtobuildourWeasleyclock:

Item Price

RaspberryPimodelB*1 US$35

ArduinoUno/RaspberryPiAlaModemode(http://wyolum.com/projects/alamode/)*1 US$30/45

AcrylicSheet24inchesx20inches*0.093inchthick*1 US$10

Woodsheet1ftx1/2ftx0.25inchthick*1 US$5

5VDCSteppermotorfromAdafruit*1(http://www.adafruit.com/product/858) US$5

RGBLEDStrip1m*1(analogones(http://www.adafruit.com/products/1004)) US$15

NPNtransistors*2(BC547orNP2222) US$1

PowerDarlingtonStepperDriver(ULN2003A) US$2

Cablesforconnection US$4

7-SegmentBackpack(http://www.adafruit.com/product/879) US$10

A8x8LEDMatrixbackpack(optional(http://www.adafruit.com/product/871)) US$10

BlinkM(optional) US$13

12V,1ADCwalltransformer(optional(https://www.sparkfun.com/products/8579)) US$8

Totalcost US$122approx.

Page 172: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheWeasleyclockcouldbeeasilyassembledwithpartsmachinedwithalasercutter.

Lasercuttingisaprocesswherepartsaremachined/engraved/cutusingahigh-powerlaserbeaminacontrolledenvironment.Thelasercutteriswidelyusedforprototypingpurposes.Thedesignfilesforlasercuttingareavailablealongwiththisbookcodebundle.Inthisexample,thedialoftheweatherclockiscutfromtheacrylicandthedesignincludesmountingholesfortheclockaswellasthesteppermotor.Theweatherkeywordsareengravedandmachinedusingwoodsheets.Theassemblyofthekeywordsandthedialareshowninthefollowingfigure:

PartialassemblyoftheWeasleyClock

Page 173: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingTheassemblyshownintheimageissufficienttotestthisexample.Youcanaddmorefeaturestothedesign.Forexample,youcanaddslotsontheacrylicboardtoembeda7-Segmentdisplay,8x8LEDmatrix,oraBlinkMRGBLEDtothedesign.

Inthisexample,theArduinoisthelow-levelcontroller,whichdrivestheRGBLEDstrip,steppermotor,andsoon,whiletheweatherdataisobtainedfromtheInternetusingtheRaspberryPi.WewilldiscusstheArduinocodeinthefirstpartofourtask.

FlowofdataandcontrolinthisWeasleyClockproject

Page 174: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 175: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ControllingthestepperusingtheArduinoThepartnumberofthesteppermotorusedinthisexampleis28BJY-48(http://www.adafruit.com/product/858).Asteppermotorisatypeofmotorthatisoperatedbyenergizingitscoilsinseveralsteps.Thecoilenergizationinseveralstepsenablesthesteppertorotateinpreciseangularsteps.Thisprecisemovementaidstheuseofasteppermotorinopenloopsystems.Sincetheworkingprincipleofasteppermotorisbeyondthescopeofthebook,let’sdiscussitscontroltechnique.

Page 176: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThesteppermotorispoweredbyacommonleadconnectedtothepowersupplyandtheotherendisconnectedtoatransistor.Sincetransistorscanbeusedasswitches,theleadsofthecoilcanbegroundedalternatively.Thisalternativesequencecausesthesteppermotortorotateandthespeedofrotationiscontrolledbyintroducingadelayinbetweenthecoilenergization.Theminimumdelayrequiredbetweeneachenergizationsteptomakethestepperrotateproperlyandavoidmissstepsis2milliseconds.Thisisduetothedesignlimitationsofthesteppermotor.

Thefollowingtableshowsthecoilenergizationsequenceforthesteppermotorinaclockwisedirection(borrowedfromthedatasheet).Theenergizationsequenceshownherewouldmakethestepperrotateinahalfstepperactuation,thatis,thestepperwouldrotate2.8125degreesforeveryactuationsequence.

NoteItisassumedthatyouarefamiliarwithsteppermotorsandtheircontroltheory.

Asteppermotorenergizationsequencefrom28BJY-48’sdatasheet

Page 177: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Eachcolumnintheprecedingdiagramindicatestheleadthatneedstobeenergizedto

rotateasinglestep.2. Forexample,inthecaseofclockwiserotation,Lead4isenergizedandallotherleads

areturnedoff.Thedatasheetexplainsthatthesteppermotorrotatesapproximately5.625degreesperstep.

3. Hence,64actuationstepsarerequired(64*5.626=360degrees)tomakeonecompleterotation.Thesteppermotorisinterfacedtoagearboxof1:64ratio,andeachrotationtakesabout4096steps.

4. Let’sreviewthecoderequiredfortheenergizationsequence(codeborrowedfromtheArduinoforumshttp://forum.arduino.cc/index.php?topic=85335.0):

//Step1

digitalWrite(motorPin4,HIGH);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

//Step2

digitalWrite(motorPin4,HIGH);

digitalWrite(motorPin3,HIGH);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

//Step3

digitalWrite(motorPin4,LOW);

digitalWrite(motorPin3,HIGH);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

//Step4

digitalWrite(motorPin4,LOW);

digitalWrite(motorPin3,HIGH);

digitalWrite(motorPin2,HIGH);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

//Step5

digitalWrite(motorPin4,LOW);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,HIGH);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

//Step6

digitalWrite(motorPin4,LOW);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,HIGH);

digitalWrite(motorPin1,HIGH);

delay(motorSpeed);

//Step7

digitalWrite(motorPin4,LOW);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,LOW);

Page 178: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

digitalWrite(motorPin1,HIGH);delay(motorSpeed);

//Step8

digitalWrite(motorPin4,HIGH);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin1,HIGH);

delay(motorSpeed);

}

5. Let’sdiscussthefirststepinthesteppermotorenergizationsequence:

//Step1

digitalWrite(motorPin4,HIGH);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin1,LOW);

delay(motorSpeed);

6. Intheprecedinglinesofcode,themotorPin4pinissettoHigh,whiletheotherpinsaresettoLow.Asshowninthefollowingfigure,thepinsmotorPin1throughmotorPin4areconnectedtoapowerDarlingtoncircuit.YoucanfindareferencetothePowerDarlingtoncircuitathttps://coefs.uncc.edu/dlsharer/files/2012/04/F5.pdf.

AnArduinosteppermotorinterface

7. Whenmotorpin4(theD11pinoftheArduinoisconnectedtothebasepinofthepowerDarlingtonpair)issettohigh,thetransistor(whichactsaswitch)connectstheorangeleadtothegroundandenergizesthecoilandtherebythesteppermovesbyasinglestep.

8. Similarly,thesteppermotor’scoilsareenergizedinthesequenceshowninthetable.Forexample,instep2,thecoils4and3areenergizedbysettingmotorPin4andmotorPin3toHighandotherpinstoLow.

Counterclockwiserotationofthesteppermotor

Page 179: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

1. Thecounterclockwiserotationisachievedbyreversingtheorderofenergization.Inthefirststep,Lead1isenergized,whichisfollowedbyLeads1and2.Thetableforcounterclockwiserotationisshownasfollows:

LeadWireColorCCWDirection

1 2 3 4 5 6 7 8

1BLU - -

2PIK - - -

3YEL - - -

4ORG - - -

2. Hence,thecodeforthefirststepwillbeasfollows:

digitalWrite(motorPin1,HIGH);

digitalWrite(motorPin2,LOW);

digitalWrite(motorPin3,LOW);

digitalWrite(motorPin4,LOW);

delay(motorSpeed);

Page 180: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingNoteIfyouarenotfamiliarwithsteppermotorsandtheircontroltechniques,thereareabundantresourcesandonesuchresourceishttp://www.societyofrobots.com/member_tutorials/node/314.

WediscussedthesteppermotorcontroltechniqueusingtheArduinomicrocontroller.Oncewehavediscussedtheprerequisites,wewilltakethiscodesampleandbuildthingsaroundit.

Page 181: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 182: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ControllingtheRGBLEDStripusingtheArduinoWedepictthemoodoftheweatherforecastbyusingRGBLEDlighting.Weindicatecoldweatherindicationswithbluecolorlighting,fairweatherconditionswithgreenlighting,andwarm/dangerousweatherconditionsusingredlighting.Inthissection,wewilllookintocontrollinganRGBLEDusingtheArduino.

TheRGBLEDstripsoldbyAdafruitindustries(http://www.adafruit.com/products/1004)consumesabout60mApersegment.ItisbestrecommendedtodrivetheRGBLEDstripusingatransistorswitchingcircuit.Weneedtousethreetransistorsforthethreecolorsanditispossibletocontroleachcolorindividuallyanditisalsopossibletoobtainacombinationofcolours.

NoteItispossibletoproduceasecondarycolorusingtheRGBcombinations.ThiscanbeachievedbyturningontheRGBsegmentsatthesametimeandvaryingthebrightnessoftheprimarycolors.TherearevastresourcesavailableforsuchtipsandtricksontheInternetandanexplanationofthisisbeyondthescopeofthisbook.

Page 183: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheAdafruitlearningwebsiteprovidesexamplesforcontrollingtheRGBLEDusingapulsewidthmodulationtechnique.TheschematicfortheAnalogRGBstripisshowninthefollowingdiagram:

RGBLEDstripschematic(borrowedfromAdafruit)

SincetheRGBstriprequires12V,wemustuseatransistorswitchingcircuittocontroltheLEDs.ThetransistorswitchingcircuitforcontrollingtheRed,Green,andBluechannelsoftheLEDstripisshowninthefollowingdiagram:

TheArduinoRGBswitchingcircuit

Page 184: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TheRGBchannelsareconnectedtotheNPNtransistorsthatactasswitches.ThebaseofthetransistorisconnectedtothePWM(PulseWidthModulation)outputoftheArduino.ThisenablesyoutoadjustthebrightnessoftheRGBchannels,andconsequently,producedifferentcolors.

Page 185: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. AdafruithasprovidedanexampleforadjustingthebrightnessoftheLEDsand

producingdifferentcolorsfromthecombinationofprimarycolors.Let’sconsiderthefollowingpieceofcode:

//fadefrombluetoviolet

for(r=0;r<256;r++){

analogWrite(REDPIN,r);

delay(FADESPEED);

}

//fadefromviolettored

for(b=255;b>0;b--){

analogWrite(BLUEPIN,b);

delay(FADESPEED);

}

2. Inthiscode,thered,greenandbluesegmentsoftheRGBLEDstripareconnectedtotheD3,D5,andD6oftheArduino,respectively.

ThevaluewrittentothepinsusingtheanalogWritefunctionsetsthebrightnessvalueofeachcolor.TheanalogWritefunctionvariesthedutycycleofthePWMchannelandacceptsvaluesbetween0and255.Thevalue0indicatesa0percentdutycycleand255indicatesa100percentdutycycle.ThedutycycledeterminesthecurrentthatflowsthroughtheLED,andinturn,controlsthebrightnessandcolor.

Page 186: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWediscussedadjustingthebrightnessoftheRGBLEDstripusingthePulseWidthModulationTechniqueandanArduinomicrocontroller-baseddevelopmentplatform.

Page 187: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 188: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

I2CCommunicationusingtheArduino(optional)Inthisproject,thereisa7-Segmentdisplay,8x8LEDmatrix,proximitysensor(todeterminethehomeposition),andaBlinkMRGBLEDthatcommunicatesviatheI2Cinterface.Wewilldiscusstheapplicationofeachcomponentinthisproject.

Page 189: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThemainrequirementforthissectionisthenecessaryI2Cdevicerequiredtointerfacewiththeweatherclock.

Page 190: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersLetusreviewaboutthe7-Segmentdisplay.

The7-Segmentdisplay1. TheAdafruit7-Segmentdisplaybackpack(reference:thetutorialavailableat

https://learn.adafruit.com/adafruit-led-backpack/0-dot-56-seven-segment-backpackprovidesinstructionsonsettingupthebackpackandtestingthebackpackwithacodesample),whichisusedtodisplaythecurrentatmospherictemperatureobtainedviatheRaspberryPi.

2. Adafruitprovideslibrariestowritetothe7-Segmentdisplay.Inordertowritetothe7-Segmentdisplay,wedeclarea7-Segmentobject:

Adafruit_7segmentmatrix_7segment=Adafruit_7segment();

WeinitializetheI2CportaddressofthedeviceintheArduinosetup()function:

matrix_7segment.begin(0x70);

Now,wecancalltheobjectandwritedataonthedisplay(codeborrowedfromAdafruitLEDbackpacklibraries):

matrix_7segment.clear();

matrix_7segment.print(temp,DEC);

matrix_7segment.writeDisplay();

8x8LEDmatrix1. TheAdafruit8x8matrixisusedtodisplaythemoodofthecurrentweathercondition

usingasmiley.(Thesetuptutorialcanbefoundathttps://learn.adafruit.com/adafruit-led-backpack/0-8-8x8-matrix).

2. Ifthecurrentweatherconditionisfair,asmileisdisplayedandafrownisdisplayedforimpendingdanger.

3. Thewriteprocessissimilartothe7-Segmentdisplay.The7-Segmentdisplayandthe8x8displaymatrixusetheMAX7219chip.Hence,itisnecessarytouseadifferentaddressfortheLEDmatrix.TheAdafruittutorial(https://learn.adafruit.com/adafruit-led-backpack/connecting-multiple-backpacks)clearlyexplainshowtochangeI2CportaddressesontheLEDbackpack.Youarewelcometoswitchtheaddressifboththe7-SegmentdisplayandtheLEDmatrixarebeingusedintheproject.

4. Itisalsopossibletowritestringstothe8x8matrixandscrolllikeamarquee.Similartothe7-Segmentdisplay,wewillinitializetheobjecttocommunicatewiththeLEDmatrix:

Adafruit_8x8matrixmatrix=Adafruit_8x8matrix();

WeinitializetheI2CportaddressofthedeviceintheArduinosetup()function:

matrix_7segment.begin(0x73);

Adafruittutorialsalsoexplainthecreationofbitmapsforthesmileystobe

Page 191: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

displayed:

staticuint8_t__attribute__((progmem))smile_bmp[]={0x3C,0x42,

0x95,0xA1,0xA1,0x95,0x42,0x3C};

staticuint8_t__attribute__((progmem))frown_bmp[]={0x3C,0x42,

0xA5,0x91,0x91,0xA5,0x42,0x3C};

staticuint8_t__attribute__((progmem))neutral_bmp[]={0x3C,0x42,

0x95,0x91,0x91,0x95,0x42,0x3C}

ThebitmapisusedtodeterminetheLEDsthatwouldhavetobeturnedontocreatethesmiley.Forexample,0x3C(binaryvalue:00111100)turnsontheLEDsexceptforthefirstandlasttwooneitherends:

matrix.clear();

matrix.setRotation(3);

matrix.drawBitmap(0,0,smile_bmp,8,8,LED_ON);

matrix.writeDisplay();

ThesetRotationfunctionisusedtorotatethedisplayimageby90degrees.ThedrawBitmapfunctionisusedtodrawthebitmaponthedisplay.InthedrawBitmapfunction,thefirsttwoargumentsspecifythexandyofthestartingpositionfollowedbythebitmap,width,heightofthebitmap,anditscolor.

BlinkM

1. WediscussedtheBlinkMRGBLEDinProject2,ARaspberryWebIDEExample.TheBlinkMisusedtoindicateimpendingdangerbyflashingaredcolorintheeventofimpendingdanger.WeusetheBlinkMlibrariestoplayaflashingredscriptinsuchscenarios:

BlinkM_playScript(script_no,0,0);

2. TheBlinkM_playScriptfunctiontakesthescriptnumberoftheRGBLED.Thesecondargumentisthenumberofrepeatsforthescript.Whenthethirdargumentiszero,thescriptisplayedinaninfiniteloop.

Proximitysensor

1. Theproximitysensorisusedtodeterminethehomepositionofthearrowthatisusedtopointtotheweatherposition.TheproximitysensorusedinthisprojectistheOSEPPProximitySensorModulefromParallax.TheproximitysensordetectsthepresenceofobjectsandcommunicatesthisviatheI2Ccommunicationport.

2. SimilartotheotherI2Cdevices,wesetthesensoraddressasfollows:

constuint8_tsensorAddr=0x20;

WeturnonthesensorintheArduinosetup()method:

WriteByte(sensorAddr,0x3,0xFE);

Thesensor’sreadingisreadby:

ReadByte(sensorAddr,0x0,&val)

Page 192: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 193: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWediscussedtheinterfacingofdifferentI2Cdevicesthatcouldbeusedinthisproject.Inthenextsection,wewillworkoncontrollingthesedevicesusinganindividualcontrolsignal.

Page 194: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 195: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SerialportcommunicationwiththeRaspberryPiAsmentionedearlier,theweatherdataisobtainedbytheRaspberryPiandcommunicatesthedatawithcontrolcharactersviatheserialport.Wewilldiscussthecontrolsignalsusedinthisproject.

Page 196: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersLet’sgetstartedbyreviewingthePythonscriptusedtooperatetheweatherdisplay.

PythonprogramfortheWeasleyclock1. Inthissection,wewilldiscussthePythoncodefortheweatherclock.Theimportant

requirementforthisprojectisthePythonweatherAPI.Weneedtodownloadandinstallittogetstarted.IfsubversionisnotinstalledontheRaspberryPi,itcanbeinstalledusingthefollowingcommand:

sudoapt-getinstallsubversion

2. Oncetheinstallationiscomplete,thePythonweatherAPIrepositorycanbeclonedasfollows:

svncheckouthttp://python-weather-api.googlecode.com/svn/trunk/

python-weather-api-read-only

3. ThePythonweatherAPIhasaPython3requirementandisinstalledasfollows:

cdpython-weather-api-read-only

python3setup.pybuild

python3setup.pyinstall

4. Let’sreviewthePythonscriptusedtooperatetheweatherdisplay.Wewillimporttheserialport,pywapi,andtime(fordelay)modulesfortheproject:

#!/usr/bin/envpython

importserial

importglob

importpprint

importpywapi

fromtimeimportsleep

Wewilldetermineandestablishconnectiontotheserialport.Thescan()functionidentifiesalltheserialportsavailableontheRaspberryPi:

#Establishserialportcommunication

defscan():

returnglob.glob('/dev/ttyS*')+glob.glob('/dev/ttyUSB*')+

glob.glob('/dev/ttyACM*')

sport_data=scan()

fornameinscan():

serialport=serial.Serial(name,9600)

sleep(5)

serialport.write(bytes("A",'ascii'))

sleep(1)

response=serialport.read()

if(response==b'A'):

sport=name

serialport.close()

break

seport=serial.Serial(sport,9600,timeout=45)

Page 197: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

5. Oncetheserialportshavebeenidentified,wetestthembysendingabyteAandawaitaresponse.WhenaresponsewiththebyteAisreceived,weidentifyandsavetheserialport.Afteridentification,wewillestablishaconnectionwiththeArduino.

6. Inthisproject,weareusingtheNOAAwebsitetoobtaintheweatherdata.Wehavetoidentifythecity’sweathercodetoobtainthecurrentlocation’sweatherstationcode.Thiscouldbesimplyobtainedbyenteringthezipcodeontheirwebsite.Forexample,theweatherstationcodeforChicagoisKORD.

WeatherstationforChicago,IL

Theweatherdataisobtainedasfollows:

result=pywapi.get_weather_from_noaa('KORD')

Thetemperaturedataisretrievedasfollows:

temperature=int(float(result['temp_f']))

Theretrieveddataiswrittentotheserialport:

temperature_string="S"+str(temperature)

#print(temperature_string)

seport.write(bytes(temperature_string,'ascii'))

Basedonthetemperaturedata,theRGBstrip,BlinkMcontroldata,and8x8matrixdataarewrittentotheArduino:

if(temperature>40):

seport.write(bytes("G",'ascii'))

sleep(5)

seport.write(bytes("P4",'ascii'))

sleep(5)

seport.write(bytes("M1",'ascii'))

sleep(5)

Wewillsettheweatherclocktopointataweatherforecastbasedonthedata

Page 198: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

obtained:

if(result['weather']=='LightSnow')or(result['weather']=='Snow')

or(result['weather']=='Flurries'):

seport.write(bytes("H",'ascii'))

sleep(5)

seport.write(bytes("T-2",'ascii'))

sleep(5)

7. Let’sreviewthecodeforthecontrolfromtheRaspberryPiandthecorrespondingacknowledgmentsignals.

ArduinoacknowledgementtocontrolsignalLetusreviewonthecontrolsignalandcontrolflowoftheweatherclock.

Controlflowfortheweatherclock

ThefollowingflowchartshowswhathappensintheArduinowhenacontrolcharacterisreceivedfromtheRaspberryPi.

Theweatherclockprogramflow

1. TheRaspberryPitriestoidentifytheArduinobysendingacharacterA.TheArduinorespondswithanacknowledgementcharacterA:

if(serial_read=='A'){

Serial.print("A");

}

2. ThisisafoolproofmechanismtoidentifyandestablishacommunicationwiththeweatherclockcontrollerfromtheRaspberryPi.

Temperaturedata

1. TheRaspberryPitemperaturedataissenttotheArduinowiththeletter/characterS.

Page 199: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Thereceiveddataisconvertedtoasignedintegerandpassedasanargumenttothe7-Segmentdisplaylibraries:

if(serial_read=='S'){

while(Serial.available()){

sb=Serial.read();

sevenseg_string[serInIndx]=sb;

serInIndx++;

temp=0;

}

temp=atoi(sevenseg_string);

memset(sevenseg_string,0,9);

}

2. WhenthecharacterSisreceived,wereadallthecharactersintothebuffersevenseg_string.Thestringisconvertedtoanintegerusingtheatoifunctionandstoredinthetempvariable.Thebufferisclearedattheendofthecycle.Thismethodtakessub-zerotemperaturesintoconsideration.

ControloftheRGBLEDstrip

1. TheindividualcolorsoftheRGBLEDarecontrolledindividuallyusingtheASCIIcharactersR,G,and,Brespectively.Eachcolorindicatesauniqueweathercondition,namely,blueindicatescoldweather,greenindicatesfairweatherconditions,andredcolorindicatesimpedingdangerinweatherconditions:

if(serial_read=='R'||serial_read=='G'||

serial_read=='B'){

color_bit=serial_read;

}

if(color_bit=='R'){

lightsequence_red();

}

elseif(color_bit=='G'){

lightsequence_green();

}

elseif(color_bit=='B'){

lightsequence_blue();

}

2. Whenthecharacterisreceived,thecorrespondinglightsequenceisturnedon.

Controlofstepperviaserialport

1. Earlier,wediscussedthecontrolofthesteppermotorusingapowerDarlingtondriverandthecontrolroutineforonefullrotation.Inthissection,wewilldiscusshowtocontrolthedirectionandthenumberofstepsbasedontheinputfromtheserialport.Inthisexample,theclockwisedirectionisindicatedby+,andcounterclockwisedirectionisindicatedby-.

Forexample,inordertomove45stepsinaclockwisedirection,thecommandwouldbe+45precededbytheletterP.Hence,itwouldbeP+45.Similarly,the

Page 200: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

counterclockwisedirectioncommandwouldbeP-45:

if(serial_read=='P'){

while(Serial.available())

{

sb=Serial.read();

serInString[serInIndx]=sb;

serInIndx++;

}

}

2. WeawaittheserialcharacterPandstoretherestofthestringinabuffer.Oncethedataisstoredinthebuffer,wewilldeterminewhetherthefirstcharacteris+or-.

TheASCIInumberforthe+signis43and45forthe-sign.Wecomparethefirstcharacterinthebufferandexecutethecommandaccordingly.SerialcommunicationsusuallytransmitASCIInumbersandhencethenumbersareconvertedintotheirdecimalequivalents:

if(serInString[0]==43){

intvar_serial=0;

for(serOutIndx=1;serOutIndx<serInIndx;serOutIndx++)

{

var_serial=var_serial*10+(serInString[serOutIndx]-48);

}

motorSpeed=20;

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

clockwise();

}

Weconvertthereceivedserialdataintotheirdecimalequivalentatthisstep:

var_serial=var_serial*10+(serInString[serOutIndx]-48);

Onceconverted,wemovethestepperforthedesirednumberofstepsineitherdirectionusingtheclockwise()andcounterclockwise()functions.

3. Wewantthesteppermotortoreachthehomepositioneverytimebeforepointingtoaparticularweathercondition.Thissystemisanopenloopandsoitisnecessarytomovethearrowtothehomepositionbeforepointingtothecurrentweathercondition.

NoteThesteppermotormovesinacounterclockwisedirectiontopointatallweatherconditionsandaclockwisedirectiontomovetowardsthehomeposition.

4. Hence,whentheletterHistransmittedviatheserialport,thearrowismovedtowardsthehomeposition:

if(serial_read=='H'){

reset_stepper();

lightsequence();

}

Page 201: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Thereset_stepper()functiontakescareofsettingthearrowtothehomeposition:

voidreset_stepper(void){

uint8_tval;

//Getthevaluefromthesensor

if(ReadByte(sensorAddr,0x0,&val)==0)

{

//ThesecondLSBindicatesifsomethingwasnotdetected,

i.e.,

//LO=objectdetected,HI=nothingdetected

while(val&0x2)

{

motorSpeed=20;

Serial.println("Nothingdetected");

if(ReadByte(sensorAddr,0x0,&val)==0){

clockwise();//Wekeepgoingclockwiseuntilthearrowis

detected

}

}

}

else

{

Serial.println("Failedtoreadfromsensor");

}

}

Inthereset_stepper()function,wewillexecutethesteppermotor’sclockwiseroutineuntiltheobjectisdetected.ThesensorreferencemanualmentionsthatanobjectisdetectedifthesecondLSBissettolow.Hence,thestepperrotatesintheclockwisedirectionuntilalowsignalisdetected.

Programmingtheweatherforecastposition

1. Intheprevioussection,wediscussedthesteppermotorcontrolviatheserialport.Sinceweareusingasteppermotor,itispossibletopointateachweatherforecastconditionbasedonapredeterminednumberofstepsfromthestep.So,wewilldeterminethenumberofstepsrequiredtopointateachweatherforecastconditionandprogramthesepositionsintotheflashmemoryoftheArduino.

WeshouldusethePROGMEMkeywordtostorethepositiondataintheflashmemoryoftheArduinosincetheyareaconstant:

constintmydata[6][2]PROGMEM={

1,10,

2,18,

3,28,

4,43,

5,54,

6,66};

Thenumbers1through6inthearraycorrespondtotheweatherforecast

Page 202: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

indicatorsstartinginthecounterclockwisedirection.Thesecondpositionindicatesthenumberofpositionsfromthehomepositiontopointtothatparticularweathercondition.ThecommandforindicatingweatherdataisprecededbytheletterT.Inordertopointtotheweatherforecast,Rain,thecommandwouldbeT-6.WhenacharacterTisreceived,westorethedatareceivedinabuffer.ItisconfirmedthatthesecondcharacterreceivedaftertheletterTisanumberbetween1and6.Wewillretrievethecorrespondingpositiondatafromtheflashmemoryusingthepgm_read_word_near()function.Oncethedataisretrieved,thesteppermotorcontrolroutineisexecutedforthedesirednumberofsteps.Nowwewillretrievethedatafromtheflashmemoryasfollows:

if(serial_read=='T'){

while(Serial.available())

{

sb=Serial.read();

serInString[serInIndx]=sb;

serInIndx++;

}

}

intvar_serial=serInString[1]-48;

serInIndx=0;

if(var_serial>0&&var_serial<=6)

{

steps=pgm_read_word_near(&mydata[(var_serial-1)][1]);

Serial.println(steps);

}

if(serInString[0]==45){

motorSpeed=20;

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

counterclockwise();

}

8x8matrixcontrol

WewillcontroltheLEDmatrixusingtheletterM.AsmileisdisplayedifM1isreceivedandafrownifM2isreceived:

if(serial_read=='M'){

sb=Serial.read();

if(sb-'0'==1){

set_display(smile_bmp);

}

elseif(sb-'0'==2){

set_display(frown_bmp);

}

}

BlinkMcontrol

TheBlinkMscriptisplayedwhenevertheletterPisreceived.TheletterPisfollowedbythescriptnumber.

Page 203: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

if(serial_read=='P'){

while(Serial.available())

{

sb=Serial.read();

serInString[serInIndx]=sb;

serInIndx++;

}

BlinkM_playScript(BlinkM_addr,serInString[0]-48,0,0);

}

Page 204: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthissection,wediscussedtheoverallcontroloftheweatherclockanditsinterfacetotheInternet.Wealsodiscussedtheinterfacingofthesensorsanddisplayingtheweatherdata.

Page 205: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 206: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,wediscussedinterfacinganArduinowiththeRaspberryPi.Thiswasfollowedbyanexampleofconstructingaweatherclock.WedemonstratedtheArduinoasalow-levelcontrollerthatinterfacesactuators,sensors,anddisplaydeviceswhiletheRaspberryPiisinterfacedwiththeInternet.Ihopeyouenjoyedtheproject!

Page 207: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 208: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisexample,thecitylocationwashard-codedintothePythonscript.Itispossibletodisplaytheweatherdatabasedonthezipcode/citylocation.Whatcouldtheinputdevicebe?Howcanthisbeachieved?

Page 209: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 210: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter4.ChristmasLightSequencerAsthenamesuggests,wewilldesignautomationandcontrolofChristmaslightsinourhomes.Wewilldecorateourhomeswithlightsforanyfestiveoccasionandworkonaprojectthatenablesustobuildfantasticprojects.Wewillbuildalocalservertocontrolthedevices.Wewillusetheweb.pyframeworktodesignthewebserver.We’dliketodedicatethischaptertothememoryofAaronSwartzwhowasthefounderoftheweb.pyframework.

Page 211: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthischapter,wewillinstallalocalwebserver-basedcontrolofGPIOpinsontheRaspberryPi.Wewillusethiswebserverframeworktocontrolitviaawebpage.

TheRaspberryPiontopofthetreeisjustanornamentfordecoration

Page 212: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Wecelebratefestiveoccasionsbydecoratingourhomes.ThedecorationsreflectourheartanditcanbeenhancedbyusingRaspberryPi.

NoteThisprojectinvolvesinterfacingAC-powereddevicestoRaspberryPi.Youshouldexerciseextremecautionwhileinterfacingthedevices,anditisstronglyrecommendedthatyousticktotherecommendeddevices.

Page 213: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesInthischapter,wewillworkonthefollowingaspects:

InterfaceoftheChristmastreelightsandotherdecorativeequipmenttotheRaspberryPiSetupthedigitally-addressableRGBmatrixInterfaceofanaudiodeviceSettingupthewebserverInterfacingdevicestothewebserver

Page 214: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistThischapterisbasedonabroadconcept.Youarefreetochoosedecorativeitemsofyourowninterest.Wechosetoshowthefollowingitemsfordemonstration:

Item EstimatedCost

Christmastree*1 30USD

Outdoordecoration(optional) 30USD

SantaClausfigurine*1 20USD

Digitallyaddressablestrip*1 30USDapproximately

PowerSwitchTail2fromAdafruitIndustries(http://www.adafruit.com/product/268) 25USDapproximately

ArduinoUno(anyvariant) 20–30USDapproximately

Page 215: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 216: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InterfacethedevicestotheRaspberryPiNoteItisimportanttoexercisecautionwhileconnectingelectricalappliancestotheRaspberryPi.Ifyoudon’tknowwhatyouaredoing,pleaseskipthissection.Adultsupervisionisrequiredwhileconnectingappliances.

Inthistask,wewilllookintointerfacingdecorativeappliances(operatedwithanACpowersupply)suchastheChristmastree.ItisimportanttointerfaceACappliancestotheRaspberryPiinaccordancewithsafetypractices.ItispossibletoconnectACappliancestotheRaspberryPiusingsolidstaterelays.However,iftheprototypeboardsaren’tconnectedproperly,itisapotentialhazard.Hence,weusethePowerSwitchTailIIsoldbyAdafruitIndustries.

NoteThePowerSwitchTailIIhasbeenratedfor110V.

AccordingtothespecificationsprovidedontheAdafruitwebsite,PowerSwitchTail’srelaycanswitchupto15Aresistiveloads.Itcanbecontrolledbyprovidinga3-12VDCsignal.WewilllookintocontrollingthelightsonaChristmastreeinthistask.

PowerSwitchTailII–imagesource:Adafruit.com

Page 217: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWehavetoconnectthePowerSwitchTailIItotheRaspberryPitotestit.ThefollowFritzingschematicshowstheconnectionoftheswitchtotheRaspberryPiusingPiCobbler.Pin25isconnectedtoin+,whilethein-pinisconnectedtotheGroundpinoftheRaspberryPi.

TheRaspberryPiconnectiontothePowerSwitchTailIIusingPiCobbler

ThePiCobblerbreakoutboardisconnectedtotheRaspberryPiasshowninthefollowingimage:

Page 218: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Inordertotestthedevice,therearetwooptionstocontrolthedevicetheGPIOPins

oftheRaspberryPi.Thiscanbecontrolledeitherusingthequick2wireGPIOlibraryorusingtheRaspiGPIOlibrary.

NoteThemaindifferencebetweenthequick2wiregpiolibraryandtheRaspiGPIOlibraryisthattheformerdoesnotrequirethatthePythonscripttoberunwithrootuserprivileges(tothosewhoarenotfamiliarwithrootprivileges,thePythonscriptneedstoberunusingsudo).InthecaseoftheRaspiGPIOlibrary,itispossibletosettheownershipofthepinstoavoidexecutingthescriptasroot.Thisisleftassomehomeworkforyou.

2. Oncetheinstallationiscomplete,let’sturnon/offthelightsonthetreewithathreesecondinterval.Thecodeforitisgivenasfollows:

#Importtherpi.gpiomodule.

importRPi.GPIOasGPIO

#Importdelaymodule.

fromtimeimportsleep

#SettoBCMGPIO

GPIO.setmode(GPIO.BCM)

#BCMpin25istheoutput.

GPIO.setup(25,GPIO.OUT)

#InitialisePin25tolow(false)sothattheChristmastreelightsare

switchedoff.

GPIO.output(25,False)

while1:

GPIO.output(25,False)

sleep(3)

GPIO.output(25,True)

sleep(3)

Intheprecedingexample,wewillgetstartedbyimportingtheraspi.gpiomoduleandthetimemoduletointroduceadelaybetweenturningon/offthelights:

importRPi.GPIOasGPIO

#Importdelaymodule

fromtimeimportsleep

WeneedtosetthemodeinwhichtheGPIOpinsarebeingused.Therearetwomodes,namelytheboard’sGPIOmodeandtheBCMGPIOmode(moreinformationavailableonhttp://sourceforge.net/p/raspberry-gpio-python/wiki/).TheformerreferstothepinnumbersontheRaspberryPiboardwhilethelatterreferstothepinnumberfoundontheBroadcomchipset.Inthisexample,wewilladopttheBCMchipset’spindescription.Wewillsetthepin25tobeanoutputpinandsetittofalsesothattheChristmastreelightsareswitchedoffatthestartoftheprogram:

Page 219: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GPIO.setup(25,GPIO.OUT)

GPIO.output(25,False)

Intheprecedingroutine,weareswitchingoffthelightsandturningthembackonwithathree-secondinterval:

while1:

GPIO.output(25,True)

sleep(3)

GPIO.output(25,False)

sleep(3)

3. Whenthepin25issettohigh,thedeviceisturnedon,anditisturnedoffwhenthepinissettolowwithathree-secondinterval.

ConnectingmultipleappliancestotheRaspberryPiLet’sconsiderascenariowherewehavetocontrolmultipleappliancesusingtheRaspberryPi.

Itispossibletoconnectamaximumof15devicestotheGPIOinterfaceoftheRaspberryPi.(Thereare17GPIOpinsontheRaspberryPiModelB,buttwoofthosepins,namelyGPIO14and15,aresettobeUARTinthedefaultstate.Thiscanbechangedafterstartup.ItisalsopossibletoconnectaGPIOexpandertoconnectmoredevicestoRaspberryPi.)

Inthecaseofappliancesthatneedtobeconnectedtothe110VACmains,itisrecommendedthatyouusemultiplepowerswitchtailstoadheretosafetypractices.

Inthecaseofdecorativelightsthatoperateusingabattery(forexample,atwo-feetChristmastree)orappliancesthatoperateatlowvoltagelevelsof12VDC,asimpletransistorcircuitandarelaycanbeusedtoconnectthedevices.Asamplecircuitisshowninthefigurethatfollows:

Atransistorswitchingcircuit

Page 220: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Intheprecedingcircuit,sincetheGPIOpinsoperateat3.3Vlevels,wewillconnecttheGPIOpintothebaseoftheNPNtransistor.Thecollectorpinofthetransistorisconnectedtooneendoftherelay.

ThetransistoractsasaswitchandwhentheGPIOpinissettohigh,thecollectorisconnectedtotheemitter(whichinturnisconnectedtotheground)andhence,energizestherelay.

Relaysusuallyhavethreeterminals,namely,thecommonterminal,NormallyOpenTerminal,andNormallyClosedTerminal.Whentherelayisnotenergized,thecommonterminalisconnectedtotheNormallyClosedTerminal.Uponenergization,theNormallyOpenTerminalisconnectedtothecommonterminal,thusturningontheappliance.

Thefreewheelingdiodeacrosstherelayisusedtoprotectthecircuitfromanyreversecurrentfromtheswitchingoftherelays.

Thetransistorswitchingcircuitaidsinoperatinganappliancethatoperatesat12VDCusingtheRaspberryPi’sGPIOpins(theGPIOpinsoftheRaspberryPioperateat3.3Vlevels).TherelayandthetransistorswitchingcircuitenablescontrollinghighcurrentdevicesusingtheRaspberryPi.

Itispossibletouseanarrayofrelays(asshowninthefollowingimage)andcontrolanarrayofdecorativelightingarrangements.ItwouldbecooltocontrollightingarrangementsaccordingtothemusicthatisbeingplayedontheRaspberryPi(aprojectideafortheholidays!).

Therelayboard(again,showninthefollowingimage)operatesat5VDCandcomeswiththecircuitrydescribedearlierinthissection.Wecanmakeuseoftheboardbypoweringuptheboardusinga5VpowersupplyandconnectingtheGPIOpinstothepinshighlightedinred.Asexplainedearlier,therelaycanbeenergizedbysettingtheGPIOpintohigh.

Arelayboard

Page 221: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthissection,wediscussedcontrollingdecorativelightsandotherholidayappliancesbyrunningaPythonscriptontheRaspberryPi.Let’smoveontothenextsectiontosetupthedigitallyaddressableRGBLEDstrip!

Page 222: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 223: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettingupthedigitallyaddressableRGBmatrixInthissection,wewilltalkaboutsettingupoptionsavailableforLEDlighting.WewilldiscusstwotypesofLEDstrips,namelyanalogRGBLEDstripsanddigitally-addressableRGBLEDstrips.

Aswediscussedthefirstoneindetailinthepreviouschapter,wewillskipitandmoveontothesecondkind.AsampleofthedigitallyaddressableRGBLEDstripisshownintheimagethatfollows:

Page 224: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffAsthenameexplains,digitally-addressableRGBLEDstripsarethosewherethecolourofeachRGBLEDcanbeindividuallycontrolled(inthecaseoftheanalogstrip,thecolourscannotbeindividuallycontrolled).

WherecanIbuythem?TherearedifferentmodelsofthedigitallyaddressableRGBLEDstripsbasedondifferentchipssuchasLPD6803,LPD8806,andWS2811.Thestripsaresoldinareelofamaximumlengthof5meters.SomesourcestobuytheLEDstripsincludeAdafruit(http://www.adafruit.com/product/306)andBanggood(http://www.banggood.com/5M-5050-RGB-Dream-Color-6803-IC-LED-Strip-Light-Waterproof-IP67-12V-DC-p-931386.html)andtheycostabout50USDforareel.Somevendors(includingAdafruit)selltheminstripsofonemeteraswell.

Page 225: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersLet’sreviewhowtocontrolandusethesedigitally-addressableRGBLEDstrips.

Howdoesitwork?MostdigitallyaddressableRGBstripscomewithterminalstopoweringtheLEDs,aclockpin,andadatapin.TheLEDsareseriallyconnectedtoeachotherandarecontrolledthroughtheSPI(SerialPeripheralInterface).

TheRGBLEDsonthestriparecontrolledbyachipthatlatchesdatafromthemicrocontroller/RaspberryPiontotheLEDswithreferencetotheclockcyclesreceivedontheclockpin.

InthecaseoftheLPD8806strip,eachchipcancontrolabout2LEDs.ItcancontroleachchanneloftheRGBLEDusingaseven-bitPWMchannel.MoreinformationonthefunctionoftheRGBLEDstripisavailableathttps://learn.adafruit.com/digital-led-strip.

ItispossibletobreaktheLEDstripintoindividualsegments.Eachsegmentcontainsabout2LEDs,andAdafruitindustrieshasprovidedanexcellenttutorialtoseparatetheindividualsegmentsoftheLEDstrip(https://learn.adafruit.com/digital-led-strip/advanced-separating-strips).

LightinguptheRGBLEDstripTherearetwowaysofconnectingtheRGBLEDstrip.TheycaneitherbeconnectedtoanArduinoandcontrolledbytheRaspberryPiorcontrolledbytheRaspberryPidirectly.

AnArduino-basedcontrol

NoteItisassumedthatyouarefamiliarwithprogrammingmicrocontrollers,especiallythoseontheArduinoplatform.

InProject3,TheArduinoRaspberryPiInterface,wediscussedconnectingananalogRGBstripusinganArduino.WeusedcontrolcommandstochangethecolorofthestripthroughtheserialportofArduino.Similarly,wecanconnecttheRGBstriptotheArduino.

Page 226: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AnArduinoconnectiontothedigitallyaddressableinterface

Intheprecedingfigure,theLEDstripispoweredbyanexternalpowersupply.(Thetinygreenadapterrepresentstheexternalpowersupply.TherecommendedpowersupplyfortheRGBLEDstripis5V/2ApermeterofLEDs(whilewritingthischapter,wegotanoldcomputerpowersupplytopoweruptheLEDs).TheClockpins(theCIpin)andtheDatapins(DI)ofthefirstsegmentoftheRGBstripareconnectedtothepinsD2andD3respectively.(WearedoingthissincewewilltesttheexamplefromAdafruitindustries.Theexampleisavailableathttps://github.com/adafruit/LPD8806/tree/master/examples.)

SincetheRGBstripconsistsofmultiplesegmentsthatareseriallyconnected,theClockOut(CO)andDataOut(DO)pinsofthefirstsegmentareconnectedtotheClockIn(CI)andDataIn(DI)pinsofthesecondsegmentandsoon.

Let’sreviewtheexample,strandtest.pde,totesttheRGBLEDstrip.TheexamplemakesuseofSoftwareSPI(BitBangingoftheclockanddatapinsforlightingeffects).ItisalsopossibletousetheSPIinterfaceoftheArduinoplatform.(Refertothisbook’swebsiteforanexample.)

Intheexample,weneedtosetthenumberofLEDsusedforthetest.Forexample,weneedtosetthenumberofLEDsonthestripto64foratwo-meterstrip.Hereishowtodothis:

1. Thefollowinglineneedstobechanged:

intnLEDs=64;

2. Oncethecodeisuploaded,theRGBmatrixshouldlightup,asshowninthisimage:

8x8RGBmatrixlitup

3. Let’squicklyreviewtheArduinosketchfromAdafruit.Wewillgetstartedbysetting

Page 227: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

upanLPD8806objectasfollows:

//nLEDSrefertonumberofLEDsinthestrip.Thiscannotexceed160

LEDs/5mduetocurrentdraw.

LPD8806strip=LPD8806(nLEDs,dataPin,clockPin);

4. Inthesetup()sectionoftheArduinosketch,wewillinitializetheRGBstripasfollows:

//StartuptheLEDstrip

strip.begin();

//Updatethestrip,tostarttheyareall'off'

strip.show();

5. Assoonasweenterthemainloop,scriptssuchascolorChaseandrainbowareexecuted.

6. WecanmakeuseofthisArduinosketchtoimplementserialportcommandstocontrolthelightingscriptsusingtheRaspberryPi.

NoteThistaskmerelyprovidessomeideasofconnectingandlightinguptheRGBLEDstrip.YoushouldfamiliarizeyourselfwiththeworkingprinciplesoftheRGBLEDstrip.

ThereareseveralexamplesavailableforcontrollingtheLEDstripusingtheArduinoplatform.Afewareavailableonthewebsiteofthisbook.

NoteTheRaspberryPihasanSPIport,andhence,itispossibletocontroltheRGBstripdirectlyfromtheRaspberryPi.Refertothisbook’swebsiteforsomeexamples.

Page 228: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthissection,wereviewedoptionsfordecorativelightingandcontrollingthemusingtheRaspberryPiandArduino.

Page 229: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 230: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InterfaceofanaudiodeviceInthistask,wewillworkoninstallingMP3andWAVfileaudioplayertoolsontheRaspbianoperatingsystem.

Page 231: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheRaspberryPiisequippedwitha3.5mmaudiojackandthespeakerscanbeconnectedtothatoutput.Inordertogetstarted,weinstalltheALSAutilitiespackageandacommand-linemp3player:

sudoapt-getinstallalsa-utils

sudoapt-getinstallmpg321

Page 232: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersInordertousethealsa-utilsormpg321players,wehavetoactivatetheBCM2835’ssounddriversandthiscanbedoneusingthemodprobecommand:

sudomodprobesnd_bcm2835

Afteractivatingthedrivers,itispossibletoplaytheWAVfilesusingtheaplaycommand(aplayisacommand-lineplayeravailableaspartofthealsa-utilspackage):

aplaytestfile.wav

AnMP3filecanbeplayedusingthempg321command(acommand-lineMP3player):

mpg321testfile.mp3

NoteIntheprecedingexamples,thecommandswereexecutedinthedirectorywheretheWAVfileortheMP3filewaslocated.IntheLinuxenvironment,itispossibletostopplayingafilebypressingCTRL+C.

Page 233: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWewereabletoinstallsoundutilitiesinthissection.Later,wewillusetheinstalledutilitiestoplayaudiofromawebpage.

ItispossibletoplaythesoundfilesontheRaspberryPiusingthemoduleavailableinPython.Someexamplesinclude:Snacksoundtoolkit,Pygame,andsoon.

Page 234: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 235: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InstallingthewebserverInthissection,wewillinstallalocalwebserveronRaspberryPi.TherearedifferentwebserverframeworksthatcanbeinstalledontheRaspberryPi.TheyincludeApachev2.0,Boost,theRESTframework,andsoon.

Page 236: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffAsmentionedearlier,wewillbuildawebserverbasedontheweb.pyframework.Thissectionisentirelyreferencedfromweb.pytutorials(http://webpy.github.io/).Inordertoinstallweb.py,aPythonmoduleinstallersuchaspiporeasy_installisrequired.Wewillinstallitusingthefollowingcommand:

sudoapt-getinstallpython-setuptools

Page 237: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersTheweb.pyframeworkcanbeinstalledusingtheeasy_installtool:

sudoeasy_installweb.py

Oncetheinstallationiscomplete,itistimetotestitwithaHelloWorld!example.

WewillopenanewfileusingatexteditoravailablewithPythonIDLEandgetstartedwithaHelloWorld!examplefortheweb.pyframeworkusingthefollowingsteps:

1. Thefirststepistoimporttheweb.pyframework:

importweb

2. Thenextstepisdefiningtheclassthatwillhandlethelandingpage.Inthiscase,itisindex:

urls=('/','index')

3. WeneedtodefinewhatneedstobedonewhenonetriestoaccesstheURL.WewillliketoreturntheHelloworld!text:

classindex:

defGET(self):

return"Helloworld!"

4. Thenextstepistoensurethatawebpageissetupusingtheweb.pyframeworkwhenthePythonscriptislaunched:

if__name__=='__main__':

app=web.application(urls,globals())

app.run()

5. Wheneverythingisputtogether,thefollowingcodeiswhatwe’llsee:

importweb

urls=('/','index')

classindex:

defGET(self):

return"Helloworld!"

if__name__=='__main__':

app=web.application(urls,globals())

app.run()

6. WeshouldbeabletostartthewebpagebyexecutingthePythonscript:

pythonhelloworld.py

WeshouldbeabletolaunchthewebsitefromtheIPaddressoftheRaspberryPi.Forexample,iftheIPaddressis10.0.0.10,thewebpagecanbeaccessedathttp://10.0.0.10:8080anditdisplaysthetextHelloworld.Yay!

Page 238: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AHelloworld!exampleusingtheweb.pyframework

Page 239: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–missiondebriefingWebuiltasimplewebpagetodisplaytheHelloworldtext.Inthenexttask,wewillbeinterfacingtheChristmastreeandotherdecorativeappliancestoourwebpagesothatwecancontrolitfromanywhereonthelocalnetwork.

ItispossibletochangethedefaultportnumberforthewebpageaccessbylaunchingthePythonscriptasfollows:

pythonhelloworld.py1234

Now,thewebpagecanbeaccessedathttp://<IP_Address_of_the_Pi>:1234.

Page 240: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 241: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InterfacingthewebserverInthissection,wewilllearntointerfaceonedecorativeapplianceandaspeaker.WewillcreateaformandbuttonsonanHTMLpagetocontrolthedevices.

Page 242: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInthistask,wewillreviewthecode(availablealongwiththischapter)requiredtointerfacedecorativeappliancesandlightingarrangingtoawebpageandcontrolledoveralocalnetwork.Let’sgetstartedwithopeningthefileusingatexteditingtool(PythonIDLE’stexteditororanyothertexteditor).

Page 243: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillimportthefollowingmodulestogetstartedwiththeprogram:

importweb

fromwebimportform

importRPi.GPIOasGPIO

importos

2. TheGPIOmoduleisinitialized,theboardnumberingisset,andensurethatallappliancesareturnedoffbysettingtheGPIOpinstoloworfalseanddeclareanyglobalvariables:

#Setboard

GPIO.setmode(GPIO.BCM)

#Initializethepinsthathavetobecontrolled

GPIO.setup(25,GPIO.OUT)

GPIO.output(25,False)

3. Thisisfollowedbydefiningthetemplatelocation:

urls=('/','index')

render=web.template.render('templates')

4. Thebuttonsusedinthewebpagearealsodefined:

appliances_form=form.Form(

form.Button("appbtn",value="tree",class_="btntree"),

form.Button("appbtn",value="Santa",class_="btnSanta"),

form.Button("appbtn",value="audio",class_="btnaudio")

)

Inthisexample,threebuttonsareused,avalueisassignedtoeachbuttonalongwiththeirclass.Inthisexample,weareusingthreebuttonsandthenameisappbtn.Avalueisassignedtoeachbuttonthatdeterminesthedesiredactionwhenabuttonisclicked.Forexample,whenaChristmastreebuttonisclicked,thelightsneedtobeturnedon.Thisactioncanbeexecutedbasedonthevaluethatisreturnedduringthebuttonpress.

5. Thehomepageisdefinedintheindexclass.TheGETmethodisusedtorenderthewebpageandPOSTforbuttonclickactions.

classindex:

defGET(self):

form=appliances_form()

returnrender.index(form,"RaspberryPiChristmaslights

controller")

defPOST(self):

userData=web.input()

ifuserData.appbtn=="tree":

globalstate

state=notstate

elifuserData.appbtn=="Santa":

#dosomethinghereforanotherappliance

Page 244: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

elifuserData.appbtn=="audio":

os.system("mpg321/home/pi/test.mp3")

GPIO.output(25,state)

raiseweb.seeother('/')

InthePOSTmethod,weneedtomonitorthebuttonclicksandperformanactionaccordingly.Forexample,whenthebuttonwiththetreevalueisreturned,wecanchangetheBooleanvalue,state.ThisinturnswitchesthestateoftheGPIOpin25.Earlier,weconnectedthepowertailswitchtopin25.

6. Theindexpagefilethatcontainstheformandbuttonsisasfollows:

$defwith(form,title)

<html>

<head>

<title>$title</title>

<linkrel="stylesheet"type="text/css"href="/static/styles.css">

</head>

<body>

<P><center><H1>ChristmasLightsController</H1></center>

<br/>

<br/>

<formclass="form"method="post">

$:form.render()

</form>

</body>

</html>

7. Thestylesofthebuttonsusedonthewebpagearedescribedasfollowsin‘styles.css‘:

form.btntree{

margin-left:200px;

margin-right:auto;

background:transparenturl("images/topic_button.png")no-repeattop

left;

width:186px;

height:240px;

padding:0px;

position:absolute;

}

form.btnSanta{

margin-left:600px;

margin-right:auto;

background:transparenturl("images/Santa-png.png")no-repeattop

left;

width:240px;

height:240px;

padding:40px;

position:absolute;

}

body{background-image:url('bg-snowflakes-3.gif');}

8. Thewebpagelookslikewhatisshowninthefollowingfigure:

Page 245: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Yay!WehaveaChristmaslightscontrollerinterface.

Page 246: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWehavewrittenasimplewebpagethatinterfacesaChristmastreeandRGBtreeandplaysMP3files.Thisisagreatprojectforaholidayweekend.

ItispossibletoviewthiswebpagefromanywhereontheInternetandturntheseapplianceson/off(FansoftheTVshowBigBangTheorymightlikethisidea.Astep-by-stepinstructiononsettingitupisavailableathttp://www.everydaylinuxuser.com/2013/06/connecting-to-raspberry-pi-from-outside.html).

Page 247: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 248: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,wehaveaccomplishedthefollowing:

InterfacingtheRGBmatrixInterfacingACappliancestoRaspberryPiDesignofawebpageInterfacingdevicestothewebpage

WeusedexamplestodemonstratethecapabilitiesofenhancingthefestivedecorationusingtheRaspberryPi.Itisdefinitelypossibletoenhancethisprojectusingourcreativity.

Page 249: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ReferencesYoucanfindweb.pytutorialsathttp://webpy.github.io/docs/0.3/tutorial.

ThePythonPit–DriveyourRaspberryPiwithamobilephone,MagPiFebruary2013edition,page34,(http://www.themagpi.com/issue/issue-9/article/the-python-pit-drive-your-raspberry-pi-with-a-mobile-phone/)

Page 250: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 251: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter5.InternetofThingsExample–AnE-mailAlertWaterFountainInthisproject,wewillworkonbuildingawaterfountainenabledbyRaspberryPi.Wewillalsodecoratethefountainwithlightingthatcanbecontrolledwiththehelpofawebinterface.Thisfountainwillenableustoreceiveemailalertsaswell.ItisagreatexampletoenabletheInternetofThingsusingtheRaspberryPi.

Page 252: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingWewilllearntobuildafountainandcontrolitusingaRaspberryPi.WewillbuildawebpagebasedontheFlaskframeworkandtrytocontrolthelightingarrangementonthefountain.Wewilldemonstratehowadecorativepiece,suchasatabletopfountain,canbeusedtoreceivee-mailortweetalerts.

FollowingisanimagethatshowsafountaincontrolledbytheRaspberryPi:

Page 253: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Tabletopfountainsaresoothingineffectandplayagreatroleinrelievingstress.ItisfuntohaveaRaspberryPiplayagreatroleincontrollingourbehavior.Italsoenablesustoremindourselvestocheckoure-mails/Twitterfeedsonaregularbasis.

Page 254: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesInthisproject,wewillbuildthetabletopfountaininthefollowingsteps:

AssemblingthefountainInstallationoftheFlaskframeworkandinterfacingthefountainControllingRGBLEDsfromthewebpageSettingupe-mailalertsforthefountain

Page 255: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistAtabletopfountaincanbebuiltinseveralways,anditispossibletoincludealotofdecorativepiecestoenhancetheappeal.TheitemslistedinthefollowingtableincludeabasiclistofitemstodemonstrateafountaincontrolledbyaPi:

Item Cost(approximate)

ADIYfountainkit,includingcontainer,pebbles,andsoon(fromhomeimprovementcompaniessuchasHomeDepotoraDIYproductsuppliersuchasAmericanScienceandSurplus). 30USD

Asubmersiblepump(source:sameastheprecedingkit). 10USD

AdigitallyaddressableRGBLEDstrip(AdafruitorBanggood.LinktosourcesofLEDprovidedinthepreviousproject).

16.00/meterUSD

Awoodendowelrod(source:anyhobbystore). 2.00USD

Anacrylicsheet(source:anyhomeimprovementstore). 12.00USD

Mountingaccessories(scotchtapeandsoon). 10.00USD

Inthistask,wewillgetstartedwithassemblingthewaterfountainforourproject.Thefountainassemblyisasimplethree-stepprocess.Thereareseveralresourcesavailableonlinetobuildadesktopfountainusingrawmaterialsavailableathome(asomewhatsimpletutorialonbuildingatabletopfountainusingasubmersiblefromapetstore:http://www.instructables.com/id/Table-Fountain/).Wewilllookintoanexampleusinganoff-the-shelfDIYfountainkitinthisstep.

Page 256: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffIfthereaderisnotabletogainaccesstoaDIYfountainkit,thefollowingitemsarerequired:

Abasin(preferablyopaquesothatitdiffuseslight)Afountain/submersiblepumpfromapetshopPebblesandgravelDecorativeaccessoriesavailablefromaquariums

Theseitemscouldbepurchasedfromahobbyshoporanaquariumsuppliesstore.

Page 257: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheDIYtabletopfountainkitcomeswithabasinthathasaprovisiontorunthe

fountainpump’scableoutofthebasinthroughasealedoutlet.

Abasinwithasealedelectricaloutlet

2. Next,wewillplacethefountainpumpinsidethebasin.

Page 258: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Fountainpumptobeplacedinsidethebasin

3. Wewillnowcoverthepumpwithacoverandplaceadecorativepot.

Fountainpumpcoveredwithadecorativepot

4. Wecanfillthesidesofthepumpwithgravel,pebbles,smallpiecesofrock,andotherdecorativeaccessories.Wethenturnonthepumpandtestthewaterflowtomake

Page 259: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

surethatwedon’tspillwaterandmakeamess.

Afountainwithdecorativeaccessories

5. We’llwrapthefountainwithadigitallyaddressableRGBLEDstripandwearedonewithassemblingthefountainwhenwepowerthefountainalongwiththeRGBLEDs.

Page 260: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AwaterfountainstrappedwithadigitallyaddressableRGBLED

Page 261: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthefirststep,wefinishedassemblingthefountainandtheRGBLEDstrip.Wewillmoveontoinstallawebframeworktoimplementlightingcontrolfortheframework,whichwecanchangebasedonourneeds.

Page 262: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 263: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InstallationoftheFlaskframeworkInthistask,wewillinstalltheFlaskframeworkontheRaspberryPiandcompleteatestwebpageontheRaspberryPi.WewillusetheFlaskframeworktocontroltheRGBLEDstrip.

Page 264: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInthepreviousprojects,weinstalledpythonmoduleinstallerssuchaspiporeasy_install.Ifeitherofthesetoolsisn’tinstalled,theycanbeinstalledbyexecutingthefollowingcommand:

sudoapt-getinstallpython-pip

Alternatively,youcanusethefollowingcommand:

sudoapt-getinstallpython-setuptools.

Next,wewillworkoninstallingtheFlaskframeworkandthefirstexample.

Page 265: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheFlaskframeworkisinstalledusingthefollowingcommand:

sudoeasy_installflask

2. Oncetheinstallationiscomplete,wewilluseanexampleavailablefromtheFlaskframeworkdocumentation(http://flask.pocoo.org/docs/0.10/quickstart/#quickstart)andcreateaPythonscript(usingPythonIDLE’seditor):

fromflaskimportFlask

app=Flask(__name__)

@app.route("/")

defhello():

return"HelloWorld!"

if__name__=="__main__":

app.run()

3. WhenweexecutethesavedfileandexecutethePythonscript,thewebserverislaunchedlocallyontheRaspberryPi:

pythonhelloworld.py

*Runningon

http://127.0.0.1:5000/

4. ThewebserverisonlyvisibletotheRaspberryPiandawebpage(webaddress:http://127.0.0.1:5000)islaunchedontheRaspberryPi’sbrowser,whichwillshowthetextHelloWorld!.

AnHelloWorldexampleontheFlaskframework-basedwebserver

5. Inordertomakethewebservervisibletoalldevicesonthelocalnetwork,weneedtochangethefollowinglineinthePythonscript:

app.run('0.0.0.0')

Page 266: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wearedoneinstallingtheFlaskframeworkforcontrollingtheframework.Wewillmoveontothenexttasktosetupthings.

Page 267: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 268: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ControllingRGBLEDsfromawebpageInthistask,wewilllearnhowtocontroltheRGBLEDsfromawebpage.WewillusethedigitallycontrolledRGBLEDstripfromAdafruitIndustries.WewillinterfaceacolorpickerandsetthecoloroftheRGBstrip.Thecolorpickerwheelwasborrowedfromcircadianlightingproject,ChrisFane,distributedunderMITlicense.(https://github.com/rasathus/circadianLighting).Wewillmodifythiscodesampletosuitourneeds.We’llalsousetheLPD8806librarywrittenbyAdamHaile,distributedunderGPLv3license.(https://github.com/adammhaile/RPi-LPD8806.git).

Page 269: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffSinceweareusingthedigitallyaddressableRGBLEDstrip,weneedtoenabletheSPIdriversontheRaspberryPi.

NoteEnablingofSPIdriversisnotnecessaryiftheyouhaveinstalledOccidentalisinProject2,ARaspberryWebIDEExample.

Thefollowingfileneedstobemodified:/etc/modprobe.d/raspi-blacklist.conf.

Theblacklistspi-bcm2708lineneedstobecommentedout(adda#atthestartoftheline).Thenwegetthedriversworkingbyexecutingthefollowingcommand:

sudomodprobespi_bcm2708

TheSPIdevicescanbefoundlistedinthe/devdirectory:

SPIdeviceslistedinthedirectory

Page 270: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheRaspberryPineedstobeconnectedtotheSPIinterfaceoftheRaspberryPi.The

RGBLEDstriphastobepoweredbya5VDCadapter.TheclockpinCIneedstobeconnectedtotheclockpinoftheRaspberryPi(pin14,SCKpinoftheRaspberryPi).

TheclockpinCIneedstobeconnectedtotheclockpinoftheRaspberryPi(pin14oftheGPIOheader,SCKpinoftheRaspberryPi).ThedatapinDI(DataIn)needstobeconnectedtotheMOSIpin(pin12oftheGPIOheader)oftheRaspberryPi.TheGND(groundpin)oftheRGBLEDstripneedstobeconnectedtotheGND(groundpin)oftheGPIOheaderoftheRaspberryPi.

ConnectingtheRGBLEDStriptotheRaspberryPiusingaPiCobbler

2. Inordertocontrolthelightingarrangement,let’smakeuseoftheCircadianlightingproject’sPythonscriptandAdamHaile’sLPD8806library.WewillgetstartedbyimportingtheFlaskframeworkandtheLPD8806library.WewillinitializetheLPD8806librarybysettingthenumberofdigitallyaddressableRGBLEDsusedinthisproject:

num=64

led=LEDStrip(num)

Thecircadianlightingproject(http://rasathus.blogspot.com/2013/02/nasa-style-circadian-lighting-wrap-up.html)usesacolorpicker(basedonRaphael.js)andacolorissetonmouseclick.TheclicksonthecolorpickerwheelareconvertedintoRGBvaluesasfollows:

rgb_array=[0,0,0]

HEX='0123456789abcdef'

HEX2=dict((a+b,HEX.index(a)*16+HEX.index(b))forainHEXfor

binHEX)

defrgb(triplet):

triplet=triplet.lower()

rgb_array[0]=HEX2[triplet[0:2]]

rgb_array[1]=HEX2[triplet[2:4]]

rgb_array[2]=HEX2[triplet[4:6]]

return

(HEX2[triplet[0:2]],HEX2[triplet[2:4]],HEX2[triplet[4:6]])

Page 271: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

deftriplet(rgb):

returnformat((rgb[0]<<16)|(rgb[1]<<8)|rgb[2],'06x')

Wheneveraclickisdetected,thepostedhexvaluesfromthewebserveraredetectedasfollows:

@app.route('/set/<hex_val>',methods=['GET','POST'])

defsend_command(hex_val):

rgb_val=rgb(hex_val)

3. TheRGBvaluesarepassedtoLPD8806viatheRaspberryPi’sSPIinterface:

led.fill(Color(rgb_val[0],rgb_val[1],rgb_val[2],0.98))

led.update()

4. Now,whenweexecutethescriptavailablealonginthewebserversamplefolder,weshouldbeabletolaunchawebserverthatwilldisplayacolourpickerasshowninthefollowingdiagram:

Aflaskframework-basedRGBinterface

Page 272: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wefinishedsettingupthewebserverthatcontrolsthefountain.Inthenexttask,wewillreviewsettingupe-mailalertsthroughcolourchangesonthefountain.

ItispossibletocontrolthelightsofthefountainbasedonasongbeingplayedontheRaspberryPi.Howcanthisbeachieved?Visitthisbook’swebsiteforsomeclues.

Page 273: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 274: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Setupofthee-mailalertsinthefountainInthistask,wewillreviewsettingupe-mailalertsfromGmailaccounts.WecanblinkanLED(asshowninthisstep)orflashtheRGBLEDstrip(thishastobeexecutedbythereader)whenane-mailofaspecificcategoryisreceived(forexample,worke-mail).

Page 275: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillgetstartedbyinstallingthepython-feedparsertool.Googleprovidesaread-onlyinboxfeedandwewillmakeuseofthefeedparsermoduletodeterminewhetherwereceivedanynewe-mails.

sudoapt-getinstallpython-feedparser

Page 276: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Inordertologinandparsethroughthee-mailfeed,wegetstartedbyimportingthe

feedparsermodule:

importsys

importfeedparser

2. Wewilldefinethevariables,includingtheGmailusernameandpassword(changedtogenericnamesbelow)alongwiththefunctionthatretrievesallunreade-mails.Refertothefollowingexample:

NoteInthisexample,wearejustretrievingthecountofanynewunreade-mails.Itispossibletoparseandidentifye-mailswithspecificlabels.Wewillleavethattothereader.Formoreinformation,refertohttps://developers.google.com/gmail/gmail_inbox_feed.

newEmail=""

username="[email protected]"

password="password"

proto="https://"

server="mail.google.com"

path="/gmail/feed/atom"

defmail():

email=

int(feedparser.parse(proto+username+":"+password+"@"+server+path)

["feed"]["fullcount"])

returnemail

TheprecedingfunctionhasbeenborrowedfromtheWonderHowTowebsite(http://null-byte.wonderhowto.com/how-to/make-gmail-notifier-python-0132845/).Let’ssavethisfunctioninaseparatefileandtrytocallitfromanotherfile.Forexample,thefunctionhasbeensavedinafilecalledparser.py.

3. Now,wewillimporttheparsermodulebyopeninganotherfileasamoduleandimplementthee-mailnotifier.Inthisfile,wewillblinkanLEDwhenthereisanewe-mail.WewillstartbyimportingtheparsermoduleandRPi.GPIO:

importparser

importtime

importRPi.GPIOasgpio

Wewillgetstartedbysettingtheoutputpinsforthee-mailnotifierexample:

gpio.setwarnings(False)

gpio.setmode(gpio.BCM)

gpio.setup(17,gpio.OUT)

Now,we’llcheckfornewe-mailsandblinkanLEDifthereisanunreade-mail:

whileTrue:

Page 277: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

mail=parser.mail()#checkforemail

count=0

ifmail>0:#printfornewemails

print(mail)

print("newemails\n")

whilecount<10:

count+=1

gpio.output(17,gpio.HIGH)#blinkLEDiftherearenewemails

time.sleep(1)

gpio.output(17,gpio.LOW)

time.sleep(1)

gpio.output(17,gpio.LOW)#setLEDtolow

else:

time.sleep(10)#repeatcyclefor10seconds

TheLEDneedstobeconnectedasshowninthefollowingfigure:

ARaspberryPie-mailnotifier–SchematiccreatedwithFritzing,RaspberryPiLibrary.Courtesy:Adafruit

NoteInthistask,wejustmadeanLEDblinkwhenanewe-mailisreceived.Youshouldtryto

Page 278: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

importtheLPD8806moduleandflashtheRGBLEDstrip.

Page 279: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wecompletedthesetupofthee-mailalertsaswellasauserinteractionelementofblinkinganLED.Thisbringsustotheendoftheassemblyandsetupofthefountain.

Page 280: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 281: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,weassembledafountain,awebserverframework,controlledtheRGBLEDs,andsetupe-mailalerts.Theyshouldlookprettyaccordingtotheuser’screativity.

Page 282: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 283: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisproject,wesetupe-mailalertswiththedisplay.IsitpossibletosetTwitteralerts?

Page 284: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 285: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter6.RaspberryPiasaPersonalAssistantInthisproject,wewillbuildatoolusingRaspberryPithatactsasapersonalassistant.Thisprojectpresentsideastoovercomedifficultiesencounteredinourday-to-daylives(forexample,keepingtrackofdailyappointments,payingbillsontime),overcomeprocrastination,oreaseourroutinestressinducingactivitiesbyautomatingthem.

Page 286: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,webuildsomethingthathelpsinsimplifyingourday-to-dayactivities,easeourburdeninperformingmundanetasks,andremindusaboutimportantappointments/tasksaswellastrackingthem.Wewillworkonimplementingasolutionforeachpossiblescenario(forexample,wewillimplementasolutiontochecke-mailsandreviewasolutiontocreateanalertforanewe-mail).

Page 287: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Wedoourbesttobesuccessfulinourcareerandleadahealthylifestyle.Whilewritingthisbook,wehadtocomeupwithaplantoovercomeourprocrastinationandtrackourtaskseffectively(especially,deliveringthedraftsofeachprojectontime!).

Page 288: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesInthisproject,wewillaccomplishthefollowing:

Settingupthee-mailfeedparserSettinguptheparserforremindersandeventsDesigninganenclosureforthepersonalassistantSettinguptheassemblyforthedishmonitorSettingupsensorsforthekeyalertsystem

Page 289: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistInthistask,wewillworkoninstallingalltoolsandPythonmodulesusedinthisproject:

1. Beforewestartinstallingthetoolsrequiredforthisproject,ifnecessary,youcanupdatetherepositoriesandpackagelistsasfollows:

sudoapt-getupdate

2. Wewillstartwithinstallingpython-feedparser.Weusedthepython-feedparsertoolinthepreviousprojectandcreatede-mailalertsforthewaterfountain.Ifyouskippedthepreviousproject,thetoolcanbeinstalledasfollows:

sudoapt-getinstallpython-feedparser

3. WewilluseGoogleCalendartoorganizeeventsandappointmentsasanexample.Weneedtoinstallthepython-gdatatooltomakeuseoftheGoogleAPIs:

sudoapt-getinstallpython-gdata

4. AnotherimportanttoolrequiredforthisprojectisOpenCV(http://opencv.org/).OpenCVisanopensourcecomputervisionframeworkdevelopedbyIntel.OpenCViswidelyusedbyresearchersandhobbyistsinapplicationssuchasobjectrecognition,machinevisionapplicationssuchascomponentinspectiononamanufacturingline,andmore.

NoteItisimportanttoknowthatittakesatleastfourhourstofinishthecompilationofOpenCV.

TheinstallationprocedureforOpenCVontheRaspberryPihasbeenborrowedfromhttp://mitchtech.net/raspberry-pi-opencv/andtheOpenCVinstallationguideforLinux(http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html).Beforewegetstartedwiththeinstallationprocess,thedependenciesforOpenCVneedtobeinstalled.Thedependenciescanbeinstalledusingthefollowingshellscriptavailablealongwiththisproject:

shOpenCVInstall.sh

Oncethedependencieshavebeeninstalled,wecangetstartedwiththeOpenCVinstallation.ThesourcefilestoinstallOpenCVcanbedownloadedfromhttp://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.10/opencv-2.4.10.zip.Weneedtoextractthedownloadedsource:

unzipopencv-2.4.10.zip

ThenextstepisthemakefilegenerationusingCMake.ThelibraryhastobecompiledwithPythonsupportthatenablesapplicationdevelopmentusingaPythonscriptlibraryandsupport.

Page 290: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

cdopencv-2.4.5

mkdirbuild

cdbuild

cmake-DCMAKE_BUILD_TYPE=RELEASE-D

CMAKE_INSTALL_PREFIX=/usr/local-DBUILD_NEW_PYTHON_SUPPORT=ON-D

BUILD_EXAMPLES=ON

Oncethemakefilehasbeengeneratedsuccessfully,OpenCVcanbebuiltandinstalledasfollows:

make

sudomakeinstall

Oncethelibraryhasbeeninstalled,weneedtotestwhethertheinstallationwassuccessfulbyexecutingoneofthePythonsamplesavailableinOpenCV:

cd~/opencv-2.4.5/samples/python

pythondelaunay.py

Iftheinstallationwassuccessful,weshouldabletolaunchtheDelaunaytriangulationsample.

Page 291: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Delaunaytriangulation–OpenCV

5. NowthatwehaveinstalledOpenCV,wewillproceedtobuildourprojectovertheforthcomingtasksoftheproject.

Page 292: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 293: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Settingupthee-mailfeedparserInthistask,wewilllearntosetupane-mailfeedparserandblinkanLED.Asanexample,wewillchecknewe-mailsinaGmailaccount.

Page 294: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffSincewealreadyinstalledthepython-feedparsermodule,wewillgetstartedwithsettingupthemailparser.Wewillbuildeachmoduleofourprojectasaseparateexample.

Page 295: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. UsingPythonIDLE,let’sgetstartedwithwritingapythonscripttoachievethistask.

Wewillgetstartedbyimportingthefeedparsermodule:

importsys

importfeedparser

2. Wewilldefinethefunctionrequiredtochecke-mails:

newEmail=""

username="[email protected]"

password="password"

proto="https://"

server="mail.google.com"

path="/gmail/feed/atom"

defmail():

email=

int(feedparser.parse(proto+username+":"+password+"@"+server+path)

["feed"]["fullcount"])

returnemail

NoteTheprecedingfunctionhasbeenborrowedfromtheWonderHowTowebsite(http://null-byte.wonderhowto.com/how-to/make-gmail-notifier-python-0132845/).

Let’ssavethisfunctioninaseparatefileandtrytocallitfromanotherfile.Forexample,thefunctionhasbeensavedinafilecalledparser.py.Wewillimportparser.pyinanotherfileasamoduleandimplementthee-mailnotifier.Inthisfile,wewillblinktheLEDwhenthereisanewe-mail.WewillstartbyimportingtheparsermoduleandRPi.GPIO:

importparser

importtime

importRPi.GPIOasgpio

Wewillgetstartedbysettingtheoutputpinsforthee-mailnotifierexample:

gpio.setwarnings(False)

gpio.setmode(gpio.BCM)

gpio.setup(17,gpio.OUT)

Wewillcheckfornewe-mailsandblinkanLEDifnecessary:

whileTrue:

mail=parser.mail()#checkforemail

count=0

ifmail>0:#printfornewemails

print(mail)

print("newemails\n")

whilecount<10:

count+=1

gpio.output(17,gpio.HIGH)#blinkLEDiftherearenewemails

time.sleep(1)

Page 296: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

gpio.output(17,gpio.LOW)

time.sleep(1)

gpio.output(17,gpio.LOW)#setLEDtolow

else:

time.sleep(10)#repeatcyclefor10seconds

3. TheLEDneedstobeconnectedasshowninthefollowingdiagram:

RaspberryPiemailnotifier–SchematiccreatedwithFritzing,RaspberryPiLibrary

Page 297: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 298: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettinguptheparserforremindersandeventsInthistask,wewillimplementamodulethatwillblinkanLEDtoremindusaboutimportanteventsandappointments.

Page 299: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheGoogleDataPythonclientlibraryisrequiredforthistask.Youalsohavetosavesometasksinyourcalendartotesttheimplementation.

Page 300: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. UsingthePythonIDLE’seditor,let’sgetstartedbycreatinganewfilecalled

calendars.py:

importgdata.calendar.service

importgdata.service

importgdata.calendar

importtime

2. WecangetstartedbydefiningaGoogleCalendarobject.WewilldefinetheusernameandpasswordforourGoogleaccount:

calendar_service=gdata.calendar.service.CalendarService()

calendar_service.email='[email protected]'

calendar_service.password='password'

calendar_service.ProgrammaticLogin()

3. Thecalendar_queryfunctionperformsaqueryforcalendareventsbydefiningatimeframeasfollows:

query=

gdata.calendar.service.CalendarEventQuery('default','private','full')

query.start_min='2014-01-01'

query.start_max='2013-05-31'

feed=calendar_service.CalendarQuery(query)

returnfeed

4. Let’screateanotherPythonscriptandtestthefunctionalityofthecalendarmodule(calendar.py).Wewillbeginbyimportingthepreviousdefinitionasamodule:

importcalendar

feed=calendar.calendar_query()

Now,wewillprintthedetailsoftheretrievedevents:

fori,an_eventinenumerate(feed.entry):

print'\t%s.%s'%(i,an_event.title.text,)

fora_wheninan_event.when:

print'\t\tStarttime:%s'%(a_when.start_time,)

print'\t\tEndtime:%s'%(a_when.end_time,)

TheprecedingexamplewasborrowedfromthedocumentationoftheGoogleCalendarAPI.Whenexecuted,theoutputwouldbesomethinglikethefollowing:

0.Sai

Starttime:2013-05-12T11:30:00.000-05:00

Endtime:2013-05-12T12:30:00.000-05:00

1.EventatFiregrillhouse

Starttime:2013-04-24T18:30:00.000-05:00

Endtime:2013-04-24T19:30:00.000-05:00

2.ChicagoHardwareStartupMeetup-FIRSTMEETING

Starttime:2013-01-23T18:30:00.000-06:00

Endtime:2013-01-23T21:00:00.000-06:00

Page 301: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

3.FreescaleSABRELiteBoard

Starttime:2013-01-30T12:00:00.000-06:00

Endtime:2013-01-30T13:00:00.000-06:00

5. SinceweareabletoretrieveandparsetheeventsontheGoogleCalendar,wewilltrytoblinkanLEDtoremindusabouttheeventsandappointments.

WewillgetstartedwithimportingtheRPi.GPIOmoduleinthesamefile:

importcalendar_special

importtime

importdatetime

importRPi.GPIOasgpio

Sinceweusedpin17forthee-mailalerts,let’susepin24forremindersandevents.TheeventscanberetrievedfromGoogleCalendarasfollows:

feed=calendar_special.calendar_query()#retrieveeventsfrom

calendar

fori,an_eventinenumerate(feed.entry):

fora_wheninan_event.when:#Weretrievethestarttimeand

endtimeforeachappointment/event

try:

start_time=

datetime.datetime.strptime(a_when.start_time.split(".")[0],"%Y-%m-

%dT%H:%M:%S")

end_time=

datetime.datetime.strptime(a_when.end_time.split(".")[0],"%Y-%m-

%dT%H:%M:%S")

exceptValueError:

print(ValueError)

continue

current_time=datetime.datetime.now()

ifend_time>current_time:#Hastheeventended?

print'\t%s.%s'%(i,an_event.title.text,)

print'\t\tStarttime:%s'%(a_when.start_time,)

print'\t\tEndtime:%s'%(a_when.end_time,)

Wewillfilteroutallupcomingeventsandlistthemwithdetails.Wewillcheckwhetherwehavesetanalertfortheevent.Ifindeedtherewasanalert,wewillblinkanLEDuntiltheeventhasended:

forreminderina_when.reminder:

ifreminder.method=="alert"\

andstart_time-datetime.timedelta(0,60*int(reminder.minutes))

<current_time:

print'\t%s.%s'%(i,an_event.title.text,)

print'\t\tStarttime:%s'%(a_when.start_time,)

print'\t\tEndtime:%s'%(a_when.end_time,)

count=0

gpio.output(24,gpio.HIGH)

time.sleep(1)

gpio.output(24,gpio.LOW)

time.sleep(1)

Page 302: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 303: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 304: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DesigninganenclosuredesignforthepersonalassistantInthistask,wewilllookintotheenclosuredesignfortheproject.Inordertomakethingssimple,wewilluseadesignthatisopensource.Theenclosureisonethatcanbeassembledinfewsimplesteps.ThisenclosurewasdesignedbyMichaelMilazzo(http://makezine.com/2013/01/18/laser-cutting-a-glueless-acrylic-project-box/).

Page 305: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThisenclosurecanbefabricatedinfewsimplestepsusingalasercutter.ThedesignavailablealongwiththisprojectinthePDFformatcanbemodifiedusingadesigntoolsuchasInkscapeorAdobeIllustrator.

Page 306: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Theenclosuredesignismeanttobemanufacturedusingalasercutter.Sincelaser

cutterscanbeeasilyaccessedfromhackerspaces,openworkshops,andsoon,itshouldbeeasytomakethisenclosure.

2. Alasercutteriseasytousewhenweadheretosafetypractices.Youmustundergotrainingtooperatealasercutter.Thefilesusedforlasercuttingareavailablefromtheprecedinglink.

3. Oncethelasercuttingoperationiscomplete,thepartsoftheenclosurelookliketheoneshowninthefollowingimage:

AGluelessbox

4. Theassemblyoftheenclosureisquiteintuitive.Wewillmakeuseofthisenclosureinthelaterpartofthisproject.

Page 307: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Anassembledenclosure

Page 308: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 309: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettinguptheassemblyforthedishmonitorInthistask,wewillsetupamonitoroverthekitchensink.WewillcheckwhethertherearedishesinthesinkandsendLEDalertstotheuser.SincewehaveinstalledOpenCValready,wewillgetstartedwiththesetupofthemonitor.

ThistaskwasinspiredbyahackerbasedinLondonwhobuiltadishdetectortoalertusersofacommunalkitchen.

NoteThecodesampleforthisfunctionhasbeenborrowedfromtheOpenCVDishDetectorprojectbyTom:http://beagleboard.org/blog/2013-11-26-project-spotlight-dirty-dish-detector/

Page 310: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillgetstartedbymountingacameraontopofthesinkandconnectingittoanoverheadcamera,asshowninthefollowingimage:

Anoverheadcameraontopofthesink

Page 311: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. WewillgetstartedbyimportingtheOpenCVmodule:

importtime

importsys

importcv2.cvascv

2. Wewillinitializethecameratocaptureframes:

capture=cv.CaptureFromCAM(0)

3. Afterinitialization,wewillgrabaframeforprocessing:

im=cv.QueryFrame(capture)

4. We’llconverttheimagetograyscaleforimageprocessingandfeaturedetection:

gray=cv.CreateImage(cv.GetSize(im),8,1)

edges=cv.CreateImage(cv.GetSize(im),cv.IPL_DEPTH_8U,1)

cv.CvtColor(im,gray,cv.CV_BGR2GRAY)

5. Wewillextractthefeaturesoftheimageusingthecannyedgedetectiontechnique.Sincetheinformationispronetonoise,weusethesmoothingtechniquetoeliminatethenoiseintheimage:

cv.Canny(gray,edges,200,100,3)

cv.Smooth(gray,gray,cv.CV_GAUSSIAN,3,3)

6. Wewillattempttodetectthedishesusingcommonshapesfoundinthedishes.ThetechniqueiscalledHoughtransformsandwewilltrytodetectcircularobjectsintheimage:

storage=cv.CreateMat(640,1,cv.CV_32FC3)

cv.HoughCircles(gray,storage,cv.CV_HOUGH_GRADIENT,1,30,100,55,0,0)

7. Wewilldrawacirclearoundeachobjectdetected.Thishelpsineliminatinganyincorrectobjectdetection:

foriinrange(storage.rows):

val=storage[i,0]

vessels=vessels+1#incrementdishesdetectedby1

radius=int(val[2])

center=(int(val[0]),int(val[1]))

cv.Circle(im,center,radius,(0,0,255),3,8,0)

8. Theobjectsdetectedcanbeviewedasfollows:

Page 312: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DishesdetectedinOpenCV

9. Ifavesselisdetected,wewilltriggeranLEDalerttoannoytheuser.

Page 313: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWehavesetupadishmonitortoalerttheuserwhendishesaredetectedusinganLED.

Page 314: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 315: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettingupsensorsforthekeyalertsystemInthistask,wewilltrytobuildamodulethattriestoalerttheuserifthethingsthatweusedaily(suchasthekeystoourapartmentdoororthecarkey)arenotfoundintherightplace.Ithelpsussavealotoftimefranticallysearchingformisplaceditems.Wewilluseareedswitchandamagnetforthismodule.

Theuniquenessaboutthistaskisthatwetrytoimproveourliveswithsimpleitemsthatareeasytopurchaseandsimpletobuild.Amagnetandareedswitchareavailablefromallhobbystores.Youcanalsouseareedswitchindoorsecuritysystems.ThefollowingisadiagramofareedswitchinterfacedtoaRaspberryPi:

ReedswitchsetupwiththeRaspberryPiGPIO

Page 316: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillinterfacethereedswitchasshownintheprecedingdiagram.Let’stestitonabreadboardbeforesettingitupinanenclosure:

ReedswitchinterfacedtoRaspberryPi

Page 317: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillbetrackingwhetherthekeyisintherightplacebyattachingabarmagnetto

thekeys.WewillsetupaGPIOpinaswegetstarted:

importRPi.GPIOasGPIO

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

GPIO.setup(18,GPIO.IN)

2. Wewillreadtheinputsandifthemagnetinthekeyisnotnearbythereedswitch,weshouldbeabletotriggeranalert:

whileTrue:

if(GPIO.input(18)):

print("Keysareintherightplace")

else

print("Keysmissing!")

3. Nowthatwehavesetaninputforthereedswitch,weshouldbeabletosetupthereedswitchinsidetheenclosureasshowninthefollowingimage:

Areedswitchwiththemagnetattachedtothekey

Page 318: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,youlearnedtouseasimplereedswitchtotheRaspberryPiandhelpimproveourlives.

Page 319: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 320: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisprojectweimplementeddifferentmodules,includinge-mailalerts,calendaralerts,adishmonitor,andakeyalertsystem.Weleaveittotheusertointegrateallsubsystemsusingtheircreativity.You(likeus)havelearnedtouseRaspberryPitoimproveourqualityoflife.

Page 321: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 322: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengesHowcanweuseRaspberryPitoenhancethelivesofseniorcitizens?

Thedishdetectorisnoiseprone.Howcanitbeimproved?

Page 323: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 324: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

References1. OpenCVinstallationontheRaspberryPiavailableathttp://mitchtech.net/raspberry-

pi-opencv/.2. OpenCVguideforinstallationonUbuntuavailableat

http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html.3. PythonGmailnotifierfromtheWonderHowTowebsite,http://null-

byte.wonderhowto.com/how-to/make-gmail-notifier-python-0132845/.4. GoogledataclientAPIdocumentationforGoogleCalendar.5. GoogleCalendarusingpynotifybyJulienDanjou.6. OpenCVdishdetector,availableat,

http://www.adafruit.com/blog/2014/03/11/beaglebone-black-used-to-detect-dirty-dishes-beagleboneblack-txinstruments-beagleboardorg/,Tom,Londonhackerspace.

Page 325: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 326: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter7.RaspberryPi-basedLineFollowingRobotInthisproject,wewillbuildalinefollowingrobotthatiscontrolledbyyourRaspberryPi.

NoteItisabsolutelynotnecessarytomakeuseoftheRaspberryPitobuildalinefollowingrobotunlessyouareusingacameratofollowtheline.WearebuildingthisrobottodemonstrateanexampleofbuildingamechatronicsystemusingtheRaspberryPi.

Page 327: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewillbuildalinefollowingrobotthatwillfollowablacklineagainstawhitebackground.Therobotwillmakeuseofapairofinfraredsensorstotracktheorientationoftherobotanddrivetherobotaccordingly.

Alinefollowingrobot

Page 328: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?ThePi,asyouhaveseeninthelastfewprojects,offersyouimmensefunctionalityandmanyadvantagesovermicrocontrollers.Youcanbringthispowerandsmallerfootprintstorobotics.So,wearegettingyoustartedoffwiththelinefollowingrobot.Onceyougetthisundercontrol,thepossibilitiesareendless,makingthisanawesomesegueintoroboticsandbeyond.

Page 329: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesInthisproject,wewillbuildthelinefollowingrobotinthefollowingsteps:

AssemblyofthePiPlateforthelinefollowingrobotSensorselection,interfacingsensors,anddatainterpretationImplementationoflinefollowinglogicbasedonsensordataTestingthemotordrivercircuitPreparationofthelinefollowingcourseDesigningthechassisforthelinefollowingrobotAstep-by-stepassemblyoftherobot

Page 330: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistThereareoff-the-shelfproductsavailabletobuildalinefollowingrobot,forexample,Make:itBasicRoboticsStarterKit(http://www.makershed.com/products/makeit-robotics-start-kit).Alternatively,inordertobuildalinefollowingrobot,thefollowingitemsarerequiredandthereadermayaddorremovecomponentstotherobotbasedonhis/hercreativity:

Item Cost

Alinefollowingsensorarray 10USD(intermsofcomponents)

DCmotorswithagearbox*2–60rpm(http://www.pololu.com/product/1594) 11USD

ArduinoUno(http://store.arduino.cc/product/A000066) 30USD

Plasticwheels–1pair(http://www.pololu.com/product/1425) 8USD

HBridgechip–forexample,L293D(http://www.pololu.com/product/24) 3USD

Anacrylicsheet(preferably12inchx24inchtocutthechassisusingalasercutter) 5USD

AUSBbatterypack(preferably10,000mAh,1Amaxoutput) 15USD

Aposterboard 3USD

PiPlatefromAdafruitIndustries(https://www.adafruit.com/product/801) 15USD

Page 331: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 332: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AssemblyofthePiPlateforthelinefollowingrobotNoteThePiPlateisnecessaryonlyifyouaregoingtobuildyourowncircuitry(insteadofanoff-the-shelfrobotkit)thatdrivestherobot.

WewillmakeuseofthePiPlatefromAdafruitIndustries.ThePiPlateisstackableandanadd-onhardwarefortheRaspberryPi.ThePiPlateislikeabreadboard/perforatedprototypingboardandenablesprototypingusingtheRaspberryPiplatform.Wewillassembletheheadersontheboard.

Page 333: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThePiPlateisavailablefromAdafruitIndustries(www.adafruit.com).Itcosts15.95USD.Thisstackableadd-onhardwareisusefulbecausethesensorsandactuatorscanbeconnectedusingthescrew-interminals.ThiswillavoidanylooseconnectionstoyourRaspberryPiwhiletherobotisinmotion.

Page 334: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. ThecontentsofthePiPlatepackageareasfollows:

ContentsofaPiPlatepackage

NoteAdultsupervisionisrequiredforsolderingandputtingthePiPlatetogether.

2. ThePiPlaterequiressolderingoftheterminals,andAdafruithassometutorialsinsettingupthePiPlate.Whentheterminalsandheadersareassembledtogether,wehavewhatisshowninthefollowingimage:

Page 335: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

APiPlatestackedontheRaspberryPi

Page 336: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingItisunlikelythattherewillbeaproblemwiththePiPlateunlessthereisacoldsolder.

Page 337: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 338: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Sensorselection,interface,anddatainterpretationInthistask,wewilldiscussthedifferentsensorsavailabletobuildalinefollowingrobotandpickasensorforthisproject.

Page 339: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersWewilldiscussthreesensorsinthistask,includinglightdetectingresistors,IRemitters/detectors,andacamera.Wewilldiscusstheiroperations,features,andtheirdistinctedgeoverothersensingtechniquesaswellastheirdisadvantages.

LightDependentResistorsAsthenamesuggests,LightDependentResistorsarethosethatchangetheirresistancewhenlightisincidentonthesurfaceoftheresistor.

LightDependentResistorsareusedincombinationwithabrightLED.Wecanmakeuseofthedifferenceinreflectivitybetweendifferentcolouredsurfacestofollowablacklineonadarksurface.

WhenLightDependentResistorisinsertedintoapotentialdividerconfiguration,asshowninthefollowingdiagram,thedropinvoltagecausesapotentialimbalanceleadingtoachangeinvoltage.Sincethereflectanceofwhiteandblackcolorsurfacesvaries,thechangeinvoltagecanbeusedtodistinguishbetweenblackandwhitecolors.ThispropertyofLightDependentResistorscanbeusedinourlinefollowingrobot:

ALightDependantResistorinapotentialdividerconfiguration

ThepotentiometerinthepotentialdividerconfigurationisusedtoadjustthesensitivityofLightDependentResistorsdependinguponthesurroundinglightingconditions.

Page 340: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

LightDependentResistorscanbeusedasasensortobuildalinefollowingrobot,exceptinthosecaseswherethesensorresponsetimeisnottrivial.Hence,LDRscannotbeusedincaseswheretherobotisdesignedtomoveathigherspeeds.

LightDependentResistorshavetobecompletelyisolatedfromlightsourcesotherthanthebrightwhiteLED.ThisistomakesurethattheLEDrespondstoreflectedlightfromthebrightLED.

Infraredemitter/detectorAninfrared(IR)emitter/detectorcombinationisthebestalternativetotheLightDependentResistors.Inbothcases(theLDRandIRsensors),theemitter(ultrabrightwhiteLED/IRLED)andthedetector(LightDependentResistorsorphotodiode)arearrangednexttoeachother.

ThefollowingdiagramshowsthecircuitforanIRemitter/detector:

AnIRemitter/detectorforthelinefollowingrobot

Theprecedingfigureshowsaphotodiodethatisconnectedtotheinvertingterminalofanop-amp.Thepotentiometer(thatisconnectedtothenon-invertingterminaloftheop-amp)

Page 341: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

canbeusedtovarythesensitivityofthesensor.

Whenlightfallsonthephotodiode,itpullsdownthe10Kresistor,andhence,theoutputoftheop-ampishigh.Thesignaldiode,1N4148,actsasasignallevelconverterbetween5Vand3.3V(RaspberryPi’sGPIOpinsare3.3Vtolerant).Whenthe5Vsideishigh,the3.3Vsideisalsohigh(thediodeisreversebiasedandhencethepullupresistorkeepsthe3.3Vsidehigh).Whentheinfraredsensorisontopoftheblacksurface,theoutputoftheop-ampislow(sincetheinvertingterminalishigh)andthepullupresistoronthe3.3Vsideispulleddown.Thus,theGPIOpinispulleddown.Theinfraredsensorshownintheprecedingdiagramcanonlybeusedincontrolledlightingconditionsastheyarepronetostrayinfraredradiationfromdaylight.

Inconditionswheretherobothastooperateunderbroaddaylightconditions,theinfraredtransmitterandreceiverhastobepulsewidthmodulatedsothatthesensorcandistinguishbetweennoiseandtheactualsignal(moreinformationcanbefoundathttp://www.ermicro.com/blog/?p=1908).

Machine-vision-basedlinefollowingrobotThefinalalternativetoasensortobuildalinefollowingrobotisacamera.TheRaspberryPifoundationhasreleaseditsowncameramoduleanditisalsosimpletointerface.

Alinefollowingrobotcanbeimplementedbygrabbingaframefromthecameramoduleandconvertingitintoagrayscaleimage.Thegrayscaleimagecanbeusedtodeterminethecurrentpositionoftherobotwithrespecttothelinethathastobefollowed.Sincewhiteandgreysurfaceshavevaryinglevelsofgreycolour,theorientationoftherobotcanbecorrectedusingadifferentialsteeringmechanism.

Acamerawouldbeoverkillforbuildingalinefollowingrobottojustfollowablacklineonawhitesurfaceinanindoorenvironment(also,abitoverwhelmingforabeginner).However,wecanuseitoutofanacademicinterest.

SensorselectionWehavediscussedthedifferentsensingoptionsavailableforbuildingalinefollowingrobot.Wewillchoosetheinfraredsensor.Wechosetheinfraredsensorforthefollowingreasons:

Itcanbeusedonlyincontrolledlightingconditions(sinceweareusinganunmodulatedinfraredlightsource)butservesasagoodstartforabeginnerItisreadilyavailableandeasytointerfaceIthasadistinctedgeoverlightdetectingresistorssinceithasabetterresponsetime

Page 342: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–missiondebriefingInthistask,wediscussedthedifferentsensoroptionsavailableforalinefollowingrobot.

Page 343: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 344: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ImplementationoflinefollowinglogicbasedonsensordataInthistask,wewillimplementasimplelinefollowingtechniqueusingtheinfraredsensor.Wewillmakeuseofapairofinfraredsensorstotrackablacklineonawhitesurface.Therobotwillmoveforwardifboththesensorsareonawhitesurface.Therobotturnsleftiftheleftsensorisontheblacklineandviceversa.

Page 345: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThesensorneedstobesolderedandconnectedtotheRaspberryPi(somethingliketheoneshownintheprecedingschematic).Alternatively,youmayuseasensorofyourchoice.

Page 346: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Asalways,wewillgetstartedbyimportingtherequiredmodules,especially

Rpi.GPIO:

importRPi.GPIOasGPIO

fromtimeimportsleep

2. Wewillsetthepinconfigurationthatwewilluseinthisprogram:

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

GPIO.setup(18,GPIO.IN)

GPIO.setup(25,GPIO.IN)

3. Thecontrollogicexplainedearlierisimplementedasfollows:

state=1

prev_state=0

whileTrue:

#bothsensorsareonwhitesurface

if((GPIO.input(18)==GPIO.HIGH)and(GPIO.input(25)==GPIO.HIGH)):

state=0

#leftsensoraloneisontheblacksurface

elif((GPIO.input(18)==GPIO.LOW)and(GPIO.input(25)==GPIO.HIGH)):

state=1

#rightsensoraloneisontheblacksurface

elif((GPIO.input(18)==GPIO.HIGH)and(GPIO.input(25)==GPIO.LOW)):

state=2

#ifsensorstatehaschangedsincelasttime,updatemotorcontrol

ifstate!=prev_state:

ifstate==0:

#moverobotforward

elifstate==1:

#turnrobotleft

elifstate==2:

#turnrobotright

prev_state=state

sleep(0.15)

Thesensorstatesarecheckedonceevery15milliseconds.Ifthereisachangeofsensorstates,themotorcontrolisupdated(asperthelogicexplainedinthistask).

4. Sinceweareusingonlytwosensors,therobotrunscrisscrossacrosstheline.Inordertoachievesmoothtrackingoftheline,asensorarrayisusedfordrivingthemotorsusingacontrolalgorithmsuchasaPIDcontrolalgorithm.

Page 347: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,weimplementedthelinefollowinglogicforourrobot.Inthenexttask,wewilldiscussmotorcontroltodrivetherobotThiswouldbeeventuallyintegratedintothelinefollowinglogic.

Page 348: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 349: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TestingthemotordrivercircuitInthisproject,wewilluseapairofDCmotorstodrivetherobot.WewilluseadualH-bridge(SN754410)drivertocontroltheDCmotors.WewilluseasoftwarePWMlibrarywrittenfortheRaspberryPi.WechoseDCmotorsforthefollowingreasons:

1. DCmotorsareeasytooperateandcontrolusinganH-bridgeinterfacedtotheRaspberryPi.

2. ThereisasoftwarePWMlibrarythatmakesiteasiertocontroltheDCmotors.

Inthistask,wewillimplementtheDCmotorcontrolcircuitandalsowriteaprogramtocontroltheDCmotors.

Page 350: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillusethesoftwarePWMfunctionavailablewithRPi.GPIO.ThesoftwarePWMfunctionisavailableonversionsgreaterthan0.5.3.WeneedtodeterminetheRPi.GPIOversioninstalledontheRaspberryPiusingacommand-lineterminal:

python

importRPi.GPIO

RPi.GPIO.VERSION

Ifthereturnedvalueisearlierthan0.53,thepackagecanbeupdatedasfollows:

sudoapt-getupdate

sudoapt-getupgrade

WewillbemakinguseofpulsewidthmodulationtodrivetheDCmotors.ItisimportantthatyoufamiliarizeyourselfwithpulsewidthmodulationtechniquestocontrolaDCmotor.WealsoneedtosetuptheDCmotorsfortestingbyconnectingthewheelstothemotor(somethingsimilartothefollowingfigure):

DCmotorswithsolderedwiresandwheelswithstrappedsiliconetires

Wealsoneedtoconstructthemotorcontrolcircuitryasshowninthefollowingschematic:

Page 351: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ASN754410motorcontrolcircuitry

AnH-bridgecircuitisusedforbidirectionalcontrolofaDCmotorusingamicrocontrollerorRaspberryPi(https://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-bridge/).TheH-Bridgetakesin2inputsforeachmotor.ThefollowingtableshowsalogictablethatdictatesthecontrolofamotorusinganH-Bridge:

TheSN754410truthtable

Forexample,ifpin1Aissettohighwhile2Aissettolowandtheleadsofthemotorareconnectedto1Yand2Yrespectively,themotorrotatesinonedirection,whileitrotatesintheoppositedirectionwhen1Aissettolowand2Aissettohigh.

Page 352: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. WewillgetstartedwiththetestingoftheDCmotorswithasimplePythonprogram.

Wewillgetstartedbyimportingthemodules:

importRPi.GPIOasGPIO

importtime

2. Wewilldeclarethepinsthatwillbeusedasoutputpins.WewillconnecttheGPIOpins,8,9,10,and,11tomotordriverpins,1A,2A,3A,and4A,respectively:

GPIO.setwarning(False)

GPIO.setmode(GPIO.BCM)

GPIO.setup(8,GPIO.OUT)#connectedto1A

GPIO.setup(9,GPIO.OUT)#connectedto2A

GPIO.setup(10,GPIO.OUT)#connectedto3A

GPIO.setup(11,GPIO.OUT)#connectedto4A

3. Wetestboththemotorsbyrotatingtheminbothdirectionsfor10secondsandstoppingthem:

whileTrue:

#Rotatebothmotorsforwardfor10seconds

GPIO.output(8,GPIO.HIGH)

GPIO.output(9,GPIO.LOW)

GPIO.output(10,GPIO.HIGH)

GPIO.output(11,GPIO.LOW)

sleep(10)

#Stopmotorsandrotateinreversedirections

GPIO.output(8,GPIO.LOW)

GPIO.output(10,GPIO.LOW)

#Goreverse

GPIO.output(9,GPIO.HIGH)

GPIO.output(11,GPIO.HIGH)

sleep(10)

#Stopmotorsandrotatebothinoppositedirections

GPIO.output(9,GPIO.LOW)

GPIO.output(11,GPIO.LOW)

GPIO.output(8,GPIO.HIGH)

GPIO.output(9,GPIO.LOW)

GPIO.output(10,GPIO.LOW)

GPIO.output(11,GPIO.HIGH)

sleep(10)

#StopMotors

GPIO.output(8,GPIO.LOW)

GPIO.output(9,GPIO.LOW)

GPIO.output(10,GPIO.LOW)

GPIO.output(11,GPIO.LOW)

4. Intheprecedingexample,boththemotorswererunningat100percentdutycycle.Wewilllookintocontrollingthemotorsusingpulsewidthmodulation.Wewillset

Page 353: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

thepinsasoutputanddeclaretheoperatingchannelfrequenciesforthePWMpins(1kHz):

GPIO.setup(8,GPIO.OUT)#connectedto1A

GPIO.setup(9,GPIO.OUT)#connectedto2A

GPIO.setup(10,GPIO.OUT)#connectedto3A

GPIO.setup(11,GPIO.OUT)#connectedto4A

GPIO.output(9,GPIO.HIGH)

GPIO.output(11,GPIO.HIGH)

motor1=GPIO.PWM(8,1000)

motor2=GPIO.PWM(10,1000)

5. Wewillstartthepulsewidthmodulationsignal(10percentdutycycle–runsat10percentoftheratedvoltage)asfollows:

motor1.start(10)

motor2.start(10)

Wecanvarythespeedofthemotorasfollows:

whileTrue:

motor1.ChangeDutyCycle(25)

motor2.ChangeDutyCycle(25)

sleep(15)

motor1.ChangeDutyCycle(50)

motor2.ChangeDutyCycle(50)

sleep(15)

motor1.ChangeDutyCycle(75)

motor2.ChangeDutyCycle(75)

sleep(15)

motor1.ChangeDutyCycle(100)

motor2.ChangeDutyCycle(100)

sleep(15)

Page 354: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,weimplementedamotordrivercircuitryandtestedit.

Page 355: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 356: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PreparationofthelinefollowingcourseInthistask,wewillpreparethelinefollowingtrackfortherobot.

Page 357: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTherearetwoapproachestobuildingalinefollowingtrack.Theyincludethefollowing:

1. PrintatrackavailablefromParallaxandsetitontopofaposterboard.2. UseelectricaltapeandbuildatrackusingatutorialfromPololu.

Thefollowingitemsarerequiredtocompletethistask:

1. Aposterboard2. Apermanentmarker3. Apencil4. Aruler5. A4sheets

Page 358: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewilluseareadilyavailablelineforthefollowingtrack

(http://www.parallax.com/sites/default/files/downloads/28136-S2-PrintableTracks.pdf)designedfortheScribblerlinefollowingrobotfromParallax.ThelinefollowingtrackfromParallaxconsistsof10individualpiecesoftrackthatcanbearrangedandcustomizedaccordingtoourneeds.

2. Wewillgetstartedwithprintingtwosetsofthetrackavailablealongwiththisproject’sdownloadsandarrangethemaccordingtoourneedsanddeterminethecomplicityofthetrack.Anexampleofthetrackisshowninthefollowingimage,andthiscanbeconsideredthefastestwayofbuildingalinefollowingtrack:

Alinefollowingtrack

UseelectricaltapeandbuildatrackPololuhaspublishedanexcellenttutorial(https://www.pololu.com/docs/pdf/0J22/building_line_courses.pdf)onbuildingatrackusingelectricaltape.Theonlydisadvantagebehindusingthismethodtobuildatrackisthatthewrinklesontheelectricaltapecanaffectthesmoothoperationoftherobot.

Page 359: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 360: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DesigningthechassisforthelinefollowingrobotInthistask,wewilldesignthechassisforthelinefollowingrobot.Thereareseveraloptionsavailableintermsofdesigntoolsforthedesignofthechassis.WechoseAutodeskInventor,buttherearealotoftoolssuchasAutodesk123Dandsoon.

Page 361: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThechassisfortherobotisfabricatedusingthelasercuttingtechnique.Youarewelcometofabricateyourownchassis.Wehavechosentouselasercuttingbecauseitistheeasiesttocomplete.Thetechniqueinvolvesdesigningthechassisfollowedbypreparingthedesignforfabricationandlasercutting.

Youmaydownloadthedesignfileavailablealongwiththisprojectanduseitforlasercutting.ThereisatrialversionofAutodeskInventoravailablefordownloadanditcanbeinstalledandusedfordesigningacustomchassis.

Asamaker/hacker,itisimportantthatyoulearnhowtousethesetoolsandhowtodesignachassis.

NoteTheuseoftoolssuchasalasercutterrequiressomebasictrainingandsupervision.Itisimportantthatyouundergotherequisitesafetytrainingbeforeoperatingsuchequipment.

Page 362: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillbeginbyconsideringthecomponentsthatgointotherobot.Thecomponents

includetheinfraredsensors,aballcaster,twoDCmotors,theRaspberryPi,thePiPlate,andthebattery.

2. SincethePiPlatewillbestackedontopoftheRaspberryPi,wewillmountthebatteryonaseparateplatemountedontopoftheRaspberryPi.Thecomponentpositionsaredesignedbasedonintuition.Thechassisisshowninthefollowingimage:

Lasercutchassisoflinefollowingrobot

3. Thetopplatethatholdsthebatterypackisshowninthefollowingimage:

Atopplateusedtomountthebatteryofthelinefollowingrobot

Page 363: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWehavefinisheddesigningthepartsandfabricatingthemusingalasercutter.

Page 364: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 365: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Astep-by-stepassemblyoftherobotInthistask,wewillassembletherobotinsimplestepsthatareaccompaniedbyaphotographicalrepresentation.

Page 366: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeneedtohavethefollowingpartsreadytoassembletherobot:

1. Topandbottomchassisplatesforthelinefollowingrobot2. Infraredsensors3. Apairof#2screwsandnuts(washersoptional)4. AballcasterassemblywithscrewsfromPololu5. 2*M2.5screwsformountingtheRaspberryPi(washersoptional)6. 4*#61-inchscrewswithspacers(washersoptional)7. ARaspberryPi8. Velcro9. Battery10. 2DCmotors11. Double-sidedtape12. APiPlate13. Amotordriver

Page 367: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillgetstartedbymountingthecastorwheel.

Mountingthecastorwheel

2. WewillmounttheRaspberryPiusingM2.5screws.

RaspberryPimountedusingM2.5screws

Page 368: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

3. ThisisfollowedbytheDCmotorscoupledwithwheelsusingthedouble-sidedtape.TheDCmotorswithaplasticgearboxfromPololudonotcomewithamountinghole,andhence,wewillusedouble-sidedtapetomountthemotors.Similarly,theinfraredsensorswerealsomountedusingdouble-sidedtapeatthecenterwithaspacingthatishalfthewidthofthetrack.

DCmotorsmountedusingdouble-sidedtape

4. WewillmountthePiPlateandthetopchassisplate.WewillusevelcrotomounttheUSBbatterypacktocompletethelinefollowingrobotassembly.

Page 369: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Anassembledrobot

5. Oncetheassemblyiscompleted,wehavetoconnectthemotorsandthesensorstogetstartedwiththetesting.

Page 370: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWehavecompletedtheassemblyofthelinefollowingrobotinthistask.Oncethemotorcontrolcodeisimplementedintothelinefollowinglogic,weareallsettotestingtherobotonthetrack.Thismayrequiresometweakingthemotorspeedtomaketherobottrackthelineeffectively.

Page 371: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 372: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,webuiltalinefollowingrobotstepbystep.Wegotstartedwiththesensorsfollowedbymotorcontrol,chassisdesign,arenadesign,andintegration.Now,wehavealinefollowingrobot.

Alinefollowingrobotonthearena

Page 373: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 374: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisproject,wedidnotmakeuseofanymotorcontrolalgorithm(likePID)tosteertherobot.Howdoweimplementone?

Page 375: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ReferencesThePololututorialonBuildingLineFollowingandLineMazeCoursescanbefoundathttp://www.pololu.com/docs/0J22

TheAdvancedLineFollowingwith3pi:PIDControltutorialcanbefoundathttp://www.pololu.com/docs/0J21/7.c

TheParallaxlinefollowingtrack:http://www.parallax.com/Portals/0/Downloads/docs/prod/robo/scribbler2/Tracks.pdf

Page 376: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 377: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter8.ConnectFourDesktopGameusingRaspberryPiInthisproject,wewillbuildadesktopgameenabledbytheRaspberryPi.Wewillbuildaprototypeusingacardboardbox,amonitor,andaninputcontrolonthecabinetandimplementoptionalspeakersandamarqueeforthegame.Thegamewillmakeuseofthepython-pygamemodule(agameengineavailableunderGPLlicense:http://pygame.org/wiki/about).

Page 378: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingAConnectFourgameisatwo-playergamewheretheobjectiveistoconnectfourcoinsofthesamecolorinavertical,horizontal,ordiagonalfashion(moreinformationisavailableathttp://en.wikipedia.org/wiki/Connect_Four).Wewillinstallthenecessarysoftwarepackagesandaddallthenecessaryaccessoriestomakeadesktopprototype.TheConnectFourgameinthisprojectisbasedonthebookMakingGameswithPython&Pygame(http://inventwithpython.com/makinggames.pdf).Thisdesktopgameisagreatstartforpeoplewhoaretryingtogettingstartedwithelectronicsasahobby.

Whenwefinishthisproject,ourcabinetwillbesomethingliketheoneshowninthefollowingimage:

Page 379: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 380: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Ifyouarelikeusandhaveevervisitedthearcadeandwonderedhowmuchfunitwillbetobuildagameyourself,thisprojectisforyou.SingleboardcomputerssuchasRaspberryPiandsitessuchasInstructables(http://www.instructables.com/)onlymakethingseasier,andofcourse,isn’titfuntoconsideradaptingthedesignandleaveyourownstamponit?WewillfocusonthePiandhowtouseitforthegameandleavetherestuptowhatyoufindontheInternetandyourownimagination.

NoteInthisproject,wewillpresentthesubsystemsofwhatcouldpossiblygointobuildingaminidesktop/tabletoparcadesuchasagameusingRaspberryPi.Wewillnotconcentrateonpresentingabetteruserinterfaceforthegameoracabinet,butratherwhatittakestobuildsomethingsimilartoanarcadegame,includinggamelaunch,hardwareinterface,andsoon.

Page 381: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesWewillbuildourConnectFourdesktopgamethroughthefollowingactivities:

Installationofthepre-requisites(Missionchecklist)AhelloworldexamplewiththePython-pygameInputcontroldesignforthegameGettingstartedwiththeConnectFourgame(UI+soundeffects)AbriefdescriptionoftheConnectFourGameAIMarqueedesignandcontrolSettingupoftheswitchesusingacardboardbox

Page 382: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistOneofthemainprerequisitesforthisprojectistheinstallationofPython-pygame.Thetoolcanbeinstalledinasinglestepasfollows:

sudoapt-getinstallpython-pygame

Thisistheonlysoftwaretoolthatwewilluseinthisproject.Werequirethefollowingitemsfortheconstructionofthearcadecabinet.Wealsoneedthefollowingitemsfortheproject:

Item EstimatedCost

Acardboardbox

MomentaryPressbuttons–Arcadestyle*8(http://na.suzohapp.com/all_catalogs/pushbuttons/58-9111-L) 2.70USDeach

16*32LEDdisplayfromAdafruitorPi-LitedisplayfortheRaspberryPi(optional) USD40USD/31USD

Amonitorofthereader’schoicewithsignalcabletoconnecttoRaspberryPi 50USDapproximately

RaspberryPi 25USD/35USD

RGBLEDstrip(optional) 10USDapproximately

Page 383: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 384: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HelloworldexamplewiththepygameInthistask,wewilllearntheusageofpygameforgamedevelopment.Wewillgetstartedwithanexamplethatopensablankwindowandwriteacoupleoflinestomonitoreventssothatwecanquittheprogramifthewindowisclosed.

Wewillgothroughtheimportantfeaturesofthepygamemodule,whichisnecessarytobuildourarcadegame,includingplayingsoundsandcontrollingthemenu.

Page 385: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffAsmentionedearlier,thisprojectisbasedonthebookMakingGameswithPython&Pygame(http://inventwithpython.com/makinggames.pdf).Inthistask,wewillgothroughselectfeaturesofthepygamemodule.Itisimportantthatyoufamiliarizeyourselfwiththedifferentfeaturesavailableunderthepygamemodule.

Page 386: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. WewillgetstartedbyimportingthemodulesrequiredfortheHelloworldexample.

Wewillimportthepygameandthesysmodule:

importpygame,sys

2. Next,wewillalsoimportpygame.locals,sinceitcontainsseveralconstantvariables:

frompygame.localsimport*

3. Inordertomakeuseofthefunctionsofthepygamemodule,weneedtoinitializethemodule:

pygame.init()

4. Wewillsetthewindowwidthandheightparametersandcreateapygame.SurfaceobjectthatisstoredinavariablecalledDISPLAYSURF:

DISPLAYSURF=pygame.display.set_mode((400,300))

5. Wewillsetthewindowtitlename:

pygame.display.set_caption('HelloWorld!')

6. Now,wewillrunaloopthatwaitsforeventsinsidethewindowandupdatethedisplaythrougheverycycle.Inthisexample,wedonothaveanythingtobeupdated.Wewillquittheprogramwhentheuserclosesthewindow:

whileTrue:#maingameloop

foreventinpygame.event.get():

ifevent.type==QUIT:

pygame.quit()

sys.exit()

pygame.display.update()

7. ThisshouldopenupablankwindowtitledHelloWorld.

PlayingsoundsusingthepygamemoduleSincethesoundeffectsformthecruxofanarcadegame,weneedtoknowhowtoplaysoundsusingthepygameplatform.

1. Wewilldeclareasoundobjecttoplaythebeeps.wavfile,availablealongwiththedownloadsofthisfile.Thefileneedstobecopiedintothesamedirectoryasthepythonscriptthatrunsthegameasfollows:

soundObj=pygame.mixer.Sound('beeps.wav')

2. Thesoundcanbeplayedinaloopbycallingtheplay()methodasfollows:

whileTrue:#maingameloop

soundObj.play()

Page 387: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

3. Wecanstopplayingthesoundfilebycallingthestop()method.

Buildingmenususingthepygamemodule1. Wewillneedasimplemenuforourdesktopgame.Wewillmakeuseofthemenuclass(distributedunderGNUGPLv3license)writtenbyScottBarlow.Let’sreviewthesimple_example.pyexample.(http://www.pygame.org/project-MenuClass-1260-.html.)

2. Inthismenuexample,amenuobjectiscreated;whenamenuoptionisselectedusingakeyboard,theselectedoptionishighlightedandprintedonaterminalwhenthereturnkeyispressed.Forexample,whenthedownkeyispressedtoselectLoadGameandthereturnkeypressed,theLoadGameoptionisprintedtotheterminal.

3. Let’sdiscusstheparametersthatneedtobepassedasargumentstocreateamenuobject.Accordingtothedocumentationavailablewiththemenuclass,amenuobjecthastobedefinedwiththefollowingparameters:

menu=cMenu(x,y,h_pad,v_pad,orientation,number,

background,buttonList)

TheparametersxandyrefertothelocationoftheoriginofthemenuobjectonthegamescreenTheparametersh_padandv_padrefertothespacingbetweenthebuttonsinthehorizontalandverticaldirectionsTheorientationparameterreferstothearrangementofthebuttonsonthescreen,thatis,'horizontal'or'vertical'Thenumberparameterreferstothenumberofbuttonsthatcanbeaccommodatedinasinglerow(whenarrangedhorizontally)orinasinglecolumn(whenarrangedvertically)ThebackgroundparameterreferstothesurfaceonwhichthemenuhastobecreatedThebuttonListparameterreferstothelistofbuttonsthatwewantonthescreen

4. Wewillgetstartedbydeclaringamenuobjectandlistingalltheoptionswewantinthemenu,namely:

menu=cMenu(50,50,20,5,'vertical',100,screen,

[('StartGame',1,None),

('ScoreBoard',2,None),

('Exit',3,None)])

5. Themenuneedstobecenteredonthesurfaceofthescreen:

menu.set_center(True,True)

6. Thetextofthemenubuttonsalsoneedstobealigned:

menu.set_alignment('center','center')

7. Inordertodisplayandupdatethemenuandselectionparameters,asimplestate

Page 388: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

machineisused:

state=0

prev_state=1

8. Thepygame.event.wait()methoddetectsanykeyboardormouseeventsandupdatesthecurrentstateaccordingly.

9. Themenuisupdatedbythemethod(duetoakeypressevent/returnkeypress):

pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE,key=0))

10. Whenthereturnkeyispressedtoselectanoption,theselectedoptionisprintedtotheterminalandthemenuisupdatedbyhighlightingtheselectedoption(inred)byrect_list,state=menu.update(e,state):

whileTrue:

ifprev_state!=state:

pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE,key=0))

prev_state=state

e=pygame.event.wait()

ife.type==pygame.KEYDOWNore.type==EVENT_CHANGE_STATE:

ifstate==0:

rect_list,state=menu.update(e,state)

elifstate==1:

print'StartGame!'

state=0

elifstate==2:

print'LoadGame!'

state=0

elifstate==3:

print'Options!'

state=0

else: print'Exit!'

pygame.quit()

sys.exit()

#Quitiftheuserpressestheexitbutton

ife.type==pygame.QUIT:

pygame.quit()

sys.exit()

#Updatethescreen

pygame.display.update()

Page 389: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWehavefinishedtestingthepygamemoduleandreviewedasimplemenudesignexamplealongwithtestingtheplayingofsoundsusingthepygamemodule.

Page 390: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 391: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GettingstartedwiththeConnectFourgame(UIandsoundeffects)Inthistask,wewillworkonsomepreliminarytweaksfortheConnectFourgame.WewilltaketheexamplefromNewGameSourceCode:FourinaRow,http://inventwithpython.com/blog/2011/06/10/new-game-source-code-four-in-a-row/,andmakeuseoftheexamplesdiscussedintheprevioustask,namely,playingsoundsandmenudesignandaddthemtotheConnectFourGamePythonscript.

Page 392: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeneedtheConnectFourgameexample(fourinarowexample—fourinarow.py)fromthebook.Theexamplecanbedownloadedfromhttp://invpy.com/fourinarowimages.zip.

Page 393: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngageThrusters1. Inthisproject,thegameneedstobelaunchedfullscreenassoonasRaspberryPi(that

hasbeensetuptolaunchthedesktopgame)ispoweredup.2. Thepygame.display.set_modemethodisusedtosetthegametofullscreenwiththe

pygame.FULLSCREENargument.Theresolutionofthegamewillbe(WindowwidthxWindowheight),inthiscase,640x480pixels:

DISPLAYSURF=pygame.display.set_mode((WINDOWWIDTH,

WINDOWHEIGHT),pygame.FULLSCREEN)

3. Inordertolaunchthegame(thePythonscript:Connect_four.py)afterRaspberryPiispoweredup,let’screateashellscriptusingatexteditorwiththefollowingcontentsandcallitstartup.sh:

#!/bin/sh

pythonConnect_four.py

4. Theshellscriptneedstobesavedtothe/home/pilocation.Alternatively,thescriptcanbesavedatanyotherlocation.

5. Theshellscripthastobemadeanexecutablefileusingthechmodcommand:

sudochmod755startup.sh

6. Inordertoexecutestartup.shuponboot,the/etc/rc.localfileneedstobemodified.Inthecommand-lineterminalofRaspberryPi,thefilecanbeopenedusingatexteditorsuchasnano:

sudonano/etc/rc.local

7. Beforethelastlineofthefile,exit0,thefollowinglineshavetobeadded:

sleep10

cd/home/pi/

/home/pi/startup.sh&

exit0

8. Thescriptisexecutedafterallthekernelmodulesareinitialized.Thescriptisexecutedfromthedirectorywherethefileshavebeensaved.

AddingamenuforthegameThenextstepistoaddamenuforthegame.Asdiscussedintheprevioustask,wewillmakeofthemenuclassavailableathttp://www.pygame.org/project-MenuClass-1260-.html

1. ThefirststepistoimportthemenuclassintotheConnectFourgame’sPythonscript:

frommenuimport*

2. Let’screateamenuobjectwiththeStartGameoptionstolaunchthegameandExittoquitthegame.Wewillintegratethemenufromthefirsttaskofthisproject.We

Page 394: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

willgetstartedbyaddingthemenuthatneedstobedrawnonthesurface:

menu=cMenu(50,50,20,5,'vertical',100,DISPLAYSURF,

[('StartGame',1,None),

('Exit',2,None)])

3. Let’ssetthebackgroundofthemenutoabluecolor:

DISPLAYSURF.fill(BGCOLOR)

4. Usingthemenudesigndiscussedintheprevioustask,let’saddalinetolaunchthegamewhentheStartGameoptionisselected.ThegameislaunchedbycallingtherunGame(isFirstGame)method:

ifstate==0:

rect_list,state=menu.update(e,state)

elifstate==1:

runGame(isFirstGame)

isFirstGame=False

state=0

elifstate==2:

print'Exit'

pygame.quit()

sys.exit()

pygame.display.update()

AddingsoundstothegameWhilethegameisinprogress,thesoundscanbeplayedusingpygame.mixer.Refertothefollowingstepstofindouthowtodothis:

1. Let’sgetstartedbyimportingpygame.mixer:

importpygame.mixer

2. Thisisfollowedbyinitializingpygame.mixer:

pygame.mixer.init()

3. Thesoundsthatwillbeplayedwhenthegameislaunchedorwhilethegameisinprogresshavetobeloaded:

menu_sound=pygame.mixer.Sound('8-bit-circus-music.wav')

moves_sound=pygame.mixer.Sound('ding.wav')

4. WechosetousesoundsfromFreeSounds(https://www.freesound.org).ThesoundsareavailableunderCreativeCommonsLicense.

TipDinghitscanbefoundathttps://www.freesound.org/people/adcbicycle/sounds/13952/and8BitCircusMusiccanbefoundathttps://www.freesound.org/people/bone666138/sounds/198896/.

5. Inthemainmenu,let’splaythe8-bit-circus-musicfileinaninfiniteloop(until

Page 395: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

theuserlaunchesagameorexitsthemenu).

menu_sound.play(-1)

6. Theparameter-1indicatesthatthefilesneedtobefiledinaloop.7. Inordertostopplayingthesound,thestop()methodhastobecalledbefore

launchingthegame:

menu_sound.stop()#stopplayingthesound

runGame(isFirstGame)

8. Thesoundfileisplayedinalooponceagainafterthegameisover.9. Similarly,thedingsoundisplayedwheneverthegameAI(calledthecomputerinthe

game)ortheplayerhasplayedaturn:

moves_sound.play()#Playdingsound

Page 396: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–missiondebriefingWehavecompletedthebasictweaksrequiredforthegame.Inthenextstep,wewillinterfacethearcadestylebuttonstothegame.

Page 397: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 398: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InterfacinggameinputsusingthePiFacemoduleInthistask,wewillreviewinterfacingthearcadestylebuttons(showninthefollowingimage)toRaspberryPitoplaythegame.Inthistask,wewilljustdiscussthesoftwarepartofthecode.

Momentaryarcadepushbuttonswitch(http://na.suzohapp.com/all_catalogs/pushbuttons/58-9111-L)

WewillmakeuseofthePiFaceinterfaceboardavailableathttp://www.piface.org.uk/products/piface_digital/tointerfacethesebuttonstoRaspberryPi.Theboardisastackableadd-onhardwarethatcanbeusedtointerfaceeightinputsandeightoutputs.ThePiFacecomeswithfourtactileswitchesandwecangetstartedwithtestingtheinputs.

ThemainreasonbehindusingthePiFaceisthatweneedtomonitortheswitchstatestodeterminethereisakeypress.ThePiFacecomeswithanI/OexpansionoptionandcanbeaccessedthroughtheSPIinterface.Thesefeaturesenablesimplecontrolofthegameinputs.

Page 399: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Prepareforliftoff1. RaspberryPi’sSerialPeripheralInterface(SPI)driversneedtoenabledbyeditingthe

/etc/modprobe.d/raspi-blacklist.conffileusingatexteditorsuchasnano:

sudonano/etc/modprobe.d/raspi-blacklist.conf

Thedriverscanbeenabledbyinsertingan#beforethefollowingline:

#blacklistspi-bcm2708

TheSPIdriversneedtobeloadedusingthemodprobecommand:

sudomodprobespi-bcm2708

Thedrivers/toolsrequiredtointerfacewiththePiFacemodulecanbeinstalledasfollows:

wgethttp://pi.cs.man.ac

.uk/download/old_install.txt

NoteTheinstallationpackagesforthePiFacemoduleareavailableasDebianpackages.Refertotheinstallationguidefromhttp://www.piface.org.uk/guides/.IfyouinstalltheDebianpackages,thePythonmoduleimportsandthemethodsusedtoreadtheinputsmightalsovaryaccordingly.

2. Let’srenamethefileandexecuteit:

mvinstall.txtinstall.sh

chmod+xinstall.sh

./install.sh

3. Oncetherequiredtoolsareinstalled,RaspberryPihastoberestartedusingthefollowingcommand:

sudoreboot

4. OnceRaspberryPihasrestarted,theemulatorthatcomesalongwiththetoolcanbetested.TheemulatorenablesyoutotestallinputsandoutputsofthePiFaceinterface.Theemulatorcanbelaunchedfromthecommand-lineterminalasfollows:

Piface/scripts/piface-emulator

5. Theemulatorinterfacewouldbesomethingliketheoneshowninthefollowingscreenshot:

Page 400: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 401: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’stestthebuttonsavailableonthePiFacemoduleusingaPythonscript:

importpiface.pfioaspfio

2. Thepiface.pfiomoduleneedstobeimportedandinitialized:

pfio.init()

3. Theread_input()methodreturnsan8-bitnumberthatrepresentstheinputstatesofalltheeightbuttons:

whileTrue:

print(pfio.read_input())

4. Eachbitofthe8-bitnumbercorrespondstoadigitalinputonthePiFacemodule.Thefollowingtableshowstheswitchpositionsthatarerepresentedbybitpositions:

S7 S6 S5 S4 S3 S2 S1 S0

Switchpositionsrepresentedbybitpositions

5. Whenaswitchispressed,aparticularbitissetandthisbitcanbeusedtointerpretthecolumnpositionoftheConnectFourgame.

6. Forexample,whenS0ispressed,thebit0issetandhencethe8-bitwordvalueis1.WhenS1ispressed,thebit1issetandthe8-bitwordvalueis2andsoon.

7. WeignorescenarioswhentwoswitchesarepressedatthesametimeastheConnectFourgameinvolvesplayingonlyonecolumnatatime.

8. TheConnectFourgamewasdesignedtobeplayedusingamouse.Let’sperformsometweakstoplayitusingbuttons.Let’sgetstartedbycommentingoutthegetHumanMove()function.

9. Whenthegameisplayedusingamouse,thecoinisactuallydraggedanddroppedbytheplayer.Thisneedstobesimulatedwhileusingthebuttons.Inordertodoso,let’screateacopyoftheanimateComputerMoving(board,column)methodandrenameitasanimatePlayerMoving(board,column).

10. Inthegame,thecomputerplaystheredcolourcoinswhilethehumanplayerplayswiththeblackcolourcoins.So,let’schangetheanimatePlayerMoving(board,column)methodtosimulatethehumanplayer’scoinmovements.

11. ThefollowingarethemodificationsrequiredintheanimatePlayerMovingmethod:

x=REDPILERECT.left

y=REDPILERECT.top

drawBoard(board,{'x':x,'y':y,'color':RED})

animateDroppingToken(board,column,RED)

12. Similarly,themaingameloopalsoneedstobemodifiedtosimulatethehumanplayer’sgamemoves:

ifturn==HUMAN:

Page 402: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

animatePlayerMoving(mainBoard,0)

makeMove(mainBoard,RED,0)

moves_sound.play()

ifisWinner(mainBoard,RED):

winnerImg=HUMANWINNERIMG

break

turn=COMPUTER#switchtootherplayer'sturn

13. Thenextstepistointerfacethebuttonstothegame.Thefollowingcodeneedstobeaddedunderthehumanplayer’sturn:

#waitforabuttonpress

whilecolumn==0:

column=pfio.read_input()

column_position=0

ifcolumn==1:

column_position=0

elifcolumn==2:

column_position=1

elifcolumn==4:

column_position=2

elifcolumn==8:

column_position=3

elifcolumn==16:

column_position=4

elifcolumn==32:

column_position=5

elifcolumn==64:

column_position=6

14. Weusetheread_input()functiontodetectanybuttonpress.Whenabuttonispressed,thereturnedvaluecanbeanywherebetween1and64.Thereturnvalueisusedtoidentifythecolumnpositionandthecoinmovementissimulated.

15. Similarly,themainmenuofthegameneedstobemodifiedtobecontrolledusingbuttons.Thegameislaunchedwhenbutton1ispressedandtheplayerleavesthegamewhenabuttonispressed:

ife.type==EVENT_CHANGE_STATE:

ifstate==0:

rect_list,state=menu.update(e,state)

column=0

whilecolumn==0:

column=pfio.read_input()

pygame.display.update()

ifcolumn==1:

state=1

elifcolumn==2:

state=2

ifstate==1:

menu_sound.stop()

runGame(isFirstGame)

Page 403: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

isFirstGame=False

state=0

prev_state=1

elifstate==2:

print'Exit'

pygame.quit()

sys.exit()

Page 404: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wecompletedthetransferofcontrolstomakeuseofthearcadestylebuttons.WewillnowproceedtothenextstagewherewewilldiscussthegameAI,marqueedesign,andsoon.

Page 405: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 406: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AbriefdescriptionoftheConnectFourGameAIInthistask,wewilldiscussthegeneralmechanismofthegame.Wewilldiscussthefunctioncallsused,gameflow,andageneralideaofthegamemechanism.Itwouldbeagoodideatofollowthiscodereviewalongwiththegamecodeavailableinthisproject.

Page 407: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWearebuildingthisarcadegamebasedonthecodefromMakingGameswithPython&PygamebyAlSweigart(http://inventwithpython.com/makinggames.pdf).Thisbookisaninterestingreadanditshouldenableustobuildourownarcadegame(notnecessarilytheConnectFourgame).

Page 408: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’sgetstartedwithreviewingthegeneralstructureofthegameusingtheflowchart

showninthefollowingdiagram:

2. Thefirststepistoimportthemodulesrequiredtolaunchandplaythegame.Thisincludesthepygame,pygame.mixer,piface,andserialmodules.

3. Afterimportingtherequisitemodules,gameparameterssuchasgamedifficulty,boardsizeintermsofwidthandheight,backgroundcolor,windowsize,colorsofthecomputer,andplayercoinsareinitialized.

4. Thegamemenuisinitializedandrenderedonthegamescreentoawaitabuttonpressbytheplayer.

Maingameloop1. Whenthestartbuttonispressed,therunGamefunctioniscalledtostartthegame.If

thegameisbeinglaunchedforthefirsttime,theisFirstGamevariableissettotrue.Thecomputeralwaysplaysfirstfortheveryfirsttimeafterthegameislaunchedandthefirstturnisrandomizedforconsecutiveplays.

2. Whenanewgameisinitialized,thegetNewBoardmethodiscalledtocreateanemptyboardobjecttogetstartedwiththegame.Allgamemovesbythecomputerandthehumanplayerarerecordedtothisobject.Thisisusedtodeterminewhetherthereisa

Page 409: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

winneraswellasthecomputertodeterminepotentialmovestoplaythegame.3. Onceweenterthemaingameloop,thegameloopisdividedintotwotasks,the

computerandthehuman’sturn.4. Whenitistheplayer’sturn,wewaitfortheplayertoplaytheirturnusingthe

buttons.Whenabuttonpressisdetected,usingtheanimatePlayerMovingmethod,acoindropissimulated.Thegame’sboardobjectisupdatedwiththelatestmove.

5. Thisisfollowedbythecomputer’sturn.ThegetComputerMovemethodcallsthegetPotentialMovesfunctiontodeterminethebestpossiblemovesavailableforthecomputer’sturn.Then,thecomputer’scoindropissimulatedusingtheanimateComputerMoving()method.

6. ThegameAIrunsacheckaftereachturnhasbeenplayedtodeterminewhethertheplayerorthecomputerisawinnerusingtheisWinnermethod.

7. Ifeitherofthemhaswonthegame,animagedeclaringthewinnerischosen.Thegamealsocheckswhetherthegamewasatie.Wheneitheroftheearliermentionedthreeeventsoccur,theprogrambreaksoutofthegameloopanddisplaysthewinner(oratie)andwaitsforthestartbuttoneventtoreturntothemainmenu.Consequently,thiswillenableyoutostartanewgame.

Page 410: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingNowthatthecodereviewiscomplete,let’smoveontothenexttasktoimplementasimplemarqueeandwireuptheinputbuttons.

Page 411: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 412: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Marqueedesignandcontrol(optional)Inthistask,wewillimplementthemarqueecontrolforourarcadegame.Wewilldisplayinformationsuchastheplayer’sturn(whetheritisthecomputerorthehumanplayer’sturn),thewinnerofthegameattheend(orwhetheritwasatie),orgame-specificmessagesonthemarquee.WewillusethePiLiteLEDMatrixdisplay(http://shop.ciseco.co.uk/pi-lite-lots-of-leds-for-the-raspberry-pi-1206-red/)thatcanbeusedtoscrollmessagesacrossthedisplay.

PiLite–Courtesy:TheCisecoPLCwebsite

Page 413: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThePiLitedisplaycanbepurchasedfromtheCisecoPLCwebsite(http://shop.ciseco.co.uk/pi-lite-lots-of-leds-for-the-raspberry-pi-1206-red/).Thedisplaycostsabout33USD.

Oneoftherequirementsistheseriallibrary,whichisrequiredtocontrolthedisplay.Itcanbeinstalledasfollows:

sudoapt-getinstallpython-serial

Oncewearedoneinstallingthemodule,weshouldbeabletoimportthemoduleandstartprogrammingthemessagesinourgame.TheCisecoPi-LiteGitHubrepositorycomeswithexamplessuchastheBarScrollexample.Itisessentialthatyoudownloadsuchexamplesandtestifthepython-serialmoduleisfunctionallycorrect.

Page 414: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillgetstartedbyimportingtheserialmoduleandinitializingtheserialport

parameters,includingthebaudrateandportname:

importserial

serialport=serial.Serial()

serialport.baudrate=9600

serialport.timeout=0

serialport.port="/dev/ttyAMA0"

2. Afterinitialization,theserialportisopenedtostartscrollingthemessagesacrossthedisplay:

try:

serialport.open()

exceptserial.SerialException,e:

sys.stderr.write("couldnotopenport%r:%s\n"%(port,e))

3. Asanexample,wewilldisplaytheWelcometoConnectFourGamemessageinthemaingamemenu:

column=pfio.read_input()

serialport.write("WelcometoConnectFourGame")

pygame.display.update()

Page 415: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wefinishedintegratingtheLEDdisplaytoRaspberryPithatrunsthegame.

Page 416: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 417: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SetupoftheswitchesusingacardboardboxInthistask,wewilldesignourarcadegamecabinetusingcardboard.Wewillusecabletiestomountthecomponentsofourarcadegame.Wewillleaveittothereadertodesignabettercabinetusingtoolsoftheirchoice.

Page 418: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeshouldputtogetheramonitor,RaspberryPi,speakers,andthepushbuttonsusedtoplaythegame.Wealsoneedplentyofcardboardtoprototypethedesignofourcabinet.

Page 419: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’sgetstartedwithmountingtheswitches.Theswitcheswillbemountedontoa

cardboardbox.2. Wegetstartedbymountingthearcadestylepushbuttonsonacardboardbox.The

arcadestylepushbuttonsusedinthisprojectrequireaholethatis1.13inchesindiameter.Carefullycreatetheholesusingasharpobject.

NoteDonothurtyourselfwhilehandlingsharpobjects.Parentalsupervisionisrequiredifchildrenareworkingonthisproject.

3. Oncethemountingholesarecutoutofthecardboardbox,weneedtomounttheswitchesasshowninthefollowingimage.Theswitchesarelockedinplacebyalocknutfromthebackside.

4. ThenextstepistointerfacethebuttonstothePiFacemodule.ThePiFacemanualdescribesthatthedigitalinputshavepullupresistorsandhencetheswitchescanbeconnectedasshowninthefigurethatfollows:

5. ThecommonterminalofthebuttonneedstobeconnectedtothegroundterminalofthePiFacemodule.Thenormallyopen(N.O.)terminalofthebuttonisconnectedtothedigitalinputterminals(S0throughS7)ofthePiFacemodule.

Page 420: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SuggestedinputconnectionsprovidedbythePiFacemanual

6. ThenextstepistoconnectamonitortoRaspberryPi.ThefollowingfigureshowsamonitorwiththeConnectFourgamelaunchedandtheswitchesmountedontoacardboardboxandinterfacedwiththePiFacemodule:

Page 421: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 422: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wefinishedsettingupthedesktopConnectFourgameusingRaspberryPi.

Page 423: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 424: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,weaccomplishedthefollowing:

1. WeusedaPythonscriptfortheConnectFourGameandtweakedittoourrequirements.

2. Weimplementedinputcontrolsusingarcadestyleswitches.3. Wewroteaprogramtocontrolthemarquee.4. Wealsosetupthingsonacardboardboxtoplaythegame.

Page 425: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 426: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisproject,weperformedcontroloftheinputswitchesasablockingoperation.Canyoufigureouthowtomonitorswitchpresseventsbystartingmultiplethreads?Howcanweimprovethespeedofthegame?

Page 427: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

References1. MakingGameswithPythonandPygameisavailableat

http://inventwithpython.com/makinggames.pdf.2. PiFaceGuidescanbefoundathttp://www.piface.org.uk/guides/.3. Pi-LiteUsers’Guidecanbefoundathttp://openmicros.org/index.php/articles/94-

ciseco-product-documentation/raspberry-pi/280-b040-pi-lite-beginners-guide.

Page 428: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 429: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter9.TheRaspberryPi-enabledPet/WildlifeMonitorInthisproject,wewilldiscusshowtheRaspberryPicaninteractwithotherdevicesonanetwork.Thisdevicecaneitherbealaptop,anArduino,oranyotherdeviceconnectedtoanetwork.WewillmakeuseofthecapabilityoftheRaspberryPitoactasacontroldeviceinthenetworkandimplementasimplesolutionthatcansafelyinteractwithourpreciouslittleanimalfriends.

Page 430: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewilllearntobuildaninteractivepetorwildlife(wecallitwildlifeinthecontextofanimalsthatarenotdomesticated,forexample,wildcats)monitorthatcanbemonitoredandcontrolledwithinanetwork(withsomeextraeffortyoushouldbeabletocontrolanywhereontheWeb).ThisprojectpresentsthreedifferentpossibilitieswherewecanmakeuseoftheRaspberryPiincombinationwithotherdevicestobuildaninteractivedeviceforpetsthatdispensetreatstointerfacewithdevicesthateitherinteractwithpets/feralcats/birds.Thisinteractivedevicecaneitherbeacamerathatcapturesamoment(forexample,awildbirdcomingandeatingoutofyourbirdfeeder)orarelayboardactivatedtofeedtreatstoouranimalfriendwhileweareawayfromhome.

NoteThisprojecthasbeenpresentedasanexampletohelpapersonenhancethequalityoflifefortheiranimalfriends.Thisprojectshouldnotbeconstruedasareplacementofhumaninteractionforouranimalfriends.Wetotallyunderstandthatpetseasethestressinourlivesandthisprojectpresentssomeexamplestomaketheirlivesbetter.

Page 431: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?WearedemonstratingthecapabilitiesoftheRaspberryPiwhilebuildingapetmonitor.Thiscanbeadoptedinanyapplicationwherethereneedstobeexchangeofinformationbetweendevices.ThisprojectdemonstratestheuseoftheRaspberryPiinthebettermentofourlivesfromanotherperspective.Ourpetsandotherferalfriends(forexample,birdsorferalcats)thatvisitusareourfamilymembersandwetryourbesttotakecareofthem.OurgoalinthisprojectistomaketheRaspberryPidoourjobbetter.

Page 432: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesInthisproject,wewillexplorethefollowingtopics:

Installingandtestingthepython-twistedframeworkSettingupandtestingSparkCoretointeractwithappliancesInstallingandtestingtheGoogleCoderprojectontheRaspberryPiAbriefoverviewofabirdfeederthattriggersacamera

Page 433: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistForthisproject,wewillneed:

1. ARaspberryPiplusSDcard(atleast4GBinsize)2. Anyoneofthefollowingboards:

AnArduinoEthernetboard(http://arduino.cc/en/Main/arduinoBoardEthernet)ASparkCoreboard(https://www.spark.io/)AnArduinoUnoplusESP8266board(http://www.banggood.com/ESP8266-Remote-Serial-Port-WIFI-Transceiver-Wireless-Module-p-947259.html)AfewresistorsandLEDstotestthingsoutAUSBwebcameraortheRapberryPi’scameramodule

Page 434: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 435: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Installingandtestingthepython-twistedframeworkInthistask,wewillreviewthepython-twistedframework(https://twistedmatrix.com/trac/).TheTwistedframeworkisanopensourceevent-drivennetworkenginethatcanbeusedtosendcontrolmessagestootherdevices(forexample,apetfeedercanbeoperatedusingRaspberryPitodispensesolidfoodtoouranimalfriends).ThemessagingprotocoliscalledAMP(AsynchronousMessagingProtocol)whichisavailableathttp://amp-protocol.net/.

Page 436: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffTheRaspberryPi(withanSDcardflashedwiththeOSimage)connectedtotheInternetisneededforthistaskalongwithanArduinoEthernetBoard(oranyoneoftheboardsmentionedearlierinthechecklist.Networkconnectivityisessential).Wewillinstallthepython-twistedframeworkandreviewaquickexampletoexchangemessagesbetweenArduinoandtheRaspberryPi.

Page 437: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Thepython-twistedframeworkcanbeinstalledfromtheterminaloftheRaspberry

Piasfollows:

sudoapt-getinstallpython-twisted

2. Oncetheinstallationiscomplete,itistimetoreviewanexampleofthepython-twistedframeworktotesttheframework(http://twistedmatrix.com/documents/current/_downloads/simpleserv.py).

1. Inthistask,wewilllaunchaserverontheRaspberryPiandtrytocommunicatetotheserverwithinthelocalnetwork.

2. Let’smodifytheprecedingexampletobindthepython-twistedservertotheIPaddressofRaspberryPisothatwecanexchangemessageswithotherdevicesonthenetwork.ThisdevicecaneitherbeanArduinooralaptop.

3. WewillmodifythelistenTCPmethodtobindtheservertotheIPaddressoftheRaspberryPiandlistentoincomingmessagesattheportaddress,8000.

reactor.listenTCP(8000,factory,50,'192.168.1.89')

4. ThewebservercanbelaunchedbyexecutingaPythonscript.5. Now,usingalaptopthatisconnectedtothesamenetwork,let’smodifythe

simpleclient.pyscripttosendandreceivemessagestotheserverjustlaunchedontheRaspberryPi(https://twistedmatrix.com/documents/14.0.1/_downloads/simpleclient.py).

6. InordertoconnecttotheserverlaunchedonRaspberryPi,theconnectTCPmethodneedstobemodifiedtoincludetheIPaddressthattheclienthastoconnect:

reactor.connectTCP('192.168.1.89',8000,f)

7. Inthisexample,theRaspberryPiistheserverandthelaptopistheclient.Theserverinthisexampleechoesallincomingmessages.Thus,whentheclientconnectsandsendsamessage,theoutputwillbesomethinglike:

Serversaid:Hello,World!

connectionlost

Connectionlost-goodbye!

3. Nowthatwehaveinstalledtheserver,let’sdiscussasimpleArduinosketchtointeractwiththeserverlaunchedontheRaspberryPi.Thesketchisavailablealongwiththisproject’sdownloads(TwistedFrameworkTest.ino).

1. WewillgetstartedbydeclaringanIPaddressobjectthatincludestheIPaddressofRaspberryPi:

//MACAddressoftheArduino

bytemac[]={0x90,0xA2,0xDA,0x0F,0x02,0xFC};

//IPAddressoftheRaspberryPi

IPAddressserver(192,168,1,89);

Page 438: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

2. TheArduinoactsasaTCPclientandconnectstotheRaspberryPi:

if(client.connect(server,8000)){

Serial.println("connected");

client.println("Hello,World!");

client.println();

//Letswaitfortheclienttoreadand

//echothemessage

//Note:Asecond'sdelayisabitexcessive

delay(1000);

//Ifthereisaresponsefromtheserver

//echobackthemessage

Serial.println("Serversays:");

while(client.available()){

charc=client.read();

Serial.print(c);

}

client.stop();

Serial.println("ClientDisconnected");

}else{

Serial.println("connectionfailed");

}

3. TheArduinoclientconnectstotheRaspberryPiandtransmitstheHello,World!message.TheRaspberryPiechoesbackthemessagetotheArduinoclient.Ascreenshotoftheserver’sresponsetotheclientisshownasfollows:

Page 439: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InteractionoftheArduinoclientwiththeRaspberryPi

4. WedemonstratedtheabilitytotransmitandreceivemessagesbetweenArduinoandtheRaspberryPi.

Page 440: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingAttheendofthisproject,wewilldiscussmakinguseofthepython-twistedframeworkandanArduinoEthernetboardtohelpyoucontrolacameratriggerorremotelydispensetreatsusingapetfeeder.

Page 441: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 442: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettingupandtestingSparkCoretointeractwithappliancesInthistask,wewillsetupSparkCore.ItisadevelopmentboardthatmakesbringingWi-Fitohardwareveryeasy.WewillusetheCoreforthisprojectbecausewelovethesimplicityofthesetupandoperation.YoucanreadmoreaboutSparkCoreattheofficialwebsite,https://www.spark.io/.

Youarewelcometouseasimilardeviceofyourchoosing.AgoodalternativewillbetouseanArduinowithaWi-Fiadapter/shield(forexample,theESP8266Wi-Fimodulecanbefoundathttp://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module)orifyouprefer,anEthernetshield(asdiscussedintheprevioustaskofthisproject).

Page 443: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInthistask,wewillsetuptheSparkCore.PoweruptheSparkCoreusingamicro-USBcableconnectedtoapowersource(5Vsource).Itcanbepoweredusingabatterypack,alaptop,ora5VUSBwallwart.Basedonyourprojectneeds,youcanuseabatterypackifthesensornodeforthepetmonitorhastobeinstalledoutdoors.

TheeasiestwaytoconnecttheSparkCoretoyourWi-Finetworkisthroughaphoneapplication.ThisandothermechanismsaredetailedontheSparkCorewebsite(http://docs.spark.io/connect/).WewillsetupourSparkCorebydownloadingtheapplicationontoanAndroidphoneandSamsungGalaxyS5throughtheGooglePlaystore(https://play.google.com/store/apps/details?id=io.spark.core.android&hl=en).TheappsearchesforSparkCoresinrangeandifyousupplytheWi-Fipassword,itsendsthecodetotheCore(s)andletsitconnecttoyourWi-Fi.

TheSparkCoreboard

Page 444: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngageThrustersWewillwarmupbyimplementingtheLEDexampleonSparkCoreorsomethingsimilar.

ThedocumentationincludescodetoconnectanLEDwitharesistortotheCore(http://docs.spark.io/examples/).Wedecidedtodosomethingevensimpler.ThereisalreadyanLEDconnectedtopinD7andwedecidedtoturnthisoneoninstead.

AlltheappsyouneedcanbedownloadedtoacustomwebpageavailableforeachSparkCorethroughausernameandpassword.

OnceyouhavesetuptheCore,youwillcreateausernameandpassword.FordifferentCores,youwillneeddifferentusernames.Usingthis,youcangototheSparkhomepage(http://www.spark.io/)andclickontheBuildbutton.Thistakesyoutothehomepageofthedevelopmentenvironment.

Usingthisdevelopmentenvironment,wecreatedasimpleLEDblinkingapplication:

voidsetup(){

pinMode(7,OUTPUT);

}

voidloop(){

//turntheLEDon(HIGHisthevoltagelevel)

digitalWrite(7,HIGH);

//waitforasecond

delay(1000);

//turntheLEDoffbymakingthevoltageLOW

digitalWrite(7,LOW);

//waitforasecond

delay(1000);

}

NoteTheprecedingcodeiswritteninCprogramminglanguage.Ifyouarejumpingdirectlytothisprojectfromotherprojects,wesuggestthatyoufamiliarizeyourselfwiththeArduinoorSparkCoreplatform.Somelearningresourcesareavailableathttps://learn.adafruit.com/search?q=Arduino

Asyoucansee,theappisquitesimple;theappsetsupthepin7asoutput.TheprogramturnsontheLEDforasecondandturnsitoffforonesecond.

Now,let’sdiscussanexamplethatismoreorlesssimilartotheexamplediscussedintheprevioustask:

TCPClientclient;

//IPAddressoftheRaspberryPi

byteserver[]={192,168,1,89};

voidsetup()

{

Serial.begin(9600);

while(!Serial.available())SPARK_WLAN_Loop();

Page 445: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

delay(1000);

Serial.println("connecting…");

if(client.connect(server,8000)){

Serial.println("connected");

client.println("Hello,World!");

client.println();

//Letswaitfortheclienttoreadand

//echothemessage

//Note:Asecond'sdelayisabitexcessive

delay(1000);

//Ifthereisaresponsefromtheserver

//echobackthemessage

Serial.println("Serversays:");

while(client.available()){

charc=client.read();

Serial.print(c);

}

client.stop();

Serial.println("ClientDisconnected");

}else{

Serial.println("connectionfailed");

}

}

voidloop()

{

//Nothingtodohere

}

TheonlydifferencebetweenthepreviousexampleandthisexampleisthatthelatterusestheTCPClientclasswhiletheformerusestheEthernetClientclass.

Page 446: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingThat’sit.YounowhaveSparkCore,allsetupandreadytogo,withyourusername,andyourownpagetodownloadappsandcollectandtransmitdatathroughtheCore.

Page 447: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 448: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

InstallingandtestingtheGoogleCoderprojectontheRaspberryPiThisisprobablythesimpleststageoftheprojectasyoushouldbefamiliarwithsettinguptheRaspberryPiforfirstuse.

TheGoogleCoderisatoolreleasedbyGooglethatenablespeopletolearnwebdevelopmentusingtheRaspberryPi.Itisatoolthatprovidesanintuitivelearningprocess.AfterinstallingtheGoogleCodertool,wewilltestinterfacingtheGPIOpinsoftheRaspberryPitothewebinterface.

Page 449: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeneedtodownloadtheGoogleCoderimagefromitsrepository.TheGoogleCoderimageisavailableathttp://googlecreativelab.github.io/coder/.

Page 450: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’sgetstartedwithsettingupGoogleCoderfortheRaspberryPi.Oncetheimage

isdownloaded,wehavetoinstalltheimageontoanSDcard.IfyouarenotfamiliarwiththeinstallationoftheRaspbianimageontoanSDcard,thefirstprojectofthisbookisreallyhelpful(wethink!).

2. OncetheRaspberryPiispoweredupafterflashingtheSDcard,MacBookusersmaylaunchthetoolfromabrowserbygoingtohttp://coder.local.

3. WindowsusershavetoinstallApple’sBonjourPrintServicesforWindows(http://support.apple.com/kb/DL999).Onceinstalled,theGoogleCodertoolcanbelaunchedusingaChromebrowser.Now,theGoogleCoderplatformcanbeaccessedathttp://coder.local.

4. Thesetupprocessisreallysimple.Ifeverythingwentasplanned,weshouldbeabletoseethelandingpageoftheGoogleCoderapplication.

TheGoogleCoderlandingpage

5. Let’stesttheBlinkyLightsexamplefromtheGoogleCoderprojectavailableathttp://googlecreativelab.github.io/coder-projects/projects/blinky_lights/.Theexampleprovidesdetailedinstruction,includingthecircuitryandcoderequiredtosetupaswitchtoreadbuttonstatesfromtheGPIOinterfaceoftheRaspberryPi(Wechosetoskiptheexplanationastheexamplealreadyprovidesadetailedelaborationoftheexamplecode).

6. TheBlinkyLightsexampledemonstratestheuseofthenode.jsbasedGPIOhelper(https://www.npmjs.com/package/pi-gpio)toread/writeGPIOpins.

Page 451: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–objectivecompleteWewillmakeuseofthethreetasksdiscussedinthisprojecttoputtogetheratriggerthatcomestoeatoutofabirdfeeder.

Page 452: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 453: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AbriefoverviewofabirdfeederthattriggersacameraInthistask,wewillsetupabirdfeederwithamotionsensor.Wheneverabirdfliesintofeedonthegrainsoutofthefeeder,themotionsensoristriggeredtosendamessagetotheRaspberryPi.AcameramoduleoraUSBcameraisconnectedtotheRaspberryPi,whichcapturessomebeautifulmomentsinourbackyard.

SrihariYamanoor(oneoftheauthorsofthisbook)hasanextensivebackyardwherethisbirdfeederhasbeeninstalled.Checkoutthisbook’swebsitetofindoutwhetherwehavecapturedanybeautifulmomentsthusfar!

Page 454: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInordertobuildthisinteractivepetfeeder,weneedthefollowingitems:

Apetfeeder.(Availablefromhomeimprovementstores,forexample,HomeDepot,Lowes,andsoon).ThePIRsensor(http://www.adafruit.com/product/189).SparkCoreoranyWi-Fienabledboard.AUSBbatterypack(http://www.adafruit.com/products/1959).rd(http://www.adafruit.com/products/64).RaspberryPiwithaTwistedframeworkinstalled.ARaspberryPicameramodulewithalensattachment.Forexample,http://store.cutedigi.com/raspberry-pi-camera-module-5mp-wide-angle-160-degree/.

Page 455: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. ThefirststepinvolvedinprogrammingSparkCoreistodetectthemotionsensor

eventsandpublishthoseresultstoRaspberryPi.2. ThesensorneedstobeconnectedtoSparkCoremountedonthebreadboardasshown

inthefollowingfigure:

AmotionsensorconnectedtoSparkCore

3. WewillmodifytheexamplefromAdafruitthatprintsthemotionsensorevents(https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/using-a-pir).

4. Wheneveramotioneventisdetected,weneedtosendanalerttothepython-twistedserverlaunchedonRaspberryPi:

if(client.connect(server,8000)){

Serial.println("MotionDetected");

client.println("MotionDetected");

client.println();

//Letswaitfortheclienttoreadand

//echothemessage

//Note:Asecond'sdelayisabitexcessive

delay(1000);

client.stop();

Serial.println("ClientDisconnected");

}else{

Serial.println("connectionfailed");

}

5. Inordertotakepicturesofthebirdfeederwhenthereisanincomingmotiondetectionevent,thecamerahastobeinterfacedtotheRaspberryPiasdemonstratedinthevideoprovidedbytheRaspberryPiFoundation(https://www.youtube.com/watch?v=GImeVqHQzsE).

6. Inordertotriggeracameratotakeasnapshotusingthepython-twistedserver,we

Page 456: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

needthepicameramodule(https://pypi.python.org/pypi/picamera).Itcanbeinstalledasfollows:

sudoapt-getinstallpython-picamera

7. Let’smodifythepython-twistedexample,simpleserv.py,toimportthepicameraanddatetimemodules(tonamethepicturescapturedbythecamerausingatimestamp).

8. IftheincomingmessageisMotionDetected,wewilltakeapictureandnamethefileusingatimestamp.

9. Inthecallbackmethod,DataReceived,let’scaptureanimage:

withpicamera.PiCamera()ascamera:

camera.start_preview()

time.sleep(2)

camera.capture('img{timestamp:%Y-%m-%d-%H-%M}.jpg')

Page 457: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 458: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Abirdtrigger

Page 459: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingCheckoutthisbook’swebsitetolookattheRaspberryPiandSparkSensorsetupthatisusedtotakepictures.Thisisreallyhelpfultolearnmoreaboutthebirdsinyourneighborhood.

Alternativesandprojectideastoconsider1. Inthisproject,wediscussedtheexamplesusingtheSparkCoreandtheArduino

Ethernetboard.AnotherexampletoconsideristheEPS8266module,whichisavailableathttp://www.banggood.com/buy/Esp8266.html,andcostsabout3USD.Refertothisbook’swebsiteforsettinguptheESP8266moduletoemulatetheseexamples.

2. InProject4,ChristmasLightSequencer,weusedaPowerSwitchTailandarelayboardexampletocontroldecorativeappliances.Similarly,wecanusethemtocontrolautomaticpetfeederstodispensetreats.

Page 460: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 461: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,weinterfacedbuiltasmallecosystemofdevicesthatweremonitoredbytheRaspberryPi.Weusedthoseexamplestobuildabirdfeeder!

Page 462: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 463: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeInthisproject,wediscussedinterfacingasensortotakepicturesofbirdsthatcometofeedfromthebirdfeeder.Isitpossibletouploadthevideofeedtosomewherethat’ssecureovertheInternet?Howdowedothis?

Page 464: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 465: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter10.RaspberryPiPersonalHealthMonitorInthisproject,wewilldiscussimplementingasolutionwhereRaspberryPiactsasapersonalhealthmonitor.Wewouldliketodedicatethisprojecttoallthepeoplewhohavebeendiagnosedwithtype2diabetesoranyotherlifestylediseases.Thisprojectpresentssometricksforthosediagnosedwithsuchlifestylediseases.

NotePleasedonotconsiderthisprojectasanalternativetoexistingtreatmentandpractices.Thisproject’strickswillhelpyouleadabetterlife.Forexample,yourRaspberryPicanremindyoutotakeyourprescribedmedication(ifany).

Page 466: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewillbuildsomesolutionstoaddresscommonproblemsencounteredbypeoplewithlifestylediseases.SimilartoProject6,RaspberryPiasaPersonalAssistant,thisprojectpresentsdifferenttipsandtrickstoleadabetterlifeineachtask.Wewilldiscussexampleswhereapersoncanbuildasimplewebservertostorehis/herdailyvitalhealthparameters(forexample,bloodpressure,bloodoxygensaturationlevels(SpO2),andsoon).Also,theservercanhelpapersontoremainphysicallyactivethroughtheday,provideaquickrecapofthee-mailparser,providetheeventremindertoolfromProject6,RaspberryPiasaPersonalAssistanttoremindapersonaboutupcomingappointments,refillhis/herprescriptions,andsoon.

Page 467: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Wedecidedtowritethisprojectbasedonthepersonalexperienceofoneoftheauthors’familymember.Itisquitestressfulforapersonwhenhe/sheisdiagnosedwithachronicconditionssuchastype2diabetes.Thepersonissubjectedtostressfulconditionsrelatedtochangeindailyfoodhabits,developingahabitofconsumingmedicationeveryday,andbeingmindfulofwhathe/sheeatseverydaywhilstensuringthattheircriticalhealthparametersareintact.Itisobviouslydifficulttoacceptasuddenchange,andthisprojectpresentssomeoptionstomitigatesuchdifficultiesandbringtheperson’shealthbackontrack.

Page 468: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesInthisproject,wewillreviewthefollowingexamples:

SettingupawebservertorecordhealthparametersAsimplephysicalexercisetoolusingRaspberryPiSettingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointmentAsimpletoolthatremindsapersontotakehis/herpills

Page 469: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistItwouldbegreattohavethefollowingcomponentsforthisproject:

ARaspberryPialongwithanSDcard(ofatleast4GBinsize)thathasbeenflashedwithanimageandrequisitepowercable.AnArduinoEthernetboard(http://arduino.cc/en/Main/arduinoBoardEthernet).Thisiscompletelyoptional.Atactileswitch,resistors(10K),andapiezoelectricbuzzer(allthesecomponentsareavailablefromRadioShack).ItwouldbegreattohavetwoRaspberryPiboardstobuildthephysicalexercisetoolusingRaspberryPi.

Page 470: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 471: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettingupawebservertorecordhealthparametersInthistask,wewillbuildasimplewebserverthatcanbeusedtomaintaincriticalhealthparameters.Let’sconsiderascenariowhereapersonisdiagnosedwithhighbloodpressure.Thedoctorasksthepatienttorecordhis/hervitalhealthparameterssuchaspulse,oxygenlevel,orbloodpressure.Forthissituation,wewillbuildasimplewebpagethatrecordsthedataandstoresitinaCSVfile.

Page 472: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillbeusingtheFlaskframework(http://Flask.pocoo.org/)todeploythewebserveronRaspberryPi.WemadeuseoftheFlaskframeworkinProject4,ChristmasLightSequencer.JustincaseyouskippedthroughProject4,ChristmasLightSequencer,aPythonpackagemanagersuchaspiporeasy_installisrequiredtoinstalltheFlaskframework:

sudoapt-getinstallpython-pip

AftertheinstallationofthePythonpackagemanageriscomplete,theFlaskframeworkmaybeinstalledasfollows:

sudopipinstallFlask

Page 473: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. WewillmodifythisbasicFlaskframeworkexample

(http://runnable.com/UhLMQLffO1YSAADK/handle-a-post-request-in-Flask-for-python)totakeinputfromabrowser:

Inthefrontendofthewebserver,let’screatetextboxesintheform_submit.htmlfilewherewecanenterthebloodpressure,oxygensaturationlevels,andpulsedata.Thelandingpagewilllookliketheoneshowninthefollowingfigure(whenopenedinabrowser):

Theformusedtorecordvitalhealthparameters

InthePythonscriptthatlaunchesthewebserver,wereadthesubmittedparametersandwritethemtoaCSVfilealongwithatimestamp:

@app.route('/',methods=['POST'])

defrecord():

#recordallthedatafromtheform

bloodPressure=request.form['BloodPressure']

SpO2=request.form['SpO2']

pulse=request.form['pulse']

#beforewritingtoacsvfile,logtimestamps

date=datetime.today().strftime('%Y-%m-%d')

time=datetime.now().strftime('%H:%M:%S')

logfile=open('static\\comments.csv','a')

logfile.write(",".join([date,time,bloodPressure,SpO2,

pulse,'\n']))

logfile.close()

return

render_template('form_action.html',date=date,time=time,bloodPressur

e=bloodPressure,SpO2=SpO2,pulse=pulse

Oncewe’redonewritingtotheCSVfile,weredirectthesubmittedformtoa

Page 474: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

pagethatdisplaystherecordedvaluesalongwiththetimestamp(asshowninthefollowingfigure):

Thepagedisplayedaftertheresultsarerecorded

2. ItispossibletoviewtherecordeddataonthewebpagebyreadingtheCSVfile.Weleavethisforyoutofigureout(lookatthisbook’swebsitefortheanswer).

Page 475: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWebuiltasimpleFlask-framework-basedwebservertorecordvitalhealthparametersusingRaspberryPi.Itispossibletoe-mailthedataatregularintervalsusingthesmtpmoduleinPython.

Page 476: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 477: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AsimpleexercisetoolusingtheRaspberryPiInthistask,wewillreviewafunexamplethatenablesapersontobephysicallyactiveevery60minutes.

Page 478: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffThisexampleisbasedontheTwistedframeworkdiscussedinthepreviousproject.ItwouldbegreattohavetwoRaspberryPiboards(setupwiththeSDcardimagesandpoweredup)oranArduinoEthernetboard.AlaptopthatisconnectedtothesamenetworkastheRaspberryPiisjustassufficient.

IfyoumissedinstallingtheTwistedframeworkinthepreviousproject,theTwistedframeworkcanbeinstalledasfollows:

sudoapt-getinstallpython-twisted

NoteIftheseconddeviceisaRaspberryPioralaptopthatrunsLinux,Mac,orWindowsoperatingsystems,theTwistedframeworkneedstobeinstalledontheseconddeviceaswell.

Page 479: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’sperformaquickreviewofwhatwewillbuildinthisproject:

Let’sconsidertwodevicesthatcanbeconnectedtoanetwork.OneofthedevicesisaRaspberryPiwhiletheotherdevicecouldeitherbeanArduinooraRaspberryPi.Wewillreviewthecoderequiredtobuildthistoolforbothcases.Thesedeviceshavetobeinstalledattwoextremecornersinsideahouse.Thiscanbedifferentfloorsofthehouseorthefarthestcornersofthehouse.AbuzzerandabuttonwillbeconnectedtoaRaspberryPi.Thebuzzerwouldgooffevery60minutesononeofthedevices.Someonehastowalkuptothedeviceandturnoffthebuzzerbypressingabutton.

Thisenablesapersontogetsomephysicalactivitybywalkingbackandforthbetweenthetwodevices(assumingtheRaspberryPidevicesareinstalledfarawayfromthepersonintheinterestofgainingsomephysicalactivity).

NoteThisexampleisjustamotivationaltoolandacasualreminderfortheconcernedpersontoremainphysicallyactive.

2. ThebuzzerandtheswitchareconnectedtotheRaspberryPiasshowninthefollowingdiagram:

AbuttonandbuzzerschematiccreatedusingFritzing

TheprecedingbreadboardrepresentationshowsanAdafruitPiCobblermountedonabreadboard.RefertoProject4,ChristmasLightSequencer,forapictorialrepresentationofhowthePiCobblerneedstobeconnectedtotheRaspberryPi.

Page 480: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GPIO#25oftheRaspberryPiisconnectedtothebaseoftheNPNtransistor,BC547.Thetransistor’scollectorpinisconnectedtothenegativeterminalofthebuzzer.Theotherendofthebuzzerisconnectedto5V.Theemitterpinofthetransistorisconnectedtotheground.Thetransistoractsasaswitchandturnsonthebuzzerwhenthebasepinissettohigh.GPIO#18oftheRaspberryPiispulledupto3.3VandatactileswitchisconnectedtotheGPIOswitch.Theotherendoftheswitchisconnectedtotheground.

3. Let’sperformaquickreviewofthetwistedservercodethatrunsontheRaspberryPi.Similartothepreviousproject,thisexampleisalsoasimplemodificationoftheTwistedframeworkexample,simpleserver(http://twistedmatrix.com/documents/current/_downloads/simpleserv.py).

Let’screateaclassthattakescareofsettingoffthebuzzerwhenthereisanincomingmessage:

#Declareinputsandoutputs.

GPIO.setmode(GPIO.BCM)

GPIO.setup(18,GPIO.IN)

GPIO.setup(25,GPIO.OUT)

GPIO.setwarnings(False)

classAsyncTask:

def__init__(self):

self.run_state=True

#avoidingthechannelargumentthrowsanerror

defterminate(self,channel):

self.run_state=False

defadd_callback(self):

GPIO.add_event_detect(18,GPIO.FALLING,callback=self.terminate)

defrun(self):

whileself.run_state==True:

GPIO.output(25,GPIO.HIGH)

time.sleep(1)

GPIO.output(25,GPIO.LOW)

time.sleep(1)

GPIO.remove_event_detect(18)

IntheAsyncTaskclass,thebuzzercanbesetoffbytriggeringaseparatethreadtocalltherunfunction.Thissetsoffthebuzzerwithaone-secondinterval.Theadd_callbackmethodisusedtoturnoffthebuzzerwhenthebuttonispressed.Theadd_event_detectmethodwaitsforthestateofGPIO#18tochangefromhightolow.Thisturnsoffthebuzzerbysettingrun_statetoFalse.Whileexitingtheinfiniteloop,weremovethecallbackfunctionsusingtheremove_event_detectmethod.Whenaclient(Arduino,laptop,oranotherRaspberryPi)sendsamessagetotheserver,thethreadisinitializedandacallbackfunctionisregisteredasfollows:

async_task=AsyncTask()

Page 481: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

async_task.add_callback()

thread=Thread(target=async_task.run,args=())

thread.start()

Tosummarize,anincomingmessagetriggersthebuzzerandapersonhastowalktotheRaspberryPi’slocationtoturnoffthebuzzer.

4. IftheclientdevicethatsendsamessagetotheRaspberryPiisalaptopthatrunsaLinux,Mac,orWindowsoperatingsystemortheRaspberryPi,itissufficienttorunthesimpleclient.pyexampleaftermodifyingthecodetochangetheserveraddresstothatoftheRaspberryPi(https://twistedmatrix.com/documents/14.0.1/_downloads/simpleclient.py).

5. Intheprecedingexample,wedemonstrateasinglecycletosetoffthebuzzer.Thiscanberepeatedincyclesof60minutesusingabatchscript(inaWindowsenvironment)orashellscript(LinuxorMacenvironment).

6. IfthedeviceisanArduino,EthernetClienthastobeinitializedandconnectedtotheRaspberryPitosendatestmessage.Thiscanberepeatedina60-minutecycle:

Serial.println("connecting…");

if(client.connect(server,8000)){

Serial.println("connected");

client.println("Hello,World!");

client.println();

//Letswaitfortheclienttoreadand

//echothemessage

//Note:Asecond'sdelayisabitexcessive

delay(1000);

//Ifthereisaresponsefromtheserver

//echobackthemessage

Serial.println("Serversays:");

while(client.available()){

charc=client.read();

Serial.print(c);

}

client.stop();

Serial.println("ClientDisconnected");

}else{

Serial.println("connectionfailed");

}

AminiprojectideaItwillbefuntoinstallanumberofRaspberryPiboardsinthesamenetworkandimplementanasynchronousmessagingprotocol.Thisprotocolcansetoffbuzzersasachainreactiontoencouragemorephysicalactivity.Pleasenotethatthismayannoyothermembersofthehousehold.

Page 482: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingWediscussedatoolthatcanannoyapersontoremainphysicallyactive.

Page 483: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 484: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Settingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointmentInthistask,wewilldiscusssettingupanLEDtoalertapersonaboutanincominge-mailtorefillaprescriptionorwhenthereisanupcomingdoctor’sappointment.

JustincaseyouskippedthroughProject6,RaspberryPiasaPersonalAssistant,thepython-feedparsertoolandthepython-gdatatoolhavetobeinstalled:

sudoapt-getinstallpython-feedparser

sudoapt-getinstallpython-gdata

NoteThistaskissimilartothee-mailnotifierwesetupinProject5,InternetofThingsExample–AnE-mailAlertWaterFountain.WewilljustdiscussaminormodificationtoblinkanLEDwhenthereisane-mailintheinboxtorefillaprescription.

Page 485: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Wewillgetstartedbycheckingforanynewincominge-mails:

email=feedparser.parse(proto+username+":"+password+"@"+server+path)

2. Let’sassumetheprescriptionrefillremindere-mailsubjectiscalledWalgreens.WewilliterativelycheckthrougheachentryandtriggeranLEDalert:

formailinemail.entries:

ifmail.title=="Walgreens":

async_task=AsyncTask()

async_task.add_callback()

thread=Thread(target=async_task.run,args=())

thread.start()

AnasynchronoustaskcanbetriggeredtoblinkanLEDuntilthealertisacknowledgedbypressingabutton.Thecircuitryissimilartotheonediscussedintheprevioustask.

3. Thisenablesapersontorespondtoane-mailandrefillhis/herprescriptionwhennecessary.Thispreventsarefillremindergettingburiedamonge-mailsandenablesthepersontokeepatabonprescriptiondelays.

Settingupareminderfordoctor’sappointmentsThisisalsosimilartotheeventnotifierthatwediscussedinProject6,RaspberryPiasaPersonalAssistant.Let’sassumethatalldoctor’sappointmentsaresavedinthecalendarasDoctor'sappointment.Itispossibletoprominentlydisplayallupcomingdoctor’sappointmentsasfollows:

fori,an_eventinenumerate(feed.entry):

ifan_event.title.text=="Doctor'sappointment":

print'\t%s.%s'%(i,an_event.title.text,)

Intheprecedingexample,wearejustprintingittoaconsole.Youcanperhapsmakeuseofadisplay,forexample,anOLEDdisplaythatiscontrolledviaaserialport,anddisplayitataprominentlocation.

Page 486: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wecompletedthesetupofane-mailnotifiertorefillprescriptionsandareminderforanupcomingdoctor’sappointment.

Page 487: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 488: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Asimpletoolthatremindsapersontotakehis/herpillsInthistask,wewillbuildasimpletoolthatremindsapersontotakehis/herpillsontime.Thecircuitryrequiredforthisexampleissimilartotheexamplesdiscussedintheprevioustasks.Wearediscussingthisexamplebecauseitisdifficultforsomeonetodevelopahabitoftakingtheirmedicationontime.Itiscriticalthatpeopleidentifiedwithchronicconditionsdonotmisstheirprescriptionschedule.

Page 489: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeextensivelydiscussedinterfacingthebuzzertoaRaspberryPiintheprevioustask.It’llbenicetohaveanenclosureforthepillboxreminder.Anexampleofapillreminderisavailablefrominstructablesathttp://www.instructables.com/id/The-Pill-Reminder/.Wewillonlydiscusshowtotriggerthebuzzerataselectedtimeoftheday.

Page 490: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

EngagethrustersLet’ssayapersonhastotakehis/herprescribedpillsat9:30inthemorning;abuzzercanbetriggeredusingthedatetimemoduleinPython:

whileTrue:

t=datetime.datetime.now()

ift.hour==9andt.minute==30:

async_task=AsyncTask()

async_task.add_callback()

thread=Thread(target=async_task.run,args=())

thread.start()

break

OtherprojectideasSimilartotheexamplesdiscussedearlier,itisalsopossibletosetreminderstosyncpedometerdata,gotothegym,orevenrecordthehealthparametersdiscussedearlierinthisproject.

Page 491: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wecompletedthepillboxremindersetuptohelpustakeourmedicationontime.

Page 492: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 493: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,wediscussedseveralexamplesofRaspberryPiactingasapersonalhealthmonitorusingasimpleconcept.Thiscanbeadaptedfordifferentscenariosaccordingtoyourcreativity.

Page 494: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 495: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeHowcanweuseRaspberryPitoenhancethelivesofseniorcitizens?

Page 496: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 497: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter11.HomeAutomationusingRaspberryPiInthisproject,wewillreviewsomeautomationexamplesusingRaspberryPi.Theseexamplescanbeconsideredasprojectsthatcanbeexecutedoveraweekend.

Page 498: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewilldiscussdifferentoptionsavailableforautomationathomeusingRaspberryPi.Theexamplesuseasimilarconcept(moreorless)andyoucanpickthetasksofyourchoiceandturnyourhomeintoasmarthome.

Page 499: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?AquickwebsearchyieldsalotofprojectsrelatedtohomeautomationusingRaspberryPi.Wehavetriedtokeepthisprojectuniquebyensuringthatitissimpleenoughtobeexecutedoveraweekend(thoughsomeexamplesmightappearrepetitiveifyouhavebeenreadingthroughtheprojectsintheircorrectorder),whileincorporatingfeedbackfromprojectsavailableallovertheWeb.

Page 500: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesWewilldiscussthefollowingexamplesinthisproject:

AsimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheeveningAcustomarywebserverexampleTurningonalawnsprinkleronlywhenthereisanorainforecast!

Page 501: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistThefollowinghardwareitemsarerequiredforthisproject:

1. RaspberryPialongwiththenecessaryaccessories(anSDcard—atleast4GBinsize,1AUSBpowersupply,andamicro-USBpowercable).

2. PowerSwitchTailIIfromAdafruitthatisavailableathttp://www.adafruit.com/product/268.

3. Ethernetcables/Wi-Fiadapter(optional,neededtoconnecttheRaspberryPitoanetwork).

4. Sensorsofyourchoice.Forexample,Soilmoisturesensor.5. Generalhardwarefromthelocalstore(thisdependsuponthereader’sproject

requirements).6. ArduinoEthernetBoard(optional)availableat

http://arduino.cc/en/Main/arduinoBoardEthernet.

Wewillinstallthesoftwareprerequisitesaswerevieweachexampleinthisproject.

Page 502: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 503: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AsimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheeveningLet’sconsiderascenariowhereapersonlivesinaneighborhoodthatisnotsowelllit.Inwinter,thetemperaturesareusuallyextremeincitiessuchasChicagoandthesunusuallysetsaround5p.m.Thepoorlylitneighborhoodalongwiththecoldweathermakesitdifficultforapersontoentertheirhome.

Wewillbuildasimplesolutionthatturnsonalight(thatcanbeeitheranoutdoororindoorhallwaylight)thatspeedsuptheprocessofenteringabuilding.

Page 504: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInthisexample,wewillmakeuseofPowerSwitchTail2(soldbyAdafruitIndustries:http://www.adafruit.com/product/268)toturnon/offthelights.

ThePowerswitchtailisratedtocontrolappliancesratedtooperateat110Vanditcanswitchresistiveloadsupto15A.ThePowerSwitchTail2canswitchon/offapplianceswhenitisactivatedbya3-12VDCsignal.

OnemainadvantageofusingthePowerSwitchTail2isthatitisopto-isolated(opto-isolationensuresthatRaspberryPiisprotectedfromanytransientvoltageswhileturningon/offthelights)andprovidesasafealternativetointerfacingelectricalappliancestoRaspberryPi.TheimagebelowshowsaPowerSwitchTail2availablefromhttp://www.adafruit.com.

PowertailswitchII–Photocourtesy:adafruit.com

SoftwareprerequisitesWewillneedtherepositorytoolGit.Thiscanbeinstalledasfollows:

sudoapt-getgit-core

Page 505: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. PowerSwitchTail2’sdatasheet

(http://www.adafruit.com/datasheets/PST%20II%20product%20insert.pdf)providesaschematicdescriptionoftheinternalcircuitryofPowerSwitchTail2.

PowerSwitchTail2isconnectedtoRaspberryPiasshowninthefollowingfigure.Thein+terminaloftheswitchisconnectedtotheGPIO#17ofRaspberryPi,whilethein-terminalisconnectedtothegroundpinofRaspberryPi.

PowerSwitchTail2’sinterfacetoRaspberryPi

ThepowercordtothelightingequipmentneedstobeconnectedtoPowerSwitchTail2.

NoteItisassumedthatyouarefamiliarwithsomeminorrewiringtoconnectindoor/outdoorlightingappliances.Priortrainingisrequiredtohandlesuchelectricalhardware.Ifyouarenotfamiliarwithhandlingrewiring,itisbesttoconnectanoff-the-shelfelectricalappliance.

2. Let’sreviewthecodeforanexamplewherethelightsneedtobeturnedonbetween5:30p.m.and10:45p.m.everyday.

WegetstartedbycreatingUnixtimestampsforthestartandendtimes(UnixtimestampsreferstothetimeelapsedsinceJanuary1,1970inseconds.Moreinformationisavailableathttp://en.wikipedia.org/wiki/Unix_time):

#Getcurrenttime

now=datetime.datetime.now()

#Createdatetimeobjects

startTime=datetime.datetime(now.year,now.month,now.day,17,30,0)

Page 506: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

endTime=datetime.datetime(now.year,now.month,now.day,22,45,0)

#Createunixtimestamps

unixStart=(startTime-

datetime.datetime(1970,1,1)).total_seconds()

unixEnd=(endTime-datetime.datetime(1970,1,1)).total_seconds()

unixNow=(now-datetime.datetime(1970,1,1)).total_seconds()

TheUnixtimestampsareusedtocheckwhetheritistimetoturnon/offtheappliances:

if(unixStart<=unixNow<=unixEnd):

GPIO.output(25,GPIO.HIGH)

while(unixStart<=unixNow<=unixEnd):

now=datetime.datetime.now()

unixNow=(now-

datetime.datetime(1970,1,1,0,0,0)).total_seconds()

print"Triggered",now.hour,":",now.minute,":",now.second

sleep(1)

GPIO.output(25,GPIO.LOW)

Page 507: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingYay!Wearedonewithasimpleautomationtaskofkeepingthelightsonatagiventimeperiodeveryday.

Alternativesolutionsandsomeprojectideastoconsider1. IfitisnotpossibletoinstallRaspberryPirightnexttothepowertailswitch,itis

possibletointerfacethePowerSwitchTail2toanArduinoEthernetboardandcontrolledbyRaspberryPiusingtheTwistedframeworkexample(hint:refertotheexamplesfromthepreviousproject,Project10,RaspberryPiPersonalHealthMonitor).ThisenablesyoutocontrolanetworkofdevicesusingRaspberryPi.

2. OnealternativetoconsiderifitisnotpossibletopurchaseaPowerSwitchTail2—SparkFunhasanexcellenttutorialonbuildingacontrollableACpoweroutlet(https://www.sparkfun.com/tutorials/119).

3. Inthisexample,weassumedthatthelightswillbeturnedonbetweentheselectedtimeslots.Itisalsopossibletoturnonthelightsbydeterminingthesunsettime.NOAAprovidesinformationoncalculatingsunsettimes,whichisavailableathttp://www.esrl.noaa.gov/gmd/grad/solcalc/calcdetails.html.

4. Anotheralternativetoturning/offlightingappliances—itwouldbeagreatideatomakecoffeeeverydayusingPowerSwitchTail2.Ifthecoffeemakerisfilledwithwaterandthecoffeepods/filterarereplaced,thecoffeemakerwillbeturnedonatthechosentime!Wewillhaveourcoffeereadyrightaftergettingoutofbed.

NotePowerSwitchTail2isdesignedforresistiveloadsandespeciallyforlimiteduse.Donottrytouseitwithheavyinductiveloadssuchasamotor.Thistoolisstrictlyrecommendedforthosewhoareknowledgeablewiththefundamentalsofelectricalengineering.

Page 508: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 509: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

AcustomarywebserverexampleAnyhomeautomationprojectusingRaspberryPiyieldsalotofexamplesthatinvolvesbuildingawebserverthatcontrolsapplianceswithinalocalnetworkthattakescareofsecuringtheplaceusingelectromechanicallocks.WewillbuildasimplewebserverthatcanbeusedtoturnoffanLEDfromawebpage.ThisconceptcanbeexpandedtocontrolmultipleappliancesandreadsensordatafromtheGPIOinterfaceofRaspberryPi.

NoteThistaskismeantforabsolutebeginnerswhoarenotfamiliarwithPythonwebframeworktools.WearediscussingthisexampleconsideringsomereadersmightjumprighttoProject11,HomeAutomationUsingRaspberryPi.

Page 510: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWewillbebuildingawebserverusingaFlaskframework(http://flask.pocoo.org/).TheFlaskframeworkcanbeinstalledasfollows:

sudoapt-getinstallpython-pip

sudopipinstallFlask

Page 511: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Thefirstpartissettingupthelandingpage.Whenauserenterstheaddressofthe

webserver,thewebpagewouldbesomethinglikewhatisshowninthefollowingscreenshot.TheHTMLpageconsistsofasinglebuttoncalledSampleButton.

Aflaskframework-basedwebserver

2. Whenabuttonisclicked,theincomingPOSTrequestisusedtoswitchthestatesoftheLEDfromONtoOFFandviceversa:

@app.route('/',methods=['POST'])

defrecord():

#recordallthedatafromtheform

globalstate

ifstate==False:

state=True

else:

state=False

GPIO.output(25,state)

returnrender_template('form_submit.html')

3. ThewebservercanbelaunchedfromtheIPaddressofRaspberryPi.Thewebpageshouldbeaccessiblefromhttp://192.168.1.76:75:

#Runtheapp:)

if__name__=='__main__':

app.run(

host="0.0.0.0",

port=int("75")

)\

Thewebserverexampleisavailablealongwiththisproject.Checkthisbook’swebsiteformoreexamples.

Page 512: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingUsingthesimpleconceptexplainedearlier,itispossibletocontrolanyappliance(byinterfacingsomecontroldevicesuchasthepowerswitchtailtoRaspberryPi’sGPIOpins).Itisalsopossibletoreadsensorstatesaswellastrackanyspecialinformation.Forexample,itispossibletotrackthestatusofapackagethatisexpectedtobedelivered.USPSprovidesstatusofshipmentsthatcanbedisplayedonthewebpage(formoreinformationonAPIs,checkouthttps://www.usps.com/business/web-tools-apis/welcome.htm).

Inalltheseexamples,wereviewedcontrolappliancesusingRaspberryPiwithinalocalnetwork.Inthelatertaskofthisproject,wewillreviewcontrollingthedevicefromanywhereovertheInternet.

Page 513: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 514: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Turningonalawnsprinkleronlywhenthereisnorainforecast!ThisexamplewasinspiredbyacommentonanarticlerelatedtoHomeAutomationusingRaspberryPi.Thecommentermentioned:

TheonlyhomeautomationthatI’minterestedin(andstillhaven’tseen)issomethingthat’llturnoffmylawnsprinklersifit’srainedacertainamountintheprecedingdaysorifit’srainingonthedaythatthesprinklersareprogrammedtogoon.

Wedecidedtowhipupaquickexamplethatwouldturnonthesprinklerwhenitisnotgoingtorainonaparticularday.

Page 515: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffInordertochecktheweatherforecast,weneedtomakethepython-weather-apilibrary(thelibraryisdistributedwithMITlicense).WewillmakeuseoftheNOAAAPI.Thelibrarycanbedownloadedusingthewgetcommand:

wgethttps://launchpad.net/python-weather-api/trunk/0.3.8/+download/pywapi-

0.3.8.tar.gz

Thesourcefilesareavailableinacompressedfolder.Thecontentsofthecompressedfilecanbeextractedasfollows:

tar–xvzfpywapi-0.3.8.tar.gz

Onceextracted,thelibrarycanbeinstalledasfollows:

pythonsetup.pybuild

sudopythonsetup.pyinstall

WealsoneedaflowcontrolvalvesimilartothisonesoldonSparkFunavailableathttps://www.sparkfun.com/products/10456.

Page 516: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. NOAA(http://www.weather.gov/)providesweatherdatageneratedfromtheweather

stationssituatedindifferentcities.Eachcity’sweatherstationhasauniquefour-lettercode.Forexample,Chicago,Illinois’codeisKORD.Wewillmakeuseofthisfour-lettercodetoretrievetheweatherforecastforacity.

2. Theweatherdataisretrievedusingthepywapilibraryasfollows:

defmain():

pp=pprint.PrettyPrinter(indent=4)

whileTrue:

result=pywapi.get_weather_from_noaa('KORD')

pp.pprint(result['weather'])

sleep(10)

3. Wewillturnonthesprinkleronlyiftheweatherforecast(availableundertheweatherkeyword)isanythingotherthanRain,LightRain,orThunderstorm:

if(result['weather']!='LightRain'or

result['weather']!='Rain'or

result['weather']!='Thunderstorm'):

GPIO.output(25,GPIO.HIGH)

4. Thesprinklercanbeturnedonusingatransistorswitchingcircuitandarelay.(Ifyouarenotfamiliarwithtransistorswitchingcircuitandrelays,Project4,ChristmasLightSequencerprovidesinformationaboutatransistorswitchingcircuitinextensivedetail).

5. Ithasnotbeendemonstratedherebutthepywapimoduleneedstobeusedinconjunctionwiththedatetimemoduletoturnonthesprinkleratselectedtimesofday.

Page 517: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingIfitisnotpossibletointerfacethesolenoidvalvedirectlytoRaspberryPi,asthesolenoidvalvecanonlybeinterfacedtoanArduinoandcontrolledusingthepython-twistedframework.

InstatessuchasCaliforniawheretherearesometimesseveredroughts,itiscommonpracticetosavewaterfromdrainpipesusingbarrels.Thepywapimodulecanbeusedtoreplacethebarrelsifthereisanupcomingrainforecast.

Page 518: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

GainingremoteaccesstoyourRaspberryPitocontrolappliancesItispossibletoremotelylogintoRaspberryPiusingSSH(SecureShell).AnorganizationcalledWeaved(http://www.weaved.com/)providesthecapabilitiestologin.

Thetutorialavailablefromhttps://www.juicypi.io/access-your-raspberry-pi-anywhere-in-the-world-using-weaved/providesdetailedinstructionstoinstalltherequisitetools.

ThisenablesyoutocontrolthedevicesinterfacedtoRaspberryPi.

Page 519: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SomeprojectideastoconsiderInhouseswithlonghallways,itisnotalwayspossibletohearthedoorbellringfromthefarendofthehouse.Itispossibletoplaceaforcesensitiveresistor(https://www.sparkfun.com/products/9375)totrackanyvisitorstothehouse.Likewise,itispossibletotrackpackagesleftonthedoormat.InProject6,RaspberryPiasaPersonalAssistant(thepersonalassistantproject),webuiltasmallenclosuretokeeptrackofkeysusingareedswitch.Asimilarconceptcanbeusedtotrackitemsusingareedswitch.ThereisawirelessprotocolcalledZ-Wavethatwasspecificallydesignedforhomeautomationpurposes.RaspberryPicanbeturnedintoacontrolcentretowirelesslycontrolappliancesusingtheZ-Wavemodules.Raspberrycompatiblemodulesareavailableforsaleathttp://razberry.z-wave.me/(checkoutthisbook’ssiteforsomeexamples).InProject5,InternetofThingsExample–AnE-mailAlertWaterFountain,webuiltawebserverthatcansetcolorsoftheRGBLEDstrip.TherearesomeinterestingideastodecorateourhomeswiththeseRGBLEDstrips(http://www.usledsupply.com/shop/install/project-photos-and-ideas.html).GEApplianceshascomeupwithaninterestingdevelopmenttoolthatcanbeusedtocontrolproductsfromGE.ThistoolincombinationwithRaspberryPi(runningTwistedserver)canbeusedtocontrolGEproductsinsomeone’shome.Inthefuture,allGEapplianceswillbecapableofbeingconnectedtoasmartdevicesnetwork.

Page 520: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 521: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,welookedintodifferentsolutionsthatcanbeimplementedusingRaspberryPioveraweekend.Wereviewedsomebasicexamplesthatcanbepossiblytweakedtoturnahomeintoasmartone.

Page 522: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 523: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter12.UsingaRaspberryPiforScienceandEducationInthisproject,wewillreviewsomeexamplesofhowtheRaspberryPicanbeusedtoeducateourselves.WewillreviewexamplesofhowtousetheRaspberryPiforself-improvementoreducatingchildreninthefieldofscience.

Page 524: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisproject,wewillreviewsomeexamplestodemonstratehowtheRaspberryPicanbeusedtoeducateourselvesforself-improvementordemonstrateasimplephysicsexperiment.

Page 525: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?ThePi,asyouhaveseeninthelastfewprojects,offersyouimmensefunctionality,andwasbasicallydesignedtoencouragelearningcomputerscienceatanaffordablecost.Aswehaveseen,thepossibilitiesofbuildinggadgetsusingtheRaspberryPiareendless,makingthisanawesomesegueintoself-improvementandscience.

Page 526: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourHotshotobjectivesInthisproject,wewilldiscussthefollowingexamples:

ImprovingyourvocabularyusingtheRaspberryPiRaspberryPiandKhanAcademyBuildingasciencefairexhibitusingtheRaspberryPi

Page 527: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 528: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ImprovingyourvocabularyusingtheRaspberryPiAsanexampleofself-improvementusingtheRaspberryPi,wewillimplementanexamplethatretrievesthewordofthedayusingtheWordnikAPI(https://www.wordnik.com/).

Page 529: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeneedtoinstalltheWordnikPythonclient(distributedundertheApacheLicense)availableasaPythonpackage:

sudopipinstallwordnik

ThenextstepistoobtainanAPIkeytomakeuseoftheAPI.ThiscanbeobtainedbyregisteringforanaccountwithWordnikandrequestinganAPIkey(http://developer.wordnik.com/).

Oncetheinstallationiscomplete,itistimetoreviewtheexample.

NoteTheWordnikAPIismerelybeingdemonstratedasanexample.RefertotheAPItermsofagreementtodeterminehowtheAPIcanbeusedinacommercialapplication.

Page 530: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. Let’sreviewanexamplethatfetchesthewordofthedayusingtheWordnikAPI.The

firststepistoimporttheWordnikPythonclient:

fromwordnikimport*

2. ThenextstepistocreateaclientthatinitializestheAPItoaccessthewordlist:

url='http://api.wordnik.com/v4'

key='APIKey'

client=swagger.ApiClient(key,url)

3. ThenextstepistoinitializetheWordnikAPIandretrievethewordoftheday:

words=WordsApi.WordsApi(client)

example=words.getWordOfTheDay()

4. ThereturnedobjectisaWordOfTheDayobject(https://github.com/wordnik/wordnik-python/blob/master/wordnik/models/WordOfTheDay.py).Let’sprinttheword,definition,andthepublisheddate:

string='TheWordoftheDayis'+example.word+'.'

printstring

string='Definition:'+example.definitions[0].text

printstring

string='Date='+example.publishDate.strftime("%D")

printstring

5. TheoutputofthisPythonscriptissomethingliketheoneshownhere:

TheWordoftheDayisasportation.

Definition:Thefeloniousremovalofgoodsfromtheplacewherethey

weredeposited.

Date=01/19/15

6. Now,thiswordofthedaycanbedisplayedonascreenatsomeprominentlocationusingaGUItoolsuchasTkinter(http://zetcode.com/gui/tkinter/)andupdatedevery24hours.Refertothisbook’swebsiteforsomeideas.

Page 531: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingInthistask,wereviewedanexampleofhowtouseyourRaspberryPiforself-improvement;similarly,thereareAPIsfromothersourcesthatprovideaquoteoftheday,jokeoftheday,andsoon.

Page 532: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 533: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiandKhanAcademyInthistask,wewillreviewanexamplethatenablesworkingonmathexercisesfromKhanAcademy(https://www.khanacademy.org/).KhanAcademyisanon-profiteducationalorganizationthatprovidesfreelearningresourcesforvarioussubjects,includingmathandcomputerscience.Inthisexample,wewillhostasimplewebserveronaRaspberryPithathoststheexercisesfromKhanAcademylocally.Thisenablescustomizationofthelearningtoolstotheuser’sneeds.Forexample,itcanbehostedonanetworkthatisnotconnectedtotheInternetandwecancustomizecontentfromKhanAcademytohelpsomeoneimproveontheirmathskills.

ThefirststepistoclonetherepositoryonaRaspberry

gitclonehttps://github.com/Khan/khan-exercises

Oncetherepositoryiscloned,itistimetolaunchthewebserver!

NoteTheexercisesaredistributedunderanon-commerciallicensewhilethewebserverframeworkisdistributedunderanMITlicense.YoumustbeawareofthelicenseagreementswhentryingtomakeuseofresourcesfromKhanAcademy.

Thelaunchoftheserverinvolvesasinglestep.Afterswitchingtothekhan-exercisesdirectory,thewebservercanbelaunchedasfollows:

python–mSimpleHTTPServer

ThewebservercanbeaccessedonalocalnetworkbyusingyourRaspberryPi’sIPaddressfromabrowserusinghttp://192.168.1.98:8000/khan-exercises/exercises/.

ThefollowingisascreenshotofthewebserverhostedonaRaspberryPi:

Page 534: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

KhanAcademyexercisesonalocalserver

Page 535: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SomeideastoconsiderWeusethiswebservertosolvepuzzlesusingtheRaspberryPi.Itcanbeusefultosharpenyourmentalacuitywhilekillingtime.

Page 536: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 537: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

BuildingasciencefairexhibitusingtheRaspberryPiInthistask,wewillbuildasimplephysicsexperimentcontrolledbytheRaspberryPi.Thiscanbeusedtoexplainhowthingssuchasasolarpanel,windmill,andsoonwork.Inthisexample,wewillbuildawindmillexperimentthatcanpossiblybeusedasademonstrativeexhibitatasciencefair.

Page 538: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PrepareforliftoffWeneedawindmillgeneratorkitfromahobbystore(forexample,http://amzn.com/B0016PBH9Q).ThekitneedstobeputtogetherleavingtheleadsoftheDCmotorexposed.

Page 539: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Engagethrusters1. TheDCmotorofthewindenergykitneedstobeinterfacedtotheRaspberryPi

GPIOpinasshowninthefollowingFritzingschematic:

AFritzingschematicshowingtheinterfaceofaDCmotorandabuttonforcontrol

2. SincetheDCmotorisinterfacedtoyourRaspberryPi’sGPIO#18,itcanbeturnedon(wearemakinguseoftheRPi.GPIOlibraries;refertopreviousprojectsifyouarenotfamiliarwithRPi.GPIO):

importRPi.GPIOasGPIO

GPIO.setmode(GPIO.BCM)

GPIO.setup(18,GPIO.OUT)

GPIO.output(25,GPIO.HIGH)

3. Whenavisitorattheexhibitionwouldliketoknowhowawindmillworks,aninstructionalaudiorecording(thedownloadavailablewiththisprojectmerelyplaysatestMP3file)canbeplayedatthepressofabuttonasfollows:

defmy_callback(channel):

os.system('mpg321recording.mp3&')

GPIO.add_event_detect(25,GPIO.FALLING,callback=my_callback)

4. ThefollowingimageshowsawindmillgeneratorkitinterfacedtoaRaspberryPi:

Page 540: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Awindmillgeneratorkit

Page 541: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Objectivecomplete–minidebriefingYourRaspberryPicanalsobeusedtobuildsomethingthatteststheskillsofpeopleatasciencefairortoprovideentertainment(raffledraw,puzzle,andsoon).

Page 542: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SomesimpleeducationalexperimentsusingtheRaspberryPi1. Asoftwaretoolthatalertswhentheinternationalspacestationfliesbyyourvicinity

canbefoundathttp://issabove.com/iss-above-and-the-raspberry-pi/.2. AcollectionofscientificexperimentarticlesusingtheRaspberryPicanbefoundat

http://www.raspberrypi.org/the-raspberry-pi-in-scientific-research/.3. ScratchisagraphicalprogrammingtooldevelopedbyMITtomotivatechildrento

getstartedwithlearningtoprogram.Scratchcanbefoundathttp://www.raspberrypi.org/tag/scratch/.

Page 543: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 544: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HotshotchallengeIsitpossibletobuildareceptionistrobotliketheoneshownatthefollowinglinkusingtheRaspberryPi?Refertohttp://roboceptionist.org/project.htmformoreinformation.

Page 545: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 546: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Chapter13.TipsandTricksInthisproject,wewilldiscusstipsandtrickstoovercomeanyproblemsonemightencounterwithRaspberryPi.Wealsoprovideprojectideas,generalinformation,andadissectionoftheRaspberryPiitself.

Page 547: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionbriefingInthisbook,wediscusseddifferentprojects,spanningdifferentdifficultylevels.Beforewrappingupthisbook,wewouldliketoshareourexperienceaboutthechallengesweencounteredandsharesometipsandresourcestoovercomesituationsthatyoumightencounterandpossiblesolutionsforthem.Wewillalsodiscusspossibleprojectideasthatyoucantrytoimplementoveraweekend.Wewillgointoeachaspectbriefly.

Page 548: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Whyisitawesome?Thisprojectsharestipsandtricks,providesprojectideas,anddiscussessolutionstoproblemsgenerallyencounteredinDIYprojects.

Page 549: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

YourobjectivesInthisproject,wewilldiscussthefollowing:

SettingupRaspberryPiasadevelopmentplatformProjectideasthatcanbeimplementedoveraweekendRemotelyloggingintoRaspberryPifromanywhereontheInternetProblemsthatmightbeencounteredwhileusingRaspberryPiCooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatformUsefulresourcesforRaspberryPi

Page 550: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionchecklistHaveyourcuriosity,attentionandpassionattheready.

Page 551: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 552: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SettingupRaspberryPiasadevelopmentplatformRaspberryPiiscurrentlythemostbasic,idealhardwareenvironmenttogetstartedwithlearningtocodeinaparticularlanguageoradvancedsystemsdevelopment.

Page 553: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#1–SimpletrickforPythondevelopmentviaremoteloginWhilewritingthisbook,wefounditconvenienttowritePythonscriptsonourlaptop/desktop,copythemovertoRaspberryPi,andtestthemviaremotelogin.ThiswasespeciallyusefulwhenwehadRaspberryPicontrollinginterfacedtotoolsonaChristmastree.ItisdifficulttosetupamonitorandkeyboardforRaspberryPiandworkfromthere.

WeusedWinSCP(http://winscp.net/eng/index.php—sincewewereusingalaptoprunningWindows)totransferfilesfromthelaptoptoRaspberryPi.Then,weusedthePuTTYSSHclient(http://www.putty.org/)foraremotelogintoRaspberryPiandtestedthescripts:

InordertoremotelylogintoRaspberryPiortransferfilesusingWinSCP,OpenSSHisrequired.TheRaspbianWheezyimagecomeswithSSHinstalledandenabledbydefault.Let’sloginafterdownloadingandinstallingWinSCP.Theusernamewouldbepiandthepasswordraspberry(unlessyou’vechangedthedefaultpassword).

TheWinSCPloginwindow

ThenextstepisittolocatethefilestobetransferredonthelocalmachineaswellasidentifyingthefolderwherethefilesneedtobecopiedtoRaspberryPi.Thefilesonthelocalmachinearelocatedontheleft-handside,whilethefilesonRaspberryPiarelocatedontheright-handsideofthewindow.

Page 554: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TransferringfilesusingWinSCP

Oncethefilesaretransferred,wecanmakeuseofPuTTYforremotelogintoRaspberryPi.Asshowninthefollowingfigure,wecanconnecttotheRaspberryPiusingtheIPaddressofRaspberryPiandloginusingthecredentialsprovidedearlier.

Page 555: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ConnectingtoRaspberryPiusingPuTTY

Page 556: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#2WebdevelopmentusingGoogleCoderGooglereleasedanopensourcetoolbasedontheRaspberryPiplatformcalledCoder(http://googlecreativelab.github.io/coder/).WemadeuseoftheGoogleCodertoolinProject9,TheRaspberryPi-enabledPet/WildlifeMonitor.GoogleCoderisanopensourcetooltolearnwebdevelopment,butitsusehasexpandedandasanopensourcetool,itisreadyforyourprojectsastheneedarises.Forexample,itispossibletobuildawebinterfacetoread/writetotheGPIOinterfaceofRaspberryPi(forexample,http://googlecreativelab.github.io/coder-projects/projects/blinky_lights/).

Page 557: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#3AdafruitOccidentalisAdafruitIndustriesreleasedaversionofRaspbian,Occidentalisthatenabledeasierhardwaredevelopmentasitfeatureddriversforallstandardcommunicationprotocols.AdafruitIndustriesalsoreleasedaweb-baseddevelopmenttoolthatcomeswithseveralPythonexamples.

Page 558: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#4JavaDevelopmentusingtheRaspberryPiOraclehasreleasedatutorialsetthatteachesJavadevelopmentusingRaspberryPi.ThisincludestutorialsoninterfacepressuresensorsandwritingJavacodetoreadbarometricpressuredatafromthesensorviatheI2Cinterface.

Page 559: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

#5TheThingboxprojectTheThingBoxProject(http://thethingbox.io/)isatoolthatallowsyoutoenableprojectsthatarerelatedtotheInternetofThingsonRaspberryPi.ItisasetoftoolsthatallowsyoutointerfacesensorsandappliancestotheInternet,availableasanOSimagethatcanbeflashedontoanSDcardandrunonRaspberryPi.OneofthetoolsavailablewiththeThingBoxProjectisNode-RED(http://nodered.org).TheNode-REDtool(showninfollowingscreenshot),infact,isagraphicalinterfacetoolthateliminatestheneedforyoutoprogramtocontrolthedevicesconnectedtoyourPi.Asthenamesuggests,anyapplicationisbuiltusingnodesandthecontrolflowisshownbyconnectedwires.

AHelloworldprojectusingNode-RED

Page 560: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 561: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RemotelyloggingintheRaspberryPifromanywhereontheInternetAcompanycalledWeaved(http://www.weaved.com/)hasreleasedatoolthatisstillunderbetatestingwhilewritingthisbook.ItenablesyoutoremotelylogintoRaspberryPithatisconnectedtotheInternetfromanywhereontheWeb(apartfromalocalnetwork).Thereisalsoatutorialtoinstallandusethetool(https://www.juicypi.io/access-your-raspberry-pi-anywhere-in-the-world-using-weaved/).Thisenablesremotecontrol/datacollection.

Page 562: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 563: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ProblemsthatmightbeencounteredwhileusingRaspberryPiThefollowingaresomeproblemsweencounteredwhileweworkedonRaspberryPi.

Page 564: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SDcardcorruptionWeencounteredSDcardcorruptionswhileworkingwithRaspberryPi.Insomecases,wehadtodiscardtheSDcardbutinothercases,wewereabletorecovertheSDcardusingAdvancedPartitionScannerWizardandre-imagetheSDcard.

Sometimesthefailureoccursbecausethereisapowerfailurewhilethecardisstillbeingwrittento.Suchfailuresareunavoidableoverthelifeofyourprojects.HereareafewwaystoavoidSDcardcorruption:

PowerdownyourPiproperlyafteruseChargeyourbatterypacksandmakesurePihasaconstantpowersupplyatalltimes

BesuretobuygoodqualitySDcardsandaswitheverythingelsedigital,havebackups.

Page 565: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PowerissuesWeencounteredissuesrelatedtothepowerdrawofRaspberryPi.Wehadlittlesuccesswiththingssuchasabatterypack(wewereabletogetitworkingusinga2700mAhbatterypack).Asyoumaybeaware,RaspberryPineedsa1A,5VUSBpowersupply.

Page 566: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

DevicespoweredbyUSBSomedevicessuchasawebcamcannotbeconnecteddirectlytotheRaspberryPiandaUSBhubmaybenecessarytoconnectsuchdevices.

Page 567: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 568: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Cooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatformThereareseveralproductsandadd-onhardwaredevelopedspecificallyforRaspberryPi.MostofthemaredesignedspecificallyforRaspberryPi.SomeofthemareavailablethroughDIYproductsellerssuchasSparkfunandAdafruitIndustries.MostproductsaredevelopedthroughcrowdfundingsitessuchasKickstarterandIndiegogo.Wemadeourbestefforttointroduceanewpieceofhardwareineachproject.Asimplewebsearchshouldpopupanewproductforaspecificapplication.

Page 569: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

TheRaspberryPimodelBversusB+,modelAversusA+TheRaspberryPimodelA+andB+hasmoreGPIOpinsthanthemodelAandB.ThemodelB+hastwomoreUSBportswhilemodelA+consumeslesspowerthanthemodelA.Hence,itispossibleuseapoweroverEthernetmodule(PoE).Checkouthttp://www.silvertel.com/component/content/article/22-latest-news/304-raspberry-pi-poe.htmlformoreinformation.

IfyouownaRaspberryPiB+butthehardwareyouowniscompatiblewithRaspberryPimodelB,youcanmakeuseofa40pinto26pinadapteravailablefromAdafruitIndustries(https://www.adafruit.com/products/1986).

Page 570: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 571: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

ProjectideasthatcanbeimplementedoveraweekendBesideswhatyouhaveseensofarinthisbook,thereareseveralcoolprojectsthatcanbeimplementedinaweekorless.Theseincludethefollowing:

AsmartalarmclockbasedonRaspberryPi,withfeaturessuchascustomalarmsounds,period,snoozeoptions,theabilitytoreportweatherconditions,alertyouabouttoday’sto-dolist,andmuchmore.Homeautomationandhomesurveillancesystems,acamerathatworksonmotion,VOCalarms,moodlighting,lightingcontrols,andsoon.Asensornetwork,wiredorwireless,tomonitorvariousparametersaroundyourhouse—temperature,plants,pets,andothers.Adigitalphotoframenetworkthatchangesimagesacrossmanyframes,dependingonthetimeofthedayandsoon.SeasonalprojectssuchaslightsforDiwali,Hanukah,orChristmas.

Page 572: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 573: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

UsefulresourcesfortheRaspberryPiInthissection,wewilldiscussusefulresourcesthatareavailableforRaspberryPi.Whilethisbookcancovereveryaspectoftheprojectsdevelopedinthisbook,wewilldefinitelyrunintotrouble.Let’slookatsomeusercommunitiesthatcantrytoaddressourproblem.

Page 574: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiFoundation’sforums:TheRaspberryPiFoundation(http://www.raspberrypi.org/forums/)hasmaintainedaforumsinceitsinception.Thisforumprovidesanswerstoavastspectrumofquestionsthatyoumayhave.ItalsooffersanopportunitytodirectlyinteractwiththecreatorsofRaspberryPi.

Page 575: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RaspberryPiStackExchange:Atthetimeofwritingthisbook,theRaspberryPiStackExchange(http://raspberrypi.stackexchange.com/)wasinthepublicbetatestingmode.Ifthissitepassesthebetatestingphase,itshouldalsocontainapoolofusefulresources.

Page 576: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Element14’sRaspberryPicommunity:TheElement14website(http://www.element14.com/community/community/raspberry-pi)hostsaseriesofblogpostsfromRaspberryPiuserswhohavebuiltanecosystemofgadgetssurroundingRaspberryPi.ThecommunitywebpagehostscontestsregularlyinordertoexhibitthetalentofRaspberryPienthusiastsandDIYhobbyists.Thecommunitywebpagealsohasauserforumtoexchangeinformation,askquestionsrelatedtoorderstatus,andsoon.

Page 577: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...
Page 578: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MissionaccomplishedInthisproject,wediscussedcertainprojectideas,tips,andtricksandproblemsyoumightencounterwhileworkingonaprojectusingRaspberryPi.Theauthorssincerelyhopethatyouhaveenjoyedthisbook.

Page 579: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

IndexA

AdafruitCobblerabout/PythondevelopmentontheWebIDE

AdafruitIndustriesURL/Prepareforliftoff,TheRaspberryPimodelBversusB+,modelAversusA+

AdafruitOccidentalisabout/#3AdafruitOccidentalis

AdafruitWebIDEOccidentalis/Whyisitawesome?

AdvancedIPScannerURL/SetupofaremoteloginintotheRaspberryPi

AI,ConnectFourgameabout/AbriefdescriptionoftheConnectFourGameAI,Engagethrustersmaingameloop/Maingameloop

AMP(AsynchronousMessagingProtocol)URL/Installingandtestingthepython-twistedframework

Arduinoabout/Whyisitawesome?distributors/WherecanyoubuyanArduino?programming,withRaspberryPi/ProgrammingtheArduinousingtheRaspberryPi,Engagethrusters

Arduinoacknowledgement,forcontrollingsignalcontrolflow,forweatherclock/Controlflowfortheweatherclocktemperaturedata/TemperaturedataRGBLEDstripcontrol/ControloftheRGBLEDstripsteppermotorcontrol/Controlofstepperviaserialportweatherforecastposition,programming/Programmingtheweatherforecastposition8x8matrixcontrol/8x8matrixcontrolBlinkMcontrol/BlinkMcontrol

ArduinoEthernetBoardURL/Missionchecklist

ArduinoEthernetboardURL/Missionchecklist

ArduinoIDEinstalling/InstallingtheArduinoIDE,Objectivecomplete–minidebriefing

ArduinoRaspberryPiinterfaceprojectabout/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectives

Page 580: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

checklist/MissionchecklistArduinoIDE,installing/InstallingtheArduinoIDE,Objectivecomplete–minidebriefingArduino,programmingwithRaspberryPi/ProgrammingtheArduinousingtheRaspberryPi,EngagethrustersRaspberryPiAlaMode/RaspberryPiAlaMode,EngagethrustersWeasleyWeatherClock/TheWeasleyweatherclock,Engagethrusters,Objectivecomplete–minidebriefingsteppermotor,controllingwithArduino/ControllingthestepperusingtheArduino,Prepareforliftoff,EngagethrustersRGBLEDstrip,controllingwithArduino/ControllingtheRGBLEDStripusingtheArduino,Prepareforliftoff,EngagethrustersI2Ccommunication,Arduinoused/I2CCommunicationusingtheArduino(optional)serialportcommunication,withRaspberryPi/SerialportcommunicationwiththeRaspberryPi

ArduinoUnoplusESP8266boardURL/Missionchecklist

Atmelseries/Whyisitawesome?audiodevice

interfacing/InterfaceofanaudiodeviceAutodeskInventor/Prepareforliftoff

Page 581: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

B8BitCircusMusic

URL/AddingsoundstothegameBarScrollexample/PrepareforliftoffBCMGPIOmode

URL/Engagethrustersbirdfeeder

settingup,withmotionsensor/Prepareforliftoff,Engagethrusters,Objectivecomplete–minidebriefingrequisites/Prepareforliftoff

BlinkM/IntroductiontothePiCrust–aprototypingplatformfortheRaspberryPiabout/TestanddebuggingexamplesusingtheWebIDEURL,fordatasheet/Engagethrusters

BonjourPrintServicesdriversURL/SetupofaremoteloginintotheRaspberryPi

Page 582: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Ccannyedgedetectiontechnique

about/Engagethrusterschassis

designing/Designingthechassisforthelinefollowingrobot,EngagethrustersChristmaslightsequencerproject

about/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/Missionchecklistdecorativeappliances,interfacing/InterfacethedevicestotheRaspberryPi,PrepareforliftoffdigitallyaddressableRGBmatrix,settingup/SettingupthedigitallyaddressableRGBmatrix,Prepareforliftoff,AnArduino-basedcontrolaudiodevice,interfacing/Interfaceofanaudiodevicewebserver,installing/Installingthewebserver,Engagethrusterswebserver,interfacing/Interfacingthewebserver,Engagethrusters,Objectivecomplete–minidebriefing

circadianlightingprojectURL/Engagethrusters

CisecoPi-Litegithubrepository/PrepareforliftoffCMake

about/Missionchecklistcommand-lineinterface-basedapproach

about/Acommand-lineinterface-basedapproachSDcardmountpoint,identifying/IdentifyingtheSDcardmountpointSDcard,unmounting/UnmounttheSDcardSDcard,flashing/FlashtheSDcard

components,RaspberryPiabout/FeaturesofaRaspberryPi

ConnectFourdesktopgameabout/Missionbriefingreferencelink/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/MissionchecklistHelloworldexample,withpygame/HelloworldexamplewiththepygameUI/GettingstartedwiththeConnectFourgame(UIandsoundeffects),EngageThrustersgameinputs,interfacingwithPiFacemodule/InterfacinggameinputsusingthePiFacemodule,Prepareforliftoff,EngagethrustersAI/AbriefdescriptionoftheConnectFourGameAImarqueecontrol/Marqueedesignandcontrol(optional)

Page 583: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

switches,settingupwithcardboardbox/Setupoftheswitchesusingacardboardbox

Page 584: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Ddatainterpretation,linefollowingrobot/EngagethrustersDCmotor

controlling,withH-Bridge/Prepareforliftoffdevices

interfacing,toRaspberryPi/InterfacethedevicestotheRaspberryPi,Prepareforliftoff,Engagethrusters

digitallyaddressableRGBmatrixsettingup/SettingupthedigitallyaddressableRGBmatrix,Prepareforliftoffworking/Howdoesitwork?

DinghitsURL/Addingsoundstothegame

dishmonitorassembling/Settinguptheassemblyforthedishmonitor,Engagethrusters,Objectivecomplete–minidebriefing

DIYtabletopfountainkitrequistes/Prepareforliftoffabout/Engagethrusters

Page 585: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Ee-mailalerts

settingup,infountain/Setupofthee-mailalertsinthefountain,Engagethrusters

e-mailfeedparsersettingup/Settingupthee-mailfeedparser,Engagethrusters,Settingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointment,Engagethrusterssettingup,forreminders/Settinguptheparserforremindersandevents,Engagethrusterssettingup,forevents/Settinguptheparserforremindersandevents,Engagethrustersdoctorappointmentsreminder,settingup/Settingupareminderfordoctor’sappointments

electricaltapeused,forbuildingtrack/Useelectricaltapeandbuildatrack

Element14URL/Element14’sRaspberryPicommunity:about/Element14’sRaspberryPicommunity:

enclosuredesign,personalassistantURL/Prepareforliftoff

Page 586: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

FFlaskframework

installing/InstallationoftheFlaskframework,Engagethrusters,Prepareforliftoff,EngagethrustersURL/Prepareforliftoff

FlaskframeworkexampleURL/Engagethrusters

FreeSoundsURL/Addingsoundstothegame

Page 587: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Ggameinputs,ConnectFourdesktopgame

interfacing/InterfacinggameinputsusingthePiFacemodule,Prepareforliftoff,Engagethrusters

GoogleCoderabout/InstallingandtestingtheGoogleCoderprojectontheRaspberryPiURL/Prepareforliftoff,#2WebdevelopmentusingGoogleCodersettingup/Engagethrustersused,forwebdevelopment/#2WebdevelopmentusingGoogleCoder

GPIOsettingup/Missionbriefing,SettinguptheGPIO,Engagethrustersfeatures/Whyisitawesome?objectives/YourHotshotobjectiveschecklist/Missionchecklistrequisites/Huntingandgatheringlibraries,installing/InstallingGPIOlibrarieslibraryinstallation,verifying/GPIOprogrammingusingPython

Page 588: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

HHelloworldexample,ConnectFourdesktopgame

about/Helloworldexamplewiththepygamepygamemodule,features/Prepareforliftoffpygamemodule,using/Engagethrusterssounds,playingwithpygamemodule/Playingsoundsusingthepygamemodulemenus,buildingwithpygamemodule/Buildingmenususingthepygamemodule,Objectivecomplete–minidebriefing

homeautomationprojectabout/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/Missionchecklistlight,turningon/Asimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheevening,Prepareforliftoffcustomarywebserverexample/Acustomarywebserverexample,Engagethrusters,Objectivecomplete–minidebriefinglawnsprinkler,turningon/Turningonalawnsprinkleronlywhenthereisnorainforecast!,Engagethrustersremoteaccess,enablingforcontrollingappliances/GainingremoteaccesstoyourRaspberryPitocontrolappliancesconsiderations/Someprojectideastoconsider

Houghtransformsabout/Engagethrusters

Page 589: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

II2Ccommunication

about/Whyisitawesome?,I2CCommunicationusingtheArduino(optional)URL,fortutorials/Whyisitawesome?7-Segmentdisplay/The7-Segmentdisplay8x8LEDmatrix/8x8LEDmatrixBlinkM/BlinkMproximitysensor/Proximitysensor

ImageWriterpackage/GUI-basedapproachInfrared(IR)emitter/detector

about/Infraredemitter/detectorinfraredsensor

used,forimplementinglinefollowinglogic/Implementationoflinefollowinglogicbasedonsensordata,Engagethrusters

InstructablesURL/Whyisitawesome?

interfaceURL/Sensorselection,interface,anddatainterpretation

issues,RaspberryPiSDcardcorruption/SDcardcorruptionpowerissues/PowerissuesdevicespoweredbyUSB/DevicespoweredbyUSB

Page 590: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

JJavadevelopment

RaspberryPiused/#4JavaDevelopmentusingtheRaspberryPi

Page 591: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Kkeyalertsystem

sensors,settingup/Settingupsensorsforthekeyalertsystem,Engagethrusters,Objectivecomplete–minidebriefing

KhanAcademyURL/RaspberryPiandKhanAcademy

KhanAcademyexampleabout/RaspberryPiandKhanAcademy

Page 592: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Llawnsprinkler

turningon/Turningonalawnsprinkleronlywhenthereisnorainforecast!,Prepareforliftoff

LEDblinkingexampleprogramming/Engagethrusterselectricalconnection/Electricaloutputofourprogram,Engagethrusters

LightDependentResistorsabout/LightDependentResistors

linefollowinglogicimplementing,withinfraredsensor/Implementationoflinefollowinglogicbasedonsensordata

linefollowingrobotabout/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectiveschecklist/Missionchecklistprerequisites/MissionchecklistPiPlate,assembling/AssemblyofthePiPlateforthelinefollowingrobotPiPlate,testing/AssemblyofthePiPlateforthelinefollowingrobotdatainterpretation/Sensorselection,interface,anddatainterpretationsensors,selecting/Engagethrustersinterface/EngagethrustersMachineVision-based/Machine-vision-basedlinefollowingrobotmotordrivercircuit,testing/Testingthemotordrivercircuittrack,preparing/Preparationofthelinefollowingcoursechassis,designing/Designingthechassisforthelinefollowingrobotassembling/Astep-by-stepassemblyoftherobotassembling,steps/Prepareforliftoff,Engagethrustersreferencelinks/References

linefollowingtrackpreparing,forrobot/Preparationofthelinefollowingcourse,Prepareforliftoff

LinuxSDcardwithRaspbianimage,flashing/Linux

LPD8806libraryURL/ControllingRGBLEDsfromawebpage

Page 593: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

MMachineVision-basedlinefollowingrobot/Machine-vision-basedlinefollowingrobotMake*itBasicRoboticsStarterKit

URL/Missionchecklistmarqueecontrol,ConnectFourgame

implementing/Marqueedesignandcontrol(optional),Prepareforliftoffmenuclass

URL/Addingamenuforthegamemotordrivercircuit

testing/Testingthemotordrivercircuit,Prepareforliftoff,Engagethrustersmultipleappliances

connecting,toRaspberryPi/ConnectingmultipleappliancestotheRaspberryPi

Page 594: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

NNOAA

URL/EngagethrustersNode-REDtool

URL/#5TheThingboxproject

Page 595: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

OOccidentalis

about/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectivesinstalling/Installation,features,andusageoftheOccidentalisoperatingsystemfromAdafruit

Occidentalisdistrorequisites/Missionchecklist

OpenCVURL/MissionchecklistURL,forinstallationonRaspberryPi/MissionchecklistURL,forinstallationonLinux/Missionchecklist

OpenCVDishDetectorprojectURL/Settinguptheassemblyforthedishmonitor

Page 596: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

PParallax/Prepareforliftoffpersonalassistant

building/Missionbriefingobjectives/Yourobjectiveschecklist/Missioncheckliste-mailfeedparser,settingup/Settingupthee-mailfeedparser,Engagethrusterse-mailfeedparser,settingupforreminders/Settinguptheparserforremindersandevents,Engagethrusterse-mailfeedparser,settingupforevents/Settinguptheparserforremindersandevents,Engagethrustersenclosure,designing/Designinganenclosuredesignforthepersonalassistant,Prepareforliftoff,Engagethrustersdishmonitor,assembling/Settinguptheassemblyforthedishmonitor,Engagethrusters,Objectivecomplete–minidebriefingsensors,settingupforkeyalertsystem/Settingupsensorsforthekeyalertsystem,Engagethrusters,Objectivecomplete–minidebriefingimplementation/Missionaccomplishedchallenges/Hotshotchallenges

personalhealthmonitorabout/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectiveschecklist/Missionchecklistwebserver,settingupforrecordinghealthparameters/Settingupawebservertorecordhealthparameters,Prepareforliftoffsimpleexercisetool,building/AsimpleexercisetoolusingtheRaspberryPi,Engagethrustersminiprojectidea/Aminiprojectideae-mailfeedparser,settingup/Settingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointment,Engagethrusterspillremindertool,building/Asimpletoolthatremindsapersontotakehis/herpills

pet/wildlifemonitorabout/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/Missionchecklistpython-twistedframework,installing/Engagethrusterspython-twistedframework,testing/Engagethrusterspython-twistedframework,using/Objectivecomplete–minidebriefing

Page 597: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

SparkCore,settingup/SettingupandtestingSparkCoretointeractwithappliancesGoogleCoder,installing/InstallingandtestingtheGoogleCoderprojectontheRaspberryPibirdfeeder,settingup/Abriefoverviewofabirdfeederthattriggersacameraconsiderations/Alternativesandprojectideastoconsider

PiCrustabout/IntroductiontothePiCrust–aprototypingplatformfortheRaspberryPi

PiFaceusing/InterfacinggameinputsusingthePiFacemoduleinstallationguide,URL/Prepareforliftoff

PiFaceinterfaceboardURL/InterfacinggameinputsusingthePiFacemodule

PiLiteLEDMatrixdisplayURL/Marqueedesignandcontrol(optional),Prepareforliftoff

pillreminderbuilding/PrepareforliftoffURL/Prepareforliftoff

PiPlatetesting/AssemblyofthePiPlateforthelinefollowingrobot,Prepareforliftoff,Objectivecomplete–minidebriefingassembling/AssemblyofthePiPlateforthelinefollowingrobot,Engagethrusters,Objectivecomplete–minidebriefing

PIRsensorURL/Prepareforliftoff

Pololuabout/PrepareforliftoffURL/Useelectricaltapeandbuildatrack

powerDarlingtoncircuitURL/Engagethrusters

PowerSwitchTail2using/Prepareforliftoffsoftwareprerequisites/Softwareprerequisitessettingup/Engagethrusters

PowerSwitchTailII/InterfacethedevicestotheRaspberryPiprojectsideas

implementing,overweekend/Projectideasthatcanbeimplementedoveraweekend

Proportional-Integral-Derivativecontrol(PID)/Hotshotchallengepulse-widthmodulation

about/Whyisitawesome?URL,fortutorials/Whyisitawesome?

PuTTYSSHclientURL/#1–SimpletrickforPythondevelopmentviaremotelogin

Page 598: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

python-twistedframeworkabout/Installingandtestingthepython-twistedframeworkinstalling/Engagethrusterstesting/Engagethrustersusing/Objectivecomplete–minidebriefing

python-twistedframeworkURL/Installingandtestingthepython-twistedframework

Pythondevelopmentviaremotelogin/#1–SimpletrickforPythondevelopmentviaremotelogin

Pythondevelopment,onWebIDEabout/PythondevelopmentontheWebIDE,PrepareforliftoffI2Cinterface/QuickintroductiontotheI2CinterfaceI2Cinterface,configuringonRaspberryPi/ConfiguringtheI2CinterfaceontheRaspberryPiI2Cinterface,configuringoonRaspberryPi/ConfiguringtheI2CinterfaceontheRaspberryPi,Engagethrusters

PythonIDLE3LEDblinkingexample,programming/Engagethrusters

Page 599: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Qquick2wirepythonAPI/InstallingGPIOlibraries

Page 600: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

RRaspberryPi

about/AquickintroductiontotheRaspberryPi,SettingupRaspberryPiasadevelopmentplatformURL/FeaturesofaRaspberryPifeatures/FeaturesofaRaspberryPicomponents/FeaturesofaRaspberryPidistributors/WherecanIbuyaRaspberryPi?requisites/RequirementstogetstartedwiththeRaspberryPidisplay/RequirementstogetstartedwiththeRaspberryPipowersupply/RequirementstogetstartedwiththeRaspberryPioperatingsystems/OperatingsystemsontheRaspberryPisettingup/SettinguptheRaspberryPiGPIO/Missionbriefingremotelogin,settingup/SetupofaremoteloginintotheRaspberryPi,Prepareforliftoff,Engagethrusterstipsandtricksproject/Missionbriefingsettingup,asdevelopmentplatform/SettingupRaspberryPiasadevelopmentplatformremotelogin,enabling/RemotelyloggingintheRaspberryPifromanywhereontheInternetissues/ProblemsthatmightbeencounteredwhileusingRaspberryPiadd-onhardwaresources/Cooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatformmodelB,versusB+/TheRaspberryPimodelBversusB+,modelAversusA+modelA,versusA+/TheRaspberryPimodelBversusB+,modelAversusA+usefulresources/UsefulresourcesfortheRaspberryPi

RaspberryPiAlaModeabout/Missionbriefing,RaspberryPiAlaModefeatures/Prepareforliftoff

RaspberryPieLinuxwikiURL/RequirementstogetstartedwiththeRaspberryPi

RaspberryPiFoundationforumsURL/RaspberryPiFoundation’sforums:about/RaspberryPiFoundation’sforums:

RaspberryPiStackExchangeabout/RaspberryPiStackExchange:URL/RaspberryPiStackExchange:

RaspberryPiWebIDEinstalling/InstallationoftheRaspberryPiWebIDE,EngagethrustersURL/InstallationoftheRaspberryPiWebIDEPythondevelopment/PythondevelopmentontheWebIDE,Prepareforliftoffexamples,testing/TestanddebuggingexamplesusingtheWebIDE,Preparefor

Page 601: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

liftoff,Engagethrustersexamples,debugging/TestanddebuggingexamplesusingtheWebIDE,Prepareforliftoff,Engagethrusters

Raspbianabout/GettingstartedwithRaspbiandownloading/DownloadingRaspbianURL/DownloadingRaspbianimage,flashingonSDcard/FlashingimageontotheSDcard

Raspbianimageflashing,onSDcard/FlashingimageontotheSDcard

Raspbianwheezy/DownloadingRaspbianraspi-configtool

info/SettinguptheRaspberryPiexpand_rootfs/SettinguptheRaspberryPioverscan/SettinguptheRaspberryPiconfigure_keyboard/SettinguptheRaspberryPichange_pass/SettinguptheRaspberryPichange_locale/SettinguptheRaspberryPichange_timezone/SettinguptheRaspberryPimemory_split/SettinguptheRaspberryPioverclock/SettinguptheRaspberryPissh/SettinguptheRaspberryPiboot_behaviour/SettinguptheRaspberryPiupdate/SettinguptheRaspberryPi

remoteloginsettingup,inRaspberryPi/SetupofaremoteloginintotheRaspberryPi,Engagethrustersenabling/RemotelyloggingintheRaspberryPifromanywhereontheInternet

resources,RaspberryPiabout/UsefulresourcesfortheRaspberryPifoundationforums/RaspberryPiFoundation’sforums:StackExchange/RaspberryPiStackExchange:Element14/Element14’sRaspberryPicommunity:

RGBLEDscontrolling,fromwebpage/ControllingRGBLEDsfromawebpage,Engagethrusters

RGBLEDstripcontrolling,withArduino/ControllingtheRGBLEDStripusingtheArduino,Prepareforliftoff,Objectivecomplete–minidebriefinglightingup/LightinguptheRGBLEDstrip,AnArduino-basedcontrol

Page 602: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

S7-segmentbackpack/Engagethrustersscienceandeducationproject

about/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectivesvocabulary,improving/ImprovingyourvocabularyusingtheRaspberryPi,EngagethrustersKhanAcademyexample/RaspberryPiandKhanAcademysciencefairexhibit,building/BuildingasciencefairexhibitusingtheRaspberryPi,Engagethrusters,Objectivecomplete–minidebriefingeducationalexperiments/SomesimpleeducationalexperimentsusingtheRaspberryPi

sciencefairexhibitbuilding/BuildingasciencefairexhibitusingtheRaspberryPi,Engagethrusters

ScribblerlinefollowingrobotURL/Engagethrusters

SDcard,withRaspbianimageflashing,onWindows/Windowsflashing,onLinux/Linux

SDcardwithRaspbianimage,flashingonLinuxcommand-lineinterface-basedapproach/Acommand-lineinterface-basedapproachGUI-basedapproach/GUI-basedapproach

sensorsselecting/Engagethrusters,SensorselectionLightDependentResistors/LightDependentResistorsInfrared(IR)emitter/detector/Infraredemitter/detector

seriallibrary/Prepareforliftoffserialportcommunication

about/SerialportcommunicationwiththeRaspberryPiPythonprogram,forWeasleyclock/PythonprogramfortheWeasleyclockArduinoacknowledgement,forcontrollingsignal/Controlflowfortheweatherclock

shebang/Engagethrustersshields/Whyisitawesome?simpleexercisetool

building/Prepareforliftoff,Engagethrusterssourcefiles

URL,forOpenCVinstallation/MissionchecklistSparkCore

URL/SettingupandtestingSparkCoretointeractwithappliances

Page 603: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

settingup/PrepareforliftoffLEDexample,implementing/EngageThrusters

SparkCoreboardURL/Missionchecklist

SparkFunURL/Alternativesolutionsandsomeprojectideastoconsider,Prepareforliftoff

SPI(SerialPeripheralInterface)/Howdoesitwork?SSH(SecureShell)/GainingremoteaccesstoyourRaspberryPitocontrolappliancessteppermotor

about/Prepareforliftoffcontrolling,Arduinoused/Prepareforliftoff,Engagethrusterscounterclockwiserotation/Counterclockwiserotationofthesteppermotor

switches,ConnectFourdesktopsettingup,withcardboardbox/Setupoftheswitchesusingacardboardbox,Prepareforliftoff,Engagethrusters

Page 604: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

Ttabletopmusicalfountainproject

building/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/Missionchecklistassembling/MissionchecklistDIYfountainkit/PrepareforliftoffFlaskframework,installing/InstallationoftheFlaskframework,EngagethrustersRGBLEDs,controllingfromwebpage/ControllingRGBLEDsfromawebpage,Engagethrusterse-mailalerts,settingup/Setupofthee-mailalertsinthefountain,Engagethrusters,Objectivecomplete–minidebriefing

TheThingBoxProjectabout/#5TheThingboxprojectURL/#5TheThingboxproject

tipsandtricksprojectabout/Missionbriefingfeatures/Whyisitawesome?objectives/Yourobjectiveschecklist/Missionchecklist

TkinterURL/Engagethrusters

trackbuilding,withelectricaltape/Useelectricaltapeandbuildatrack

Page 605: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

UUI,ConnectFourgame

about/GettingstartedwiththeConnectFourgame(UIandsoundeffects),Prepareforliftoffmenu,adding/Addingamenuforthegamesounds,adding/Addingsoundstothegame

USBBatterypackURL/Prepareforliftoff

Page 606: Raspberry Pi Mechatronics Projects HOTSHOT1.droppdf.com/files/NgUWj/raspberry-pi... · Raspberry Pi Mechatronics Projects HOTSHOT Credits About the Authors About the Reviewers ...

WWeasleyWeatherClock

about/TheWeasleyweatherclockrequisites/Prepareforliftoffassembling/Engagethrusters

WeavedURL/GainingremoteaccesstoyourRaspberryPitocontrolappliances,RemotelyloggingintheRaspberryPifromanywhereontheInternet

web.pytutorialsURL/References

webdevelopmentGoogleCoderused/#2WebdevelopmentusingGoogleCoder

webserverinstalling/Installingthewebserver,Engagethrustersinterfacing/Interfacingthewebserver,Engagethrusters,Objectivecomplete–minidebriefingsettingup,forrecordinghealthparameters/Settingupawebservertorecordhealthparameters,Prepareforliftoff,Engagethrusters

Win32DiskImagertool/WindowsWindows

SDcardwithRaspbianimage,flashing/WindowsWinSCP

URL/#1–SimpletrickforPythondevelopmentviaremoteloginWonderHowTo

URL/EngagethrustersWordnikAPI

URL/ImprovingyourvocabularyusingtheRaspberryPiinstalling/Prepareforliftoffusing/Engagethrusters

WordOfTheDayobjectURL/Engagethrusters