tentacle.netprophet/raspberrypi/Raspberry...Table of Contents Raspberry Pi Mechatronics Projects...

of 606 /606

Embed Size (px)

Transcript of tentacle.netprophet/raspberrypi/Raspberry...Table of Contents Raspberry Pi Mechatronics Projects...

  • 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

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

    http://mechatronicscraze.wordpress.com/

  • 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.Getintouchwithusatformoredetails.

    Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

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

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

    http://www.PacktPub.comhttp://www.PacktPub.commailto:[email protected]://www.PacktPub.comhttps://www2.packtpub.com/books/subscription/packtlib

  • Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

  • FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

    http://www.PacktPub.com

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

    http://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,andmentionthebooktitleviathesubjectofyourmessage.

    Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.

    mailto:[email protected]://www.packtpub.com/authors

  • CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

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

    http://www.packtpub.comhttp://www.packtpub.com/support

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

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

    http://www.packtpub.com/submit-erratahttp://www.packtpub.com/support

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

    Pleasecontactusatwithalinktothesuspectedpiratedmaterial.

    Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.

    mailto:[email protected]

  • QuestionsYoucancontactusatifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.

    mailto:[email protected]

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

    http://www.raspberrypi.org/

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

    http://elinux.org/RPi_Hub

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

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

    RaspbianwheezyontheRaspberryPiFoundation’swebsite

    FlashingimageontotheSDcardWewilldiscussflashingtheSDcardwiththeRaspbianimageonbothWindowsandLinuxmachines.

    Windows

    Extractthefilestoalocationofyourchoice.TheWin32DiskImagertoolisrequiredtopreparetheSDcardwiththeRaspbianimage.

    TipAstandardRaspbianimageisabout1.8GBbig.ItisstronglyrecommendedthatyouuseanSDcardthatisatleastof4GBbig.

    http://www.raspberrypi.org/downloads/

  • 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/sdbFlashtheSDcard

    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-

    http://quick2wire.com/articles/how-to-add-quick2wire-as-a-raspbian-software-source/

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

    Inthecommandline,therepositoryisaddedbyusingthenanotexteditor:

    sudonano/etc/apt/sources.list

    Thefollowinglinesneedtobeaddedtothefile:

    #Quick2WireSoftwaredebhttp://dist.quick2wire.com/raspbianwheezymaindeb-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]@quick2wire.com.gpg.key

    3. Thecacheisupdatedandthelatestsoftwarepackagescanbedownloadedasfollows:

    sudoapt-getupdatesudoapt-getupgrade

    4. Thequick2wiretoolisinstalledasfollows:

    sudoapt-getinstallquick2wire-gpio-adminsudoapt-getinstallquick2wire-python3-api

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

  • GPIOprogrammingusingPythonInthissection,wewillensurethatthelibraryiscorrectlyinstalledandaddtheusertothegroup.ThiswillenabletheusertousetheGPIOpinswithouthavingrootprivileges.ThiswillbefollowedbythesectionongettingstartedwithGPIOcontrolprogramminginPython.

  • EngagethrustersInordertogetstartedwithprogrammingintheRaspberryPi,wewilllaunchPythonIDLE3fromthedesktop.

    LaunchingIDLE3fromthedesktop

    1. Now,wehavetogetstartedwithprogrammingtheLEDblinkingexampleinIDLE3.2. ThisLEDblinkingsamplecodeisasfollows:

    fromtimeimportsleepfromquick2wire.gpioimportpins,Out

    withpins.pin(7,direction=Out)asout_pin:whileTrue:out_pin.value=1sleep(1)out_pin.value=0sleep(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=1sleep(1)LED_output=0sleep(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.GPIOasGPIOfromtimeimportsleep

    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

    https://pypi.python.org/pypi/RPi.GPIO

  • 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

    http://picru.st

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

    https://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-3

  • 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

    https://www.adafruit.com/product/914https://www.adafruit.com/product/879https://www.sparkfun.com/products/8579

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

    https://learn.sparkfun.com/tutorials/pulse-width-modulationhttps://learn.sparkfun.com/tutorials/i2c

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

    https://github.com/adafruit/Adafruit-Pi-Finder/releases/latest

  • Engagethrusters1. YoucanfinddetailedinstructionsoninstallingtheOccidentalistoolat

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

    cannotincludethemheresincechangesweremadetoOccidentalisinstallationprocessafterwefinishedwritingthisbook.

    https://github.com/adafruit/Adafruit-Pi-Finder

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

    http://www.advanced-ip-scanner.com/http://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:[email protected]'spassword:raspberry

    Alternatively,wecanalsologinusingtheIPaddressoftheRaspberryPiinsteadofthelocalname,raspberrypi.local.

  • Objectivecomplete–minidebriefingIftheusernameandpasswordareenteredcorrectly,weshouldbeabletoremotelylogintotheRaspberryPitoinstallthewebserver.

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

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

    http://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

    https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code

  • 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.hourminute=now.minutesecond=now.second

    Sincethe7-segmentLEDbackpackconsistsoffourdigits,wewritethecurrenttimeateachpositionasfollowsalongwithacolon:

    #Sethourssegment.writeDigit(0,int(hour/10))#Tenssegment.writeDigit(1,hour%10)#Ones#Setminutessegment.writeDigit(3,int(minute/10))#Tenssegment.writeDigit(4,minute%10)#Ones

  • #Togglecolonsegment.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',,0,0.Let’sdiscusshowtoexecutethisusingaPythonscriptontheRaspberryPiinterfacedwiththeBlinkMLED.ThePythonscriptofthisexampleiscalledPlay_blinkm.py:

    http://thingm.com/fileadmin/thingm/downloads/BlinkM_datasheet.pdf

  • ThePlay_blinkm.pyfilecanbeexecutedbycreatinganewfileintherepositorythatwascreatedwhenyousignedupforaBitbucketaccount.Whenthefileissaved,thechangesaresavedtoyourBitbucketaccount.Thecodeforthisisgivenasfollows:

    #!/usr/bin/python#python-smbusimportsmbus#createi2cobjectbus=smbus.SMBus(1)#refertodatasheetforscriptsequence#Playscriptbywriting0x70orponthebusbus.write_byte(0x09,0x70)#playscriptno:6bus.write_byte(0x09,0x06)#playthescriptinfinitelybus.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',,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.

    http://www.arduino.cc

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

    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.

    http://wyolum.com/projects/alamode/alamode-getting-started/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.

    http://wyolum.com/projects/alamode/http://www.adafruit.com/product/858http://www.adafruit.com/products/1004http://www.adafruit.com/product/879http://www.adafruit.com/product/871https://www.sparkfun.com/products/8579

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

    http://www.adafruit.com/product/858

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

    //Step1digitalWrite(motorPin4,HIGH);digitalWrite(motorPin3,LOW);digitalWrite(motorPin2,LOW);digitalWrite(motorPin1,LOW);delay(motorSpeed);//Step2digitalWrite(motorPin4,HIGH);digitalWrite(motorPin3,HIGH);digitalWrite(motorPin2,LOW);digitalWrite(motorPin1,LOW);delay(motorSpeed);//Step3digitalWrite(motorPin4,LOW);digitalWrite(motorPin3,HIGH);digitalWrite(motorPin2,LOW);digitalWrite(motorPin1,LOW);delay(motorSpeed);//Step4digitalWrite(motorPin4,LOW);digitalWrite(motorPin3,HIGH);digitalWrite(motorPin2,HIGH);digitalWrite(motorPin1,LOW);delay(motorSpeed);//Step5digitalWrite(motorPin4,LOW);digitalWrite(motorPin3,LOW);digitalWrite(motorPin2,HIGH);digitalWrite(motorPin1,LOW);delay(motorSpeed);//Step6digitalWrite(motorPin4,LOW);digitalWrite(motorPin3,LOW);digitalWrite(motorPin2,HIGH);digitalWrite(motorPin1,HIGH);delay(motorSpeed);//Step7digitalWrite(motorPin4,LOW);digitalWrite(motorPin3,LOW);digitalWrite(motorPin2,LOW);

    http://forum.arduino.cc/index.php?topic=85335.0

  • digitalWrite(motorPin1,HIGH);delay(motorSpeed);//Step8digitalWrite(motorPin4,HIGH);digitalWrite(motorPin3,LOW);digitalWrite(motorPin2,LOW);digitalWrite(motorPin1,HIGH);delay(motorSpeed);}

    5. Let’sdiscussthefirststepinthesteppermotorenergizationsequence:

    //Step1digitalWrite(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

    https://coefs.uncc.edu/dlsharer/files/2012/04/F5.pdf

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

    http://www.societyofrobots.com/member_tutorials/node/314

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

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

    NoteItispossibletoproduceasecondarycolorusingtheRGBcombinations.ThiscanbeachievedbyturningontheRGBsegmentsatthesametimeandvaryingthebrightnessoftheprimarycolors.TherearevastresourcesavailableforsuchtipsandtricksontheInternetandanexplanationofthisisbeyondthescopeofthisbook.

    http://www.adafruit.com/products/1004

  • PrepareforliftoffTheAdafruitlearningwebsiteprovidesexamplesforcontrollingtheRGBLEDusingapulsewidthmodulationtechnique.TheschematicfortheAnalogRGBstripisshowninthefollowingdiagram:

    RGBLEDstripschematic(borrowedfromAdafruit)

    SincetheRGBstriprequires12V,wemustuseatransistorswitchingcircuittocontroltheLEDs.ThetransistorswitchingcircuitforcontrollingtheRed,Green,andBluechannelsoftheLEDstripisshowninthefollowingdiagram:

    TheArduinoRGBswitchingcircuit

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

  • Engagethrusters1. AdafruithasprovidedanexampleforadjustingthebrightnessoftheLEDsand

    producingdifferentcolorsfromthecombinationofprimarycolors.Let’sconsiderthefollowingpieceofcode:

    //fadefrombluetovioletfor(r=0;r<256;r++){analogWrite(REDPIN,r);delay(FADESPEED);}//fadefromviolettoredfor(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.