tentacle.netprophet/raspberrypi/raspberry...table of contents raspberry pi mechatronics projects...

606

Upload: others

Post on 23-May-2020

34 views

Category:

Documents


2 download

TRANSCRIPT

RaspberryPiMechatronicsProjectsHOTSHOT

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

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

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

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

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

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

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

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

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

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

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

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

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

RemotelyloggingintheRaspberryPifromanywhereontheInternet

ProblemsthatmightbeencounteredwhileusingRaspberryPi

SDcardcorruption

Powerissues

DevicespoweredbyUSB

Cooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatform

TheRaspberryPimodelBversusB+,modelAversusA+

Projectideasthatcanbeimplementedoveraweekend

UsefulresourcesfortheRaspberryPi

RaspberryPiFoundation’sforums:

RaspberryPiStackExchange:

Element14’sRaspberryPicommunity:

Missionaccomplished

Index

RaspberryPiMechatronicsProjectsHOTSHOT

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

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

DishaHaria

ProductionCoordinators

AparnaBhagat

ManuJoseph

CoverWork

AparnaBhagat

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.

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.

www.PacktPub.com

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.

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

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.

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

platformsuchasanArduino.TheRaspberryPiactsasaserverthatcontrolsallsuchnodesinthenetwork.

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

Project13,TipsandTricks,isaprojectpackedwithtipsandtricksthatwillhelpyouusetheRaspberryPi!

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

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

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

ConventionsInthisbook,youwillfindseveralheadingsappearingfrequently.Togiveclearinstructionsofhowtocompleteaprocedureortask,weuse:

MissionbriefingThissectionexplainswhatyouwillbuild,withascreenshotofthecompletedproject.

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

YourHotshotobjectivesThissectionexplainstheeightmajortasksrequiredtocompleteyourproject.

Task1Task2Task3Task4Task5Task6Task7Task8

MissionchecklistThissectionexplainsanypre-requisitesfortheproject,suchasresourcesorlibrariesthatneedtobedownloaded,andsoon.

Task1Thissectionexplainsthetaskthatyouwillperform.

PrepareforliftoffThissectionexplainsanypreliminaryworkthatyoumayneedtodobeforebeginningworkonthetask.

EngagethrustersThissectionliststhestepsrequiredinordertocompletethetask.

Objectivecomplete–minidebriefingThissectionexplainshowthestepsperformedintheprevioussectionallowsustocompletethetask.Thissectionismandatory.

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.

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.

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

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

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

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

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.

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

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.

QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.

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

AquickintroductiontotheRaspberryPiIfwesearchforthetermRaspberryPiovertheweboropentheRaspberryPiFoundation’swebpage,wewillfindthattheRaspberryPiisacomputerthatisthesizeofacreditcard.

PartsofaRaspberryPi

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)

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

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.

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

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

RaspbianwheezyontheRaspberryPiFoundation’swebsite

FlashingimageontotheSDcardWewilldiscussflashingtheSDcardwiththeRaspbianimageonbothWindowsandLinuxmachines.

Windows

Extractthefilestoalocationofyourchoice.TheWin32DiskImagertoolisrequiredtopreparetheSDcardwiththeRaspbianimage.

TipAstandardRaspbianimageisabout1.8GBbig.ItisstronglyrecommendedthatyouuseanSDcardthatisatleastof4GBbig.

TheWin32DiskImagertool

WecanflashtheSDcardinthreesimplesteps(asshownintheprecedingscreenshot):

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

ConfirmoverwritingtheSDcard

5. Itcantakeawhilebeforethewritecycleiscompleted.

Linux

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

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

SettinguptheRaspberryPiNowthattheimageisflashed,let’sgetstartedwithsettinguptheRaspberryPiforthefirsttime.WewillhavetoinserttheSDcardslotfoundontheothersideoftheRaspberryPi.

AflashedSDcardintheslot

Whenthekeyboardandthemouseareconnected,wecangetstartedbypoweringuptheRaspberryPi!

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

TheRaspi-configscreen

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.

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

Whyisitawesome?Thinkofsaying“HelloWorld”asbothanodtoprogrammingtraditionandadryruntoensureyouarewellequipped!

YourHotshotobjectivesTheobjectivesforthismissionarequitesimple,andyettakeusallseveralmilestonesfurther!HerearetheobjectivesoftheHelloWorldmission:

CollectallthenecessarytoolsSetuptheGPIOperipheralIntroduceourselvestotheRaspberryPienvironmentTurnalightemittingdiode(LED)onandoffwitha1seconddelay

MissionchecklistGoovertheprevioussections,andmakesureyouhaveallthetools.DownloadtheGPIOlibraries,andensureyoucanlogintotheRaspberryPiremotely,andyouareallset!

NoteTherearetwodifferentwaystouseaRaspberryPi.Theyare:

ConnectingamonitortotheHDMIportortheRCAjackandakeyboardtotheUSBportoftheRaspberryPi.RemotelyloggingintotheRaspberryPifromthereader’sworkstation.

Ifyouareabeginner,itisbesttousethefirstmethodwhilethesecondmethodcanbeusedifyouarefamiliarwiththeLinuxoperatingsystemandremotelogincapabilities.

OncewecompletethesetupprocessbyselectingFinish,theRaspberryPirebootsandexpandsthefilesystemifnecessary.

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

EngagethrustersYouwillneedallofthetoolslistedintheprevioussectiontogetthroughthisproject.Takeyourtimeandmakesureyouhaveeverythinghandy!

Objectivecomplete–minidebriefingDoyouhaveallthetools?Readytogo?Thenontothenexttask!

SettinguptheGPIOWeneedtoenabletheGPIOperipheralsinourRaspbianinstallationtogetstarted.Inordertodownloadtherequiredtoolsandsetthingsinmotion,theRaspberryPineedstobeconnectedtotheInternet.

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

EngagethrustersWealsoneedtoknowtheGPIOperipheralsavailabletoconductourexperiment.ThefollowingfigureshowstheGPIOmapsoftheRaspberryPiRev1andRev2:

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

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

TheRaspberryPiGPIOperipheral

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-

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

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

GPIOprogrammingusingPythonInthissection,wewillensurethatthelibraryiscorrectlyinstalledandaddtheusertothegroup.ThiswillenabletheusertousetheGPIOpinswithouthavingrootprivileges.ThiswillbefollowedbythesectionongettingstartedwithGPIOcontrolprogramminginPython.

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:

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

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()

Objectivecomplete–minidebriefingInthissection,wefinishedwritingaprogramtomakeanLEDblink.Inthenextsection,wewillputacircuittogetherthatmakesanLEDblink.

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

EngagethrustersWewillconnecttheLEDandtheresistortotheGPIOpinandthegroundpin,asshowninthisimage:

LEDblinkingcircuit

NoteIfwearenotcarefulwiththehandlingoftheRaspberryPiGPIOpins,itmayeithertemporarilyresettheRaspberryPiorsometimesevenpermanentlydamagetheGPIOpin.ThereareseveraltutorialsinbasicelectronicsavailableovertheWeb.Itisimportantthatyoufamiliarizeyourselfwiththebasicsofelectronics.

Onceweconnectthecircuitasshownintheprecedingimage,wewillbeabletoexecutetheprogramandconcludeourexperiment.

Wecanexecutetheprogrambyrunningthemodule,asshowninthefollowingscreenshot:

ExecutingthePythonexample

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

pronetoencourage,improveuponitandopensourceitforotherstobenefit!

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

PiCruststackedontopoftheRaspberryPi

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

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

Intheforthcomingprojects,wewilllookintoI2Ccommunication,SPIcommunication,andUARTcommunication(serialport).

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

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.

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

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.

YourHotshotobjectivesInthisproject,wewilldiscussthefollowingfeatures:

BootstrappingyourRaspberryPibyinstallingOccidentalisSetupofremoteloginintotheRaspberryPiInstallationoftheRaspberryPiWebIDEPythondevelopmentontheWebIDETestanddebuggingexamplesusingtheWebIDE

NoteThisprojectshouldnotbeconsideredasanattempttopromoteAdafruitIndustriesortheirproductsdevelopedfortheirplatform.ThisprojectmerelydemonstratessimplificationofdevelopmentontheRaspberryPiusingatoolfromAdafruitIndustries.

MissionchecklistInordertogetstarted,thefirststepistoinstalltheOccidentalisdistro,whichisaderivativeoftheRaspbianoperatingsystem.

Thethingsrequiredtogetstartedareasfollows:

A4GBSDcardflashedwiththeRaspbianOSAnOccidentalisimage.AnEthernetcable

Installation,features,andusageoftheOccidentalisoperatingsystemfromAdafruitThefirststepisinstallingOccidentalisontheRaspberryPi.

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

Engagethrusters1. YoucanfinddetailedinstructionsoninstallingtheOccidentalistoolat

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

cannotincludethemheresincechangesweremadetoOccidentalisinstallationprocessafterwefinishedwritingthisbook.

Objectivecomplete–minidebriefingOncetheinstallationiscomplete,wehavetoensurethattheRaspberryPiaswellasthedevelopmentmachineareconnectedtothenetworkviatheEthernetportoraUSBWi-Fidongle.

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.

PrepareforliftoffTheIPaddressoftheRaspberryPicanbeidentifiedusingtoolssuchasAdvancedIPScanner,asshowninthefollowingscreenshot:

AlistofdevicesandIPaddressesconnectedtoanetworksimilartotheRaspberryPi

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.

Objectivecomplete–minidebriefingIftheusernameandpasswordareenteredcorrectly,weshouldbeabletoremotelylogintotheRaspberryPitoinstallthewebserver.

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

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.

AdafruitWebIDElaunchedforthefirsttime

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

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

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

NoteTheearliermentionedproductsaremerelyexamplestodemonstratetheAdafruitWebIDE.Therearealternativeprototypingplatformsandproductsavailableforahigherorlowerprice.

TheCobblermountedonabreadboard

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):

7-segmentbackpackconnectionsonabreadboard

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

Beforewegetstartedwiththeexample,weneedtodeterminetheI2Cbustowhichthedeviceisconnectedbyusingthefollowingcommand:

sudoi2cdetect–y0

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

Thei2cdetectoutput

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

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

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

#Togglecolon

segment.setColon(second%2)#Togglecolonat1Hz

#Waitonesecond

Thisexerciseisrepeatedwithaonesecondinterval.

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

Objectivecomplete–minidebriefingWewereabletotestanAdafruitproductusingtheirWebIDEinthissection.

A7-segmentbackpackconnectedtotheCobbler

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

BlinkMconnectedtotheCobbler

NoteItisimportanttopayattentionwhileconnectingdevicestotheGPIOheaderoftheRaspberryPi.IftherearedevicesthatdrawalotofcurrentfromtheGPIOpins,itmayresetthePiorpermanentlydamageitintheeventofashortcircuit.Itisassumedthatyouarefamiliarwithbasicelectronicsandcapableofhandlingsuchdevices.

PrepareforliftoffSimilartothepreviousexperiment,weneedtodeterminethebustowhichthedeviceisconnectedusingthei2cdetectcommand.Asshowninthefollowingscreenshot,thedeviceisconnectedtobus1andthedeviceaddressis0x09:

Blinkmconnectedtobus1

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:

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

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

Debugterminals

WhenwestartdebuggingaPythonscript,thetoolbaratthetoppresentsuswithtwooptions,namelyStepOverandStepIn,asshowninthefollowingscreenshot:

TheAdafruitdebugtoolbar

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

Objectivecomplete–minidebriefingInthissection,weinterfacedandcontrolledanRGBLEDusinganI2CinterfaceanddiscussedsomeoptionsavailablefordebuggingintheAdafruitWebIDE.

TheAdafruitWebIDEcanconsiderablyreducetheturnaroundtimeforanyprojectdevelopmentactivity.

MissionaccomplishedInthisproject,weworkedontwosimpleexperimentsusingtheI2CinterfaceontheRaspberryPi.ThetwoexamplesdiscussedusingtheAdafruitWebIDEreflectthefactthatthetoolcanhelpsavetimeforanyelectronicsprojectinvolvingaRaspberryPisinceitcomeswithsomeoftheprerequisitesinstalledalongwithawebinterfacethatjustmakesremotedevelopmenteasier.

WehopethatyouhadfuntakingtheOccidentalisdistributionforatestdriveandfinditusefulinyourprojects.

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

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

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

NoteTheRaspberryPicomeswithaGPIOpinsetthatisquitecapableofinterfacingandcontroldevices.WewouldliketodiscusstheArduinoRaspberryPiinterfacebecauseyoumayhaveprojectsthatwereoriginallybuiltusinganArduino,especiallyinscenarioswherearemotefirmwareupdateneedstobeperformedontheArduinoplatformusingtheRaspberryPi.ThisprojectpresentstheoptionsofenhancingthecapabilitiesoftheArduinomicrocontrollerusingaRaspberryPi.

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

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.

YourHotshotobjectivesInthisproject,wewilldothefollowing:

InstalltheArduinoIDEProgramtheArduinousingtheRaspberryPiRaspberryPiAlaMode(oranyotherArduinodevelopmentboard)IntroductiontoWeasleyWeatherClockandBillofMaterialsControlthestepperusingtheArduinoControltheRGBLEDStripusingtheArduinoI2CCommunicationusingtheArduino(optional)SerialportcommunicationwiththeRaspberryPi

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

InstallingtheArduinoIDEInthissection,wewillinstalltheArduinoIDEontheRaspberryPi.

PrepareforliftoffAnArduinomicrocontrollerdevelopmentplatform(anyvariantthatcouldbeprogrammedusingtheArduinoIDEisfine)isabsolutelyessentialforthissectionoftheproject.

Engagethrusters1. TheIDEcouldbeinstalledbyexecutingthefollowingcommandinthecommand

lineterminal:

sudoapt-getinstallarduino

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

arduino

TheArduinoIDEisshowninthefollowingscreenshot:

TheArduinoIDEinterface

Objectivecomplete–minidebriefingNowthatwehaveinstalledtheArduinoIDE,let’smoveontothenextsectionandrunanexampletestusingtheArduinodevelopmentplatform.

ProgrammingtheArduinousingtheRaspberryPiWewillintroduceourselvestotheArduinoIDEwithanLEDblinkingexample.

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

Engagethrusters1. WegetstartedbyidentifyingtheArduino’sserialportenumeratedontheRaspberry

Pi.2. TheserialportisidentifiedfromTools|SerialPort.Usuallythereisonlyoneserial

portasshowninthefollowingscreenshot.Ifthereismorethanoneserialportdeviceconnected,itisrecommendedthatyouproceedwithcaution.

3. WecanprogramtheArduinobyclickingontheUploadbutton.

TheArduinoIDEinterface

Objectivecomplete–minidebriefingIftheArduinoisconnectedandtheserialportwascorrectlyidentified,theprogramshouldbeuploadedsuccessfully.

SketchuploadedusingtheArduinoIDE

MostArduinoproductscomewithanonboardLEDtotesttheLEDblinkingexample.

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

RaspberryPiAlaModemodestackedontheRaspberryPi

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.

Engagethrusters1. Oncethearchiveisdownloadedfromtheirwebpage,weextractthecontents:

tar–xvzfalamode-setup.tar.gz

2. Oncethefilesareextracted,thesetupisasfollows:

sudo./setup

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

Objectivecomplete–minidebriefingAftertheinstallationiscomplete,weshouldhavetheRaspberryPiAlaModemodeenumeratedandbereadytostartprogrammingthehardwareadd-onboard.

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

TheWeasleyweatherclockisonethatdisplaysthecurrentoutdoortemperatureandtheforecast.Italsowarnsusaboutimpendingdangersduetoconditionssuchastornadoes,blizzards,andsoon.

AWeasleyweatherclockbuiltusingtheArduinoandtheRaspberryPi

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.

Engagethrusters1. TheWeasleyclockcouldbeeasilyassembledwithpartsmachinedwithalasercutter.

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

PartialassemblyoftheWeasleyClock

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

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

FlowofdataandcontrolinthisWeasleyClockproject

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

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

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

NoteItisassumedthatyouarefamiliarwithsteppermotorsandtheircontroltheory.

Asteppermotorenergizationsequencefrom28BJY-48’sdatasheet

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);

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

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);

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

WediscussedthesteppermotorcontroltechniqueusingtheArduinomicrocontroller.Oncewehavediscussedtheprerequisites,wewilltakethiscodesampleandbuildthingsaroundit.

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

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

NoteItispossibletoproduceasecondarycolorusingtheRGBcombinations.ThiscanbeachievedbyturningontheRGBsegmentsatthesametimeandvaryingthebrightnessoftheprimarycolors.TherearevastresourcesavailableforsuchtipsandtricksontheInternetandanexplanationofthisisbeyondthescopeofthisbook.

PrepareforliftoffTheAdafruitlearningwebsiteprovidesexamplesforcontrollingtheRGBLEDusingapulsewidthmodulationtechnique.TheschematicfortheAnalogRGBstripisshowninthefollowingdiagram:

RGBLEDstripschematic(borrowedfromAdafruit)

SincetheRGBstriprequires12V,wemustuseatransistorswitchingcircuittocontroltheLEDs.ThetransistorswitchingcircuitforcontrollingtheRed,Green,andBluechannelsoftheLEDstripisshowninthefollowingdiagram:

TheArduinoRGBswitchingcircuit

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

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.

Objectivecomplete–minidebriefingWediscussedadjustingthebrightnessoftheRGBLEDstripusingthePulseWidthModulationTechniqueandanArduinomicrocontroller-baseddevelopmentplatform.

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

PrepareforliftoffThemainrequirementforthissectionisthenecessaryI2Cdevicerequiredtointerfacewiththeweatherclock.

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

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)

Objectivecomplete–minidebriefingWediscussedtheinterfacingofdifferentI2Cdevicesthatcouldbeusedinthisproject.Inthenextsection,wewillworkoncontrollingthesedevicesusinganindividualcontrolsignal.

SerialportcommunicationwiththeRaspberryPiAsmentionedearlier,theweatherdataisobtainedbytheRaspberryPiandcommunicatesthedatawithcontrolcharactersviatheserialport.Wewilldiscussthecontrolsignalsusedinthisproject.

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)

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

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.

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

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();

}

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

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.

if(serial_read=='P'){

while(Serial.available())

{

sb=Serial.read();

serInString[serInIndx]=sb;

serInIndx++;

}

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

}

Objectivecomplete–minidebriefingInthissection,wediscussedtheoverallcontroloftheweatherclockanditsinterfacetotheInternet.Wealsodiscussedtheinterfacingofthesensorsanddisplayingtheweatherdata.

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

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

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

MissionbriefingInthischapter,wewillinstallalocalwebserver-basedcontrolofGPIOpinsontheRaspberryPi.Wewillusethiswebserverframeworktocontrolitviaawebpage.

TheRaspberryPiontopofthetreeisjustanornamentfordecoration

Whyisitawesome?Wecelebratefestiveoccasionsbydecoratingourhomes.ThedecorationsreflectourheartanditcanbeenhancedbyusingRaspberryPi.

NoteThisprojectinvolvesinterfacingAC-powereddevicestoRaspberryPi.Youshouldexerciseextremecautionwhileinterfacingthedevices,anditisstronglyrecommendedthatyousticktotherecommendeddevices.

YourobjectivesInthischapter,wewillworkonthefollowingaspects:

InterfaceoftheChristmastreelightsandotherdecorativeequipmenttotheRaspberryPiSetupthedigitally-addressableRGBmatrixInterfaceofanaudiodeviceSettingupthewebserverInterfacingdevicestothewebserver

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

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

PrepareforliftoffWehavetoconnectthePowerSwitchTailIItotheRaspberryPitotestit.ThefollowFritzingschematicshowstheconnectionoftheswitchtotheRaspberryPiusingPiCobbler.Pin25isconnectedtoin+,whilethein-pinisconnectedtotheGroundpinoftheRaspberryPi.

TheRaspberryPiconnectiontothePowerSwitchTailIIusingPiCobbler

ThePiCobblerbreakoutboardisconnectedtotheRaspberryPiasshowninthefollowingimage:

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:

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

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

Objectivecomplete–minidebriefingInthissection,wediscussedcontrollingdecorativelightsandotherholidayappliancesbyrunningaPythonscriptontheRaspberryPi.Let’smoveontothenextsectiontosetupthedigitallyaddressableRGBLEDstrip!

SettingupthedigitallyaddressableRGBmatrixInthissection,wewilltalkaboutsettingupoptionsavailableforLEDlighting.WewilldiscusstwotypesofLEDstrips,namelyanalogRGBLEDstripsanddigitally-addressableRGBLEDstrips.

Aswediscussedthefirstoneindetailinthepreviouschapter,wewillskipitandmoveontothesecondkind.AsampleofthedigitallyaddressableRGBLEDstripisshownintheimagethatfollows:

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.

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.

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

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.

Objectivecomplete–minidebriefingInthissection,wereviewedoptionsfordecorativelightingandcontrollingthemusingtheRaspberryPiandArduino.

InterfaceofanaudiodeviceInthistask,wewillworkoninstallingMP3andWAVfileaudioplayertoolsontheRaspbianoperatingsystem.

PrepareforliftoffTheRaspberryPiisequippedwitha3.5mmaudiojackandthespeakerscanbeconnectedtothatoutput.Inordertogetstarted,weinstalltheALSAutilitiespackageandacommand-linemp3player:

sudoapt-getinstallalsa-utils

sudoapt-getinstallmpg321

EngagethrustersInordertousethealsa-utilsormpg321players,wehavetoactivatetheBCM2835’ssounddriversandthiscanbedoneusingthemodprobecommand:

sudomodprobesnd_bcm2835

Afteractivatingthedrivers,itispossibletoplaytheWAVfilesusingtheaplaycommand(aplayisacommand-lineplayeravailableaspartofthealsa-utilspackage):

aplaytestfile.wav

AnMP3filecanbeplayedusingthempg321command(acommand-lineMP3player):

mpg321testfile.mp3

NoteIntheprecedingexamples,thecommandswereexecutedinthedirectorywheretheWAVfileortheMP3filewaslocated.IntheLinuxenvironment,itispossibletostopplayingafilebypressingCTRL+C.

Objectivecomplete–minidebriefingWewereabletoinstallsoundutilitiesinthissection.Later,wewillusetheinstalledutilitiestoplayaudiofromawebpage.

ItispossibletoplaythesoundfilesontheRaspberryPiusingthemoduleavailableinPython.Someexamplesinclude:Snacksoundtoolkit,Pygame,andsoon.

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

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

sudoapt-getinstallpython-setuptools

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!

AHelloworld!exampleusingtheweb.pyframework

Objectivecomplete–missiondebriefingWebuiltasimplewebpagetodisplaytheHelloworldtext.Inthenexttask,wewillbeinterfacingtheChristmastreeandotherdecorativeappliancestoourwebpagesothatwecancontrolitfromanywhereonthelocalnetwork.

ItispossibletochangethedefaultportnumberforthewebpageaccessbylaunchingthePythonscriptasfollows:

pythonhelloworld.py1234

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

InterfacingthewebserverInthissection,wewilllearntointerfaceonedecorativeapplianceandaspeaker.WewillcreateaformandbuttonsonanHTMLpagetocontrolthedevices.

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

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

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:

Yay!WehaveaChristmaslightscontrollerinterface.

Objectivecomplete–minidebriefingWehavewrittenasimplewebpagethatinterfacesaChristmastreeandRGBtreeandplaysMP3files.Thisisagreatprojectforaholidayweekend.

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

MissionaccomplishedInthisproject,wehaveaccomplishedthefollowing:

InterfacingtheRGBmatrixInterfacingACappliancestoRaspberryPiDesignofawebpageInterfacingdevicestothewebpage

WeusedexamplestodemonstratethecapabilitiesofenhancingthefestivedecorationusingtheRaspberryPi.Itisdefinitelypossibletoenhancethisprojectusingourcreativity.

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/)

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

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

FollowingisanimagethatshowsafountaincontrolledbytheRaspberryPi:

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

YourobjectivesInthisproject,wewillbuildthetabletopfountaininthefollowingsteps:

AssemblingthefountainInstallationoftheFlaskframeworkandinterfacingthefountainControllingRGBLEDsfromthewebpageSettingupe-mailalertsforthefountain

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.

PrepareforliftoffIfthereaderisnotabletogainaccesstoaDIYfountainkit,thefollowingitemsarerequired:

Abasin(preferablyopaquesothatitdiffuseslight)Afountain/submersiblepumpfromapetshopPebblesandgravelDecorativeaccessoriesavailablefromaquariums

Theseitemscouldbepurchasedfromahobbyshoporanaquariumsuppliesstore.

Engagethrusters1. TheDIYtabletopfountainkitcomeswithabasinthathasaprovisiontorunthe

fountainpump’scableoutofthebasinthroughasealedoutlet.

Abasinwithasealedelectricaloutlet

2. Next,wewillplacethefountainpumpinsidethebasin.

Fountainpumptobeplacedinsidethebasin

3. Wewillnowcoverthepumpwithacoverandplaceadecorativepot.

Fountainpumpcoveredwithadecorativepot

4. Wecanfillthesidesofthepumpwithgravel,pebbles,smallpiecesofrock,andotherdecorativeaccessories.Wethenturnonthepumpandtestthewaterflowtomake

surethatwedon’tspillwaterandmakeamess.

Afountainwithdecorativeaccessories

5. We’llwrapthefountainwithadigitallyaddressableRGBLEDstripandwearedonewithassemblingthefountainwhenwepowerthefountainalongwiththeRGBLEDs.

AwaterfountainstrappedwithadigitallyaddressableRGBLED

Objectivecomplete–minidebriefingInthefirststep,wefinishedassemblingthefountainandtheRGBLEDstrip.Wewillmoveontoinstallawebframeworktoimplementlightingcontrolfortheframework,whichwecanchangebasedonourneeds.

InstallationoftheFlaskframeworkInthistask,wewillinstalltheFlaskframeworkontheRaspberryPiandcompleteatestwebpageontheRaspberryPi.WewillusetheFlaskframeworktocontroltheRGBLEDstrip.

PrepareforliftoffInthepreviousprojects,weinstalledpythonmoduleinstallerssuchaspiporeasy_install.Ifeitherofthesetoolsisn’tinstalled,theycanbeinstalledbyexecutingthefollowingcommand:

sudoapt-getinstallpython-pip

Alternatively,youcanusethefollowingcommand:

sudoapt-getinstallpython-setuptools.

Next,wewillworkoninstallingtheFlaskframeworkandthefirstexample.

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')

Objectivecomplete–minidebriefingInthistask,wearedoneinstallingtheFlaskframeworkforcontrollingtheframework.Wewillmoveontothenexttasktosetupthings.

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

PrepareforliftoffSinceweareusingthedigitallyaddressableRGBLEDstrip,weneedtoenabletheSPIdriversontheRaspberryPi.

NoteEnablingofSPIdriversisnotnecessaryiftheyouhaveinstalledOccidentalisinProject2,ARaspberryWebIDEExample.

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

Theblacklistspi-bcm2708lineneedstobecommentedout(adda#atthestartoftheline).Thenwegetthedriversworkingbyexecutingthefollowingcommand:

sudomodprobespi_bcm2708

TheSPIdevicescanbefoundlistedinthe/devdirectory:

SPIdeviceslistedinthedirectory

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]])

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

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

ItispossibletocontrolthelightsofthefountainbasedonasongbeingplayedontheRaspberryPi.Howcanthisbeachieved?Visitthisbook’swebsiteforsomeclues.

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

PrepareforliftoffWewillgetstartedbyinstallingthepython-feedparsertool.Googleprovidesaread-onlyinboxfeedandwewillmakeuseofthefeedparsermoduletodeterminewhetherwereceivedanynewe-mails.

sudoapt-getinstallpython-feedparser

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:

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

importtheLPD8806moduleandflashtheRGBLEDstrip.

Objectivecomplete–minidebriefingInthistask,wecompletedthesetupofthee-mailalertsaswellasauserinteractionelementofblinkinganLED.Thisbringsustotheendoftheassemblyandsetupofthefountain.

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

HotshotchallengeInthisproject,wesetupe-mailalertswiththedisplay.IsitpossibletosetTwitteralerts?

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

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

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

YourobjectivesInthisproject,wewillaccomplishthefollowing:

Settingupthee-mailfeedparserSettinguptheparserforremindersandeventsDesigninganenclosureforthepersonalassistantSettinguptheassemblyforthedishmonitorSettingupsensorsforthekeyalertsystem

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.

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.

Delaunaytriangulation–OpenCV

5. NowthatwehaveinstalledOpenCV,wewillproceedtobuildourprojectovertheforthcomingtasksoftheproject.

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

PrepareforliftoffSincewealreadyinstalledthepython-feedparsermodule,wewillgetstartedwithsettingupthemailparser.Wewillbuildeachmoduleofourprojectasaseparateexample.

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)

gpio.output(17,gpio.LOW)

time.sleep(1)

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

else:

time.sleep(10)#repeatcyclefor10seconds

3. TheLEDneedstobeconnectedasshowninthefollowingdiagram:

RaspberryPiemailnotifier–SchematiccreatedwithFritzing,RaspberryPiLibrary

SettinguptheparserforremindersandeventsInthistask,wewillimplementamodulethatwillblinkanLEDtoremindusaboutimportanteventsandappointments.

PrepareforliftoffTheGoogleDataPythonclientlibraryisrequiredforthistask.Youalsohavetosavesometasksinyourcalendartotesttheimplementation.

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

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)

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

PrepareforliftoffThisenclosurecanbefabricatedinfewsimplestepsusingalasercutter.ThedesignavailablealongwiththisprojectinthePDFformatcanbemodifiedusingadesigntoolsuchasInkscapeorAdobeIllustrator.

Engagethrusters1. Theenclosuredesignismeanttobemanufacturedusingalasercutter.Sincelaser

cutterscanbeeasilyaccessedfromhackerspaces,openworkshops,andsoon,itshouldbeeasytomakethisenclosure.

2. Alasercutteriseasytousewhenweadheretosafetypractices.Youmustundergotrainingtooperatealasercutter.Thefilesusedforlasercuttingareavailablefromtheprecedinglink.

3. Oncethelasercuttingoperationiscomplete,thepartsoftheenclosurelookliketheoneshowninthefollowingimage:

AGluelessbox

4. Theassemblyoftheenclosureisquiteintuitive.Wewillmakeuseofthisenclosureinthelaterpartofthisproject.

Anassembledenclosure

SettinguptheassemblyforthedishmonitorInthistask,wewillsetupamonitoroverthekitchensink.WewillcheckwhethertherearedishesinthesinkandsendLEDalertstotheuser.SincewehaveinstalledOpenCValready,wewillgetstartedwiththesetupofthemonitor.

ThistaskwasinspiredbyahackerbasedinLondonwhobuiltadishdetectortoalertusersofacommunalkitchen.

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

PrepareforliftoffWewillgetstartedbymountingacameraontopofthesinkandconnectingittoanoverheadcamera,asshowninthefollowingimage:

Anoverheadcameraontopofthesink

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:

DishesdetectedinOpenCV

9. Ifavesselisdetected,wewilltriggeranLEDalerttoannoytheuser.

Objectivecomplete–minidebriefingWehavesetupadishmonitortoalerttheuserwhendishesaredetectedusinganLED.

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

Theuniquenessaboutthistaskisthatwetrytoimproveourliveswithsimpleitemsthatareeasytopurchaseandsimpletobuild.Amagnetandareedswitchareavailablefromallhobbystores.Youcanalsouseareedswitchindoorsecuritysystems.ThefollowingisadiagramofareedswitchinterfacedtoaRaspberryPi:

ReedswitchsetupwiththeRaspberryPiGPIO

PrepareforliftoffWewillinterfacethereedswitchasshownintheprecedingdiagram.Let’stestitonabreadboardbeforesettingitupinanenclosure:

ReedswitchinterfacedtoRaspberryPi

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

Objectivecomplete–minidebriefingInthistask,youlearnedtouseasimplereedswitchtotheRaspberryPiandhelpimproveourlives.

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

HotshotchallengesHowcanweuseRaspberryPitoenhancethelivesofseniorcitizens?

Thedishdetectorisnoiseprone.Howcanitbeimproved?

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.

Chapter7.RaspberryPi-basedLineFollowingRobotInthisproject,wewillbuildalinefollowingrobotthatiscontrolledbyyourRaspberryPi.

NoteItisabsolutelynotnecessarytomakeuseoftheRaspberryPitobuildalinefollowingrobotunlessyouareusingacameratofollowtheline.WearebuildingthisrobottodemonstrateanexampleofbuildingamechatronicsystemusingtheRaspberryPi.

MissionbriefingInthisproject,wewillbuildalinefollowingrobotthatwillfollowablacklineagainstawhitebackground.Therobotwillmakeuseofapairofinfraredsensorstotracktheorientationoftherobotanddrivetherobotaccordingly.

Alinefollowingrobot

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

YourHotshotobjectivesInthisproject,wewillbuildthelinefollowingrobotinthefollowingsteps:

AssemblyofthePiPlateforthelinefollowingrobotSensorselection,interfacingsensors,anddatainterpretationImplementationoflinefollowinglogicbasedonsensordataTestingthemotordrivercircuitPreparationofthelinefollowingcourseDesigningthechassisforthelinefollowingrobotAstep-by-stepassemblyoftherobot

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

AssemblyofthePiPlateforthelinefollowingrobotNoteThePiPlateisnecessaryonlyifyouaregoingtobuildyourowncircuitry(insteadofanoff-the-shelfrobotkit)thatdrivestherobot.

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

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

Engagethrusters1. ThecontentsofthePiPlatepackageareasfollows:

ContentsofaPiPlatepackage

NoteAdultsupervisionisrequiredforsolderingandputtingthePiPlatetogether.

2. ThePiPlaterequiressolderingoftheterminals,andAdafruithassometutorialsinsettingupthePiPlate.Whentheterminalsandheadersareassembledtogether,wehavewhatisshowninthefollowingimage:

APiPlatestackedontheRaspberryPi

Objectivecomplete–minidebriefingItisunlikelythattherewillbeaproblemwiththePiPlateunlessthereisacoldsolder.

Sensorselection,interface,anddatainterpretationInthistask,wewilldiscussthedifferentsensorsavailabletobuildalinefollowingrobotandpickasensorforthisproject.

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

LightDependentResistorsAsthenamesuggests,LightDependentResistorsarethosethatchangetheirresistancewhenlightisincidentonthesurfaceoftheresistor.

LightDependentResistorsareusedincombinationwithabrightLED.Wecanmakeuseofthedifferenceinreflectivitybetweendifferentcolouredsurfacestofollowablacklineonadarksurface.

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

ALightDependantResistorinapotentialdividerconfiguration

ThepotentiometerinthepotentialdividerconfigurationisusedtoadjustthesensitivityofLightDependentResistorsdependinguponthesurroundinglightingconditions.

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)

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

Objectivecomplete–missiondebriefingInthistask,wediscussedthedifferentsensoroptionsavailableforalinefollowingrobot.

ImplementationoflinefollowinglogicbasedonsensordataInthistask,wewillimplementasimplelinefollowingtechniqueusingtheinfraredsensor.Wewillmakeuseofapairofinfraredsensorstotrackablacklineonawhitesurface.Therobotwillmoveforwardifboththesensorsareonawhitesurface.Therobotturnsleftiftheleftsensorisontheblacklineandviceversa.

PrepareforliftoffThesensorneedstobesolderedandconnectedtotheRaspberryPi(somethingliketheoneshownintheprecedingschematic).Alternatively,youmayuseasensorofyourchoice.

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.

Objectivecomplete–minidebriefingInthistask,weimplementedthelinefollowinglogicforourrobot.Inthenexttask,wewilldiscussmotorcontroltodrivetherobotThiswouldbeeventuallyintegratedintothelinefollowinglogic.

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

1. DCmotorsareeasytooperateandcontrolusinganH-bridgeinterfacedtotheRaspberryPi.

2. ThereisasoftwarePWMlibrarythatmakesiteasiertocontroltheDCmotors.

Inthistask,wewillimplementtheDCmotorcontrolcircuitandalsowriteaprogramtocontroltheDCmotors.

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:

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.

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

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)

Objectivecomplete–minidebriefingInthistask,weimplementedamotordrivercircuitryandtestedit.

PreparationofthelinefollowingcourseInthistask,wewillpreparethelinefollowingtrackfortherobot.

PrepareforliftoffTherearetwoapproachestobuildingalinefollowingtrack.Theyincludethefollowing:

1. PrintatrackavailablefromParallaxandsetitontopofaposterboard.2. UseelectricaltapeandbuildatrackusingatutorialfromPololu.

Thefollowingitemsarerequiredtocompletethistask:

1. Aposterboard2. Apermanentmarker3. Apencil4. Aruler5. A4sheets

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.

DesigningthechassisforthelinefollowingrobotInthistask,wewilldesignthechassisforthelinefollowingrobot.Thereareseveraloptionsavailableintermsofdesigntoolsforthedesignofthechassis.WechoseAutodeskInventor,buttherearealotoftoolssuchasAutodesk123Dandsoon.

PrepareforliftoffThechassisfortherobotisfabricatedusingthelasercuttingtechnique.Youarewelcometofabricateyourownchassis.Wehavechosentouselasercuttingbecauseitistheeasiesttocomplete.Thetechniqueinvolvesdesigningthechassisfollowedbypreparingthedesignforfabricationandlasercutting.

Youmaydownloadthedesignfileavailablealongwiththisprojectanduseitforlasercutting.ThereisatrialversionofAutodeskInventoravailablefordownloadanditcanbeinstalledandusedfordesigningacustomchassis.

Asamaker/hacker,itisimportantthatyoulearnhowtousethesetoolsandhowtodesignachassis.

NoteTheuseoftoolssuchasalasercutterrequiressomebasictrainingandsupervision.Itisimportantthatyouundergotherequisitesafetytrainingbeforeoperatingsuchequipment.

Engagethrusters1. Wewillbeginbyconsideringthecomponentsthatgointotherobot.Thecomponents

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

2. SincethePiPlatewillbestackedontopoftheRaspberryPi,wewillmountthebatteryonaseparateplatemountedontopoftheRaspberryPi.Thecomponentpositionsaredesignedbasedonintuition.Thechassisisshowninthefollowingimage:

Lasercutchassisoflinefollowingrobot

3. Thetopplatethatholdsthebatterypackisshowninthefollowingimage:

Atopplateusedtomountthebatteryofthelinefollowingrobot

Objectivecomplete–minidebriefingWehavefinisheddesigningthepartsandfabricatingthemusingalasercutter.

Astep-by-stepassemblyoftherobotInthistask,wewillassembletherobotinsimplestepsthatareaccompaniedbyaphotographicalrepresentation.

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

Engagethrusters1. Wewillgetstartedbymountingthecastorwheel.

Mountingthecastorwheel

2. WewillmounttheRaspberryPiusingM2.5screws.

RaspberryPimountedusingM2.5screws

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

DCmotorsmountedusingdouble-sidedtape

4. WewillmountthePiPlateandthetopchassisplate.WewillusevelcrotomounttheUSBbatterypacktocompletethelinefollowingrobotassembly.

Anassembledrobot

5. Oncetheassemblyiscompleted,wehavetoconnectthemotorsandthesensorstogetstartedwiththetesting.

Objectivecomplete–minidebriefingWehavecompletedtheassemblyofthelinefollowingrobotinthistask.Oncethemotorcontrolcodeisimplementedintothelinefollowinglogic,weareallsettotestingtherobotonthetrack.Thismayrequiresometweakingthemotorspeedtomaketherobottrackthelineeffectively.

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

Alinefollowingrobotonthearena

HotshotchallengeInthisproject,wedidnotmakeuseofanymotorcontrolalgorithm(likePID)tosteertherobot.Howdoweimplementone?

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

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

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

Whenwefinishthisproject,ourcabinetwillbesomethingliketheoneshowninthefollowingimage:

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

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

YourobjectivesWewillbuildourConnectFourdesktopgamethroughthefollowingactivities:

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

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

HelloworldexamplewiththepygameInthistask,wewilllearntheusageofpygameforgamedevelopment.Wewillgetstartedwithanexamplethatopensablankwindowandwriteacoupleoflinestomonitoreventssothatwecanquittheprogramifthewindowisclosed.

Wewillgothroughtheimportantfeaturesofthepygamemodule,whichisnecessarytobuildourarcadegame,includingplayingsoundsandcontrollingthemenu.

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

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()

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

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()

Objectivecomplete–minidebriefingWehavefinishedtestingthepygamemoduleandreviewedasimplemenudesignexamplealongwithtestingtheplayingofsoundsusingthepygamemodule.

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

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

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

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

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

Objectivecomplete–missiondebriefingWehavecompletedthebasictweaksrequiredforthegame.Inthenextstep,wewillinterfacethearcadestylebuttonstothegame.

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.

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:

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:

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)

isFirstGame=False

state=0

prev_state=1

elifstate==2:

print'Exit'

pygame.quit()

sys.exit()

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

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

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

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

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.

Objectivecomplete–minidebriefingNowthatthecodereviewiscomplete,let’smoveontothenexttasktoimplementasimplemarqueeandwireuptheinputbuttons.

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

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.

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()

Objectivecomplete–minidebriefingInthistask,wefinishedintegratingtheLEDdisplaytoRaspberryPithatrunsthegame.

SetupoftheswitchesusingacardboardboxInthistask,wewilldesignourarcadegamecabinetusingcardboard.Wewillusecabletiestomountthecomponentsofourarcadegame.Wewillleaveittothereadertodesignabettercabinetusingtoolsoftheirchoice.

PrepareforliftoffWeshouldputtogetheramonitor,RaspberryPi,speakers,andthepushbuttonsusedtoplaythegame.Wealsoneedplentyofcardboardtoprototypethedesignofourcabinet.

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.

SuggestedinputconnectionsprovidedbythePiFacemanual

6. ThenextstepistoconnectamonitortoRaspberryPi.ThefollowingfigureshowsamonitorwiththeConnectFourgamelaunchedandtheswitchesmountedontoacardboardboxandinterfacedwiththePiFacemodule:

Objectivecomplete–minidebriefingInthistask,wefinishedsettingupthedesktopConnectFourgameusingRaspberryPi.

MissionaccomplishedInthisproject,weaccomplishedthefollowing:

1. WeusedaPythonscriptfortheConnectFourGameandtweakedittoourrequirements.

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

HotshotchallengeInthisproject,weperformedcontroloftheinputswitchesasablockingoperation.Canyoufigureouthowtomonitorswitchpresseventsbystartingmultiplethreads?Howcanweimprovethespeedofthegame?

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.

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

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

NoteThisprojecthasbeenpresentedasanexampletohelpapersonenhancethequalityoflifefortheiranimalfriends.Thisprojectshouldnotbeconstruedasareplacementofhumaninteractionforouranimalfriends.Wetotallyunderstandthatpetseasethestressinourlivesandthisprojectpresentssomeexamplestomaketheirlivesbetter.

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

YourobjectivesInthisproject,wewillexplorethefollowingtopics:

Installingandtestingthepython-twistedframeworkSettingupandtestingSparkCoretointeractwithappliancesInstallingandtestingtheGoogleCoderprojectontheRaspberryPiAbriefoverviewofabirdfeederthattriggersacamera

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

Installingandtestingthepython-twistedframeworkInthistask,wewillreviewthepython-twistedframework(https://twistedmatrix.com/trac/).TheTwistedframeworkisanopensourceevent-drivennetworkenginethatcanbeusedtosendcontrolmessagestootherdevices(forexample,apetfeedercanbeoperatedusingRaspberryPitodispensesolidfoodtoouranimalfriends).ThemessagingprotocoliscalledAMP(AsynchronousMessagingProtocol)whichisavailableathttp://amp-protocol.net/.

PrepareforliftoffTheRaspberryPi(withanSDcardflashedwiththeOSimage)connectedtotheInternetisneededforthistaskalongwithanArduinoEthernetBoard(oranyoneoftheboardsmentionedearlierinthechecklist.Networkconnectivityisessential).Wewillinstallthepython-twistedframeworkandreviewaquickexampletoexchangemessagesbetweenArduinoandtheRaspberryPi.

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);

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:

InteractionoftheArduinoclientwiththeRaspberryPi

4. WedemonstratedtheabilitytotransmitandreceivemessagesbetweenArduinoandtheRaspberryPi.

Objectivecomplete–minidebriefingAttheendofthisproject,wewilldiscussmakinguseofthepython-twistedframeworkandanArduinoEthernetboardtohelpyoucontrolacameratriggerorremotelydispensetreatsusingapetfeeder.

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).

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

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();

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.

Objectivecomplete–minidebriefingThat’sit.YounowhaveSparkCore,allsetupandreadytogo,withyourusername,andyourownpagetodownloadappsandcollectandtransmitdatathroughtheCore.

InstallingandtestingtheGoogleCoderprojectontheRaspberryPiThisisprobablythesimpleststageoftheprojectasyoushouldbefamiliarwithsettinguptheRaspberryPiforfirstuse.

TheGoogleCoderisatoolreleasedbyGooglethatenablespeopletolearnwebdevelopmentusingtheRaspberryPi.Itisatoolthatprovidesanintuitivelearningprocess.AfterinstallingtheGoogleCodertool,wewilltestinterfacingtheGPIOpinsoftheRaspberryPitothewebinterface.

PrepareforliftoffWeneedtodownloadtheGoogleCoderimagefromitsrepository.TheGoogleCoderimageisavailableathttp://googlecreativelab.github.io/coder/.

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.

Objectivecomplete–objectivecompleteWewillmakeuseofthethreetasksdiscussedinthisprojecttoputtogetheratriggerthatcomestoeatoutofabirdfeeder.

AbriefoverviewofabirdfeederthattriggersacameraInthistask,wewillsetupabirdfeederwithamotionsensor.Wheneverabirdfliesintofeedonthegrainsoutofthefeeder,themotionsensoristriggeredtosendamessagetotheRaspberryPi.AcameramoduleoraUSBcameraisconnectedtotheRaspberryPi,whichcapturessomebeautifulmomentsinourbackyard.

SrihariYamanoor(oneoftheauthorsofthisbook)hasanextensivebackyardwherethisbirdfeederhasbeeninstalled.Checkoutthisbook’swebsitetofindoutwhetherwehavecapturedanybeautifulmomentsthusfar!

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/.

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

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')

Abirdtrigger

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.

MissionaccomplishedInthisproject,weinterfacedbuiltasmallecosystemofdevicesthatweremonitoredbytheRaspberryPi.Weusedthoseexamplestobuildabirdfeeder!

HotshotchallengeInthisproject,wediscussedinterfacingasensortotakepicturesofbirdsthatcometofeedfromthebirdfeeder.Isitpossibletouploadthevideofeedtosomewherethat’ssecureovertheInternet?Howdowedothis?

Chapter10.RaspberryPiPersonalHealthMonitorInthisproject,wewilldiscussimplementingasolutionwhereRaspberryPiactsasapersonalhealthmonitor.Wewouldliketodedicatethisprojecttoallthepeoplewhohavebeendiagnosedwithtype2diabetesoranyotherlifestylediseases.Thisprojectpresentssometricksforthosediagnosedwithsuchlifestylediseases.

NotePleasedonotconsiderthisprojectasanalternativetoexistingtreatmentandpractices.Thisproject’strickswillhelpyouleadabetterlife.Forexample,yourRaspberryPicanremindyoutotakeyourprescribedmedication(ifany).

MissionbriefingInthisproject,wewillbuildsomesolutionstoaddresscommonproblemsencounteredbypeoplewithlifestylediseases.SimilartoProject6,RaspberryPiasaPersonalAssistant,thisprojectpresentsdifferenttipsandtrickstoleadabetterlifeineachtask.Wewilldiscussexampleswhereapersoncanbuildasimplewebservertostorehis/herdailyvitalhealthparameters(forexample,bloodpressure,bloodoxygensaturationlevels(SpO2),andsoon).Also,theservercanhelpapersontoremainphysicallyactivethroughtheday,provideaquickrecapofthee-mailparser,providetheeventremindertoolfromProject6,RaspberryPiasaPersonalAssistanttoremindapersonaboutupcomingappointments,refillhis/herprescriptions,andsoon.

Whyisitawesome?Wedecidedtowritethisprojectbasedonthepersonalexperienceofoneoftheauthors’familymember.Itisquitestressfulforapersonwhenhe/sheisdiagnosedwithachronicconditionssuchastype2diabetes.Thepersonissubjectedtostressfulconditionsrelatedtochangeindailyfoodhabits,developingahabitofconsumingmedicationeveryday,andbeingmindfulofwhathe/sheeatseverydaywhilstensuringthattheircriticalhealthparametersareintact.Itisobviouslydifficulttoacceptasuddenchange,andthisprojectpresentssomeoptionstomitigatesuchdifficultiesandbringtheperson’shealthbackontrack.

YourHotshotobjectivesInthisproject,wewillreviewthefollowingexamples:

SettingupawebservertorecordhealthparametersAsimplephysicalexercisetoolusingRaspberryPiSettingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointmentAsimpletoolthatremindsapersontotakehis/herpills

MissionchecklistItwouldbegreattohavethefollowingcomponentsforthisproject:

ARaspberryPialongwithanSDcard(ofatleast4GBinsize)thathasbeenflashedwithanimageandrequisitepowercable.AnArduinoEthernetboard(http://arduino.cc/en/Main/arduinoBoardEthernet).Thisiscompletelyoptional.Atactileswitch,resistors(10K),andapiezoelectricbuzzer(allthesecomponentsareavailablefromRadioShack).ItwouldbegreattohavetwoRaspberryPiboardstobuildthephysicalexercisetoolusingRaspberryPi.

SettingupawebservertorecordhealthparametersInthistask,wewillbuildasimplewebserverthatcanbeusedtomaintaincriticalhealthparameters.Let’sconsiderascenariowhereapersonisdiagnosedwithhighbloodpressure.Thedoctorasksthepatienttorecordhis/hervitalhealthparameterssuchaspulse,oxygenlevel,orbloodpressure.Forthissituation,wewillbuildasimplewebpagethatrecordsthedataandstoresitinaCSVfile.

PrepareforliftoffWewillbeusingtheFlaskframework(http://Flask.pocoo.org/)todeploythewebserveronRaspberryPi.WemadeuseoftheFlaskframeworkinProject4,ChristmasLightSequencer.JustincaseyouskippedthroughProject4,ChristmasLightSequencer,aPythonpackagemanagersuchaspiporeasy_installisrequiredtoinstalltheFlaskframework:

sudoapt-getinstallpython-pip

AftertheinstallationofthePythonpackagemanageriscomplete,theFlaskframeworkmaybeinstalledasfollows:

sudopipinstallFlask

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

pagethatdisplaystherecordedvaluesalongwiththetimestamp(asshowninthefollowingfigure):

Thepagedisplayedaftertheresultsarerecorded

2. ItispossibletoviewtherecordeddataonthewebpagebyreadingtheCSVfile.Weleavethisforyoutofigureout(lookatthisbook’swebsitefortheanswer).

Objectivecomplete–minidebriefingWebuiltasimpleFlask-framework-basedwebservertorecordvitalhealthparametersusingRaspberryPi.Itispossibletoe-mailthedataatregularintervalsusingthesmtpmoduleinPython.

AsimpleexercisetoolusingtheRaspberryPiInthistask,wewillreviewafunexamplethatenablesapersontobephysicallyactiveevery60minutes.

PrepareforliftoffThisexampleisbasedontheTwistedframeworkdiscussedinthepreviousproject.ItwouldbegreattohavetwoRaspberryPiboards(setupwiththeSDcardimagesandpoweredup)oranArduinoEthernetboard.AlaptopthatisconnectedtothesamenetworkastheRaspberryPiisjustassufficient.

IfyoumissedinstallingtheTwistedframeworkinthepreviousproject,theTwistedframeworkcanbeinstalledasfollows:

sudoapt-getinstallpython-twisted

NoteIftheseconddeviceisaRaspberryPioralaptopthatrunsLinux,Mac,orWindowsoperatingsystems,theTwistedframeworkneedstobeinstalledontheseconddeviceaswell.

Engagethrusters1. Let’sperformaquickreviewofwhatwewillbuildinthisproject:

Let’sconsidertwodevicesthatcanbeconnectedtoanetwork.OneofthedevicesisaRaspberryPiwhiletheotherdevicecouldeitherbeanArduinooraRaspberryPi.Wewillreviewthecoderequiredtobuildthistoolforbothcases.Thesedeviceshavetobeinstalledattwoextremecornersinsideahouse.Thiscanbedifferentfloorsofthehouseorthefarthestcornersofthehouse.AbuzzerandabuttonwillbeconnectedtoaRaspberryPi.Thebuzzerwouldgooffevery60minutesononeofthedevices.Someonehastowalkuptothedeviceandturnoffthebuzzerbypressingabutton.

Thisenablesapersontogetsomephysicalactivitybywalkingbackandforthbetweenthetwodevices(assumingtheRaspberryPidevicesareinstalledfarawayfromthepersonintheinterestofgainingsomephysicalactivity).

NoteThisexampleisjustamotivationaltoolandacasualreminderfortheconcernedpersontoremainphysicallyactive.

2. ThebuzzerandtheswitchareconnectedtotheRaspberryPiasshowninthefollowingdiagram:

AbuttonandbuzzerschematiccreatedusingFritzing

TheprecedingbreadboardrepresentationshowsanAdafruitPiCobblermountedonabreadboard.RefertoProject4,ChristmasLightSequencer,forapictorialrepresentationofhowthePiCobblerneedstobeconnectedtotheRaspberryPi.

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()

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.

Objectivecomplete–minidebriefingWediscussedatoolthatcanannoyapersontoremainphysicallyactive.

Settingupane-mailfeedparsertorefillaprescriptionaswellasremindtheuseraboutanupcomingdoctor’sappointmentInthistask,wewilldiscusssettingupanLEDtoalertapersonaboutanincominge-mailtorefillaprescriptionorwhenthereisanupcomingdoctor’sappointment.

JustincaseyouskippedthroughProject6,RaspberryPiasaPersonalAssistant,thepython-feedparsertoolandthepython-gdatatoolhavetobeinstalled:

sudoapt-getinstallpython-feedparser

sudoapt-getinstallpython-gdata

NoteThistaskissimilartothee-mailnotifierwesetupinProject5,InternetofThingsExample–AnE-mailAlertWaterFountain.WewilljustdiscussaminormodificationtoblinkanLEDwhenthereisane-mailintheinboxtorefillaprescription.

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.

Objectivecomplete–minidebriefingInthistask,wecompletedthesetupofane-mailnotifiertorefillprescriptionsandareminderforanupcomingdoctor’sappointment.

Asimpletoolthatremindsapersontotakehis/herpillsInthistask,wewillbuildasimpletoolthatremindsapersontotakehis/herpillsontime.Thecircuitryrequiredforthisexampleissimilartotheexamplesdiscussedintheprevioustasks.Wearediscussingthisexamplebecauseitisdifficultforsomeonetodevelopahabitoftakingtheirmedicationontime.Itiscriticalthatpeopleidentifiedwithchronicconditionsdonotmisstheirprescriptionschedule.

PrepareforliftoffWeextensivelydiscussedinterfacingthebuzzertoaRaspberryPiintheprevioustask.It’llbenicetohaveanenclosureforthepillboxreminder.Anexampleofapillreminderisavailablefrominstructablesathttp://www.instructables.com/id/The-Pill-Reminder/.Wewillonlydiscusshowtotriggerthebuzzerataselectedtimeoftheday.

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.

Objectivecomplete–minidebriefingInthistask,wecompletedthepillboxremindersetuptohelpustakeourmedicationontime.

MissionaccomplishedInthisproject,wediscussedseveralexamplesofRaspberryPiactingasapersonalhealthmonitorusingasimpleconcept.Thiscanbeadaptedfordifferentscenariosaccordingtoyourcreativity.

HotshotchallengeHowcanweuseRaspberryPitoenhancethelivesofseniorcitizens?

Chapter11.HomeAutomationusingRaspberryPiInthisproject,wewillreviewsomeautomationexamplesusingRaspberryPi.Theseexamplescanbeconsideredasprojectsthatcanbeexecutedoveraweekend.

MissionbriefingInthisproject,wewilldiscussdifferentoptionsavailableforautomationathomeusingRaspberryPi.Theexamplesuseasimilarconcept(moreorless)andyoucanpickthetasksofyourchoiceandturnyourhomeintoasmarthome.

Whyisitawesome?AquickwebsearchyieldsalotofprojectsrelatedtohomeautomationusingRaspberryPi.Wehavetriedtokeepthisprojectuniquebyensuringthatitissimpleenoughtobeexecutedoveraweekend(thoughsomeexamplesmightappearrepetitiveifyouhavebeenreadingthroughtheprojectsintheircorrectorder),whileincorporatingfeedbackfromprojectsavailableallovertheWeb.

YourobjectivesWewilldiscussthefollowingexamplesinthisproject:

AsimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheeveningAcustomarywebserverexampleTurningonalawnsprinkleronlywhenthereisanorainforecast!

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.

AsimpleexamplethatcontrolslimitedindoorandoutdoorlightingintheeveningLet’sconsiderascenariowhereapersonlivesinaneighborhoodthatisnotsowelllit.Inwinter,thetemperaturesareusuallyextremeincitiessuchasChicagoandthesunusuallysetsaround5p.m.Thepoorlylitneighborhoodalongwiththecoldweathermakesitdifficultforapersontoentertheirhome.

Wewillbuildasimplesolutionthatturnsonalight(thatcanbeeitheranoutdoororindoorhallwaylight)thatspeedsuptheprocessofenteringabuilding.

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

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)

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)

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.

AcustomarywebserverexampleAnyhomeautomationprojectusingRaspberryPiyieldsalotofexamplesthatinvolvesbuildingawebserverthatcontrolsapplianceswithinalocalnetworkthattakescareofsecuringtheplaceusingelectromechanicallocks.WewillbuildasimplewebserverthatcanbeusedtoturnoffanLEDfromawebpage.ThisconceptcanbeexpandedtocontrolmultipleappliancesandreadsensordatafromtheGPIOinterfaceofRaspberryPi.

NoteThistaskismeantforabsolutebeginnerswhoarenotfamiliarwithPythonwebframeworktools.WearediscussingthisexampleconsideringsomereadersmightjumprighttoProject11,HomeAutomationUsingRaspberryPi.

PrepareforliftoffWewillbebuildingawebserverusingaFlaskframework(http://flask.pocoo.org/).TheFlaskframeworkcanbeinstalledasfollows:

sudoapt-getinstallpython-pip

sudopipinstallFlask

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.

Objectivecomplete–minidebriefingUsingthesimpleconceptexplainedearlier,itispossibletocontrolanyappliance(byinterfacingsomecontroldevicesuchasthepowerswitchtailtoRaspberryPi’sGPIOpins).Itisalsopossibletoreadsensorstatesaswellastrackanyspecialinformation.Forexample,itispossibletotrackthestatusofapackagethatisexpectedtobedelivered.USPSprovidesstatusofshipmentsthatcanbedisplayedonthewebpage(formoreinformationonAPIs,checkouthttps://www.usps.com/business/web-tools-apis/welcome.htm).

Inalltheseexamples,wereviewedcontrolappliancesusingRaspberryPiwithinalocalnetwork.Inthelatertaskofthisproject,wewillreviewcontrollingthedevicefromanywhereovertheInternet.

Turningonalawnsprinkleronlywhenthereisnorainforecast!ThisexamplewasinspiredbyacommentonanarticlerelatedtoHomeAutomationusingRaspberryPi.Thecommentermentioned:

TheonlyhomeautomationthatI’minterestedin(andstillhaven’tseen)issomethingthat’llturnoffmylawnsprinklersifit’srainedacertainamountintheprecedingdaysorifit’srainingonthedaythatthesprinklersareprogrammedtogoon.

Wedecidedtowhipupaquickexamplethatwouldturnonthesprinklerwhenitisnotgoingtorainonaparticularday.

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.

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.

Objectivecomplete–minidebriefingIfitisnotpossibletointerfacethesolenoidvalvedirectlytoRaspberryPi,asthesolenoidvalvecanonlybeinterfacedtoanArduinoandcontrolledusingthepython-twistedframework.

InstatessuchasCaliforniawheretherearesometimesseveredroughts,itiscommonpracticetosavewaterfromdrainpipesusingbarrels.Thepywapimodulecanbeusedtoreplacethebarrelsifthereisanupcomingrainforecast.

GainingremoteaccesstoyourRaspberryPitocontrolappliancesItispossibletoremotelylogintoRaspberryPiusingSSH(SecureShell).AnorganizationcalledWeaved(http://www.weaved.com/)providesthecapabilitiestologin.

Thetutorialavailablefromhttps://www.juicypi.io/access-your-raspberry-pi-anywhere-in-the-world-using-weaved/providesdetailedinstructionstoinstalltherequisitetools.

ThisenablesyoutocontrolthedevicesinterfacedtoRaspberryPi.

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.

MissionaccomplishedInthisproject,welookedintodifferentsolutionsthatcanbeimplementedusingRaspberryPioveraweekend.Wereviewedsomebasicexamplesthatcanbepossiblytweakedtoturnahomeintoasmartone.

Chapter12.UsingaRaspberryPiforScienceandEducationInthisproject,wewillreviewsomeexamplesofhowtheRaspberryPicanbeusedtoeducateourselves.WewillreviewexamplesofhowtousetheRaspberryPiforself-improvementoreducatingchildreninthefieldofscience.

MissionbriefingInthisproject,wewillreviewsomeexamplestodemonstratehowtheRaspberryPicanbeusedtoeducateourselvesforself-improvementordemonstrateasimplephysicsexperiment.

Whyisitawesome?ThePi,asyouhaveseeninthelastfewprojects,offersyouimmensefunctionality,andwasbasicallydesignedtoencouragelearningcomputerscienceatanaffordablecost.Aswehaveseen,thepossibilitiesofbuildinggadgetsusingtheRaspberryPiareendless,makingthisanawesomesegueintoself-improvementandscience.

YourHotshotobjectivesInthisproject,wewilldiscussthefollowingexamples:

ImprovingyourvocabularyusingtheRaspberryPiRaspberryPiandKhanAcademyBuildingasciencefairexhibitusingtheRaspberryPi

ImprovingyourvocabularyusingtheRaspberryPiAsanexampleofself-improvementusingtheRaspberryPi,wewillimplementanexamplethatretrievesthewordofthedayusingtheWordnikAPI(https://www.wordnik.com/).

PrepareforliftoffWeneedtoinstalltheWordnikPythonclient(distributedundertheApacheLicense)availableasaPythonpackage:

sudopipinstallwordnik

ThenextstepistoobtainanAPIkeytomakeuseoftheAPI.ThiscanbeobtainedbyregisteringforanaccountwithWordnikandrequestinganAPIkey(http://developer.wordnik.com/).

Oncetheinstallationiscomplete,itistimetoreviewtheexample.

NoteTheWordnikAPIismerelybeingdemonstratedasanexample.RefertotheAPItermsofagreementtodeterminehowtheAPIcanbeusedinacommercialapplication.

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.

Objectivecomplete–minidebriefingInthistask,wereviewedanexampleofhowtouseyourRaspberryPiforself-improvement;similarly,thereareAPIsfromothersourcesthatprovideaquoteoftheday,jokeoftheday,andsoon.

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:

KhanAcademyexercisesonalocalserver

SomeideastoconsiderWeusethiswebservertosolvepuzzlesusingtheRaspberryPi.Itcanbeusefultosharpenyourmentalacuitywhilekillingtime.

BuildingasciencefairexhibitusingtheRaspberryPiInthistask,wewillbuildasimplephysicsexperimentcontrolledbytheRaspberryPi.Thiscanbeusedtoexplainhowthingssuchasasolarpanel,windmill,andsoonwork.Inthisexample,wewillbuildawindmillexperimentthatcanpossiblybeusedasademonstrativeexhibitatasciencefair.

PrepareforliftoffWeneedawindmillgeneratorkitfromahobbystore(forexample,http://amzn.com/B0016PBH9Q).ThekitneedstobeputtogetherleavingtheleadsoftheDCmotorexposed.

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:

Awindmillgeneratorkit

Objectivecomplete–minidebriefingYourRaspberryPicanalsobeusedtobuildsomethingthatteststheskillsofpeopleatasciencefairortoprovideentertainment(raffledraw,puzzle,andsoon).

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/.

HotshotchallengeIsitpossibletobuildareceptionistrobotliketheoneshownatthefollowinglinkusingtheRaspberryPi?Refertohttp://roboceptionist.org/project.htmformoreinformation.

Chapter13.TipsandTricksInthisproject,wewilldiscusstipsandtrickstoovercomeanyproblemsonemightencounterwithRaspberryPi.Wealsoprovideprojectideas,generalinformation,andadissectionoftheRaspberryPiitself.

MissionbriefingInthisbook,wediscusseddifferentprojects,spanningdifferentdifficultylevels.Beforewrappingupthisbook,wewouldliketoshareourexperienceaboutthechallengesweencounteredandsharesometipsandresourcestoovercomesituationsthatyoumightencounterandpossiblesolutionsforthem.Wewillalsodiscusspossibleprojectideasthatyoucantrytoimplementoveraweekend.Wewillgointoeachaspectbriefly.

Whyisitawesome?Thisprojectsharestipsandtricks,providesprojectideas,anddiscussessolutionstoproblemsgenerallyencounteredinDIYprojects.

YourobjectivesInthisproject,wewilldiscussthefollowing:

SettingupRaspberryPiasadevelopmentplatformProjectideasthatcanbeimplementedoveraweekendRemotelyloggingintoRaspberryPifromanywhereontheInternetProblemsthatmightbeencounteredwhileusingRaspberryPiCooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatformUsefulresourcesforRaspberryPi

MissionchecklistHaveyourcuriosity,attentionandpassionattheready.

SettingupRaspberryPiasadevelopmentplatformRaspberryPiiscurrentlythemostbasic,idealhardwareenvironmenttogetstartedwithlearningtocodeinaparticularlanguageoradvancedsystemsdevelopment.

#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.

TransferringfilesusingWinSCP

Oncethefilesaretransferred,wecanmakeuseofPuTTYforremotelogintoRaspberryPi.Asshowninthefollowingfigure,wecanconnecttotheRaspberryPiusingtheIPaddressofRaspberryPiandloginusingthecredentialsprovidedearlier.

ConnectingtoRaspberryPiusingPuTTY

#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/).

#3AdafruitOccidentalisAdafruitIndustriesreleasedaversionofRaspbian,Occidentalisthatenabledeasierhardwaredevelopmentasitfeatureddriversforallstandardcommunicationprotocols.AdafruitIndustriesalsoreleasedaweb-baseddevelopmenttoolthatcomeswithseveralPythonexamples.

#4JavaDevelopmentusingtheRaspberryPiOraclehasreleasedatutorialsetthatteachesJavadevelopmentusingRaspberryPi.ThisincludestutorialsoninterfacepressuresensorsandwritingJavacodetoreadbarometricpressuredatafromthesensorviatheI2Cinterface.

#5TheThingboxprojectTheThingBoxProject(http://thethingbox.io/)isatoolthatallowsyoutoenableprojectsthatarerelatedtotheInternetofThingsonRaspberryPi.ItisasetoftoolsthatallowsyoutointerfacesensorsandappliancestotheInternet,availableasanOSimagethatcanbeflashedontoanSDcardandrunonRaspberryPi.OneofthetoolsavailablewiththeThingBoxProjectisNode-RED(http://nodered.org).TheNode-REDtool(showninfollowingscreenshot),infact,isagraphicalinterfacetoolthateliminatestheneedforyoutoprogramtocontrolthedevicesconnectedtoyourPi.Asthenamesuggests,anyapplicationisbuiltusingnodesandthecontrolflowisshownbyconnectedwires.

AHelloworldprojectusingNode-RED

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.

ProblemsthatmightbeencounteredwhileusingRaspberryPiThefollowingaresomeproblemsweencounteredwhileweworkedonRaspberryPi.

SDcardcorruptionWeencounteredSDcardcorruptionswhileworkingwithRaspberryPi.Insomecases,wehadtodiscardtheSDcardbutinothercases,wewereabletorecovertheSDcardusingAdvancedPartitionScannerWizardandre-imagetheSDcard.

Sometimesthefailureoccursbecausethereisapowerfailurewhilethecardisstillbeingwrittento.Suchfailuresareunavoidableoverthelifeofyourprojects.HereareafewwaystoavoidSDcardcorruption:

PowerdownyourPiproperlyafteruseChargeyourbatterypacksandmakesurePihasaconstantpowersupplyatalltimes

BesuretobuygoodqualitySDcardsandaswitheverythingelsedigital,havebackups.

PowerissuesWeencounteredissuesrelatedtothepowerdrawofRaspberryPi.Wehadlittlesuccesswiththingssuchasabatterypack(wewereabletogetitworkingusinga2700mAhbatterypack).Asyoumaybeaware,RaspberryPineedsa1A,5VUSBpowersupply.

DevicespoweredbyUSBSomedevicessuchasawebcamcannotbeconnecteddirectlytotheRaspberryPiandaUSBhubmaybenecessarytoconnectsuchdevices.

Cooladd-onhardwaresourcesdevelopedfortheRaspberryPiplatformThereareseveralproductsandadd-onhardwaredevelopedspecificallyforRaspberryPi.MostofthemaredesignedspecificallyforRaspberryPi.SomeofthemareavailablethroughDIYproductsellerssuchasSparkfunandAdafruitIndustries.MostproductsaredevelopedthroughcrowdfundingsitessuchasKickstarterandIndiegogo.Wemadeourbestefforttointroduceanewpieceofhardwareineachproject.Asimplewebsearchshouldpopupanewproductforaspecificapplication.

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).

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.

UsefulresourcesfortheRaspberryPiInthissection,wewilldiscussusefulresourcesthatareavailableforRaspberryPi.Whilethisbookcancovereveryaspectoftheprojectsdevelopedinthisbook,wewilldefinitelyrunintotrouble.Let’slookatsomeusercommunitiesthatcantrytoaddressourproblem.

RaspberryPiFoundation’sforums:TheRaspberryPiFoundation(http://www.raspberrypi.org/forums/)hasmaintainedaforumsinceitsinception.Thisforumprovidesanswerstoavastspectrumofquestionsthatyoumayhave.ItalsooffersanopportunitytodirectlyinteractwiththecreatorsofRaspberryPi.

RaspberryPiStackExchange:Atthetimeofwritingthisbook,theRaspberryPiStackExchange(http://raspberrypi.stackexchange.com/)wasinthepublicbetatestingmode.Ifthissitepassesthebetatestingphase,itshouldalsocontainapoolofusefulresources.

Element14’sRaspberryPicommunity:TheElement14website(http://www.element14.com/community/community/raspberry-pi)hostsaseriesofblogpostsfromRaspberryPiuserswhohavebuiltanecosystemofgadgetssurroundingRaspberryPi.ThecommunitywebpagehostscontestsregularlyinordertoexhibitthetalentofRaspberryPienthusiastsandDIYhobbyists.Thecommunitywebpagealsohasauserforumtoexchangeinformation,askquestionsrelatedtoorderstatus,andsoon.

MissionaccomplishedInthisproject,wediscussedcertainprojectideas,tips,andtricksandproblemsyoumightencounterwhileworkingonaprojectusingRaspberryPi.Theauthorssincerelyhopethatyouhaveenjoyedthisbook.

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

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

B8BitCircusMusic

URL/AddingsoundstothegameBarScrollexample/PrepareforliftoffBCMGPIOmode

URL/Engagethrustersbirdfeeder

settingup,withmotionsensor/Prepareforliftoff,Engagethrusters,Objectivecomplete–minidebriefingrequisites/Prepareforliftoff

BlinkM/IntroductiontothePiCrust–aprototypingplatformfortheRaspberryPiabout/TestanddebuggingexamplesusingtheWebIDEURL,fordatasheet/Engagethrusters

BonjourPrintServicesdriversURL/SetupofaremoteloginintotheRaspberryPi

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)

switches,settingupwithcardboardbox/Setupoftheswitchesusingacardboardbox

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

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

FFlaskframework

installing/InstallationoftheFlaskframework,Engagethrusters,Prepareforliftoff,EngagethrustersURL/Prepareforliftoff

FlaskframeworkexampleURL/Engagethrusters

FreeSoundsURL/Addingsoundstothegame

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

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

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

JJavadevelopment

RaspberryPiused/#4JavaDevelopmentusingtheRaspberryPi

Kkeyalertsystem

sensors,settingup/Settingupsensorsforthekeyalertsystem,Engagethrusters,Objectivecomplete–minidebriefing

KhanAcademyURL/RaspberryPiandKhanAcademy

KhanAcademyexampleabout/RaspberryPiandKhanAcademy

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

MMachineVision-basedlinefollowingrobot/Machine-vision-basedlinefollowingrobotMake*itBasicRoboticsStarterKit

URL/Missionchecklistmarqueecontrol,ConnectFourgame

implementing/Marqueedesignandcontrol(optional),Prepareforliftoffmenuclass

URL/Addingamenuforthegamemotordrivercircuit

testing/Testingthemotordrivercircuit,Prepareforliftoff,Engagethrustersmultipleappliances

connecting,toRaspberryPi/ConnectingmultipleappliancestotheRaspberryPi

NNOAA

URL/EngagethrustersNode-REDtool

URL/#5TheThingboxproject

OOccidentalis

about/Missionbriefingfeatures/Whyisitawesome?objectives/YourHotshotobjectivesinstalling/Installation,features,andusageoftheOccidentalisoperatingsystemfromAdafruit

Occidentalisdistrorequisites/Missionchecklist

OpenCVURL/MissionchecklistURL,forinstallationonRaspberryPi/MissionchecklistURL,forinstallationonLinux/Missionchecklist

OpenCVDishDetectorprojectURL/Settinguptheassemblyforthedishmonitor

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

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

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

Qquick2wirepythonAPI/InstallingGPIOlibraries

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

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

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

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

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

UUI,ConnectFourgame

about/GettingstartedwiththeConnectFourgame(UIandsoundeffects),Prepareforliftoffmenu,adding/Addingamenuforthegamesounds,adding/Addingsoundstothegame

USBBatterypackURL/Prepareforliftoff

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