programming arduino getting started with sketches...

177

Upload: trancong

Post on 31-Aug-2018

292 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 2: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 3: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ProgrammingArduino™

GettingStartedwithSketchesSimonMonk

Page 4: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Copyright © 2012 by The McGraw-Hill Companies. All rights reserved. Except aspermittedundertheUnitedStatesCopyrightActof1976,nopartofthispublicationmaybe reproduced or distributed in any form or by any means, or stored in a database orretrievalsystem,withoutthepriorwrittenpermissionofthepublisher.

ISBN:978-0-07-178423-8

MHID:0-07-178423-3

ThematerialinthiseBookalsoappearsintheprintversionofthistitle:ISBN:978-0-07-178422-1,MHID:0-07-178422-5.

All trademarks are trademarks of their respective owners. Rather than put a trademarksymbol after every occurrence of a trademarked name, we use names in an editorialfashiononly,andtothebenefitofthetrademarkowner,withnointentionofinfringementof the trademark.Where such designations appear in this book, they have been printedwithinitialcaps.

McGraw-HilleBooksareavailableatspecialquantitydiscounts touseaspremiumsandsales promotions, or for use in corporate training programs.To contact a [email protected].

All trademarks or copyrights mentioned herein are the possession of their respec-tiveownersandMcGraw-Hillmakesnoclaimofownershipby thementionofproducts thatcontainthesemarks.

“Arduino”isatrademarkoftheArduinoteam.

Information has been obtained by McGraw-Hill from sources believed to be reliable.However, because of the possibility of human or mechanical error by our sources,McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, orcompletenessofanyinformationandisnotresponsibleforanyerrorsoromissionsortheresultsobtainedfromtheuseofsuchinformation.

TERMSOFUSE

ThisisacopyrightedworkandTheMcGraw-HillCompanies,Inc.(“McGraw-Hill”)andits licensors reserve all rights in and to thework. Use of this work is subject to theseterms. Except as permitted under theCopyrightAct of 1976 and the right to store andretrieve one copy of the work, youmay not decompile, disassemble, reverse engineer,reproduce,modify,createderivativeworksbasedupon, transmit,distribute,disseminate,sell,publishorsublicensetheworkoranypartofitwithoutMcGraw-Hill’spriorconsent.Youmayusetheworkforyourownnoncommercialandpersonaluse;anyotheruseofthework is strictly prohibited.Your right to use theworkmaybe terminated if you fail tocomplywiththeseterms.

THEWORKISPROVIDED“ASIS.”McGRAW-HILLANDITSLICENSORSMAKENOGUARANTEESORWARRANTIESASTOTHEACCURACY,ADEQUACYORCOMPLETENESSOFORRESULTSTOBEOBTAINEDFROMUSINGTHEWORK,INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THEWORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY

Page 5: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TOIMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR APARTICULAR PURPOSE.McGraw-Hill and its licensors do not warrant or guaranteethatthefunctionscontainedintheworkwillmeetyourrequirementsorthatitsoperationwillbeuninterruptedorerrorfree.NeitherMcGraw-Hillnoritslicensorsshallbeliabletoyouoranyoneelseforanyinaccuracy,errororomission,regardlessofcause,intheworkorforanydamagesresultingtherefrom.McGraw-Hillhasnoresponsibilityforthecontentof any information accessed through thework.Under no circumstances shallMcGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive,consequentialorsimilardamagesthatresultfromtheuseoforinabilitytousethework,evenifanyofthemhasbeenadvisedofthepossibilityofsuchdamages.Thislimitationofliabilityshallapplytoanyclaimorcausewhatsoeverwhethersuchclaimorcausearisesincontract,tortorotherwise.

Page 6: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Tomyboys,StephenandMatthew,fromaveryproudDad.

Page 7: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

AbouttheAuthorSimonMonkhasabachelor’sdegreeincyberneticsandcomputerscienceandadoctorateinsoftwareengineering.Hehasbeenanactiveelectronicshobbyistsincehisschooldaysand is an occasional author in hobby electronics magazines. He is also author of 30Arduino Projects for the Evil Genius and 15 Dangerously Mad Projects for the EvilGenius.

Page 8: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 9: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

CONTENTSAcknowledgments

Introduction

1ThisIsArduino

Microcontrollers

DevelopmentBoards

ATourofanArduinoBoard

PowerSupply

PowerConnections

AnalogInputs

DigitalConnections

Microcontroller

OtherComponents

TheOriginsofArduino

TheArduinoFamily

Uno,Duemilanove,andDiecimila

Mega

Nano

Bluetooth

Lilypad

Other“Official”Boards

ArduinoClonesandVariants

Conclusion

2GettingStarted

PoweringUp

InstallingtheSoftware

UploadingYourFirstSketch

TheArduinoApplication

Conclusion

3CLanguageBasics

Page 10: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Programming

WhatIsaProgrammingLanguage?

Blink—Again!

Variables

ExperimentsinC

NumericVariablesandArithmetic

Commands

if

for

while

The#defineDirective

Conclusion

4Functions

WhatIsaFunction?

Parameters

Global,Local,andStaticVariables

ReturnValues

OtherVariableTypes

floats

boolean

OtherDataTypes

CodingStyle

Indentation

OpeningBraces

Whitespace

Comments

Conclusion

5ArraysandStrings

Arrays

MorseCodeSOSUsingArrays

StringArrays

StringLiterals

Page 11: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

StringVariables

AMorseCodeTranslator

Data

GlobalsandSetup

Theloopfunction

TheflashSequenceFunction

TheflashDotOrDashFunction

PuttingItAllTogether

Conclusion

6InputandOutput

DigitalOutputs

DigitalInputs

Pull-upResistors

InternalPull-upResistors

Debouncing

AnalogOutputs

AnalogInput

Conclusion

7TheStandardArduinoLibrary

RandomNumbers

MathFunctions

BitManipulation

AdvancedI/O

GeneratingTones

FeedingShiftRegisters

Interrupts

Conclusion

8DataStorage

Constants

ThePROGMEMDirective

EEPROM

StoringanintinEEPROM

Page 12: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

StoringafloatinEEPROM(Unions)

StoringaStringinEEPROM

ClearingtheContentsofEEPROM

Compression

RangeCompression

Conclusion

9LCDDisplays

AUSBMessageBoard

UsingtheDisplay

OtherLCDLibraryFunctions

Conclusion

10ArduinoEthernetProgramming

EthernetShields

CommunicatingwithWebServers

HTTP

HTML

ArduinoasaWebServer

SettingArduinoPinsovertheNetwork

Conclusion

11C++andLibraries

ObjectOrientation

ClassesandMethods

Built-inLibraryExample

WritingLibraries

TheHeaderFile

TheImplementationFile

CompletingYourLibrary

Conclusion

Index

Page 13: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 14: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ACKNOWLEDGMENTSIthankLindaforgivingmethetime,space,andsupporttowritethisbookandforputtingupwiththevariousmessesmyprojectscreatearoundthehouse.

IalsothankStephenandMatthewMonkfortakinganinterestinwhattheirDadisupto

andtheirgeneralassistancewithprojectwork.

Finally,IwouldliketothankRogerStewart,SapnaRastogi,andeveryoneinvolvedintheproductionofthisbook.It’sapleasuretoworkwithsuchagreatteam.

Page 15: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 16: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

INTRODUCTIONArduino interface boards provide a low-cost, easy-to-use technology to createmicrocontroller-basedprojects.Withalittleelectronics,youcanmakeyourArduinodoallsortsof things, fromcontrolling lights inanart installation tomanaging thepoweronasolarenergysystem.

There are many project-based books that show you how to connect things to yourArduino,including30ArduinoProjectsfortheEvilGeniusbythisauthor.However,thefocusofthisbookisonprogrammingtheArduino.

ThisbookwillexplainhowtomakeprogrammingtheArduinosimpleandenjoyable,avoidingthedifficultiesofuncooperativecodethatsooftenafflictaproject.Youwillbetaken through the process of programming the Arduino step by step, starting with thebasicsoftheCprogramminglanguagethatArduinosuse.

So,WhatIsArduino?

Arduinoisasmallmicrocontrollerboardwithauniversalserialbus(USB)plugtoconnectto your computer and a number of connection sockets that can be wired to externalelectronicssuchasmotors,relays,lightsensors,laserdiodes,loudspeakers,microphones,andmore.Theycaneitherbepowered through theUSBconnection from thecomputer,froma9Vbattery,orfromapowersupply.Theycanbecontrolledfromthecomputerorprogrammedbythecomputerandthendisconnectedandallowedtoworkindependently.

Theboarddesignisopensource.ThismeansthatanyoneisallowedtomakeArduino-compatibleboards.Thiscompetitionhasleadtolowcostsfortheboards.

ThebasicboardsaresupplementedbyaccessoryshieldboardsthatcanbepluggedontopoftheArduinoboard.Inthisbook,wewillusetwoshields—anLCDdisplayshieldandanEthernetshield—thatwillallowustoturnourArduinointoatinywebserver.

ThesoftwareforprogrammingyourArduinoiseasytouseandalsofreelyavailableforWindows,Mac,andLINUXcomputers.

WhatWillINeed?

Thisisabookintendedforbeginners,butitisalsointendedtobeusefultothosewhohaveusedArduinoforawhileandwanttolearnmoreaboutprogrammingtheArduinoorgainabetterunderstandingofthefundamentals.

Youdonotneedtohaveanyprogrammingexperienceoratechnicalbackground,andthe book’s exercises do not require any soldering. All you need is the desire to makesomething.

Page 17: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Ifyouwanttomakethemostofthebookandtryoutsomeoftheexperiments,thenitisusefultohavethefollowingonhand:

•Afewlengthsofsolidcorewire

•Acheapdigitalmultimeter

BotharereadilyavailableforafewdollarsfromahobbyelectronicsshopsuchasRadioShack.YouwillofcoursealsoneedanArduinoUnoboard.

IfyouwanttogoastepfurtherandexperimentwithEthernetandtheliquidcrystaldisplay(LCD)shield,thenyouwillneedtobuyshieldsthatareavailablefromonlinestores.SeeChapters9and10fordetails.

UsingthisBook

Thisbook isstructured togetyoustarted ina reallysimplewayandgraduallybuildonwhatyouhave learned.Youmay,however, findyourselfskippingorskimmingsomeoftheearlychaptersasyoufindtherightleveltoenterthebook.

Thebookisorganizedintothefollowingchapters:

•Chapter 1: This Is Arduino An introduction to the Arduino hardware, this chapterdescribes what it is capable of, and the various types of, Arduino boards that areavailable.

•Chapter2:GettingStartedHereyouconductyourfirstexperimentswithyourArduinoboard:installingthesoftware,poweringitup,anduploadingyourfirstsketch.

•Chapter3:CLanguageBasicsThischaptercovers thebasicsof theC language; forcomplete programming beginners, the chapters also serves as an introduction toprogrammingingeneral.

• Chapter 4: Functions This chapter explains the key concept of using and writingfunctions in Arduino sketches. These sketches are demonstrated throughout withrunnablecodeexamples.

•Chapter5:ArraysandStringsHereyoulearnhowtomakeandusedatastructuresthatare more advanced than simple integer variables. A Morse code example project isslowlydevelopedtoillustratetheconceptsbeingexplained.

•Chapter6:InputandOutputYoulearnhowtousethedigitalandanaloginputsandoutputsontheArduinoinyourprograms.AmultimeterwillbeusefultoshowyouwhatishappeningontheArduino’sinput/outputconnections.

•Chapter7:TheStandardArduinoLibraryThischapterexplainshowtomakeuseofthestandardArduinofunctionsthatcomeintheArduino’sstandardlibrary.

•Chapter8:DataStorageHereyou learnhow towrite sketches that can savedata inelectrically erasable read-only memory (EEPROM) and make use of the Arduino’sbuilt-inflashmemory.

Page 18: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

•Chapter9:LCDDisplaysInthischapter,youprogramwiththeLCDShieldlibrarytomakeasimpleUSBmessageboardexample.

•Chapter 10:ArduinoEthernet Programming You learn how tomake the ArduinobehavelikeawebserverasyougetalittlebackgroundonHyperTextMarkupLanguage(HTML)andtheHyperTextTransferProtocol(HTTP).

•Chapter11:C++andLibrariesYougobeyondC,lookingataddingobject-orientationandwritingyourownArduinolibraries.

Resources

Thisbookissupportedbyanaccompanyingwebsite:

www.arduinobook.com

Thereyouwillfindallthesourcecodeusedinthisbookaswellasotherresources,suchaserrata.

Page 19: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 20: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

1ThisIsArduino

Arduino is amicrocontroller platform that has captured the imagination of electronicsenthusiasts. Its ease of use and open source nature make it a great choice for anyonewantingtobuildelectronicprojects.

Ultimately, it allowsyou toconnect electronics through itspins so that it cancontrol

things—for instance, turn lights ormotors on and off or sense things such as light andtemperature.ThisiswhyArduinoissometimesgiventhedescriptionphysicalcomputing.BecauseArduinos can be connected to your computer by a universal serial bus (USB)lead,thisalsomeansthatyoucanusetheArduinoasaninterfaceboardtocontrolthosesameelectronicsfromyourcomputer.

ThischapterisanintroductiontotheArduino,includingthehistoryandbackgroundoftheArduino,aswellasanoverviewofthehardware.

Microcontrollers

TheheartofyourArduinoisamicrocontroller.Prettymucheverythingelseontheboardisconcernedwithproviding theboardwithpowerandallowing it tocommunicatewithyourdesktopcomputer.

Amicrocontrollerreallyisalittlecomputeronachip.Ithaseverythingandmorethanthe first home computers had. It has a processor, a kilobyte or two of random accessmemory (RAM) for holding data, a few kilobytes of erasable programmable read-onlymemory(EPROM)orflashmemoryforholdingyourprogramsandithasinputandoutputpins.Theseinput/output(I/O)pinslinkthemicrocontrollertotherestofyourelectronics.

Inputscanreadbothdigital(istheswitchonoroff?)andanalog(whatisthevoltageatapin?).Thisopensup theopportunityofconnectingmanydifferent typesof sensor forlight,temperature,sound,andmore.

Outputscanalsobeanalogordigital.So,youcansetapintobeonoroff(0voltsor5volts)and thiscan turn light-emittingdiodes(LEDs)onandoffdirectly,oryoucanusethe output to control higher power devices such as motors. They can also provide ananalogoutputvoltage.Thatis,youcansettheoutputofapintosomeparticularvoltage,allowingyoutocontrolthespeedofamotororthebrightnessofalight,ratherthansimplyturningitonoroff.

ThemicrocontrolleronanArduinoboard is the28-pinchipfitted intoasocketat thecenteroftheboard.Thissinglechipcontainsthememoryprocessorandalltheelectronicsfor theinput/outputpins.It ismanufacturedbythecompanyAtmel,whichisoneof themajormicrocontrollermanufacturers.Eachofthemicrocontrollermanufacturersactually

Page 21: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

produces dozens of different microcontrollers grouped into different families. Themicrocontrollersarenotallcreatedforthebenefitofelectronicshobbyistslikeus.Wearea small part of this vastmarket. These devices are really intended for embedding intoconsumerproducts,includingcars,washingmachines,DVDplayers,children’stoys,andevenairfresheners.

ThegreatthingabouttheArduinoisthatitreducesthisbewilderingarrayofchoicesbystandardizing on one microcontroller and sticking with it. (Well, as we see later, thisstatementisnotquitetrue,butit’scloseenough.)

Thismeans thatwhen you are embarking on a newproject, you do not first need toweighalltheprosandconsofthevariousflavorsofmicrocontroller.

DevelopmentBoards

Wehaveestablishedthatthemicrocontrollerisreallyjustachip.Achipwillnotjustworkonitsownwithoutsomesupportingelectronicstoprovideitwitharegulatedandaccuratesupply of electricity (microcontrollers are fussy about this) as well as a means ofcommunicatingwiththecomputerthatisgoingtoprogramthemicrocontroller.

This is where development boards come in. An Arduino board is really amicrocontroller development board that happens to be an independent open sourcehardwaredesign.Thismeansthatthedesignfilesfortheprintedcircuitboard(PCB)andtheschematicdiagramsareallpubliclyavailable,andeveryoneisfreetousethedesignstomakeandsellhisorherownArduinoboards.

Allthemicrocontrollermanufacturers—includingAtmel,whichmakestheATmega328microcontroller used in anArduino board—also provide their own development boardsandprogrammingsoftware.Althoughtheyareusuallyfairlyinexpensive,thesetendtobeaimed at professional electronics engineers rather than hobbyists. Thismeans that suchboardsandsoftwarearearguablyhardertouseandrequireagreaterlearninginvestmentbeforeyoucangetanythingusefuloutofthem.

ATourofanArduinoBoard

Figure1-1showsanArduinoboard.Let’stakeaquicktourofthevariouscomponentsontheboard.

Page 22: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure1-1AnArduinoUnoboard

PowerSupply

Referring to Figure 1-1, directly below the USB connector is the 5-volt (5V) voltageregulator. This regulates whatever voltage (between 7V and 12V) is supplied from thepowersocketintoaconstant5V.

The5Vvoltageregulatorchipisactuallyquitebigforasurfacemountcomponent.Thisis so that it can dissipate the heat required to regulate the voltage at a reasonably highcurrent.Thisisusefulwhendrivingexternalelectronics.

PowerConnections

NextletuslookattheconnectorsatthebottomofFigure1-1.Youcanreadtheconnectionnamesnext to the connectors.The first isReset.Thisdoes the same thing as theResetbuttonon theArduino.Rather like rebootingaPC,using theResetconnector resets themicrocontroller so that itbegins itsprogram from the start.To reset themicrocontrollerwiththeResetconnector,youmomentarilysetthispinlow(connectingitto0V).

Therestofthepinsinthissectionjustprovidedifferentvoltages(3.5V,5V,GND,and9V),astheyarelabeled.GND,orground,justmeanszerovolts.Itisthereferencevoltagetowhichallothervoltagesontheboardarerelative.

Page 23: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

AnalogInputs

ThesixpinslabeledasAnalogInA0toA5canbeusedtomeasurethevoltageconnectedtothemsothatthevaluecanbeusedinasketch.Notethattheymeasureavoltageandnotacurrent.Onlyatinycurrentwilleverflowintothemanddowntogroundbecausetheyhaveaverylargeinternalresistance.Thatis,thepinhavingalargeinternalresistanceonlyallowsatinycurrenttoflowintothepin.

Although these inputs are labeled as analog, and are analog inputs by default, theseconnectionscanalsobeusedasdigitalinputsoroutputs.

DigitalConnections

Wenowswitchtothetopconnectorandstartontheright-handsideinFigure1-1.HerewefindpinslabeledDigital0to13.Thesecanbeusedaseitherinputsoroutputs.Whenusedas outputs, they behave rather like the power supply voltages discussed earlier in thissection,exceptthattheseareall5Vandcanbeturnedonorofffromyoursketch.So,ifyouturnthemonfromyoursketchtheywillbeat5V,andifyouturnthemofftheywillbeat 0V. As with the power supply connectors, you must be careful not to exceed theirmaximumcurrentcapabilities.Thefirsttwooftheseconnections(0and1)arealsolabeledRX and TX, for receive and transmit. These connections are reserved for use incommunicationandareindirectlythereceiveandtransmitconnectionsforyourUSBlinktoyourcomputer.

These digital connections can supply 40 mA (milliamps) at 5V. That is more thanenoughtolightastandardLED,butnotenoughtodriveanelectricmotordirectly.

Microcontroller

Continuing our tour of the Arduino board, the microcontroller chip itself is the blackrectangulardevicewith28pins.Thisisfittedintoadualinline(DIL)socketsothatitcanbeeasilyreplaced.The28-pinmicrocontrollerchipusedontheArduinoUnoboardistheATmega328.Figure1-2isablockdiagramshowingthemainfeaturesofthisdevice.

The heart—or, perhaps more appropriately, the brain—of the device is the centralprocessing unit (CPU). It controls everything that goes onwithin the device. It fetchesprogram instructionsstored in the flashmemoryandexecutes them.Thismight involvefetchingdatafromworkingmemory(RAM),changingit,andthenputtingitback.Or,itmaymeanchangingoneofthedigitaloutputsfrom0Vto5V.

TheEEPROMmemoryisalittleliketheflashmemoryinthatitisnonvolatile.Thatis,youcanturnthedeviceoffandonanditwillnothaveforgottenwhatisintheEEPROM.Whereas the flashmemory is intended for storingprogram instructions (fromsketches),theEEPROMisusedtostoredatathatyoudonotwanttoloseintheeventofaresetorthepowerbeingturnedoff.

Page 24: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure1-2ATmega328blockdiagram

OtherComponents

Above the microcontroller is a small, silver, rectangular component. This is a quartzcrystal oscillator. It ticks 16 million times a second, and on each of those ticks, themicrocontroller can perform one operation—addition, subtraction, or anothermathematicaloperation.

To the right of the crystal is theReset switch. Clicking on this switch sends a logicpulse to the Reset pin of the microcontroller, causing the microcontroller to start itsprogramafreshandclearitsmemory.Notethatanyprogramstoredonthedevicewillberetained, because this is kept in non-volatile flash memory—that is, memory thatremembersevenwhenthedeviceisnotpowered.

TotherightoftheResetbuttonistheSerialProgrammingConnector.ItoffersanothermeansofprogrammingtheArduinowithoutusing theUSBport.BecausewedohaveaUSBconnectionandsoftwarethatmakesitconvenienttouse,wewillnotavailourselvesofthisfeature.

In the top-left cornerof theboardnext to theUSBsocket is theUSB interface chip.ThischipconvertsthesignallevelsusedbytheUSBstandardtolevelsthatcanbeuseddirectlybytheArduinoboard.

TheOriginsofArduino

Arduinowasoriginallydevelopedasanaidforteachingstudents.Itwassubsequently(in2005)developedcommerciallybyMassimoBanziandDavidCuartielles.Ithassincegoneontobecomeenormouslysuccessfulwithmakers,students,andartistsforitseaseofuseanddurability.

AnotherkeyfactorinitssuccessisthatallthedesignsforArduinoarefreelyavailable

Page 25: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

underaCreativeCommonslicense.Thishasallowedmanylower-costalternativestotheboards to appear. Only the name Arduino is protected, so such clones often have“*dunino” names, such as Boarduino, Seeeduino, and Freeduino. However, the officialboards manufactured in Italy still sell extremely well.Many big retailers sell only theofficialboards,whicharenicelypackagedandofhighquality.

YetanotherreasonforthesuccessofArduinoisthatitisnotlimitedtomicrocontrollerboards.ThereareahugenumberofArduino-compatibleshieldboardsthatplugdirectlyinto the top of an Arduino board. Because shields are available for almost everyconceivable application, you often can avoid using a soldering iron and instead plugtogethershieldsthatcanbestackedoneuponanother.Thefollowingarejustafewofthemostpopularshields:

•Ethernet,whichgivesanArduinoweb-servingcapabilities

•Motor,whichdriveselectricmotors

•USBHost,whichallowscontrolofUSBdevices

•Relays,whichswitchesrelaysfromyourArduino

Figure1-3showsanArduinoUnowithanEthernetshieldattached.

Figure1-3ArduinoUnowithanEthernetshield

Page 26: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

TheArduinoFamily

ItisusefultohavealittlebackgroundonthevariousArduinoboards.WewillbeusingtheArduinoUnoasourstandarddevice.Indeed,thisisbyfarthemostusedoftheArduinoboards,buttheboardsareallprogrammedusingthesamelanguageandlargelyhavethesameconnectionstotheoutsideworld,soyoucaneasilyuseadifferentboard.

Uno,Duemilanove,andDiecimila

TheArduinoUnois the latest incarnationof themostpopularseriesofArduinoboards.The series includes theDiecimila (Italian for 10,000) and theDuemilanove (Italian for2011).Figure1-4showsanArduinoclone.BynowyoumayhaveguessedthatArduinoisanItalianinvention.

These older boards look very similar to theArduinoUno. They both have the sameconnectorsandaUSBsocketandaregenerallycompatiblewitheachother.

ThemostsignificantdifferencebetweentheUnoandtheearlierboardsisthattheUnousesadifferentUSBchip.Thisdoesnotaffecthowyouusetheboard,butitdoesmakeinstallation of theArduino software easier and allows higher speeds of communicationwiththecomputer.

TheUnocanalsosupplymorecurrentonits3.3VsupplyandalwayscomesequippedwiththeATmega328.TheearlierboardswillhaveeitheranATmega328orATmega168.TheATmega328hasmorememory,butunlessyouarecreatinga large sketch, thiswillmakenodifference.

Figure1-4TheArduinoDuemilanove

Page 27: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Mega

TheArduinoMega (Figure 1-5) is themuscle car ofArduino boards. It boasts a hugecollectionofinputoutputports,butcleverlyaddstheseasextraconnectorsatoneendoftheboard,allowingittoremainpin-compatiblewiththeArduinoUnoandalltheshieldsavailableforArduino.

Itusesaprocessorwithmore inputoutputpins, theATmega1280,which isa surfacemount chip that is fixedpermanently to theboard.So,unlikewith theUnoand similarboards,youcannotreplacetheprocessorifyouaccidentallydamageit.

Theextraconnectorsarearrangedat theendof theboard.Extra featuresprovidedbytheMegaincludethefollowing:

•54input/outputpins

• 128KB of flashmemory for storing sketches and fixed data (compared to the Uno’s32KB)

•8KBofRAMand4KBofEEPROM

Nano

The Arduino Nano (Figure 1-6) is a very useful device for use with a solderlessbreadboard.Ifyoufitpinstoit,itcanjustplugintothebreadboardasifitwereachip.

Figure1-5AnArduinoMegaboard

Page 28: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure1-6ArduinoNano

ThedownsideoftheNanoisthatbecauseitissomuchsmallerthananUno,itcannot

acceptUno-sizedshields.

Bluetooth

The Arduino Bluetooth (Figure 1-7) is an interesting device as it includes BluetoothhardwareinplaceoftheUSBconnector.Thisallowsthedevicetoevenbeprogrammedwirelessly.

TheArduinoBluetooth isnotacheapboard,and it isoftencheaper toattacha third-partyBluetoothmoduletoaregularArduinoUno.

Lilypad

TheLilypad(Figure1-8)isatiny,thinArduinoboardthatcanbestitchedintoclothingforapplicationsthathavebecomeknownaswearablecomputing.

TheLilypaddoesnothaveaUSBconnection,andyoumustuseaseparateadaptortoprogramit.Ithasanexceptionallybeautifuldesign.

Page 29: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure1-7ArduinoBluetooth

Figure1-8ArduinoLilypad

Other“Official”Boards

ThepreviouslydescribedArduinoboardsarethemostusefulandpopularones.However,therangeofArduinoboardsconstantlychanges,soforacompleteandup-to-datepictureof the Arduino family, see the official Arduino website list atwww.arduino.cc/en/Main/Hardware.

ArduinoClonesandVariants

Unofficial boards fall into two categories. Some just take the standard open sourcehardwaredesignsofArduino andbuild a cheaper one.Somenamesyou can search forboardsofthisnatureincludethefollowing:

•Roboduino

•Freeduino

•Seeeduino(yes,withthreee’s)

Page 30: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Moreinterestingly,someArduino-compatibledesignsareintendedtoextendorimprovetheArduinoinsomeway.Newvariantsareappearingallthetime,andfartoomanyexisttomentionthemall.However,thefollowingaresomeofthemoreinterestingandpopularvariants:

•Chipkit,ahigh-speedvariantbasedonaPICprocessor,butwhichisfairlycompatiblewithArduino

•Femtoduino,averysmallArduino

•Ruggeduino,withisanArduinoboardwithbuilt-inI/Oprotection

•Teensy,alow-costnano-typedevice

Conclusion

NowthatyouhaveexploredtheArduinohardwarealittle,it’stimetosetupyourArduinosoftware.

Page 31: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 32: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

2GettingStarted

Having introduced the Arduino, and learnt a little about what it is that we areprogramming, it is time to learn how install the software that we will need on ourcomputerandtostartworkingonsomecode.

PoweringUp

WhenyoubuyanArduinoboard,it isusuallypreinstalledwithasampleBlinkprogramthatwillmakethelittlebuilt-inlight-emittingdiode(LED)flash.

TheLEDmarkedLiswireduptooneofthedigitalinputoutputsocketsontheboard.Itis connected to digital pin 13. This limits pin 13 to being the one used as an output.However, theLEDuses only a small amount of current, so you can still connect otherthingstothatconnector.

AllyouneedtodotogetyourArduinoupandrunningissupplyitwithsomepower.Theeasiestwaytodothisistopluginit intotheUSBportonyourcomputer.Youwillneedatype-A-to-type-BUSBlead.Thisisthesametypeofleadthatisnormallyusedtoconnectacomputertoaprinter.

If everything isworkingOK, theLEDshouldblink.NewArduinoboardscomewiththisBlinksketchalreadyinstalledsothatyoucanverifythattheboardworks.

InstallingtheSoftware

Tobe able to install new sketchesontoyourArduinoboard, youneed to domore thansupplypowertoitovertheUSB.YouneedtoinstalltheArduinosoftware(Figure2-1).

Full and comprehensive instructions for installing this software onWindows, Linux,andMaccomputerscanbefoundattheArduinowebsite(www.arduino.cc).

Once you have successfully installed the Arduino software and, depending on yourplatform,USBdrivers,youshouldnowbeabletouploadaprogramtotheArduinoboard.

Page 33: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-1TheArduinoapplication

UploadingYourFirstSketch

TheblinkingLEDistheArduinoequivalenttothe“HelloWorld”programusedinotherlanguagesasthetraditionalfirstprogramtorunwhenlearninganewlanguage.Let’stestouttheenvironmentbyinstallingthisprogramonyourArduinoboardandthenmodifyingit.

When you start the Arduino application on your computer, it opens with an emptysketch.Fortunately,theapplicationshipswithawiderangeofusefulexamples.SofromtheFilemenu,opentheBlinkexampleasshowninFigure2-2.

Page 34: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-2TheBlinksketch

Younowneed to transferorupload that sketch toyourArduinoboard.Soplugyour

Arduinoboard intoyour computerusing theUSB lead.You should see thegreen “On”LEDontheArduinolightup.TheArduinoboardwillprobablyalreadybeflashing,astheboards are generally shippedwith theBlink sketch already installed. But let’s install itagainandthenmodifyit.

Whenyouplugtheboardin,ifyouareusingaMac,youmaygetthemessage,“Anewnetworkinterfacehasbeendetected.”JustclickCancel;yourMacisconfusedandthinksthattheUnoisaUSBmodem.

Before you can upload a sketch, youmust tell theArduino applicationwhat type ofboardyouareusingandwhichserialportyouareconnectedto.Figures2-3and2-4showhowyoudothisfromtheToolsmenu.

Page 35: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-3Selectingtheboardtype

Figure2-4Selectingtheserialport(inWindows)

OnaWindowsmachine,theserialportisalwaysCOM3.OnMacsandLinuxmachines,

youwillseeamuchlongerlistofserialdevices(seeFigure2-5).Thedevicewillnormally

Page 36: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

bethetopselectioninthelist,withanamesimilarto/dev/tty.usbmodem621.

NowclickontheUploadiconinthetoolbar.ThisisshownhighlightedinFigure2-6.

Afteryouclickthebutton,thereisashortpausewhilethesketchiscompiledandthenthetransferbegins.Ifitisworking,thentherewillbesomefuriousblinkingofLEDsasthesketchistransferred,afterwhichyoushouldseethemessage“DoneUploading”atthebottom of the Arduino application window and a further message similar to “Binarysketchsize:1018bytes(ofa14336bytemaximum).”

Figure2-5Selectingtheserialport(onaMac)

Onceuploaded,theboardautomaticallystartsrunningthesketchandyouwillseethe

LEDstarttoblink.

Ifthisdidnotwork,thencheckyourserialandboardtypesettings.

Nowlet’smodifythesketchtomaketheLEDblinkfaster.Todothis,let’salterthetwoplacesinthesketchwherethereisadelayfor1,000millisecondssothatthedelayis500milliseconds.Figure2-7showsthemodifiedsketchwiththechangeshighlighted.

Page 37: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-6Uploadingthesketch

ClickontheUploadbuttonagain.Then,oncethesketchhasuploaded,youshouldsee

yourLEDstarttoblinktwiceasfastasitdidbefore.

Congratulations,youarenowreadytostartprogrammingyourArduino.First,though,let’stakeamini-touroftheArduinoapplication.

Page 38: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-7ModifyingtheBlinksketch

TheArduinoApplication

SketchesinArduinoarelikedocumentsinawordprocessor.Youcanopenthemandcopyparts from one to another. So you see options toOpen, Save, and SaveAs in the Filemenu.YouwillnotnormallyuseOpenbecausetheArduinoapplicationhastheconceptofaSketchbookwhereallyoursketchesarekeptcarefullyorganizedintofolders.Yougainaccess to the Sketchbook from the File menu. As you have just installed the Arduinoapplication for the first time, your Sketchbook will be empty until you create somesketches.

Asyouhaveseen,theArduinoapplicationcomeswithaselectionofexamplesketchesthatcanbeveryuseful.HavingmodifiedtheBlinkexamplesketch,ifyoutryandsaveit,yougetamessagethatsays,“Somefilesaremarkedread-onlysoyouwillneedtosavethissketchinadifferentlocation.”

Try this now. Accept the default location, but change the filename to MyBlink, asshowninFigure2-8.

Nowifyougoto theFilemenuandthenclickonSketches,youwillseeMyBlinkasoneofthesketcheslisted.Ifyoulookatyourcomputer’sfilesystem,onaPC,youwillfindthatthesketchhasbeenwrittenintoMyDocuments\Arduino,andonMacorLinux,theyareinDocuments/Arduino.

All of the sketches used in this book can be downloaded as a zip file(Programming_Arduino.zip)fromwww.arduinobook.com.Isuggest thatnowis the timetodownload this file andunzip it into theArduino folder that contains the sketches. Inother words, when you have unzipped the folder, there should be two folders in yourArduinofolder:oneforthenewlysavedMyBlinkandonecalledProgrammingArduino(seeFigure2-9).TheProgrammingArduinofolderwillcontainallthesketches,numberedaccordingtochapter,sothatsketch03-01,forexample,issketch1ofChapter3.

Page 39: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-8SavingacopyofBlink

These sketcheswill not appear in your Sketchbookmenu until you quit theArduino

applicationandrestartit.Dosonow.ThenyourSketchbookmenushouldlooksimilartothatshowninFigure2-10.

Figure2-9Installingthesketchesfromthebook

Page 40: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure2-10Sketchbookwiththebook’ssketchesinstalled

Conclusion

Yourenvironmentisallsetupandreadytogo.

Inthenextchapter,wewilllookatsomeofthebasicprinciplesoftheClanguagethattheArduinousesandstartwritingsomecode.

Page 41: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 42: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

3CLanguageBasics

Theprogramming language used to programArduinos is a language calledC. In thischapter,yougettounderstandthebasicsoftheClanguage.Youwillusewhatyoulearnhere in every sketch you develop as an Arduino programmer. To get the most out ofArduino,youneedtounderstandthesefundamentals.

Programming

It is not uncommon forpeople to speakmore thanone language. In fact, themoreyoulearn,theeasieritseemstolearnspokenlanguagesasyoustarttofindcommonpatternsofgrammar and vocabulary.The same is true of programming languages. So, if you haveusedanyotherprogramminglanguage,youwillquicklypickupC.

Thegoodnews is that thevocabularyof aprogramming language is far smaller thanthatofaspokenlanguage,andbecauseyouwriteitratherthansayit, thedictionarycanalwaysbeathandwheneveryouneedtolookthingsup.Also,thegrammarandsyntaxofaprogramming languageareextremely regular, andonceyoucome togripswitha fewsimpleconcepts,learningmorequicklybecomessecondnature.

Itisbesttothinkofaprogram—orasketch,asprogramsarecalledinArduino—asalistofinstructionstobecarriedoutintheorderthattheyarewrittendown.Forexample,supposeyouweretowritethefollowing:

Thesethreelineswouldeachdosomething.Thefirstlinewouldsettheoutputofpin13toHIGH.ThisisthepinwithanLEDbuiltintotheArduinoboard,soatthispointtheLEDwouldlight.Thesecondlinewouldsimplywaitfor500milliseconds(halfasecond)andthenthethirdlinewouldturntheLEDbackoffagain.SothesethreelineswouldachievethegoalofmakingtheLEDblinkonce.

You have already seen a bewildering array of punctuation used in strangeways andwordsthatdon’thavespacesbetweenthem.Afrustrationofmanynewprogrammersis,“Iknowwhat Iwant to do, I just don’t knowwhat I need towrite!”Fear not, allwill beexplained.

Firstofall,let’sdealwiththepunctuationandthewaythewordsareformed.Thesearebothpartofwhatistermedthesyntaxofthelanguage.Mostlanguagesrequireyoutobeextremelypreciseaboutsyntax,andoneofthemainrulesisthatnamesforthingshavetobe a singleword.That is, they cannot include spaces.So,digitalWrite is the name for

Page 43: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

something. It’s the nameof a built-in function (you’ll learnmore about functions later)thatwilldothejobofsettinganoutputpinontheArduinoboard.Notonlydoyouhavetoavoidspacesinnames,butalsonamesarecasesensitive.SoyoumustwritedigitalWrite,notDigitalWriteorDigitalwrite.

ThefunctiondigitalWriteneedstoknowwhichpintosetandwhethertoset thatpinHIGHorLOW.Thesetwopiecesofinformationarecalledarguments,whicharesaidtobepassedtoafunctionwhenitiscalled.Theparametersforafunctionmustbeenclosedinparenthesesandseparatedbycommas.

Theconvention is toplace theopeningparenthesis immediatelyafter the last letterofthe function’s name and to put a space after the comma before the next parameter.However,youcansprinklespacecharacterswithintheparenthesesifyouwant.

Ifthefunctiononlyhasoneargument,thenthereisnoneedforacomma.

Notice how each line endswith a semicolon. It would bemore logical if theywereperiods, because the semicolonmarks the end of one command, a bit like the end of asentence.

Inthenextsection,youwillfindoutabitmoreaboutwhathappenswhenyoupresstheUploadbuttonontheArduinointegrateddevelopmentenvironment(IDE).Thenyouwillbeabletostarttryingoutafewexamples.

WhatIsaProgrammingLanguage?

ItisperhapsalittlesurprisingthatwecangettoChapter3inabookaboutprogrammingwithoutdefiningexactlywhataprogramminglanguageis.WecanrecognizeanArduinosketchandprobablyhavearoughideaofwhatitistryingtodo,butweneedtolookabitdeeper intohowsomeprogramminglanguagecodegoesfrombeingwordsonapagetosomethingthatdoessomethingreal,liketurnanLEDonandoff.

Figure3-1summarizestheprocessinvolvedfromtypingcodeintotheArduinoIDEtorunningthesketchontheboard.

Page 44: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure3-1Fromcodetoboard

WhenyoupresstheUploadbuttononyourArduinoIDE,itlaunchesachainofevents

that results in your sketch being installed on theArduino and being run.This is not asstraightforwardassimplytakingthetextthatyoutypedintotheeditorandmovingittotheArduinoboard.

The first step is to do something called compilation. This takes the code you havewritten and translates it into machine code—the binary language that the Arduinounderstands. If you click the triangularVerify button on theArduino IDE, this actuallyattempts to compile theC that you havewrittenwithout trying to send the code to theArduinoIDE.Aside-effectofcompilingthecodeisthatitischeckedtomakesurethatitconformstotherulesoftheClanguage.

IfyoutypeCiaoBellaintoyourArduinoIDEandclickonthePlaybutton,theresultswillbeasshowninFigure3-2.

Figure3-2Arduinosdon’tspeakItalian

The Arduino has tried to compile the words “Ciao Bella,” and despite its Italian

heritage,ithasnoideawhatyouaretalkingabout.ThistextisnotC.So,theresultisthatat thebottomof the screenwehave that crypticmessage “error:Ciaodoesnot nameatype.”Whatthisactuallymeansisthatthereisalotwrongwithwhatyouhavewritten.

Let’stryanotherexample.Thistimewewilltrycompilingasketchwithnocodeatallinit(seeFigure3-3).

This time, the compiler is telling you that your sketch does not have setup or loop

Page 45: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

functions.AsyouknowfromtheBlinkexample thatyouran inChapter2,youhave tohave some “boilerplate” code, as it is called, before you can addyour owncode into asketch.InArduinoprogrammingthe“boilerplate”codetakestheformofthe“setup”and“loop”functionsthatmustalwaysbepresentinasketch.

Figure3-3Nosetuporloop

Youwill learnmuchmoreabout functions later in thebook,but fornow, let’saccept

that you need this boilerplate code and just adapt your sketch so it will compile (seeFigure3-4).

The Arduino IDE has looked at your efforts at writing code and found them to beacceptable. It tells you this by saying “Done Compiling” and reporting the size of thesketch to you: 450bytes.The IDE is also telling you that themaximum size is 32,256bytes,soyoustillhavelotsofroomtomakeyoursketchbigger.

Let’sexaminethisboilerplatecodethatwillformthestartingpointforeverysketchthatyoueverwrite.Therearesomenewthingshere.Forexample,thereisthewordvoidandsomecurlybraces.Let’sdealwithvoidfirst.

Page 46: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure3-4Asketchthatwillcompile

Thelinevoidsetup()meansthatyouaredefiningafunctioncalledsetup.InArduino,

somefunctionsarealreadydefinedforyou,suchasdigitalWriteanddelay,whereasyoumustor candefineothers foryourself. setup and loop are two functions that youmustdefineforyourselfineverysketchthatyouwrite.

TheimportantthingtounderstandisthathereyouarenotcallingsetuporlooplikeyouwouldcalldigitalWrite,butyouareactuallycreatingthesefunctionssothattheArduinosystemitselfcancallthem.Thisisadifficultconcepttograsp,butonewaytothinkofitisasbeingsimilartoadefinitioninalegaldocument.

Most legal documents have a “definitions” section that might say, for example,somethinglikethefollowing:

By defining a term in this way—for example, simply using the word “author” as

shorthand for “The person or persons responsible for creating the book”—lawyers canmake their documents shorter and more readable. Functions work much like suchdefinitions.Youdefineafunctionthatyouorthesystemitselfcanthenuseelsewhereinyoursketches.

Goingbacktovoid,thesetwofunctions(setupandloop)donotreturnavalueassomefunctions do, so you have to say that they are void, using the void keyword. If youimagineafunctioncalledsinthatperformedthetrigonometricfunctionofthatname,then

Page 47: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

thisfunctionwouldreturnavalue.Thevaluereturnedtousefromthecallwouldbethesinoftheanglepassedasitsargument.

Ratherlikealegaldefinitionuseswordstodefineaterm,wewritefunctionsinCthatcanthenbecalledfromC.

Afterthespecialkeywordvoidcomesthenameofthefunctionandthenparenthesestocontainanyarguments. In thiscase, therearenoarguments,butwestillhaveto includetheparenthesesthere.Thereisnosemicolonaftertheclosingparenthesisbecausewearedefining a function rather than calling it, so we need to say what will happen whensomethingdoescallthefunction.

Those things that are to happenwhen the function is calledmust be placed betweencurlybraces.Curlybracesand thecode inbetween themareknownasablock of code,andthisisaconceptthatyouwillmeetagainlater.

Notethatalthoughyoudohavetodefineboththefunctionssetupandloop,youdonotactuallyhave toput any linesof code in them.However, failing toaddcodewillmakeyoursketchalittledull.

Blink—Again!

ThereasonthatArduinohasthetwofunctionssetupandloopistoseparatethethingsthatonlyneedtobedoneonce,whentheArduinostartsrunningitssketch,fromthethingsthathavetokeephappeningcontinuously.

Thefunctionsetupwilljustberunoncewhenthesketchstarts.Let’saddsomecodetoit thatwill blink the LED built onto the board.Add the lines to your sketch so that itappearsasfollowsandthenuploadthemtoyourboard:

Thesetupfunctionitselfcallstwobuilt-infunctions,pinModeanddigitalWrite.You

already know about digitalWrite, but pinMode is new. The function pinMode sets aparticularpintobeeitheraninputoranoutput.So,turningtheLEDonisactuallyatwo-stageprocess.First,youhavetosetpin13tobeanoutput,andsecond,youneedtosetthatoutputtobehigh(5V).

Whenyourunthissketch,onyourboardyouwillseethattheLEDcomesonandstayson.Thisisnotveryexciting,solet’satleasttrytomakeitflashbyturningitonandoffintheloopfunctionratherthaninthesetupfunction.

Page 48: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

YoucanleavethepinModecallinthesetupfunctionbecauseyouonlyneedtocallitonce.Theprojectwouldstillworkifyoumoveditintotheloop,butthereisnoneedanditisagoodprogramminghabittodothingsonlyonceifyouonlyneedtodothemonce.Somodifyyoursketchsothatitlookslikethis:

Run this sketchandseewhathappens. Itmaynotbequitewhatyouwereexpecting.

TheLEDisbasicallyonallthetime.Hmm,whyshouldthisbe?

Trysteppingthroughthesketchalineatatimeinyourhead:

1.Runsetupandsetpin13tobeanoutput.

2.Runloopandsetpin13tohigh(LEDon).

3.Delayforhalfasecond.

4.Setpin13tolow(LEDoff).

5.Runloopagain,goingbacktostep2,andsetpin13tohigh(LEDon).

Theproblem liesbetweensteps4and5.What ishappening is that theLED isbeingturned off, but the very next thing that happens is that it gets turned on again. ThishappenssoquicklythatitappearsthattheLEDisonallthetime.

The microcontroller chip on the Arduino can perform 16 million instructions persecond.That’snot16millionClanguagecommands,butitisstillveryfast.So,ourLEDwillonlybeoffforafewmillionthsofasecond.

Tofixtheproblem,youneedtoaddanotherdelayafteryouturntheLEDoff.Yourcodeshouldnowlooklikethis:

Page 49: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

TryagainandyourLEDshouldblinkawaymerrilyoncepersecond.

Youmayhavenoticed thecommentat the topof the listingsaying“sketch3-01.”Tosaveyousometyping,wehaveuploadedtothebook’swebsiteallthesketcheswithsuchacommentatthetop.Youcandownloadthemfromhttp://www.arduinobook.com.

Variables

InthisBlinkexample,youusepin13andhavetorefertoitinthreeplaces.Ifyoudecidedtouseadifferentpin,thenyouwouldhavetochangethecodeinthreeplaces.Similarly,ifyouwantedtochangetherateofblinking,controlledbytheargumenttodelay,youwouldhavetochange500tosomeothernumberinmorethanoneplace.

Variablescanbethoughtofasgivinganametoanumber.Actually, theycanbealotmorepowerfulthanthis,butfornow,youwillusethemforthispurpose.

Whendefiningavariable inC,youhavetospecify the typeof thevariable.Wewantour variables to bewhole numbers,which inC are called ints. So to define a variablecalledledPinwithavalueof13,youneedtowritethefollowing:

NoticethatbecauseledPinisaname,thesamerulesapplyasthoseoffunctionnames.

So,therecannotbeanyspaces.Theconventionistostartvariableswithalowercaseletterand begin each new word with an uppercase letter. Programmers will often call this“bumpycase”or“camelcase.”

Let’sfitthisintoyourBlinksketchasfollows:

Page 50: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

WehavealsosneakedinanothervariablecalleddelayPeriod.

Everywhereinthesketchwhereyouusedtoreferto13,younowrefertoledPin,andeverywhereyouusedtoreferto500,younowrefertodelayPeriod.

If you want to make the sketch blink faster, you can just change the value ofdelayPeriodinoneplace.Trychangingitto100andrunningthesketchonyourArduinoboard.

Thereareothercunningthingsthatyoucandowithvariables.Let’smodifyyoursketchso that the blinking starts really fast and gradually gets slower and slower, as if theArduino is getting tired. To do this, all you need to do is to add something to thedelayPeriodvariableeachtimethatyoudoablink.

Modify the sketchbyadding the single lineat theendof the loop function so that itappears,as in thefollowinglisting,andthenrunthesketchontheArduinoboard.PresstheResetbuttonandseeitstartfromafastrateofflashingagain.

Page 51: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

YourArduino is doing arithmetic now. Every time that loop is called, it will do the

normal flashof theLED,but then itwill add100 to thevariabledelayPeriod.Wewillcomebacktoarithmeticshortly,butfirstyouneedabetterwaythanaflashingLEDtoseewhattheArduinoisupto.

ExperimentsinC

YouneedawaytotestyourexperimentsinC.OnewayistoputtheCthatyouwanttotestoutintothesetupfunction,evaluatethemontheArduino,andthenhavetheArduinodisplayanyoutputbacktosomethingcalledtheSerialMonitor,asshowninFigures3-5and3-6.

The Serial Monitor is part of the Arduino IDE. You access it by clicking on therightmost icon in the toolbar. Itspurpose is toactasacommunicationchannelbetweenyourcomputerandtheArduino.YoucantypeamessageinthetextentryareaatthetopoftheSerialMonitorandwhenyoupressReturnorclickSend,itwillsendthatmessagetothe Arduino. Also if the Arduino has anything to say, this message will appear in theSerialMonitor.Inbothcases,theinformationissentthroughtheUSBlink.

Figure3-5WritingCinsetup

Page 52: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure3-6TheSerialMonitor

Asyouwouldexpect, there isabuilt-infunctionthatyoucanuse inyoursketches to

send amessage back to the SerialMonitor. It is calledSerial.println and it expects asingleargument,whichconsistsoftheinformationthatyouwanttosend.Thisinformationisusuallyavariable.

YouwillusethismechanismtotestoutafewthingsthatyoucandowithvariablesandarithmeticinC;frankly,it’stheonlywayyoucanseetheresultsofyourexperimentsinC.

NumericVariablesandArithmetic

Thelastthingyoudidwasaddthefollowinglinetoyourblinkingsketchtoincreasetheblinkingperiodsteadily:

Looking closely at this line, it consists of a variable name, then an equals sign, then

whatiscalledanexpression(delayPeriod+100).Theequalssigndoessomethingcalledassignment. That is, it assigns a new value to a variable, and the value it is given isdeterminedbywhatcomesaftertheequalssignandbeforethesemicolon.Inthiscase,thenewvalue tobegiven to thedelayPeriodvariable is theoldvalueofdelayPeriodplus100.

Let’s test out this newmechanism to seewhat theArduino is up to by entering thefollowingsketch,runningit,andopeningtheSerialMonitor:

Page 53: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure3-7showswhatyoushouldseeintheSerialMonitorafterthiscoderuns.

Totakeaslightlymorecomplexexample,theformulaforconvertingatemperatureindegreesCentigradeintodegreesFahrenheitistomultiplyitby5,divideby9,andthenadd32.Soyoucouldwritethatinasketchlikethis:

Figure3-7Simplearithmetic

Thereareafewthingstonoticehere.First,notethefollowingline:

Whenwewrite such a line,we are actually doing two things:We are declaring an intvariablecalleddegC,andwearesayingthatitsinitialvaluewillbe20.Alternatively,youcouldseparatethesetwothingsandwritethefollowing:

Youmustdeclareanyvariable justonce,essentially telling thecompilerwhat typeof

variable it is—in this case, int.However, you can assign the variable a value asmanytimesasyouwant:

Page 54: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

So, in the Centigrade to Fahrenheit example, you are defining the variable degC andgivingitaninitialvalueof20,butwhenyoudefinedegF,itdoesnotgetaninitialvalue.Itsvaluegetsassignedonthenextline,accordingtotheconversionformula,beforebeingsenttotheSerialMonitorforyoutosee.

Lookingat theexpression,youcanseethatyouusetheasterisk(*)formultiplicationand the slash (/) for division. The arithmetic operators+, −, *, and / have an order ofprecedence—that is, multiplications are done first, then divisions, then additions andsubtractions.Thisisinaccordancewiththeusualuseofarithmetic.However,sometimesitmakes itclearer touseparentheses in theexpressions.So, forexample,youcouldwritethefollowing:

Theexpressionsthatyouwritecanbeaslongandcomplexasyouneedthemtobe,and

inadditiontotheusualarithmeticoperators,thereareotherlesscommonlyusedoperatorsandabigcollectionofvariousmathematicalfunctionsthatareavailabletoyou.Youwilllearnabouttheselater.

Commands

TheClanguagehasanumberofbuilt-incommands.Inthissection,weexploresomeoftheseandseehowtheycanbeofuseinyoursketches.

if

Inoursketchessofar,wehaveassumedthatyourlinesofprogrammingwillbeexecutedinorderoneafter theother,withnoexceptions.Butwhat ifyoudon’twant todo that?Whatifyouonlywanttoexecutepartofasketchifsomeconditionistrue?

Let’sreturntoourgraduallyslowing-downBlinkingLEDexample.Atthemoment,itwillgraduallygetslowerandsloweruntileachblinkislastinghours.Let’slookathowwecanchange it so thatonce ithassloweddowntoacertainpoint, itgoesback to its faststartingspeed.

Todothis,youmustuseanifcommand;themodifiedsketchisasfollows.Tryitout.

Page 55: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

The if command looks a little like a functiondefinition, but this resemblance is only

superficial.Thewordintheparenthesisisnotanargument;itiswhatiscalledacondition.Sointhiscase, theconditionis that thevariabledelayPeriodhasavalue that isgreaterthan3,000.Ifthisistrue,thenthecommandsinsidethecurlybraceswillbeexecuted.Inthiscase,thecodesetsthevalueofdelayPeriodbackto100.

Iftheconditionisnottrue,thentheArduinowilljustcontinueonwiththenextthing.Inthiscase,thereisnothingafterthe“if”,sotheArduinowillruntheloopfunctionagain.

Runningthroughthesequenceofeventsinyourheadwillhelpyouunderstandwhatisgoingon.So,hereiswhathappens:

1.ArduinorunssetupandinitializestheLEDpintobeanoutput.

2.Arduinostartsrunningloop.

3.TheLEDturnson.

4.Adelayoccurs.

5.TheLEDturnsoff.

6.Adelayoccurs.

7.Add100tothedelayPeriod.

8.Ifthedelayperiodisgreaterthan3,000setitbackto100.

9.Gobacktostep2.

We used the symbol<,whichmeans less than. It is one example ofwhat are calledcomparisonoperators.Theseoperatorsaresummarizedinthefollowingtable:

Page 56: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Tocomparetwonumbers,youusethe==command.Thisdoubleequalssigniseasily

confusedwiththecharacter=,whichisusedtoassignvaluestovariables.

Thereisanotherformofifthatallowsyoutodoonethingiftheconditionistrueandanotherifitisfalse.Wewillusethisinsomepracticalexampleslaterinthebook.

for

Inadditiontoexecutingdifferentcommandsunderdifferentcircumstances,youalsooftenwillwanttorunaseriesofcommandsanumberoftimesinaprogram.Youalreadyknowonewayofdoingthis,usingtheloopfunction.Assoonasallthecommandsintheloopfunctionhavebeen run, itwill start again automatically.However, sometimesyouneedmorecontrolthanthat.

So, for example, let’s say that youwant towrite a sketch that blinks 20 times, thenpausedfor3seconds,andthenstartedagain.Youcoulddothatbyjustrepeatingthesamecodeoverandoveragaininyourloopfunction,likethis:

Page 57: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

But thisrequiresa lotof typingandthereareseveralmuchbetterwaystodothis.Let’sstartbylookingathowyoucanuseafor loopandthenlookatanotherwayofdoingitusingacounterandanifstatement.

Thesketchtoaccomplishthiswithaforloopis,asyoucansee,alotshorterandeasiertomaintainthanthepreviousexample:

Page 58: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Theforlooplooksabitlikeafunctionthattakesthreearguments,althoughherethose

argumentsareseparatedbysemicolonsratherthantheusualcommas.ThisisjustaquirkoftheClanguage.Thecompilerwillsoontellyouwhenyougetitwrong.

The first thing in the parentheses after for is a variable declaration. This specifies avariabletobeusedasacountervariableandgivesitaninitialvalue—inthiscase,0.

Thesecondpartisaconditionthatmustbetrueforyoutostayintheloop.Inthiscase,youwillstayinthe loopaslongas i is less than20,butassoonas i is20ormore, theprogramwillstopdoingthethingsinsidetheloop.

Thefinalpartiswhattodoeverytimeyouhavedoneallthethingsintheloop.Inthiscase,thatistoincrementiby1sothatitcan,after20tripsaroundtheloop,ceasetobelessthan100andcausetheprogramtoexittheloop.

Tryenteringthiscodeandrunningit.Theonlywaytogetfamiliarwiththesyntaxandall thatpeskypunctuationis to type it inandhavethecompiler tellyouwhenyouhavedonesomethingwrong.Eventuallyitwillallstarttomakesense.

Onepotentialdownsideofthisapproachisthattheloopfunctionisgoingtotakealongtime.Thisisnotaproblemforthissketch,becauseallitisdoingisflashinganLED.Butoften,theloopfunctioninasketchwillalsobecheckingthatkeyshavebeenpressedorthatserialcommunicationshavebeenreceived.Iftheprocessorisbusyinsideaforloop,itwillnotbeabletodothis.Generally,itisagoodideatomaketheloopfunctionrunasfastaspossiblesothatitcanberunasfrequentlyaspossible.

Thefollowingsketchshowshowtoachievethis:

Page 59: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Youmayhavenoticedthefollowingline:

ThisisjustCshorthandforthefollowing:

Sonoweachtimethatloopisrun,itwilltakejustabitmorethan200milliseconds,unlessit’sthe20thtimeroundtheloop,inwhichcaseitwilltakethesameplusthethreesecondsdelay between each batch of 20 flashes. In fact, for some applications, even this is tooslow,andpuristswouldsaythatyoushouldnotusedelayatall.Thebestsolutiondependsontheapplication.

while

AnotherwayofloopinginCistousethewhilecommandinplaceoftheforcommand.Youcanaccomplishthesamethingastheprecedingforexampleusingawhilecommandasfollows:

Page 60: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Theexpressioninparenthesesafterwhilemustbetruetostayintheloop.Whenitisno

longertrue,thenthesketchcontinuesrunningthecommandsafterthefinalcurlybrace.

The#defineDirective

Forconstantvalueslikepinassignmentsthatdonotchangeduringtherunningofasketch,there is an alternative to using a variable.You can use a command called#define thatallowsyoutoassociateavaluewithaname.Everywherethat thisnameappearsinyoursketch,thevaluewillbesubstitutedbeforethesketchiscompiled.

Asanexample,youcoulddefineapinassignmentforaLEDlikethis:

Notethatthe#definedirectivedoesnotusean“=”betweenthenameandthevalue.It

does not even need a “;” on the end. This is because it is not actually part of the Clanguageitself;butiscalledapre-compilerdirectivethatisrunbeforecompilation.

Thisapproach,intheauthor’sopinion,islesseasytoreadthanusingavariable,butitdoeshave theadvantage thatyoudonotuseanymemory to store it. It is something toconsiderifmemoryisatapremium.

Conclusion

This chapter has got you startedwithC.You canmakeLEDsblink in various excitingways and get the Arduino to send results back to you over the USB by using theSerial.printlnfunction.Youalsoworkedouthowtouseifandforcommandstocontrolthe order in which your commands are executed, and learned a little aboutmaking anArduinodosomearithmetic.

In the next chapter, you will look more closely at functions. The chapter will alsointroducethevariabletypesotherthantheinttypethatyouusedinthischapter.

Page 61: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 62: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

4Functions

Thischapter focusesmostlyon the typeof functions thatyoucanwriteyourself ratherthanthebuilt-infunctionssuchasdigitalWriteanddelaythatarealreadydefinedforyou.

Thereasonthatyouneedtobeabletowriteyourownfunctionsisthatassketchesstart

togeta littlecomplicated, thenyoursetupandloop functionswillgrowandgrowuntiltheyarelongandcomplicatedanditbecomesdifficulttoseehowtheywork.

Thebiggestprobleminsoftwaredevelopmentofanysortismanagingcomplexity.Thebestprogrammerswritesoftwarethatiseasytolookatandunderstandandrequiresverylittleinthewayofexplanation.

Functions are a key tool in creating easy-to-understand sketches that can be changedwithoutdifficultyorriskofthewholethingfallingintoacrumpledmess.

WhatIsaFunction?

Afunctionisalittlelikeaprogramwithinaprogram.Youcanuseittowrapupsomelittlethingthatyouwanttodo.Afunctionthatyoudefinecanbecalledfromanywhereinyoursketchandcontainsitsownvariablesanditsownlistofcommands.Whenthecommandshavebeen run,execution returns to thepoint justafterwherever itwas in thecode thatcalledthefunction.

By way of an example, code that flashes a light-emitting diode (LED) is a primeexampleofsomecodethatshouldbeputinafunction.Solet’smodifyourbasic“blink20times”sketchtouseafunctionthatwewillcreatecalledflash:

Page 63: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

So,allwehavereallydonehere is tomove thefour linesofcode that flash theLED

fromthemiddleoftheforlooptobeinafunctionoftheirowncalledflash.NowyoucanmaketheLEDflashanytimeyoulikebyjustcallingthenewfunctionbywritingflash().Notetheemptyparenthesesafterthefunctionname.Thisindicatesthatthefunctiondoesnot take any parameters. The delay value that it uses is set by the same delayPeriodfunctionthatyouusedbefore.

Parameters

Whendividingyoursketchupintofunctions,itisoftenworththinkingaboutwhatservicea functioncouldprovide. In thecaseof flash, this is fairlyobvious.But this time, let’sgivethisfunctionparametersthattellitboth,howmanytimestoflashandhowshortorlongtheflashesshouldbe.ReadthroughthefollowingcodeandthenIwillexplainjusthowparametersworkinalittlemoredetail.

Page 64: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Now, ifwe lookatour loop function, ithasonly two lines in it.Wehavemoved the

bulkoftheworkofftotheflashfunction.Noticehowwhenwecallflashwenowsupplyitwithtwoargumentsinparentheses.

Wherewedefinethefunctionatthebottomofthesketch,wehavetodeclarethetypeofvariable in theparameters. In this case, theyareboth ints.We are in fact definingnewvariables.However,thesevariables(numFlashesandd)canonlybeusedwithintheflashfunction.

This is agood functionbecause itwrapsupeverythingyouneed inorder to flashanLED.TheonlyinformationthatitneedsfromoutsideofthefunctionistowhichpintheLED is attached. If youwanted, you couldmake this a parameter too—something thatwouldbewellworthdoingifyouhadmorethanoneLEDattachedtoyourArduino.

Global,Local,andStaticVariables

Aswasmentionedbefore,parameterstoafunctioncanbeusedonlyinsidethatfunction.So,ifyouwrotethefollowingcode,youwouldgetanerror:

Page 65: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Ontheotherhand,supposeyouwrotethis:

This code would not result in a compilation error. However, you need to be careful,becauseyounowactuallyhave twovariables calledx and they can eachhavedifferentvalues.Theonethatyoudeclaredonthefirstlineiscalledaglobalvariable.It iscalledglobal because it can be used anywhere you like in the program, including inside anyfunctions.

However,becauseyouusethesamevariablenamexinsidethefunction,asaparameter,youcannotuse theglobalvariablex simplybecausewheneveryou refer tox inside thefunction,the“local”versionofxhaspriority.Theparameterxissaidtoshadowtheglobalvariable of the same name. This can lead to some confusion when trying to debug aproject.

Inadditiontodefiningparameters,youcanalsodefinevariablesthatarenotparametersbutarejustforusewithinafunction.Thesearecalledlocalvariables.Forexample:

ThelocalvariabletimesToFlashwillonlyexistwhilethefunctionisrunning.Assoonasthe function has finished its last command, it will disappear. This means that localvariablesarenotaccessiblefromanywhereinyourprogramotherthaninthefunctioninwhichtheyaredefined.

So,forinstance,thefollowingexamplewillcauseanerror:

Page 66: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Seasoned programmers generally treat global variableswith suspicion. The reason isthattheygoagainsttheprincipalofencapsulation.Theideaofencapsulation isthatyoushouldwrapup in a package everything that has to dowith a particular feature.Hencefunctionsaregreatforencapsulation.Theproblemwith“globals”(asglobalvariablesareoftencalled)isthattheygenerallygetdefinedatthebeginningofasketchandmaythenbeusedalloverthesketch.Sometimesthereisaperfectlylegitimatereasonforthis.Othertimes, people use them in a lazy way when it would be far more appropriate to passparameters.Inourexamplessofar,ledPinisagooduseofaglobalvariable.It’salsoveryconvenientandeasytofindupatthetopofthesketch,makingiteasytochange.Actually,ledPinisreallyaconstant,becausealthoughyoumaychangeitandthenrecompileyoursketch, you are unlikely to allow the variable to change while the sketch is actuallyrunning. For this reason, youmay prefer to use the#define commandwe described inChapter3.

Anotherfeatureoflocalvariablesisthattheirvalueisinitializedeverytimethefunctionisrun.Thisisnowheremoretrue(andofteninconvenient)thanintheloopfunctionofanArduinosketch.Let’stryandusealocalvariableinplaceofglobalvariableinoneoftheexamplesfromthepreviouschapter:

Sketch4-03isbasedonthesketch3-09,butattemptstousealocalvariableinsteadof

theglobalvariabletocountthenumberofflashes.

This sketch is broken. Itwill notwork, because every time loop is run, the variablecountwillbegiventhevalue0again,socountwillneverreach20andtheLEDwilljustkeepflashingforever.Thewholereasonthatwemadecountaglobalinthefirstplacewasso that its value would not be reset. The only place that we use count is in the loopfunction,sothisiswhereitshouldbeplaced.

Page 67: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Fortunately, there is a mechanism in C that gets around this conundrum. It is thekeywordstatic.Whenyouuse thekeywordstatic in frontofavariabledeclaration inafunction,ithastheeffectofinitializingthevariableonlythefirsttimethatthefunctionisrun.Perfect!That’sjustwhatisrequiredinthissituation.Wecankeepourvariableinthefunction where it’s used without it getting set back to 0 every time the function runs.Sketch4-04showsthisinoperation:

ReturnValues

Computer science, as an academic discipline, has as its parents mathematics andengineering.Thisheritagelingersoninmanyofthenamesassociatedwithprogramming.Thewordfunctionisitselfamathematicalterm.Inmathematics,theinputtothefunction(theargument)completelydeterminestheoutput.Wehavewrittenfunctionsthattakeaninput,butnonethatgiveusbackavalue.Allourfunctionshavebeen“void”functions.Ifafunctionreturnsavalue,thenyouspecifyareturntype.

Let’s look at writing a function that takes a temperature in degrees Centigrade andreturnstheequivalentindegreesFahrenheit:

Page 68: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Thefunctiondefinitionnowstartswith int rather thanvoid to indicate that thefunctionwillreturnaninttowhatevercallsit.Thismightbeabitofcodethatlookslikethis:

Anynon-voidfunctionhastohaveareturnstatementinit.Ifyoudonotputonein,the

compilerwilltellyouthatitismissing.Youcanhavemorethanonereturn inthesamefunction.Thismight arise if youhave an if statementwith alternative actionsbasedonsomecondition.Someprogrammersfrownonthis,butifyourfunctionsaresmall(asallfunctionsshouldbe),thenthispracticewillnotbeaproblem.

Thevalueafterreturncanbeanexpression;itdoesnothavetojustbethenameofavariable.Soyoucouldcompresstheprecedingexampleintothefollowing:

If the expression being returned ismore than just a variable name, then it should be

enclosedinparenthesesasintheprecedingexample.

OtherVariableTypes

All our examples of variables so far have been int variables. This is by far the mostcommonlyusedvariabletype,buttherearesomeothersthatyoushouldbeawareof.

floats

Onesuchtype,whichisrelevanttotheprevioustemperatureconversionexample,isfloat.This variable type represents floating point numbers—that is, numbers thatmayhave adecimalpointinthem,suchas1.23.Youneedthisvariabletypewhenwholenumbersarejustnotpreciseenough.

Notethefollowingformula:

Ifyougivecthevalue17,thenfwillbe17*9/5+32or62.6.Butiffisanint,thenthevaluewillbetruncatedto62.

The problem becomes even worse if we are not careful of the order in which weevaluatethings.Forinstance,supposethatwedidthedivisionfirst,asfollows:

Page 69: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Theninnormalmathterms,theresultwouldstillbe62.6,butifallthenumbersareints,thenthecalculationwouldproceedasfollows:

1.17isdividedby5,whichgives3.4,whichisthentruncatedto3.

2.3isthenmultipliedby9and32isaddedtogivearesultof59—whichisquitealongwayfrom62.6.

For circumstances like this, we can use floats. In the following example, ourtemperatureconversionfunctionisrewrittentousefloats:

Noticehowwehaveadded.0totheendofourconstants.Thisensuresthatthecompilerknowstotreatthemasfloatsratherthanints.

boolean

Booleanvaluesarelogical.Theyhaveavaluethatiseithertrueorfalse.

IntheClanguage,Boolean isspelledwithalowercaseb,but ingeneraluse,Booleanhasanuppercaseinitialletter,asitisnamedafterthemathematicianGeorgeBoole,whoinventedtheBooleanlogicthatiscrucialtocomputerscience.

Youmaynotrealizeit,butyouhavealreadymetBooleanvalueswhenwewerelookingattheifcommand.Theconditioninanifstatement,suchas(count==20),isactuallyanexpressionthatyieldsabooleanresult.Theoperator==iscalledacomparisonoperator.Whereas+ isanarithmeticoperatorthataddstwonumberstogether,== isacomparisonoperatorthatcomparestwonumbersandreturnsavalueofeithertrueorfalse.

YoucandefineBooleanvariablesandusethemasfollows:

BooleanvaluescanbemanipulatedusingBooleanoperators.So,similartohowyoucan

performarithmeticonnumbers,youcanalsoperformoperationsonBooleanvalues.ThemostcommonlyusedBooleanoperatorsareand,whichiswrittenas&&,andor,whichiswrittenas||.

Figure4-1showstruthtablesfortheandandoroperators.

FromthetruthtablesinFigure4-1,youcanseethatforand,ifbothAandBaretrue,

Page 70: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

thentheresultwillbetrue;otherwise,theresultwillbefalse.

Ontheotherhand,withtheoroperator,ifeitherAorBorbothAandBaretrue,thentheresultwillbetrue.TheresultwillbefalseonlyifneitherAnorBistrue.

In addition to and and or, there is the not operator, written as !. You will not besurprisedtolearnthat“nottrue”isfalseand“notfalse”istrue.

Figure4-1Truthtables

YoucancombinetheseoperatorsintoBooleanexpressionsinyourifstatements,asthe

followingexampleillustrates:

OtherDataTypes

Asyouhaveseen,theintandoccasionallythefloatdatatypesarefineformostsituations;however, some other numeric types can be useful under some circumstances. In anArduino sketch, the int type uses 16 bits (binary digits). This allows it to representnumbersbetween−32767and32768.

OtherdatatypesavailabletoyouaresummarizedinTable4-1.This table isprovidedmainlyforreference.Youwillusesomeoftheseothertypesasyouprogressthroughthebook.

Page 71: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Table4-1DataTypesinC

One thing to consider is that if data types exceed their range, then strange things

happen.So,ifyouhaveabytevariablewith255initandyouadd1toit,youget0.Morealarmingly, ifyouhavean intvariablewith32767andyouadd1 to it,youwillendupwith−32768.

Until you are completely comfortable with these different data types, I wouldrecommendstickingtoint,asitworksforprettymucheverything.

CodingStyle

TheCcompilerdoesnotreallycareabouthowyoulayoutyourcode.Forallitcares,youcanwriteeverythingonasinglelinewithsemicolonsbetweeneachstatement.However,well-laid-out,neatcodeismucheasiertoreadandmaintainthanpoorlylaid-outcode.Inthissense,readingcodeisjustlikereadingabook:Formattingisimportant.

Tosomeextent,formattingisamatterofpersonal taste.Noonelikesto thinkthathehasbad taste, soargumentsabouthowcode should lookcanbecomepersonal. It isnotunknownforprogrammers,onbeingrequiredtodosomethingwithsomeoneelse’scode,tostartbyreformattingallthecodeintotheirpreferredstyleofpresentation.

Page 72: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

As an answer to this problem, coding standards are often laid down to encourageeveryone to lay out his or her code in the sameway and adopt “good practice” whenwritingprograms.

TheClanguagehasadefactostandardthathasevolvedovertheyears,andthisbookisgenerallyfaithfultothatstandard.

Indentation

Intheexamplesketchesthatyouhaveseen,youcanseethatweoftenindenttheprogramcode from the left margin. So, for example when defining a void function, the voidkeywordisattheleftmargin,asistheopeningcurlybraceonthenextline,butthenallthetextwithinthecurlybracesisindented.Theamountofindentationdoesnotreallymatter.Somepeopleusetwospaces,somefour.YoucanalsopressTabtoindent.Inthisbook,weusetwospacesforindentation.

If youwere tohave an if statement inside a functiondefinition, thenonce againyouwouldaddtwomorespacesforthelineswithinthecurlybracesoftheifcommand,asinthefollowingexample:

Youmight includeanother if inside the first if,whichwouldaddyetanother levelof

indentation,makingsixspacesfromtheleftmargin.

Allofthismightsoundabittrivial,butifyoueversortthroughsomeoneelse’sbadlyformattedsketches,youwillfinditverydifficult.

OpeningBraces

There are two schools of thought as towhere to put the first curly brace in a functiondefinition,ifstatement,orforloop.Onewayistoplacethecurlybraceonthelineaftertherestofthecommand,aswehaveinalltheexamplessofar,orputitonthesameline,likethis:

Page 73: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ThisstyleismostcommonlyusedintheJavaprogramminglanguage,whichsharesmuchof the same syntax as C. I prefer the first form, which seems to be the form mostcommonlyusedintheArduinoworld.

Whitespace

The compiler ignores spaces tabs and new lines, apart from using them as a way ofseparatingthe“tokens”orwordsinyoursketch.Thusthefollowingexamplewillcompilewithoutaproblem:

Thiswillwork,butgoodlucktryingtoreadit.

Whereassignmentsaremade,somepeoplewillwritethefollowing:

Butotherswillwritethefollowing:

Which of these two styles you use really does not matter, but it is a good idea to beconsistent.Iusethefirstform.

Comments

Commentsare text that iskept inyoursketchalongwithall the realprogramcode,butwhich actually performs no programming function whatsoever. The sole purpose ofcomments is tobea reminder toyouorothersas towhy thecode iswrittenas it is.Acommentlinemayalsobeusedtopresentatitle.

Thecompilerwillcompletely ignoreanytext that ismarkedasbeingacomment.Wehaveincludedcommentsastitlesatthetopofmanyofthesketchesinthebooksofar.

Therearetwoformsofsyntaxforcomments:

Page 74: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

•Thesinglelinecommentthatstartswith//andfinishesattheendoftheline

•Themultilinecommentthatstartswitha/*andendswitha*/

Thefollowingisanexampleusingbothformsofcomments:

Inthisbook,Imostlysticktothesingle-linecommentformat.

Goodcommentshelpexplainwhat ishappeninginasketchorhowtousethesketch.Theyareusefulifothersaregoingtouseyoursketch,butequallyusefultoyourselfwhenyouarelookingatasketchthatyouhavenotworkedonforafewweeks.

Somepeoplearetoldinprogrammingcoursesthatthemorecomments,thebetter.Mostseasonedprogrammerswilltellyouthatwell-writtencoderequiresverylittleinthewayofcommentsbecause it is self-explanatory.Youshouldusecomments for the followingreasons:

•Toexplainanythingyouhavedonethatisalittletrickyornotimmediatelyobvious

• To describe anything that the user needs to do that is not part of the program; forexample,//thispinshouldbeconnectedtothetransistorcontrollingtherelay

•Toleaveyourselfnotes;forexample,//todo:tidythis-it’samess

Thislastpointillustratesausefultechniqueoftodosincomments.Programmersoftenputtodosintheircodetoremindthemselvesofsomethingtheyneedtodolater.Theycanalwaysusethesearchfacilityintheir integrateddevelopmentenvironment(IDE)tofindalloccurrencesof//todointheirprogram.

Thefollowingarenotgoodexamplesofreasonsyoushouldusecomments:

•Tostatetheblatantlyobvious;forexample,a=a+1;//add1toa.

• To explain badlywritten code. Don’t comment on it; just write it clearly in the firstplace.

Conclusion

Thishasbeenabit of a theoretical chapter.Youhavehad to absorb somenewabstract

Page 75: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

concepts concernedwith organizing our sketches into functions and adopting a style ofprogrammingthatwillsaveyoutimeinthelongrun.

Inthenextchapter,youcanstarttoapplysomeofwhatyouhavelearnedandlookatbetterwaysofstructuringyourdataandusingtextstrings.

Page 76: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 77: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

5ArraysandStrings

AfterreadingChapter4,youhaveareasonableappreciationastohowtostructureyoursketchestomakeyourlifeeasier.Ifthereisonethingthatagoodprogrammerlikes,it’saneasylife.Nowourattentionisgoingtoturntothedatathatyouuseinyoursketches.

ThebookAlgorithms+DataStructures=ProgramsbyNiklausWirthhasbeenaround

foragoodwhilenow,butstillmanagestocapturetheessencesofcomputerscienceandprogramminginparticular.Icanstronglyrecommendit toanyonewhofindsthemselvesbittenbytheprogrammingbug.Italsocapturestheideathattowriteagoodprogram,youneedtothinkaboutboththealgorithm(whatyoudo)andthestructureofthedatayouuse.

Youhave looked at loops, if statements, andwhat is called the “algorithmic” side ofprogramminganArduino;youarenowgoingtoturntohowyoustructureyourdata.

Arrays

Arraysareawayofcontainingalistofvalues.Thevariablesthatyouhavemetsofarhavecontained only a single value, usually an int. By contrast, an array contains a list ofvalues,andyoucanaccessanyoneofthosevaluesbyitspositioninthelist.

C,incommonwiththemajorityofprogramminglanguages,beginsitsindexpositionsat0ratherthan1.Thismeansthatthefirstelementisactuallyelementzero.

Toillustrate theuseofarrays,wecouldcreateanexampleapplication that repeatedlyflashes“SOS”inMorsecodeusingtheArduinoboard’sbuilt-inLED.

Morsecodeusedtobeavitalmethodofcommunicationinthe19thand20thcenturies.Becauseofitscodingoflettersasaseriesoflongandshortdots,Morsecodecanbesentovertelegraphwires,overaradiolink,andusingsignalinglights.Theletters“SOS”(anacronymfor“saveoursouls”)isstillrecognizedasaninternationalsignalofdistress.

The letter “S” is represented as three short flashes (dots) and the letter “O” by threelongflashes(dashes).Youaregoingtouseanarrayof ints toholdthedurationofeachflashthatyouaregoingtomake.Youcanthenuseaforlooptostepthrougheachoftheitemsinthearray,makingaflashoftheappropriateduration.

First let’shave a lookat howyouaregoing to create an arrayof ints containing thedurations.

Youindicatethatavariablecontainsanarraybyplacing[]afterthevariablename.

Page 78: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Inthiscase,youaregoingtosetthevaluesforthedurationsatthetimethatyoucreatethearray.Thesyntaxfordoingthisistousecurlybracesandthenvalueseachseparatedbycommas.Don’tforgetthesemicolonontheendoftheline.

Youcanaccessanygivenelementofthearrayusingthesquarebracketnotation.So,ifyouwanttogetthefirstelementofthearray,youcanwritethefollowing:

To illustrate this, let’s create an array and then print out all its values to the Serial

Monitor:

UploadthesketchtoyourboardandthenopentheSerialMonitor.Ifalliswell,youwill

seesomethinglikeFigure5-1.

This is quite neat, because if youwanted to addmore durations to the array, all youwouldneedtodoisaddthemtothelistinsidethecurlybracesandchange“9”intheforlooptothenewsizeofthearray.

Page 79: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure5-1TheSerialMonitorShowingtheOutputofSketch5-01

Youhave tobea littlecarefulwitharrays,because thecompilerwillnot tryandstop

youfromaccessingelementsofdatathatarebeyondtheendofthearray.Thisisbecausethearrayisreallyapointertoanaddressinmemory,asshowninFigure5-2.

Programs keep their data, both ordinary variables and arrays, inmemory. Computermemory isarrangedmuchmore rigidly than thehumankindofmemory. It iseasiest tothinkof thememory inanArduinoasacollectionofpigeonholes.Whenyoudefineanarrayofnineelements,forexample,thenextavailableninepigeonholesarereservedforitsuseandthevariableissaidtopointatthefirstpigeonholeorelementofthearray.

Goingbacktoourpointaboutaccessbeingallowedbeyondtheboundsofyourarray,ifyoudecidedtoaccessdurations[10],thenyouwouldstillMemorygetbackanint,butthevalue of this int could be anything. This is in itself fairly harmless, except that if youaccidentallygetavalueoutsideofthearray,youarelikelytogetconfusingresultsinyoursketch.

Page 80: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure5-2ArraysandPointers

However,what is farworse is if you try changing a value outside of the size of the

array.Forinstance,ifyouweretoincludesomethinglikethefollowinginyourprogram,theresultscouldsimplymakeyoursketchbreak:

Thepigeonholedurations[10]maybeinuseassomecompletelydifferentvariable.So

alwaysmakesurethatyoudonotgooutsideofthesizeofthearray.Ifyoursketchstartsbehavingstrangely,thencheckforthiskindofproblem.

MorseCodeSOSUsingArrays

Sketch5-02showshowyoucanuseanarraytomakeyouremergencysignalofSOS:

Page 81: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Anobviousadvantageofthisapproachisthatitisveryeasytochangethemessageby

simplyalteringthedurationsarray.Insketch5-05,youwilltaketheuseofarraysastagefurthertomakeamoregeneral-purposeMorsecodeflasher.

StringArrays

Intheprogrammingworld,thewordstringhasnothingtodowithlongthinstuffthatyoutieknotsin.Astringisasequenceofcharacters.It’sthewayyoucangetyourArduinotodealwith text.Forexample, thesketch5-03will repeatedlysendthe text“Hello” to theSerialMonitoronetimepersecond:

StringLiterals

Page 82: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Stringliteralsareenclosedindoublequotationmarks.Theyareliteralinthesensethatthestringisaconstant,ratherliketheint123.

Asyouwouldexpect,youcanputstringsinavariable.Thereisalsoanadvancedstringlibrary,butfornowyouwillusestandardCstrings,suchastheoneinsketch5-03.

InC,astringliteralisactuallyanarrayofthetypechar.Thetypecharisabitlikeintinthatitisanumber,butthatnumberisbetween0and127andrepresentsonecharacter.Thecharactermaybealetterofthealphabet,anumber,apunctuationmark,oraspecialcharactersuchasataboralinefeed.ThesenumbercodesforlettersuseastandardcalledASCII;SomeofthemostcommonlyusedASCIIcodesareshowninTable5-1.

Table5-1CommonASCIICodes

Thestringliteral“Hello”isactuallyanarrayofcharacters,asshowninFigure5-3.

Notethatthestringliteralhasaspecialnullcharacterattheend.Thischaracterisusedtoindicatetheendofthestring.

StringVariables

Asyouwouldexpect,stringvariablesareverysimilartoarrayvariables,exceptthatthereisausefulshorthandmethodfordefiningtheirinitialvalue.

Thisdefinesanarrayofcharactersandinitializesittotheword“Hello.”Itwillalsoadd

afinalnullvalue(ASCII0)tomarktheendofthestring.

Figure5-3TheStringLiteral“Hello”

Page 83: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Althoughtheprecedingexampleismostconsistentwithwhatyouknowaboutwriting

arrays,itwouldbemorecommontowritethefollowing:

Thisisequivalent,andthe*indicatesapointer.Theideaisthatnamepointstothefirst

charelementofthechararray.ThatisthememorylocationthatcontainstheletterH.

Youcanrewritesketch5-03touseavariableaswellasastringconstant,asfollows:

AMorseCodeTranslator

Let’sputtogetherwhatyouhavelearnedaboutarraysandstringstobuildamorecomplexsketchthatwillacceptanymessagefromtheSerialMonitorandflashitoutonthebuilt-inLED.

ThelettersinMorsecodeareshowninTable5-2.

SomeoftherulesofMorsecodearethatadashisthreetimesaslongasadot,thetimebetweeneachdashordotisequaltothedurationofadot,thespacebetweentwolettersisthesamelengthasadash,andthespacebetweentwowordsisthesamedurationassevendots.

For this project, we will not worry about punctuation, although it would be aninterestingexerciseforyoutotryaddingthistothesketch.ForafulllistofalltheMorsecharacters,seeen.wikipedia.org/wiki/Morse_code.

Page 84: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Table5-2MorseCodeLetters

Data

Youaregoingtobuildthisexampleastepatatime,startingwiththedatastructurethatyouaregoingtousetorepresentthecodes.

It is important to understand that there is no one solution to this problem.Differentprogrammerswillcomeupwithdifferentwaystosolveit.So,it isamistaketothinktoyourself, “Iwould never have come upwith that.”Well, no, quite possibly youwouldcomeupwithsomethingdifferentandbetter.Everyonethinksindifferentways,andthissolutionhappenstobetheonethatfirstpoppedintotheauthor’shead.

RepresentingthedataisallaboutfindingawayofexpressingTable5-2inC.Infact,youaregoingtosplitthedataintotwotables:onefortheletters,andoneforthenumbers.Thedatastructureforthelettersisasfollows:

Whatyouhavehereisanarrayofstringliterals.So,becauseastringliteralisactually

an array of char,what you actually have here is an array of arrays—something that isperfectlylegalandreallyquiteuseful.

ThismeansthattofindMorseforA,youwouldaccessletters[0],whichwouldgiveyouthestring .-.This approach isnot terriblyefficient,becauseyouareusingawholebyte

Page 85: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

(eightbits)ofmemorytorepresentadashoradot,whichcouldberepresentedinabit.However,youcaneasilyjustifythisapproachbysayingthatthetotalnumberofbytesisstillonlyabout90andwedohave2Ktoplaywith.Equallyimportantly,itmakesthecodeeasytounderstand.

Numbersusethesameapproach:

GlobalsandSetup

Youneedtodefineacoupleofglobalvariables:oneforthedelayperiodforadot,andonetodefinewhichpintheLEDisattachedto:

Thesetupfunctionisprettysimple;youjustneedtosettheledPinasanoutputandset

uptheserialport:

Theloopfunction

Youarenowgoingtostartontherealprocessingworkintheloopfunction.Thealgorithmforthisfunctionisasfollows:

•IfthereisacharactertoreadfromUSB:

•Ifit’saletter,flashitusingthelettersarray

•Ifit’sanumber,flashitusingthenumbersarray

•Ifit’saspace,flashfourtimesthedotdelay

That’sall.Youshouldnotthinktoofarahead.Thisalgorithmrepresentswhatyouwanttodo,orwhatyourintentionis,andthisstyleofprogrammingiscalledprogrammingbyintention.

IfyouwritethisalgorithminC,itwilllooklikethis:

Page 86: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Therearea fewthingshere thatneedexplaining.First, there isSerial.available().To

understandthis,youfirstneedtoknowalittleabouthowanArduinocommunicateswithyourcomputeroverUSB.Figure5-4summarizesthisprocess.

In the situation where the computer is sending data from the Serial Monitor to theArduino board, then theUSB is converted from theUSB signal levels and protocol tosomethingthatthemicrocontrollerontheArduinoboardcanuse.Thisconversionhappensinaspecial-purposechipontheArduinoboard.Thedataisthenreceivedbyapartofthemicrocontroller called the Universal Asynchronous Receiver/Transmitter (UART). TheUARTplacesthedataitreceivesintoabuffer.Thebufferisaspecialareaofmemory(128bytes)thatcanholddatathatisremovedassoonasitisread.

Page 87: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure5-4SerialcommunicationwithanArduino

Thiscommunicationhappensregardlessofwhatyoursketchisdoing.So,eventhough

youmaybemerrilyflashingLEDs,datawillstillarriveinthebufferandsitthereuntilyouarereadytoreadit.Youcanthinkofthebufferasbeingabitlikeane-mailinbox.

The way that you check to see whether you “have mail” is to use the functionSerial.available().Thisfunctionreturnsthenumberofbytesofdatainthebufferthatarewaiting for you to read. If there are nomessageswaiting to be read, then the functionreturns0.This iswhythe if statementchecks tosee that therearemore thanzerobytesavailable to read,and if theyare, then the first thing that the statementdoes is read thenextavailablechar, using the functionSerial.read().This functiongets assigned to thelocalvariablech.

Nextisanotheriftodecidewhatkindofthingitisthatyouwanttoflash:

Atfirst,thismightseemabitstrange.Youareusing<=and>=tocomparecharacters.

You can do that because each character is actually represented by a number (itsASCIIcode).So,ifthecodeforthecharacterissomewherebetweenaandz(97and122),thenyouknowthat thecharacter thathascomefromthecomputer isa lowercase letter.YouthencallafunctionthatyouhavenotwrittenyetcalledflashSequence,towhichyouwillpass a string of dots and dashes; for example, to flash a, you would pass it .- as itsargument.

Youaredevolvingresponsibilitytothisfunctionforactuallydoingtheflashing.Youarenottryingtodoitinsidetheloop.Thisletsuskeepthecodeeasytoread.

HereistheCthatdeterminesthestringofdashesanddotsthatyouneedtosendtotheflashSequencefunction:

Once again, this looks a little strange. The function appears to be subtracting one

character from another. This is actually a perfectly reasonable thing to do, because thefunctionisactuallysubtractingtheASCIIvalues.

Rememberthatyouarestoringthecodesforthelettersinanarray.Sothefirstelementof the array contains a string of dashes and dots for the letter A, the second elementincludesthedotsanddashesforB,andsoon.Soyouneedtofindtherightpositioninthearray for the letter that you have just fetched from the buffer. The position for anylowercaseletterwillbethecharactercodefortheletterminusthecharactercodefora.So,forexample,a–aisactually97–97=0.Similarly,c–aisactually99–97=2.So,in

Page 88: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

thefollowingstatement,ifchistheletterc,thenthebitinsidethesquarebracketswouldevaluateto2,andyouwouldgetelement2fromthearray,whichis-.-:

Whatthissectionhasjustdescribedisconcernedwithlowercaseletters.Youalsohavetodealwithuppercaselettersandnumbers.Thesearebothhandledinasimilarmanner.

TheflashSequenceFunction

WehaveassumedafunctioncalledflashSequenceandmadeuseofit,butnowyouneedtowriteit.Wehaveplannedforittotakeastringcontainingaseriesofdashesanddotsandtomakethenecessaryflasheswiththecorrecttimings.

Thinkingaboutthealgorithmfordoingthis,youcanbreakitintothefollowingsteps:

•Foreachelementofthestringofdashesanddots(suchas.-.-)

• flash that dot or dashUsing the concept of programming by intention, let’s keep thefunctionassimpleasthat.

TheMorsecodesarenotthesamelengthforallletters,soyouneedtolooparoundthestringuntilyouencountertheendmarker,\0.Youalsoneedacountervariablecalledithatstartsat0andisincrementedastheprocessinglooksateachdotanddash:

Again,youdelegatetheactualjobofflashinganindividualdotordashtoanewmethod

called flashDotOrDash, which actually turns the LED on and off. Finally, when theprogramhasflashedthedotsanddashes,itneedstopauseforthreedotsworthofdelay.Notethehelpfuluseofacomment.

TheflashDotOrDashFunction

The last function in your chain of functions is the one that actually does the work ofturning theLEDonandoff.As its argument, the functionhasa singlecharacter that iseitheradot(.)oradash(–).

AllthefunctionneedstodoisturntheLEDonanddelayforthedurationofadotifit’sa dot and three times the duration of a dot if it’s a dash, then turn the LED off again.Finallyitneedstodelayfortheperiodofadot,togivethegapbetweenflashes.

Page 89: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

PuttingItAllTogether

Puttingallthistogether,thefulllistingisshowninsketch5-05.UploadittoyourArduinoboardandtryitout.Rememberthattouseit,youneedtoopentheSerialMonitorandtypesome text into the area at the top and click Send. You should then see that text beingflashedasMorsecode.

Page 90: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Thissketchincludesaloopfunctionthatiscalledautomaticallyandrepeatedlycallsa

flashSequence function that you wrote, which itself repeatedly calls a flashDotOrDashfunctionthatyouwrote,whichcallsdigitalWriteanddelayfunctionsthatareprovidedbyArduino!

Thisishowyoursketchesshouldlook.Breakingthingsupintofunctionsmakesitmucheasiertogetyourcodeworkingandmakesiteasierwhenyoureturntoitafteraperiodofnotusingit.

Page 91: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Conclusion

Inadditiontolookingatstringsandarraysinthischapter,youhavealsobuilt thismorecomplexMorsetranslatorthatIhopewillalsoreinforcetheimportanceofbuildingyourcodewithfunctions.

In the next chapter, you learn about input and output, bywhichwemean input andoutputofanaloganddigitalsignalsfromtheArduino.

Page 92: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 93: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

6InputandOutput

TheArduino is about physical computing, and thatmeans attaching electronics to theArduino board. So you need to understand how to use the various options for yourconnectionpins.

Outputs can be digital,which justmeans switched between being at 0V or at 5V, or

analog,whichallowsyoutosetthevoltagetoanyvoltagebetween0Vand5V—althoughit’snotquiteassimpleasthat,asweshallsee.

Likewise, inputs can either be digital (for example, determining whether a buttonpressedornot)oranalog(suchasfromalightsensor).

Inabookthatisessentiallyaboutsoftwareratherthanhardware,wearegoingtotryandavoidbeingdraggedintotoomuchdiscussionofelectronics.However,itwillhelpyoutounderstandwhatishappeninginthischapterifyoucanfindyourselfamultimeterandashortlengthofsolidcorewire.

DigitalOutputs

In earlier chapters, you have made use of the LED attached to digital pin 13 of theArduino board. For example, in Chapter 5, you used it as aMorse code signaler. TheArduinoboardhasawholeloadofdigitalpinsavailable.

Let’sexperimentwithoneoftheotherpinsontheArduino.Youwillusedigitalpin4,andtoseewhatisgoingon,youwillfixsomewiretoyourmultimeterleadsandattachthemtoyourArduino.Figure6-1showsthearrangement.Ifyourmultimeterhascrocodileclips,striptheinsulationofftheendsofsomeshortlengthsofsolidcorewireandattachthecliptooneend,fittingtheotherendintotheArduinosocket.Ifyourmultimeterdoesnothavecrocodileclipsthenwraponeofthestrippedwireendsaroundtheprobe.

Page 94: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-1Measuringoutputswithamultimeter

Themultimeter needs to be set to its 0–20Vdirect current (DC) range.The negative

lead (black) shouldbe connected to theground (GND)pin and thepositive toD4.ThewireisjustconnectedtotheprobeleadandpokedintothesocketheadersontheArduinoboard.

Loadsketch6-01:

Page 95: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

At the top of the sketch, you can see the command pinMode. You should use this

commandforeverypinthatyouareusinginaprojectsothatArduinocanconfiguretheelectronics connected to that pin to be either an input or an output, as in the followingexample:

Asyoumighthaveguessed,pinModeisabuilt-infunction.Itsfirstargumentisthepin

numberinquestion(anint),andthesecondargumentisthemode,whichmustbeeitherINPUTorOUTPUT.Notethatthemodenamemustbealluppercase.

Thisloopwaitsforacommandofeither1or0tocomefromtheSerialMonitoronyourcomputer.Itit’sa1,thenpin4willbeturnedon;otherwise,itwillbeturnedoff.

UploadthesketchtoyourArduinoandthenopentheSerialMonitor(showninFigure6-2).

So,withthemultimeterturnedonandpluggedintotheArduino,youshouldbeabletoseeitsreadingchangebetween0Vandabout5VasyousendcommandstotheboardfromtheSerialMonitorbyeitherpressing1andthenReturnorpressing0and thenReturn.Figure6-3showsthemultimeterreadingaftera1hasbeensentfromtheSerialMonitor.

Iftherearenotenoughpinslabeled“D”foryourproject,youcanactuallyusethepinslabeled“A”(foranalog)asdigitaloutputstoo.Todothis,youjusthavetoadd14tothe

Page 96: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

analogpinnumber.Youcouldtrythisoutbymodifyingthefirstlineinsketch6-01tousepin14andmovingyourpositivemultimeterleadtopinA0ontheArduino.

Thatisreallyallthereistodigitaloutputs,solet’smoveonswiftlytodigitalinputs.

Figure6-2TheSerialMonitor

Page 97: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-3SettingtheoutputtoHigh

DigitalInputs

Themost common use of digital inputs is to detectwhen a switch has been closed.Adigitalinputcaneitherbeonoroff.Ifthevoltageattheinputislessthan2.5V(halfwayto5V),itwillbe0(off),andifitisabove2.5V,itwillbe1(on).

Disconnectyourmultimeteranduploadthesketch6-02ontoyourArduinoboard:

Aswithusinganoutput,youneedtotelltheArduinointhesetupfunctionthatyouare

goingtouseapinasaninput.YougetthevalueofadigitalinputusingthedigitalReadfunction.Thisreturns0or1.

Pull-upResistors

ThesketchreadstheinputpinandwritesitsvaluetotheSerialMonitoroncepersecond.SouploadthesketchandopentheSerialMonitor.Youshouldseeavalueappearoncepersecond.PushoneendofyourbitofwireintothesocketforD5andpinchtheendofthewirebetweenyourfinger,asshowninFigure6-4.

ContinuepinchingforafewsecondsandwatchthetextappearontheSerialMonitor.YoushouldseeamixtureofonesandzerosappearintheSerialMonitor.ThereasonforthisisthattheinputstotheArduinoboardareverysensitive.Youareactingasanantenna,pickingupelectricalinterference.

Taketheendofthewirethatyouwereholdingandpushitintothesocketfor+5VasshowninFigure6-5.ThestreamoftextintheSerialMonitorshouldchangetoones.

Page 98: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-4Adigitalinputwithahumanantenna

Figure6-5Pin5connectedto+5V

Page 99: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Nowtaketheendthatwasin+5VandputitintooneoftheGNDconnectionsontheArduino.Asyouwouldexpect,theSerialMonitorshouldnowdisplayzeros.

Atypicaluse foran inputpin is toconnectaswitch to it.Figure6-6showshowyoumightbeexpectingtoconnectyourswitch.

The problem with this is that if the switch is not closed, then the input pin is notconnectedtoanything.Itissaidtobefloating,andcouldeasilygiveyouafalsereading.Youneedyourinputtobemorepredictable,andthewaytodothisiswithwhatiscalledapull-upresistor.Figure6-7shows thestandarduseofapull-upresistor. Ithas theeffectthat if the switch is open, then the resistorpulls up the floating input to5V.Whenyoupress the switch and close the contact, the switch overrides the effect of the resistor,forcingtheinputto0V.Oneside-effectof this is,whiletheswitchisclosed,5Vwillbeacrosstheresistor,causingacurrenttoflow.So,thevalueoftheresistorisselectedtobelowenoughtomakeitimmunefromanyelectricalinterference,butatthesametimehighenoughtopreventexcessivecurrentdrainwhentheswitchisclosed.

Figure6-6ConnectingaswitchtoanArduinoboard

Page 100: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-7Switchwithapull-upresistor

InternalPull-upResistors

Fortunately, theArduinoboardhas software-configurablepull-up resistorsbuilt into thedigitalpins.Bydefault, theyare turnedoff.Soallyouneed todo toenable thepull-upresistoronpin5forsketch6-02istoaddthefollowingline:

This linegoes in thesetup function rightafteryoudefine thepinasan input. Itmay

seemalittlestrangetodoadigitalWritetoaninput,butthisisjustthewayitworks.

Sketch 6-03 is themodified version.Upload it to yourArduino board and test it byactinglikeanantennaagain.Youshouldfindthatthistimetheinputstaysat1intheSerialMonitor.

Page 101: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Debouncing

Whenyoupressapushbutton,youwouldexpectthatyouwouldjustgetasinglechangefrom1(withapull-upresistor)to0asthebuttonisdepressed.Figure6-8showswhatcanhappenwhen you press a button. Themetal contacts in the button bounce. So a singlebuttonpressbecomesaseriesofpressesthateventuallystabilize.

Allthishappensveryquickly;thetotaltimespanofthebuttonpressontheoscilloscopetraceisonly200milliseconds.Thisisavery“ropey”oldswitch.Anewtactile,click-typebuttonmaynotevenbounceatall.

Sometimesbouncingdoesnotmatteratall.Forinstance,sketch6-04willlighttheLEDwhile thebutton ispressed. In reality,youwouldnotuseanArduino todo this;wearefirmlyintherealmsoftheoryratherthanpracticehere.

Figure6-8Oscilloscopetraceofabuttonpress

Page 102: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Looking at the loop function of sketch 6-04, the function reads the digital input and

assignsitsvaluetoavariableswitchOpen.Thisisa0ifthebuttonispressedanda1ifitisn’t(rememberthatthepinispulledupto1whenthebuttonisnotpressed).

WhenyouprogramdigitalWrite to turn theLEDonor off, youneed to reverse thisvalue.Youdothisusingthe!ornotoperator.

IfyouuploadthissketchandconnectyourwirebetweenD5andGND(seeFigure6-9),youshouldseetheLEDlight.Bouncingmaybegoingonhere,butitisprobablytoofastforyoutoseeanddoesnotmatter.

One situation where key bouncing wouldmatter is if you weremaking your switchtoggletheLEDonandoff.Thatis,ifyoupressthebutton,theLEDcomesonandstayson,andwhenyoupress thebuttonagain, it turnsoff. Ifyouhadabutton thatbounced,thenwhethertheLEDwasonoroffwouldjustdependonwhetheryouhadanoddorevennumberofbounces.

Sketch6-05justtogglestheLEDwithoutanyattemptat“debouncing.”TryitoutusingyourwireasaswitchbetweenpinD5andGND:

Page 103: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

YouwillprobablyfindthatsometimestheLEDtoggles,butothertimesitappearsnotto

toggle.Thisisbouncinginaction!

Asimplewaytotacklethisproblemissimplytoaddadelayafteryoudetectthefirstbuttonpress,asshowninsketch6-06:

Page 104: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-9Usingawireasaswitch

Byputtingadelayhere,nothingelsecanhappenfor500milliseconds,bywhichtime

anybouncingwillhavesubsided.Youshouldfindthatthismakesthetogglingmuchmorereliable.Aninterestingside-effectisthatifyouholdthebuttondown,theLEDjustkeepsflashing.

Ifthatisallthereistothesketch,thenthisdelayisnotaproblem.However,ifyoudomoreintheloop,thenusingadelaycanbeaproblem;forexample,theprogramwouldbeunabletodetectthepressofanyotherbuttonduringthat500milliseconds.

So, this approach is sometimes not good enough and youwill need to be a bitmoresophisticated.Youcanwriteyourownadvanceddebouncingcodebyhand,butdoingsogetscomplicatedandfortunatelysomefinefolkshavedonealltheworkforyou.

Page 105: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-10AddingtheBouncelibraryinWindows

Afterdownloadingthefile,unzipitandplacetheunzippedfolder,calledBounce,into

thelibrariessubfolderinthefolderwhereallyoursketchesaresaved.OnWindows,thisfolder isMyDocuments\Arduino, and onMac and Linux, it is Documents/Arduino. Ifthere is no libraries subfolder, then youwill need to create one. Figure6-10 shows thefolderstructureinWindowsafteralibraryhasbeenadded.

Afteraddingthelibrary,youneedtorestarttheArduinoapplicationforthechangestotakeeffect.Onceyoudoso,youcanusetheBouncelibraryinanysketchesthatyouwrite.

Sketch6-07showshowyoucanusetheBouncelibrary.UploadittoyourboardandseehowreliabletheLEDtogglinghasbecome.

Page 106: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Using the library is pretty straightforward.The first thing that youwill notice is this

line:

ThisisnecessarytotellthecompilertousetheBouncelibrary.

Youthenhavethefollowingline:

Donotworryaboutthesyntaxofthislineatthemoment;itisactuallyC++ratherthanCsyntax,andyouwillnotbemeetingC++untilChapter11.Fornow,youwilljusthavetobe content to know that this sets up a bouncer object for the pin specified, with adebounceperiodof5milliseconds.

Fromnowon,youusethatbouncerobjecttofindoutwhatthekeyisdoingratherthanreading the digital input directly. It has put a kind of debouncingwrapper around yourinputpin.So,decidingwhetherabuttonhasbeenpressediswrappedupinthisline:

ThefunctionupdatereturnstrueifsomethinghaschangedwiththebouncerobjectandthesecondpartoftheconditioncheckswhetherthebuttonwentLOW.

Page 107: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

AnalogOutputs

Afewofthedigitalpins—namelydigitalpins3,5,6,9,10,and11—canprovidevariableoutputotherthanjust5Vornothing.Thesearethepinsontheboardwitha~or“PWM”next to them. PWM stands for PulseWidthModulation, which refers to the means ofcontrollingtheamountofpowerattheoutput.Itdoessobyrapidlyturningtheoutputonandoff.

The pulses are always delivered at the same rate (roughly 500 per second), but thelength of the pulses is varied. If youwere to use PWM to control the brightness of anLED, then if thepulsewere long,yourLEDwouldbeonall the time. If, however, thepulses are short, then theLED is actually lit only for a small portion of the time.ThishappenstoofastfortheobservereventotellthattheLEDisflickering,anditjustappearsthattheLEDislighterordimmer.

Before you try using an LED, you can test this out with your multimeter. Set themultimeteruptomeasurethevoltagebetweenGNDandpinD3(seeFigure6-11).

Nowuploadsketch6-08toyourboardandopentheSerialMonitor(seeFigure6-12).Enter thesingledigit3andpressReturn.Youshouldseeyourvoltmeter registerabout3V.Youcanthentryanyothernumberbetween0and5.

Page 108: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure6-11Measuringtheanalogoutput

Figure6-12Settingthevoltageatananalogoutput

TheprogramdeterminesthevalueofPWMoutputbetween0and255bymultiplying

Page 109: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

thedesiredvoltage (0 to5)by51. (Readersmaywish to refer toWikipedia fora fullerdescriptionofPWM.)

YoucansetthevalueoftheoutputbyusingthefunctionanalogWrite,whichrequiresanoutputvaluebetween0and255,where0isoffand255isfullpower.ThisisactuallyagreatwaytocontrolthebrightnessofanLED.Ifyouweretotrytocontrolthebrightnessbyvaryingthevoltageacross theLED,youwouldfindthatnothingwouldhappenuntilyougottoabout2V;thentheLEDwouldveryquicklygetquitebright.BycontrollingthebrightnessusingPWMandvaryingtheaverageamountof timethat theLEDison,youachievemuchmorelinearcontrolofthebrightness.

AnalogInput

Digitalinputsjustgiveyouanon/offanswerastowhatishappeningataparticularpinonthe Arduino board. Analog inputs, however, give you a value between 0 and 1023dependingonthevoltageattheanaloginputpin.

The program reads the analog input using the analogRead function. Sketch 6-09displays thereadingandactualvoltageat theanalogpinA0in theSerialMonitoreveryhalfsecond,soopentheSerialMonitorandwatchthereadingsappear.

Whenyourunthissketch,youwillnoticethatthereadingschangequiteabit.Aswith

thedigitalinputs,thisisbecausetheinputisfloating.

TakeoneendofthewireandputitintoaGNDsocketsothatA0isconnectedtoGND.Yourreadingsshouldnowstayat0.MovetheendoftheleadthatwasinGNDandputitinto5Vandyoushouldgetareadingofaround1023,whichisthemaximumreading.So,if youwere to connectA0 to the 3.3V socket on theArduino board, theArduino volt

Page 110: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

metershouldtellyouthatyouhaveabout3.3V.

Conclusion

ThisconcludesourchapteronthebasicsofgettingsignalsintoandoutoftheArduino.Inthenextchapter,wewill lookat someof the featuresprovided in the standardArduinolibrary.

Page 111: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 112: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

7TheStandardArduinoLibrary

This library is where all the goodies live. You can only get so far with the core Clanguage;whatyoureallyneed isabigcollectionof functions thatyoucanuse inyoursketches.

You have already met a fair few of these, such as pinMode, digitalWrite, and

analogWrite.Butactually,therearemanymore.Therearefunctionsthatyoucanusefordoingmath,makingrandomnumbers,manipulatingbits,detectingpulsesonaninputpin,andusingsomethingcalledinterrupts.

TheArduinolanguageisbasedonanearlierlibrarycalledWiringanditcomplementsanotherlibrarycalledProcessing.TheProcessinglibraryisverysimilartoWiring,butitisbasedontheJavalanguageratherthanCandisusedonyourcomputertolinktoAndroidoverUSB. In fact, theArduino application that you run on your computer is based onProcessing.IfyoufindyourselfwantingtowritesomefancyinterfaceonyourcomputertotalktoanArduino,thentakealookatProcessing(www.processing.org).

RandomNumbers

Despite the experience of anyone using a PC, computers are in actual fact verypredictable. Occasionally it is useful to be able to deliberately make your Arduinounpredictable.Forexample,youmightwanttomakearobottakea“random”patharoundaroom,headingforarandomamountoftimeinonedirection,turningarandomnumberof degrees, and then setting off again. Or, you might be contemplating making anArduino-baseddiethatgivesyouarandomnumberbetweenoneandsix.

The Arduino standard library provides you with a feature to do just this. It is thefunction calledrandom.random returns an int and it can take either one argument ortwo.Ifitjusttakesoneargument,thenitwillreturnarandomnumberbetweenzeroandtheargumentminusone.

The two argument version produces a random number between the first argument(inclusive)andthesecondargumentminusone.Thusrandom(1,10)producesarandomnumberbetweenoneandnine.

Sketch7-01pumpsoutnumbersbetweenoneandsixtotheSerialMonitor.

Page 113: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

If you upload this sketch to yourArduino and open theSerialMonitor, youwill see

somethinglikeFigure7-1.

Ifyourunthisafewtimesyouwillprobablybesurprisedtoseethat,everytimeyourunthesketch,yougetthesameseriesof‘random’numbers.

The output is not really random; the numbers are called pseudo-random numbersbecause theyhave a randomdistribution.That is, if you ran this sketch andcollected amillionnumbers,youwouldgetprettymuchthesamenumberofones,twos,threes,andsoon.Thenumbersarenot randomin thesenseofbeingunpredictable. In fact, it is soagainsttheworkingsofamicrocontrollertoberandomthatitjustplaincan’tdoitwithoutsomeinterventionfromtherealworld.

Figure7-1Randomnumbers

Youcanprovidethisinterventiontomakeyoursequenceofnumberslesspredictableby

seeding therandomnumbergenerator.Thisbasicallyjustgivesitastartingpointforthesequence. But, if you think about it, you cannot just use random to seed the randomnumber generator. A commonly used trick is to use the fact that (as discussed in thepreviouschapter)ananaloginputwillfloat.Soyoucanusethevaluereadfromananaloginputtoseedtherandomnumbergenerator.

ThefunctionthatdoesthisiscalledrandomSeed.Sketch7-02showshowyoucanadd

Page 114: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

abitmorerandomnesstoyourrandomnumbergenerator.

Try pressing the Reset button a few times. You should now see that your random

sequenceisdifferenteverytime.

Thistypeofrandomnumbergenerationcouldnotbeusedforanykindoflottery.Formuch better random number generation, you would need hardware random numbergeneration,whichissometimesbasedonrandomevents,suchascosmicrayevents.

MathFunctions

Onrareoccasions,youwillneedtodoalotofmathonanArduino,overandabovetheodd bit of arithmetic.But, should you need to, there is a big library ofmath functionsavailable to you. The most useful of these functions are summarized in the followingtable:

Page 115: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

BitManipulation

A bit is a single digit of binary information, that is, either 0 or 1. The word bit is acontractionofbinarydigit.Mostofthetime,youuseintvariablesthatactuallycomprise16bitsThisisabitwastefulifyouonlyneedtostoreasimpletrue/falsevalue(1or0).Actually,unlessyouarerunningshortofmemory,beingwastefulislessofaproblemthancreatingdifficult-to-understand code, but sometimes it is useful tobe able topackyourdatatightly.

Eachbit inthe intcanbe thoughtofashavingadecimalvalue,andyoucanfindthedecimalvalueoftheintbyaddingupthevaluesofallthebitsthatarea1.SoinFigure7-2, thedecimalvalueof the intwouldbe38.Actually, it getsmore complicated to dealwithnegativenumbers,butthatonlyhappenswhentheleftmostbitbecomesa1.

Whenyouare thinkingabout individualbits, decimalvaluesdonot reallyworkverywell.It isverydifficult tovisualizewhichbitsaresetinadecimalnumbersuchas123.For that reason, programmers often use something called hexadecimal, or, morecommonly,justhex.Hexisnumberbase16.Soinsteadofhavingdigits0to9,youhavesixextradigits,AtoF.Thismeansthateachhexdigitrepresentsfourbits.Thefollowingtableshowstherelationshipamongdecimal,hex,andbinarywiththenumbers0to15:

Page 116: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

So, in hex, any int can be represented as a four-digit hex number. Thus, the binary

number10001100wouldinhexbe8C.TheClanguagehasaspecialsyntaxforusinghexnumbers.Youcanassignahexvaluetoanintasfollows:

TheArduino standard libraryprovides some functions that let youmanipulate the16

bitswithinanintindividually.ThefunctionbitReadreturnsthevalueofaparticularbitinanint;so,forthefollowingexamplewouldassignthevalue0tothevariablecalledbit:

Inthesecondargument,thebitpositionstartsat0andgoesupto15.Itstartswiththeleastsignificantbit.Sotherightmostbitisbit0,thenextbittotheleftisbit1,andsoon.

As you would expect, the counterpart to bitRead is bitWrite, which takes threearguments.Thefirst is thenumber tomanipulate, thesecond is thebitposition,and thethirdisthebitvalue.Thefollowingexamplechangesthevalueoftheintfrom2to3(indecimalorhex):

Page 117: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure7-2Anint

AdvancedI/O

There are some useful little functions that you can use to make your life easier whenperformingvariousinput/outputtasks.

GeneratingTones

Thetonefunctionallowsyoutogenerateasquare-wavesignal(seeFigure7-3)ononeofthedigitaloutputpins.Themostcommonreasontodothisistogenerateanaudibletoneusingaloudspeakerorbuzzer.

Thefunctiontakeseithertwoorthreearguments.Thefirstargumentisalwaysthepinnumberonwhichthetoneistobegenerated,thesecondargumentisthefrequencyofthetone in hertz (Hz), and the optional final argument is the duration of the tone. If noduration is specified, then the tone will continue playing indefinitely, as is the case insketch7-03.This iswhywehaveput the tone functioncall insetup rather than in theloopfunction.

Figure7-3Asquare-wavesignal

Page 118: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Tostopatonethatisplaying,youusethefunctionnoTone.Thisfunctionhasjustone

argument,whichisthepinonwhichthetoneisplaying.

FeedingShiftRegisters

SometimestheArduinoUnojustdoesn’thaveenoughpins.WhendrivingalargenumberofLEDs,forexample,acommontechniqueistouseashiftregisterchip.Thischipreadsdataonebitatatime,andthenwhenithasenough,itlatchesallthosebitsontoasetofoutputs(oneperbit).

Tohelpyouusethistechnique,thereisahandyfunctioncalledshift-Out.Thisfunctiontakesfourarguments:

•Thenumberofthepinonwhichthebittobesentwillappear.

•Thenumberofthepintobeusedasaclockpin.Thistoggleseverytimeabitissent.

•Aflagtodeterminewhetherthebitswillbesentstartingwiththeleastsignificantbitorthemostsignificant.ThisshouldbeoneoftheconstantsMSBFIRSTorLSBFIRST.

•Thebyteofdatatobesent.

Interrupts

Oneofthethingsthattendtofrustrateprogrammersusedto“programminginthelarge”isthat theArduino candoonlyone thing at a time. If you like tohave lots of threadsofexecution all running at the same time in your programs, then you are out of luck.Althoughafewpeoplehavedevelopedprojects thatcanexecutemultiple threads in thisway, generally this capability is unnecessary for the type of uses that an Arduino isnormallyputto.TheclosestanArduinogetstosuchexecutionistheuseofinterrupts.

TwoofthepinsontheArduino(D2andD3)canhaveinterruptsattachedtothem.Thatis, these pins act as inputs that, if the pins receive a signal in a specified way, theArduino’sprocessorwillsuspendwhateveritwasdoingandrunafunctionattachedtothatinterrupt.

Sketch 7-04 blinks an LED, but then changes the blink period when an interrupt isreceived.YoucansimulateaninterruptbyconnectingyourwirebetweenpinD2andGNDandusingtheinternalpull-upresistortokeeptheinterrupthighmostofthetime.

Page 119: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Thefollowingisthekeylineinthesetupfunctionofthissketch:

Figure7-4Typesofinterruptsignals

The first argument specifies which of the two interrupts you want to use. Rather

confusingly,a0heremeansyouareusingpin2,whilea1meansyouareusingpin3.

Page 120: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

The next argument is the name of the function that is to be calledwhen there is aninterrupt,andthefinalargumentisaconstantthatwillbeoneofCHANGE,RISING,orFALLING.Figure7-4summarizestheseoptions.

If the interruptmode isCHANGE, theneitheraRISINGfrom0 to1oraFALLINGfrom1to0willbothtriggeraninterrupt.

You can disable interrupts using the functionnoInterrupts. This stops all interruptsfrom both interrupt channels. You can resume using interrupts again by calling thefunctioninterrupts.

Conclusion

Inthischapter,youhavelookedatsomeofthehandyfeaturesthattheArduinostandardlibraryprovides.These featureswill saveyou someprogramming effort, and if there isonethingthatagoodprogrammerlikes,itisbeingabletousehigh-qualityworkdonebyotherpeople.

Inthenextchapter,wewillextendwhatwelearnedaboutdatastructuresinChapter5andlookathowyougoaboutrememberingdataontheArduinoafterthepowergoesoff.

Page 121: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 122: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

8DataStorage

Whenyougivevaluestovariables,theArduinoboardwillrememberthosevaluesonlyaslongasthepowerison.Themomentthatyouturnthepowerofforresettheboard,allthatdataislost.

Inthischapter,welookatsomewaystohangontothatdata.

Constants

Ifthedatathatyouwanttostoredoesnotchange,thenyoucanjustsetthedataupeachtimethattheArduinostarts.AnexampleofthisapproachisthecaseinthelettersarrayinyourMorsecodetranslatorofChapter5(sketch5-05).

Youusedthefollowingcodetodefineavariableofthecorrectsizeandfillitwiththedatathatyouneeded:

Youmayrememberthatyoudidthecalculationanddecidedthatyouhadplentyofyour

meager2Ktospare.However,ifmemorywasabittight,itwouldbefarbettertobeabletostorethisdatainthe32Kofflashmemoryusedtostoreprograms,ratherthanthe2KofRAM.There is ameansofdoing this. It is adirectivecalledPROGMEN; it lives in alibraryandisabitawkwardtouse.

ThePROGMEMDirective

To store your data in flash memory, you have to include the PROGMEM library asfollows:

Page 123: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Thepurposeofthiscommandistotellthecompilertousethepgmspacelibraryforthissketch.Inthiscase,alibraryisasetoffunctionsthatsomeoneelsehaswrittenandthatyou can use in your sketcheswithout having to understand all the details of how thosefunctionswork.

Becauseyouareusingthislibrary,thePROGMEMkeywordandthepgm_read_wordfunctionareavailable.Youwillusebothinthesketchesthatfollow.

This library is includedaspartof theArduinosoftwareand isanofficiallysupportedArduino library. A good collection of such official libraries is available, and manyunofficial libraries, developed by people like you andmade for others to use, are alsoavailable on the Internet. Such unofficial libraries must be installed into your Arduinoenvironment.Youwilllearnmoreabouttheselibraries,aswellashowtowriteyourownlibraries,inChapter11.

WhenusingPROGMEM,youhave tomakesure thatyouusespecialPROGMEM-friendly data types. Unfortunately, that does not include an array of char arrays. YouactuallyhavetodefineavariableforeachstringusingaPROGMEMstringtypeandthenputthemallinaPROGMEMarraytype,likethis:

Ihavenotlistedsketch8-01here,asit isalittlelengthy,butyoumaywishtoloadit

andverifythatitworksthesamewayastheRAM-basedversion.

Inadditiontocreatingthedatainaspecialway,youalsohavetoreadthedatabackaspecialway.YourcodetogetthecodestringforaMorseletterfromthearrayhastobemodifiedtolooklikethis:

ThisusesabuffervariableintowhichthePROGMEMstringiscopied,sothatitcan

beusedasaregularchararray.Thisneedstobedefinedasaglobalvariableasfollows:

Thisapproachworksonlyifthedataisconstant—thatis,youarenotgoingtochangeit

whilethesketchisrunning.Inthenextsection,youwilllearnaboutusingtheEEPROMmemorythatisintendedforstoringpersistentdatathatcanbechanged.

EEPROM

Page 124: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

TheATMega328 at the heart of anArduinoUno has a kilobyte of electrically erasableread-onlymemory(EEPROM).EEPROMisdesignedtorememberitscontentsformanyyears.Despiteitsname,itisnotreallyread-only.Youcanwritetoit.

TheArduinocommandsforreadingandwritingtoEEPROMarejustasawkwardtouseastheonesforusingPROGMEM.YouhavetoreadandwritetoandfromEEPROMonebyteatatime.

Theexampleofsketch8-02allowsyoutoenterasingle-digitlettercodefromtheSerialMonitor.The sketch then remembers thedigit and repeatedlywrites itouton theSerialMonitor.

Totrythissketch,opentheSerialMonitorandenteranewcharacter.Thenunplugthe

Arduinoandplug itback in.Whenyoureopen theSerialMonitor,youwillsee that theletterhasbeenremembered.

ThefunctionEEPROM.write takes twoarguments.The first is theaddress,which isthe memory location in EEPROM and should be between 0 and 1023. The secondargument is thedata towriteat that location.Thismustbeasinglebyte.Acharacter isrepresentedaseightbits,sothisisfine,butyoucannotdirectlystorea16-bitint.

StoringanintinEEPROM

Tostoreatwo-byteintinlocations0and1oftheEEPROM,youwouldhavetodothis:

Page 125: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

The functionshighByte and lowByte are useful for separating an int into twobytes.

Figure8-1showshowthisintisactuallystoredintheEEPROM.

Figure8-1Storinga16-bitintegerinEEPROM

To read the int back out of EEPROM, you need to read the two bytes from the

EEPROMandreconstructtheint,asfollows:

The<<operatorisabitshiftoperatorthatmovestheeighthighbytestothetopofthe

intandthenaddsinthelowbyte.

StoringafloatinEEPROM(Unions)

StoringafloatinEEPROMisalittlemoretricky.Todothis,youcanuseafeatureofCcalledunions.Thesedatastructuresareinterestinginthattheycanbethoughtofasawaytomake the same area ofmemory accessible tomore thanonevariable.What ismore,thesevariablesareallowed tobeofdifferent typesas longas theyare the samesize inbytes.

Thefollowinguniondefinitionallowsbothafloatandaninttorefertothesametwobytesofmemory:

Page 126: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Youcanthenputafloatintotheunionasfollows:

ThenyoucanseparateanintegerintoitstwobytesforstorageinEEPROMasfollows:

Readingthefloatbackoutagainrequiresyoutodothereverse.Firstyouassemblethe

twobytesintoasingleint, thenyouputtheintintotheunionandpull itoutagainasafloat.

StoringaStringinEEPROM

Writing and reading character strings into theEEPROMare pretty straightforward; youjusthavetowriteeachcharacteratatime,asinthefollowingexample:

Toreadthestringbackintoacharacterarray,youcandosomethinglikethis:

ClearingtheContentsofEEPROM

Page 127: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

WhenwritingtoEEPROM,rememberthatevenuploadinganewsketchwillnotcleartheEEPROM,soyoumayhaveleftovervaluesintherefromapreviousproject.Sketch8-03resetsallthecontentsofEEPROMtozeros:

Alsobe aware that you canwrite to anEEPROM locationonly about 100,000 times

beforeitwillbecomeunreliable.SoonlywriteavaluebacktoEEPROMwhenyoureallyneedto.EEPROMisalsoquiteslow,takingabout3millisecondstowriteabyte.

Compression

WhensavingdatatoEEPROMorwhenusingPROGMEM,youwillsometimesfindthatyou havemore to save than you have room to save it.When this happens, it is worthfindingthemostefficientwayofrepresentingthedata.

RangeCompression

Youmayhaveavalueforwhichonthefaceofityouneedanintorafloatthatareboth16-bit.Forexample,torepresentatemperatureindegreesCelsius,youmightuseafloatvalue such as 20.25.When you are storing that intoEEPROM, lifewould be somucheasier ifyoucouldfit it intoasinglebyte,andyoucouldstore twiceasmuchas ifyouusedafloat.

Onewaythatyoucandothisistochangethedatabeforeyoustoreit.Rememberthatabytewillallowyoutostoreapositivenumberbetween0and255.Soifyouonlycaredabout the temperature to the nearest degreeCelsius, then you could simply convert thefloattoanintanddiscardthepartafterthedecimalpoint.Thefollowingexampleshowshowtodothis:

Page 128: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ThevariabletempFloatcontainsthefloatingpointvalue.The(int)commandiscalled

atypecastandisusedtoconvertavariablefromonetypetoanothercompatibletype.Inthiscase,thetypecastconvertsthefloatof(forexample)20.25toanintthatwillsimplytruncatethenumberto20.

Ifyouknowthatthehighesttemperaturethatyoucareaboutis60degreesCelsiusandthat the lowest is 0 degrees Celsius, then you could multiply every temperature by 4before converting it to a byte and saving it. Then when you read the data back fromEEPROM,youcandivideby4togetavaluethathasaprecisionof0.25ofadegree.

The following code example (sketch 8-04) saves such a temperature into EEPROM,thenreadsitbackanddisplaysitintheSerialMonitorasproof:

Thereareothermeansofcompressingdata.Forinstance,ifyouaretakingreadingsthat

changeslowly—again,changesintemperatureareagoodexampleofthis—thenyoucanrecord the first temperature at full resolution and then just record the changes intemperature from theprevious reading.This changewillgenerallybe small andoccupyfewerbytes.

Conclusion

Younowknowalittleabouthowtomakeyourdatahangaroundafterthepowerhasgoneoff.Inthenextchapter,youwilllookatLCDdisplays.

Page 129: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 130: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

9LCDDisplays

Inthis chapter, you look at how towrite software to controlLCDdisplays. Figure9-1showsthekindofLCDdisplayused.

Thisisabookaboutsoftware,nothardware,butinthischapter,wewillhavetoexplain

a little abouthow the electronicsof thesedisplayswork so thatyouunderstandhow todrivethem.

TheLCDmodulethatweuseisaprebuiltArduinoshieldthatcanjustbepluggedontopofanArduinoboard.Inadditiontoitsdisplay,italsohassomebuttons.Thereareanumberofdifferentshields,butnearlyallofthemusethesameLCDcontrollerchip(theHD44780),solookforashieldthatusesthiscontrollerchip.

I used the DFRobot LCD Keypad Shield for Arduino. This module supplied byDFRobot (www.robotshop.com) is inexpensive and provides an LCD display that is 16charactersby2rowsandalsohassixpushbuttons.

Theshieldcomesassembled,sonosolderingisrequired;youjustplugitontopofyourArduinoboard(seeFigure9-2).

TheLCD shield uses seven of theArduino pins to control theLCDdisplay and oneanalogpinforthebuttons.SowecannotusetheseArduinopinsforanyotherpurpose.

Figure9-1AnAlphanumericLCDshield

Page 131: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure9-2LCDshieldattachedtoanArduinoboard

AUSBMessageBoard

Forasimpleexampleofasimpleuseofthedisplay,wearegoingtomakeaUSBmessageboard.ThiswilldisplaymessagessentfromtheSerialMonitor.

TheArduino IDE comeswith anLCD library. This greatly simplifies the process ofusinganLCDdisplay.Thelibrarygivesyouusefulfunctionsthatyoucancall:

•clearclearsthedisplayofanytext.

•setCursorsetsthepositioninrowandcolumnwherethenextthingthatyouprintwillappear.

•printwritesastringatthatposition.

Thisexampleislistedinsketch9-01:

Page 132: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Aswith allArduino libraries, you have to start by including the library tomake the

compilerawareofit.

ThenextlinedefineswhichArduinopinsareusedbytheshieldandforwhatpurpose.If you are using a different shield, then youmaywell find that the pin allocations aredifferent,socheckinthedocumentationfortheshield.

Inthiscase,thesixpinsusedtocontrolthedisplayareD4,D5,D6,D7,D8,andD9.

Page 133: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ThepurposeofeachofthesepinsisdescribedinTable9-1.

Table9-1LCDshieldpinassignments

Thesetupfunctionisstraightforward.YoustartserialcommunicationssothattheSerial

Monitor can send commands and initialize theLCD librarywith the dimensions of thedisplaybeingused.Youalsodisplaythemessage“ArduinoRules”ontwolinesbysettingthecursortotop-left,printing“Arduino,”thenmovingthecursortothestartofthesecondrowandprinting“Rules.”

Most of the action takes place in the loop function, which checks for any incomingcharactersfromtheSerialMonitor.Thesketchdealswithcharactersoneatatime.

Apart from ordinary characters that the sketch will simply display, there are also acouple of special characters. If the character is a #, then the sketch clears the wholedisplay, and if the character is a /, the sketchmoves to the second line.Otherwise, thesketch simply displays the character at the current cursor position using write. Thefunctionwrite is likeprint, but it prints only a single character rather than a string ofcharacters.

UsingtheDisplay

Tryoutsketch9-01byuploadingittotheboardandthenattachingtheshield.NotethatyoushouldalwaysunplugtheArduinoboardsothatitisoffbeforeyoupluginashield.

OpenuptheSerialMonitorandtrytypinginthetextshowninFigure9-3.

Page 134: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure9-3Sendingcommandstothedisplay

OtherLCDLibraryFunctions

Inadditiontothefunctionsthatyouhaveusedinthisexample,thereareanumberofotherfunctionsthatyoucanuse:

•homeisthesameassetCursor(0,0):itmovesthecursortotop-left.

•cursordisplaysacursor.

•noCursorspecifiesnottodisplayacursor.

•blinkmakesthecursorblink.

•noBlinkstopsthecursorfromblinking.

•noDisplayturnsoffthedisplaywithoutremovingthecontent.

•displayturnsthedisplaybackonafternoDisplay.

•scrollDisplayLeftmovesallthetextonthedisplayonecharacterpositiontotheleft.

•scrollDisplayRightmovesallthetextonthedisplayonecharacterpositiontotheright.

• autoscroll activates amode inwhich, as new characters are added at the cursor, theexisting text is pushed in the direction determined by the functions leftToRight andrightToLeft.

•noAutoscrollturnsautoscrollmodeoff.

Conclusion

Youcanseethatprogrammingshieldsisnothard,particularlywhenthereisalibrarythatcandoalotofthework.

Inthenextchapter,youwilluseanEthernetshieldthatwillallowyoutoconnect the

Page 135: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ArduinototheInternet.

Page 136: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 137: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

10ArduinoEthernetProgramming

Inthischapter,youwilluseanEthernetshieldtoenableyourArduinotoworkoveryourhomenetwork(seeFigure10-1).

Figure10-1ArduinowithEthernet

EthernetShields

When buying an Ethernet shield, you need to take a little care, as you need to use an“official”shieldbasedontheWiznetchipsetandnotoneofthecheaperbutmoredifficulttouseunofficialboardsbasedontheENC28J60Ethernetcontrollerchip.

TheEthernetshieldsarequitepowerhungry,soyouwillalsoneeda9Vor12Vpowersupplyratedat1Aormore.ThissupplywillbeattachedtotheArduinopowersocket.

CommunicatingwithWebServers

BeforelookingathowtheArduinodealswithcommunicationbetweenabrowserandthewebserverthatituses,youneedsomeunderstandingoftheHyperTextTransferProtocol

Page 138: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

(HTTP)andtheHyperTextMarkupLanguage(HTML).

HTTP

TheHyperText Transport Protocol is themethod bywhichweb browsers communicatewithawebserver.

Whenyougotoapageusingawebbrowser,thebrowsersendsarequesttotheserverhosting that page, sayingwhat itwants.What the browser asks formay be simply thecontentsof apage inHTML.Thewebserver is always listening for such requests, andwhenitreceivesone,itprocessesit.Inthissimplecase,processingtherequestjustmeanssendingbackHTMLthatyouhavespecifiedintheArduinosketch.

HTML

TheHyperTextMarkupLanguageisawayofaddingformattingtoordinarytextsothatitlooksgoodwhenthebrowserdisplaysit.Forexample,thefollowingcodeisHTMLthatdisplaysonabrowserpageasshowninFigure10-2:

TheHTMLcontainstags.Tagshaveastartandanendandusuallycontainothertags.

Thestartofataghasa<andthenthetagname,andthena>;forexample,<html>.Theend of a tag is similar except that it has a / after the<. In the preceding example, theoutermost tag is<html> that contains a tab called<body>.Allweb pages should startwithsuchtags,andyoucanseethecorrespondingendsforthosetagsattheendofthefile.Notethatyouhavetoputtheendtagsintherightorder,sothebodytagmustbeclosedbeforethehtmltag.

Nowwegettotheinterestingbitinthemiddle,theh1andptags.Thesearethepartsoftheexamplethatareactuallydisplayed.

Theh1 tag indicatesa level1header.Thishas theeffectofdisplaying the text that itcontains ina largeboldfont.Thep tag isaparagraph tag,andsoall the textcontainedwithinitisdisplayedasaparagraph.

ThisreallyjustscratchesthesurfaceofHTML.ManybooksandInternetresourcesareavailableforlearningaboutHTML.

Page 139: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure10-2AnHTMLexample

ArduinoasaWebServer

ThefirstexamplesketchsimplyusestheArduinoandEthernetshieldtomakeasmallwebserver.It’sdefinitelynotaGoogleserverfarm,butitwillallowyoutosendawebrequesttoyourArduinoandviewtheresultsinabrowseronyourcomputer.

Before uploading the sketch 10–01, there are a couple of changes that you need tomake.Ifyoulookatthetopofthesketch,youwillseethefollowinglines:

Thefirstofthese,themacaddress,mustbeuniqueamongallthedevicesconnectedto

yournetwork.ThesecondoneistheIPaddress.WhereasmostdevicesthatyouconnecttoyourhomenetworkwillhaveIPaddressesassignedto themautomaticallybyaprotocolcalled Dynamic Host Configuration Protocol (DHCP), this is not true for the Ethernetshield.Forthisdevice,youhavetodefineanIPaddressmanually.Thisaddresscannotbeanyfournumbers;theymustbenumbersthatqualifyasbeinginternalIPaddressesandfitin the range of IP addresses expected by your home router. Typically, the first threenumberswillbesomethinglike10.0.1.xor192.168.1.x,wherex isanumberbetween0and255.SomeoftheseIPaddresseswillbeinusebyotherdevicesonyournetwork.Tofind an unused but valid IP address, connect to the administration page for your homerouterandlookforanoptionthatsays“DHCP.”YoushouldfindalistofdevicesandtheirIPaddresses,similartothatshowninFigure10-3.SelectafinalnumbertouseinyouIPaddress.Inthiscase,192.168.1.30lookedlikeagoodbet,andindeeditworkedfine.

Attach theArduino toyourcomputerusing theUSBleadandupload thesketch.Youcan now disconnect theUSB lead and attach the power supply to theArduino and theEthernetlead.

Page 140: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Openaconnectiononyourcomputer’sbrowsertotheIPaddressthatyouassignedfortheEthernetshield.SomethingverymuchlikeFigure10-4shouldappear.

Figure10-3FindinganunusedIPaddress

Figure10-4ASimpleArduinoserverexample

Thelistingforsketch10-01isasfollows:

Page 141: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

AswiththeLCDlibrarydiscussedinChapter9,astandardArduinolibrarytakescare

ofinterfacingwiththeEthernetshield.

ThesetupfunctioninitializestheEthernetlibraryusingthemacandIPaddressesthatyousetearlier.

Theloopfunctionisresponsibleforservicinganyrequeststhatcometothewebserverfromabrowser. Ifa request iswaitingforaresponse, thencallingserver.availablewill

Page 142: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

returnaclient.Aclient isanobject;youwill learnabitmoreaboutwhat thismeans inChapter11.Butfornow,allthatyouneedtoknowisthatwhetheraclientexists(testedbythe first if statement); then you can then determinewhether it is connected to thewebserverbycallingclient.connected.

Thenextthreelinesofcodeprintoutareturnheader.Thisjusttellsthebrowserwhattypeofcontenttodisplay.Inthiscase,thebrowseristodisplayHTMLcontent.

Oncetheheaderhasbeenwritten,allthatremainsistowritetheremainingHTMLbacktothebrowser.Thismustincludetheusual<html>and<body>tags,andalsoincludesa<h1>headertagandtwo<p>tagsthatwilldisplaythevalueontheanaloginputA0andthevaluereturnedby themillis function; thatvalue is thenumberofmillisecondssincetheArduinowaslastreset.

Finally,client.stop tells the browser that themessage is complete. The browser thendisplaysthepage.

SettingArduinoPinsovertheNetwork

ThissecondexampleofusinganEthernetshieldallowsyoutoturntheArduinopinsD3toD7onandoffusingawebform.

Unlikethesimpleserverexample,youaregoingtohavetofindawaytopassthepinsettingstotheArduino.

ThemethodfordoingthisiscalledpostingdataandispartoftheHTTPstandard.Forthismethodtowork,youhavetobuildthepostingmechanismintotheHTMLsothattheArduinoreturnsHTMLtothebrowser,whichrendersaform.Thisform(showninFigure10-5)hasaselectionofOnandOffforeachpinandanUpdatebuttonthatwillsendthepinsettingstotheArduino.

Figure10-5Themessagesendingform

Page 143: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

WhentheUpdatebuttonispressed,asecondrequestissenttotheArduino.Thiswillbe

justlikethefirstrequest,exceptthattherequestwillcontainrequestparametersthatwillcontainthevaluesofthepins.

Arequestparameterissimilarinconcepttoafunctionparameter.Afunctionparameterenablesyoutogetinformationtoafunction,suchasthenumberoftimestoblink,andarequestparameterenablesyoutopassdatatotheArduinothatisgoingtohandlethewebrequest.WhentheArduinoreceives thewebrequest, itcanextract thepinsettingsfromtherequestparameterandchangetheactualpins.

Thecodeforthesecondexamplesketchfollows:

Page 144: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 145: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 146: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Thesketchusestwoarraystocontrolthepins.Thefirst,pins,justspecifieswhichpins

aretobeused.ThepinStatearrayholdsthestateofeachpin:either0or1.

Toget the informationcomingfromthebrowserformaboutwhichpinsshouldbeonandwhichshouldbeoff, it isnecessary toread theheadercomingfromthebrowser. Infact,allyouneediscontainedinthefirstlineoftheheader.Youwilluseacharacterarrayline1tocontainthefirstlineoftheheader.

WhentheuserclicksontheUpdatebuttonandsubmitstheformfromthebrowser,theURLforthepagewilllooksomethinglikethis:

Therequestparameterscomeafterthe?andareeachseparatedbyan&.Lookingatthe

firstparameter(0=1), thismeans that thefirstpin in thearray(pins[0])shouldhave thevalue 1. If youwere to look at the first line of the header, youwould see those samerequestparametersthere:

Beforetheparameters,thereisthetextGET/.Thisspecifiesthepagerequestedbythe

browser.Inthiscase,/indicatestherootpage.

Intheloopofthesketch,youcallthereadHeaderfunctiontoreadthefirstlineoftheheader.You thenuse thepageNameIs function tocheck that thepage request is for therootpage/.

The sketch then generates the header and the start of the HTML form that is to bedisplayed. Before writing the HTML for each of the pins, the sketch calls thesetValuesFromParams function to read each of the request parameters and set theappropriatevaluesinthepinStatesarray.Thisarrayisthenusedtosetthevaluesofthepin outputs before thewriteHTMLforPin function is called for each of the pins. Thisfunctiongeneratesaselectionlistforeachpin.Ithastobuildthislistpartbypart.Theifstatementsensurethattheappropriateoptionsareselected.

The functions readHeader, pageNameIs, and valueOfParam are useful general-purposefunctionsthatyoucanmakeuseofinyourownsketches.

YoucanuseyourmultimeterasyoudidinChapter6toverifythatthepinsareindeed

Page 147: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

turningonandoff.Ifyouarefeelingmoreadventurous,youcouldattachLEDsorrelaystothepinstocontrolthings.

Conclusion

Having used shields and associated libraries in the last two chapters, it is now time toinvestigatethefeaturesthatenablelibrariestobewrittenandlearnhowtowritelibrariesofyourown.

Page 148: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 149: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

11C++andLibraries

Arduinos are simple microcontrollers. Most of the time, Arduino sketches are quitesmall,sousingtheCprogramminglanguageworksjustfine.However,theprogramminglanguage for Arduino is actually C++ rather than C. C++ is an extension to the Cprogramminglanguagethataddssomethingcalledobjectorientation.

ObjectOrientation

Thisisonlyashortbook,soanin-depthexplanationoftheC++programminglanguageisbeyonditsscope.Thebookcan,however,coverthebasicsofC++andobjectorientation.Butthemaingoalistoincreasetheencapsulationofyourprograms.Encapsulationkeepsrelevantthingstogether,somethingthatmakesC++verysuitableforwritinglibrariessuchasthosethatyouhaveusedfortheEthernetandLCDsketchesinearlierchapters.

There aremany good books on the topics ofC++ and object-oriented programming.Lookforthehigher-ratedbooksonthetopicinyourfavoriteonlinebookstore.

ClassesandMethods

Objectorientationusesaconceptcalledclassestoaidencapsulation.Generally,aclassislikeasectionofaprogramthat includesbothvariables—calledmembervariables—andmethods,which are like functions but apply to the class. These functions can either bepublic,inwhichcasethemethodsandfunctionsmaybeusedbyotherclasses,orprivate,inwhichcasethemethodscanbecalledonlybyothermethodswithinthesameclass.

WhereasanArduinosketchiscontainedinasinglefile,whenyouareworkinginC++,youtendtousemorethanonefile.Infact,therearegenerallytwofilesforeveryclass:Aheader file, which has the extension .h, and the implementation file, which has theextension.cpp.

Built-inLibraryExample

TheLCDlibraryhasbeenused in the twopreviouschapters, so let’s lookmorecloselyandseewhatisgoingoninalittlemoredetail.

Referringback to sketch9-01 (open this in yourArduino IDE), you can see that theincludecommandincludesthefileLiquidCrystal.h:

Page 150: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

ThisfileistheheaderfilefortheclasscalledLiquidCrystal.Thisfile tells theArduinosketchwhatitneedstoknowtobeabletousethelibrary.Youcanactuallyretrievethisfile if you go to your Arduino installation folder and file and find the filelibraries/LiquidCrystal.Youwillneedtoopenthefileinatexteditor.IfyouareusingaMac,thenright-clickontheArduinoappitselfandselectthemenuoptionShowPackageContents.ThennavigatetoContents/Resources/Java/libraries/LiquidCrystal.

ThefileLiquidCrystal.hcontainslotsofcode,asthisisafairlylargelibraryclass.Thecodefortheactualclassitself,wherethenutsandboltsofdisplayingamessageactuallyreside,areinthefileLiquidCrystal.cpp.

Inthenextsection,asimpleexamplelibrarywillbecreatedthatshouldputtheconceptsbehindalibraryintocontext.

WritingLibraries

Creating an Arduino library might seem like the kind of thing that only a seasonedArduinoveteranshouldattempt,butactuallyitisprettystraight-forwardtomakealibrary.Forexample,youcanconvertintoalibrarytheflashfunctionfromChapter4thatcausesanLEDtoflashforaspecifiednumberoftimes.

TocreatetheC++filesthatareneededtodothis,youwillneedatexteditorforyourcomputer—somethinglikeTextPadonWindowsorText-MateonMac.

TheHeaderFile

Start by creating a folder to contain all the library files. You should create this folderinside the librariesfolderofyourArduinodocumentsfolder. InWindows,your librariesfolder will be inMy Documents\Arduino. On theMac, you will find it in your homedirectory,Documents/Arduino/, and onLinux, itwill be in the sketchbook directory ofyourhomedirectory.IfthereisnolibrariesfolderinyourArduino,thencreateone.

This libraries folder is where any libraries you write yourself, or any “unofficial”contributedlibraries,mustbeinstalled.

CallthefolderFlasher.Startthetexteditorandtypethefollowingintoit:

Page 151: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

SavethisfileintheFlasherfolderwiththenameFlasher.h.Thisis theheaderfilefor

the libraryclass.This file specifies thedifferentpartsof theclass.Asyoucansee, it isdividedintopublicandprivateparts.

The public part containswhat looks like the start of two functions. These are calledmethodsanddifferfromfunctionsonlyinsofaras theyareassociatedwithaclass.Theycanbeusedonlyaspartoftheclass.Unlikefunctions,theycannotbeusedontheirown.

The first method,Flasher, begins with an uppercase letter, which is something youwouldnotusewithafunctionname.Italsohasthesamenameastheclass.Thismethodiscalled a constructor, which you can apply to create a newFlasher object to use in asketch.

Forexample,youcouldputthefollowinginasketch:

ThiswouldcreateanewFlashercalledslowFlasherthatwouldflashonpinD13withadurationof500milliseconds.

Thesecondmethodintheclassiscalledflash.Thismethodtakesasingleargumentofthenumberoftimestoflash.Becauseitisassociatedwithaclass,whenyouwanttocallit,youhavetorefertotheobjectthatyoucreatedearlier,asfollows:

This would cause the LED to flash ten times at the period that you specified in theconstructortotheFlasherobject.

Theprivatesectionof theclasscontainstwovariabledefinitions:onefor thepin,andone for the duration,which is simply calledd. Every time that you create an object ofclassFlasher, itwillhave these twovariables.Thisenables it to remember thepinanddurationwhenanewFlasherobjectiscreated.

These variables are calledmember variables because they aremembers of the class.Their names generally are unusual in that they start with an underscore character;

Page 152: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

however, this is just a common convention, not a programming necessity. Anothercommonlyusednamingconventionistousealowercasem(formember)asthefirstletterofthevariablename.

TheImplementationFile

Theheader filehas justdefinedwhat theclass looks like.Younowneedaseparate filethatactuallydoes thework.This iscalledthe implementationfileandhas theextension.cpp.

So,createanewfilecontainingthefollowingandsaveitasFlasher.cppintheFlasherfolder:

There is someunfamiliar syntax in this file.Themethodnames arebothprefixedby

Flasher::.ThisindicatesthatthemethodsbelongtotheFlasherclass.

Theconstructormethod(Flasher)justassignseachofitsparameterstotheappropriateprivatemembervariable.Thedurationparameterisdividedbytwobeforebeingassignedtothemembervariable_d.This isbecause thedelay iscalled twice,and it seemsmorelogicalforthedurationtobethetotaldurationoftheflashandthegapbetweenflashes.

The flash function actually carries out the business of flashing; it loops for theappropriatenumberoftimes,turningtheLEDonandofffortheappropriatedelay.

CompletingYourLibrary

Youhavenowseenalloftheessentialsforcompletingthelibrary.Youcouldnowdeploythis library and it wouldwork just fine. However, there are two further steps that youshouldtaketocompleteyourlibrary.Oneistodefinethekeywordsusedinthelibraryso

Page 153: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

thattheArduinoIDEcanshowthemintheappropriatecolorwhenusersareeditingcode.Theotheristoincludesomeexamplesofhowtousethelibrary.

Keywords

Todefinethekeywords,youhavetocreateafilecalledkeywords.txt,whichgoesintotheFlasherdirectory.Thisfilecontainsjustthetwofollowinglines:

This isessentiallya two-columntableina textfile.Theleftcolumnis thekeywordandthe right column an indication of the type of keyword it is. Class names should be aKEYWORD1andmethodsshouldbeKEYWORD2.Itdoesnotmatterhowmanyspacesortabsyouputbetweenthecolumns,buteachkeywordshouldstartonanewline.

Examples

Theotherthingthatyou,asagoodArduinocitizen,shouldincludeaspartofthelibraryisa folder of examples. In this case, the library is so simple that a single example willsuffice.

TheexamplesmustallbeplacedinafoldercalledexamplesinsidetheFlasherfolder.Theexample is in fact justanArduinosketch, soyoucancreate theexampleusing theArduino IDE. But first, you have to quit and then reopen theArduino IDE tomake itawareofthenewlibrary.

After restarting theArduino IDE, from theArduino IDE’smenu, selectFileand thenNewtocreateanewsketchwindow.ThenfromtheMenu,selectSketchandtheImportLibraryoption.TheOptionsshouldlooksomethinglikeFigure11-1.

Thelibrariesabovethelineinthesubmenuaretheofficiallibraries;belowthislinearethe“unofficial”contributed libraries. Ifallhasgonewell,youshouldseeFlasher in thelist.

IfFlasherisnotinthelist,itisverylikelythattheFlasherfolderisnotinthelibrariesfolderofyoursketchesfolder,sogobackandcheck.

Page 154: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Figure11-1ImportingtheFlasherlibrary

Typetheflowingintothesketchwindowthathasjustbeencreated:

Page 155: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

The Arduino IDE will not allow you to save the example sketch directly into the

libraries folder, so save it somewhereelseunder thenameSimpleFlasherExampleandthenmovethewholeSimpleFlasherExamplefolderthatyoujustsavedintotheexamplesfolderinyourlibrary.

If you restart your Arduino IDE, you should now see that you are able to open theexamplesketchfromthemenuasshowninFigure11-2.

Figure11-2Openingtheexamplesketch

Conclusion

There ismore toC++andtowritinglibraries,but thischaptershouldgetyoustarted.Itshould alsobe sufficient formost ofwhat you are likely to dowith anArduino.TheseArduinosaresmalldevicesandthetemptationisoftentooverengineersolutionsthatcouldotherwisebeverysimpleandstraightforward.

That concludes themain body of this book. For further information onArduino andwhere to go next, a good starting point is always the official Arduino website at

Page 156: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

www.arduino.cc.Also,pleaserefertothebook’swebsiteatwww.arduinobook.com,whereyouwillfinderrataandotherusefulresources.

If you are looking for help or advice, the Arduino community onwww.arduino.com/forumisextremelyhelpful.YouwillalsofindtheauthorontherewiththeusernameSi.

Page 157: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches
Page 158: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

IndexPleasenotethatindexlinkspointtopagebeginningsfromtheprintedition.Locationsareapproximate in e-readers, and you may need to page down one or more times afterclickingalinktogettotheindexedmaterial.

Symbols

>=(greaterthanorequalto)comparisonoperator,44

<=(lessthanorequalto)comparisonoperator,44

−(minus)operator,42

!=(notequalto)comparisonoperator,44

/(slash),asdivisionoperators,42

;(semicolon),inprogrammingsyntax,29

||(or)operator,60

+(plus),asadditionoperator,42

=(assignment)operator,assigningvaluestovariables,40

==(equalto)comparisonoperator,44,60

&&(and)operator,manipulatingvalues,60

*(asterisk),asmultiplicationoperator,42

[](squarebrackets),inarraysyntax,68

<<(bitshiftoperator),119

<(lessthan)comparisonoperator,44

>(greaterthan)comparisonoperator,44

A

absfunction,mathfunctionsinlibrary,108

addition(+)operator,42

Algorithms+DataStructures=Programs(Wirth),67

alphanumericLCDShield,126

analoginputs,4–5,102–103

analogoutputs,100–102

analogReadfunction,102

Page 159: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

analogWritefunction,102

and(&&)operator,manipulatingvalues,60

ArduinoBluetooth,11–12

ArduinoDiecimila,9

ArduinoDuemilanove,9

ArduinoLilypad,11–12

ArduinoMega,10

ArduinoNano,10–11

Arduino,originsof,7

ArduinoUno

inArduinofamilyofdevelopmentboards,9

ATMega328processorin,117

arguments

passingtofunctions,28–29

ofrandomfunction,106

oftonefunction,111

arithmetic

numericvariablesand,40–42

operators,42

arrays

overviewof,67–71

PROGMEMand,116–117

SOSsignalexample,71–72

stringarrays.Seestrings

fortranslatingMorsecode.SeeMorsecodetranslator

ASCIIcode,73

assignment(=)operator,assigningvaluestovariables,40

asterisk(*),asmultiplicationoperator,42

ATmega1280,Megaand,10

ATmega168,Unoand,9

ATmega328

Unoand,9,117

Page 160: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

useonArduinoboards,3

autoscrollfunction,LCDlibrary,130

B

binarylanguage,compilingcodeinto,30

binaryvalues,hexadecimalanddecimalequivalents,109–110

bitmanipulationfunctions,108–110

bitshiftoperator(<<),119

bitReadfunction,110

bits,109

bitWritefunction,110

blinkfunction,LCDlibrary,130

Blinksketch

default,17–18

LEDsand,15

modifying,20–22

running,35–36

setupandloopfunctionsin,34–35

blocks,ofcode,34

Bluetooth,11–12

bodytags,HTML,137

Booleans

datatypesinClanguage,61

manipulatingvalues,59–61

buffervariables,whenusingchararraywithPROGMEM,117

bytedatatype,61

C

C++language

classesandmethods,143–144

creatingexamplesforlibrary,148–150

creatingheaderfileforlibraryclass,145–146

creatingimplementationfileforlibraryclass,146–147

definingkeywordsforlibrary,148

Page 161: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

exampleusingbuiltinlibrary,144

objectorientationin,143

writinglibraries,144–145

Clanguage

C++asextensionto,143

codingstyles,62

forcommand,45–48

commands,42

compilationprocess,30–32

datatypesin,61–62

#definedirective,48–49

examiningfunctionsinboilerplatecode,32–34

ifcommand,42–44

numericvariablesandarithmeticprocessesin,40–42

runningBlinksketch,35–36

setupandloopfunctionsinBlinksketch,34–35

testingexperimentsin,38–40

variables,36–38

whilecommand,48

zeroasindexin,68

callingfunctions,28

casesensitivity,syntaxofprogramminglanguagesand,28

CHANGEconstant,typesofinterruptsignals,114

char

datatypesinClanguage,61

PROGMEMand,116–117

stringliteralsand,72

charactersequences.Seestrings

Chipkitboard,13

classes,C++,143–144

clearfunction,LCDlibrary,127

code

Page 162: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

blocksof,34

compilationof,30–32

formattingstylesorstandards,62

translatingtoboard,29–30

COM3ports,asserialportforWindowscomputers,18–19

commands,Clanguage

forcommand,45–48

ifcommand,42–44

overviewof,42

whilecommand,48

comments

codeformattingstylesorstandards,64–65

reasonsforusingornotusing,65–66

comparisonoperators

comparingvalueswithequalto(==),60

typesof,44

compilationprocess

arraysand,70

translatingcodeintomachinecode,30–32

compression,datastorageand,121–123

computermemory,datain,70

conditions,ifcommandand,43

constants

defining,55

storing,115–116

constrainfunction,mathfunctionsinlibrary,108

constructormethods,146–147

controllerchip,forusewithLCDshield,125

cos,mathfunctionsinlibrary,108

CreativeCommonslicense,forArduinodesigns,7

curlybraces({})

codeformattingstylesorstandards,63

Page 163: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

insyntaxofblocksofcode,34

cursorfunction,LCDlibrary,130

D

data,representationofnumbersandletters,75–76

datastorage

clearingEEPROMcontents,121

compressionand,121–123

constants,115–116

EEPROM,117–118

overviewof,115

PROGMEMdirective,116–117

storingfloatsinEEPROM,119–120

storingintsinEEPROM,118–119

storingstringsinEEPROM,120

datatypes,inClanguage,61–62

debouncing,buttonpressesand,94–100

decimalvalue,hexadecimalandbinaryequivalents,109–110

#definedirective

forassociatingavaluewithaname,48–49

fordefiningconstants,55

delayPeriodvariable

conditionsusedwith,43

exampleofuseof,37–38

developmentboards

analoganddigitalconnections,4–5

inArduinofamily,8

Bluetooth,11–12

componentson,3

crystal,Resetswitch,SerialProgrammingConnector,andUSBconnection,6–7

Lilypad,11–13

Mega,10

microcontrollerson,5–6

Page 164: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

Nano,10–11

overviewof,2–3

powerconnections,4

powersupply,4

selectingtypeof,18

Uno,Duemilanove,andDiecimila,9

DFRRobotLCDKeypadShield,125

DHCP(DynamicHostConfigurationProtocol),134

Diecimila,9

digitalconnections,onArduinoboards,4–5

digitalinputs

buttonpressesanddebouncing,94–100

internalpull-upresistors,93–94

overviewof,89–90

pull-upresistorsand,90–93

digitaloutputs

measuringwithmultimeter,85–87,89

overviewof,85

pinModefunctionforconfiguringpinelectronics,87–88

digitalReadfunction,90

digitalWritefunction,34–35,93

DIL(dualinline)socket,4

displayfunction,LCDlibrary,130

division(/)operator,42

doubles,datatypesinClanguage,61

dualinline(DIL)socket,4

Duemilanove,9

DynamicHostConfigurationProtocol(DHCP),134

E

EEPROM(electricallyerasableread-onlymemory)

clearingcontentsof,121

compressingdataand,121

Page 165: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

floatsstoredin,119–120

intsstoredin,118–119

readingto/writingfrom,117–118

stringsstoredin,120

elements,ofarrays,70

ENC28J60Ethernetcontrollerchip,132

encapsulation

globalvariablesand,55

objectorientationincreasing,143

EPROM(erasableprogrammableread-onlymemory),1

equalto(==)comparisonoperator,44,60

Ethernet

Arduinoshields,7–8,131

communicatingwithwebservers,132–133

passingpinsettingsoverthenetwork,137–142

selectingofficialWiznet-basedshield,132

usingArduinoaswebserver,134–137

examples,creatingforC++library,148–150

F

FALLINGconstant,typesofinterruptsignals,114

Femtoduino,unofficialArduinoboards,13

Filemenu,accessingSketchbookfrom,22–23

flashmemory

onmicrocontroller,1

storingdatain,116–117

flashDotOrDashfunction,81

flashSequencefunction,79–80

floatingpointnumbers.Seefloats

floats

datatypesinClanguage,61

overviewof,59

rangecompressionand,121–122

Page 166: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

storinginEEPROM,119–120

forcommand,45–48

Freeduino,unofficialArduinoboards,13

functions

Booleansand,59–61

callingandpassingargumentsto,28–29

codingstylesorstandardsforformatting,62

collectionof.Seelibraries,Arduino

commenting,64–66

datatypesinClanguage,61–62

definingvs.predefined,51

examininginboilerplatecode,32–34

floats,59

global,local,andstaticvariablesand,54–57

indentation,62–63

openingbraces,63

overviewof,51–52

parameters,53–54

pre-definedvs.defining,33

returningvalues,57–58

setupandloopfunctionsinBlinksketch,34–35

forusewithLCDdisplays,130

variabletypes,58

whitespaces,64

G

globalvariables,54–56,76

greaterthan(>)comparisonoperator,44

greaterthanorequalto(>=)comparisonoperator,44

H

HD44780,controllerchipusedwithLCDshield,125

header(.h)files

creatingforlibraryclass,145–146

Page 167: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

neededforeachC++class,144

headertags,HTML,133,137

hexadecimalvalues,decimalandbinaryequivalents,109–110

highBytefunction,118

homefunction,LCDlibrary,130

HTML(HyperTextMarkupLanguage),132,137,142

HTTP(HyperTextTransportProtocol),132,137

I

I/O(input/output)

advancedfunctionsfor,111–114

analoginputs,102–103

analogoutputs,100–102

buttonpressesanddebouncing,94–100

digitalinputs,89–90

digitaloutputs,85–89

internalpull-upresistors,93–94

overviewof,85

pinsonmicrocontroller,1–2

pull-upresistorsand,90–93

ifcommand,42–44,60

implementation(.cpp)file

creatingforlibraryclass,146–147

neededforeachC++class,144

indentation,codeformattingstylesorstandards,62–63

input/output.SeeI/O(input/output)

interference,pull-upresistorsand,90

interrupts,112–114

ints

16bitsusedinnumericrepresentation,61

datatypesinClanguage,61

decimalvalueof,109

declaring,53–54

Page 168: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

hexvalueof,110

randomfunctionreturning,106

rangecompressionand,121–122

returnvaluesand,58

storinginEEPROM,118–119

IPaddresses,usingArduinoaswebserverand,134–136

K

keywords,definingforC++library,148

L

LCDdisplays

functionsthatcanbeusedwith,130

overviewof,125–126

sendingmessagesto,129

USBmessageboard,127–129

ledPinvariable,37

LEDs(light-emittingdiodes),15–16

lessthan(<)comparisonoperator,44

lessthanorequalto(<=)comparisonoperator,44

letters,datarepresentationinMorsecodetranslator,75–76

libraries,Arduino

bitmanipulationfunctionsin,108–110

interrupts,112–114

mathfunctions,108

overviewof,105

PROGMEMlibrary,116–117

randomnumbers,105–108

shift-Outfunction,112

tonefunction,111–112

libraries,C++

creatingexamplesforlibrary,148–150

creatingheaderfileforlibraryclass,145–146

creatingimplementationfileforlibraryclass,146–147

Page 169: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

definingkeywordsfor,148

exampleusingbuiltin,144

writing,144–145

light-emittingdiodes(LEDs),15–16

Lilypad,11–12

localvariables,55–56

log,mathfunctionsinlibrary,108

longdatatype,inClanguage,61

loopfunction

inBlinksketchexample,34–35

defining,33

forEthernetshield,137

ifcommandand,43–44

forLCDshield,129

forloops,45–48

forMorsecodetranslator,76–80

requiredinallsketches,31

whileloops,48

lowBytefunction,118

LSBFIRSTconstant,112

M

macaddresses,usingArduinoaswebserverand,134

Maccomputers

creatingC++librariesand,145

TextMateastexteditor,145

map,mathfunctionsinlibrary,108

mathfunctions,inArduinolibrary,108

max,mathfunctionsinlibrary,108

Mega,10

membervariables,C++,143,146

memory

dataincomputermemory,70

Page 170: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

flashmemory,1,116–117

methods,C++,143–144

microcontrollers

onArduinodevelopmentboard,2–3

overviewof,1–2

processingspeedof,35

min,mathfunctionsinlibrary,108

minus(−)operator,42

Morsecode

historyof,68

SOSexampleusingarrays,71–72

Morsecodetranslator

datarepresentation,75–76

flashDotOrDashfunction,81

flashSequencefunction,80

globalvariablesandsetupfunctionfor,76

loopfunctionfor,76–80

overviewof,74–75

storingconstantsusedin,115–116

testinginSerialMonitor,81–83

Motorshield,7

MSBFIRSTconstant,112

multimeter,measuringoutputswith,85–87,100–102

multiplicationoperator(*),42

N

namingconventions,forvariables,146

Nano,10–11

noAutoscrollfunction,LCDlibrary,130

noBlinkfunction,LCDlibrary,130

noCursorfunction,LCDlibrary,130

noDisplayfunction,LCDlibrary,130

noInterruptsfunction,114

Page 171: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

notequalto(!=)comparisonoperator,44

numbers,datarepresentationinMorsecodetranslator,75–76

numericvariables,40–42

O

objectorientation,inC++,143

objects,creating,146

operators,59–61

arithmetic,42

assignment(=),40

bitshift(<<),119

comparison,44

or(||)operator,60

output.SeeI/O(input/output)

P

pageNameIsfunction,142

paragraphtags,HTML,133,137

parameters

addingtofunctions,53–54

globalvariablesand,54–55

syntaxofprogramminglanguages,28

PCB(printedcircuitboard),3

pgm_read_wordfunction,116

physicalcomputing,Arduinodescribedas,1

pinModefunction

forconfiguringpinelectronics,87–88

setupfunctioncalling,34–35

pins

controllingLCDdisplay,125

I/Opinsonmicrocontroller,1–2

interruptsattachedto,113

LCDshieldpinassignments,128

passingpinsettingsoverthenetwork,137–142

Page 172: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

shift-Outfunctionfeedingshiftregisters,112

pinStatearrays,141–142

plus(+),asadditionoperator,42

postingdata,HTTPand,137

pow,mathfunctionsinlibrary,108

powerconnections,4

powersupply

onArduinoboard,4

requiredbyEthernetshield,132

poweringupArduinoboards,15–16

printfunction,LCDlibrary,127

printedcircuitboard(PCB),3

privatemethods,C++,144

Processinglibrary,105

PROGMEMdirective

compressingdataand,121

storingdatainflashmemory,116–117

programmingbyintention,77

programminglanguages

C++language.SeeC++language

Clanguage.SeeClanguage

syntaxof,28–29

translatingcodetoboard,29–30

vocabularyof,27

programs.Seesketches

pseudo-randomnumbers,106

publicmethods,C++,144

pull-upresistors

enablinginternal,93–94

overviewof,90–93

simulationofinterruptusing,113

PulseWidthModulation(PWM),100–102

Page 173: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

punctuation,syntaxofprogramminglanguages,28

pushbuttons,debouncing,94

PWM(PulseWidthModulation),100–102

Q

quartzcrystaloscillator,onArduinoboards,6–7

R

RAM(randomaccessmemory),1

randomfunction,105–108

randomnumbergenerator,107–108

randomSeedfunction,107

rangecompression,121–123

readHeaderfunction,142

relays,Arduinoshields,7

Resetconnector,powerconnections,4

Resetswitch,onArduinoboard,6

resistors,pull-up.Seepull-upresistors

returnvalues,functionsand,57–58

RISINGconstant,typesofinterruptsignals,114

Roboduino,unofficialArduinoboards,13

Ruggeduino,unofficialArduinoboards,13

S

scrollDisplayLeftfunction,LCDlibrary,130

scrollDisplayRightfunction,LCDlibrary,130

Seeeduino,unofficialArduinoboards,13

SerialMonitor

displayingmessagessentfrom,127

exampleusingnumericvariablesandarithmetic,40–41

readingelectricalinterference,90–92

testingexperimentsinC,38–40

testingMorsecodetranslatorin,81–83

viewingarrayin,68–69

serialport,selectingfromToolmenu,18–20

Page 174: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

SerialProgrammingConnector,6

Serial.available(),77–78

setCursorfunction,LCDlibrary,127

setupfunction

inBlinksketchexample,34–35

defining,33

forEthernetshield,137

forLCDshield,129

inMorsecodetranslator,76

requiredinallsketches,31

setValuesFromParamsfunction,142

shieldboards

forEthernet,131

forLCDdisplay,125

listofpopular,7

selectingofficialWiznet-basedshield,132

shift-Outfunction,112

shiftregisters,112

sin,mathfunctionsinlibrary,108

Sketchbook,22–25

sketches

accessingfromFilemenu,22–23

boilerplatecodefor,31

collectionoffunctionsfor.Seelibraries,Arduino

downloading,23–25

asprograms,28

uploadingfirst,17–22

slash(/),asdivisionoperators,42

software,installing,16

sqrt,mathfunctionsinlibrary,108

squarebrackets([]),inarraysyntax,68

staticvariables,56–57

Page 175: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

stringarrays.Seestrings

stringliterals,72–73,76

stringvariables,73–74

strings

overviewof,72

storinginEEPROM,120

stringliterals,72–73

stringvariables,73–74

fortranslatingMorsecode.SeeMorsecodetranslator

subtraction(–)operator,42

switches

connectingtoinputpinonboard,92

pull-upresistorsand,93

usingwireas,95,97

syntax,ofprogramminglanguages,28–29

T

tags,HTML,133,137

tan,mathfunctionsinlibrary,108

Teensy,unofficialArduinoboards,13

tempFloatvariable,122

texteditors,forcreatingC++files,145

text,HTMLformatting,132–133

TextMate(Maccomputers),145

TextPad(Windowscomputers),145

threads,executingsingle,112–113

todos,commentingoncode,65–66

tonefunction,111–112

Toolsmenu,18–20

truthtables,usingwithvalues,60

typecasts,convertingfloattoint,122

U

UART(UniversalAsynchronousReceiver/Transmitter),78

Page 176: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

unions,storingfloatsinEEPROM,119–120

UniversalAsynchronousReceiver/Transmitter(UART),78

Uno

inArduinofamilyofdevelopmentboards,9

ATMega328processorin,117

unsignedint,datatypesinClanguage,61

unsignedlong,datatypesinClanguage,61

USB

communicatingvia,77–78

componentonArduinodevelopmentboards,6–7

connectingvia,1

installingdriversfor,16

pluggingArduinoboardintoUSBport,15

USBHostshield,7

USBmessageboard,127–129

V

valueOfParamfunction,142

values

assigningtovariables,40

#definedirectiveforassociatingwithaname,48–49

functionsreturning,57–58

listofvaluesinarrays,67

manipulatingvalues,59–61

storing.Seedatastorage

variables

Booleansand,59–61

C++membervariables,143

datatypesinClanguage,61–62

defininginClanguage,36–38

forFlasherobject,146

floats,59

global,54–55

Page 177: Programming Arduino Getting Started with Sketches …1.droppdf.com/files/rRP6M/programming-arduino-getting-started-wi… · Programming Arduino™ Getting Started with Sketches

local,55–56

numeric,40–42

static,56–57

typesof,58

Verifybutton,forcheckingcode,30

vocabulary,ofprogramminglanguages,27

voidkeyword,32–33

W

webbrowsers

communicatingviaHTTP,132

textformattedusingHTML,132–133

webservers

communicatingwith,132–133

usingArduinoas,134–137

whilecommand,48

whitespace,codeformattingstylesorstandards,64

Windowscomputers

creatingC++libraries,145

serialportfor,18–19

TextPadastexteditor,145

Wiringlibrary,Arduinolibrarybasedon,105

Wiznetchipset,132

writefunction,LCDlibrary,129

writeHTMLforPinfunction,142