Programming
Arduino™
GettingStartedwith
Sketches
SimonMonk
Copyright © 2012 by TheMcGraw-HillCompanies.Allrights reserved. Except aspermitted under the UnitedStatesCopyrightActof1976,no part of this publicationmay be reproduced ordistributed inany formorbyany means, or stored in adatabase or retrieval system,without the prior writtenpermissionofthepublisher.
ISBN:978-0-07-178423-8
MHID:0-07-178423-3
The material in this eBookalso appears in the printversion of this title: ISBN:978-0-07-178422-1, MHID:0-07-178422-5.
All trademarks aretrademarksoftheirrespectiveowners. Rather than put atrademarksymbolafterevery
occurrence of a trademarkedname, we use names in aneditorial fashion only, and tothe benefit of the trademarkowner, with no intention ofinfringement of thetrademark. Where suchdesignations appear in thisbook, theyhavebeenprintedwithinitialcaps.
McGraw-Hill eBooks areavailable at special quantitydiscountstouseaspremiums
and sales promotions, or foruse in corporate trainingprograms. To contact arepresentative please e-mailus at [email protected].
All trademarks or copyrightsmentioned herein are thepossessionoftheirrespec-tiveowners and McGraw-Hillmakesnoclaimofownershipby the mention of productsthatcontainthesemarks.
“Arduino” is a trademark oftheArduinoteam.
Information has beenobtained by McGraw-Hillfrom sources believed to bereliable.However,becauseofthe possibility of human ormechanical error by oursources, McGraw-Hill, orothers,McGraw-Hilldoesnotguarantee the accuracy,adequacy,orcompletenessofany information and is not
responsible for any errors oromissions or the resultsobtainedfromtheuseofsuchinformation.
TERMSOFUSE
This is a copyrighted workand The McGraw-HillCompanies, Inc. (“McGraw-Hill”) and its licensorsreserveallrightsinandtothework. Use of this work issubjecttotheseterms.Except
as permitted under theCopyright Act of 1976 andtheright tostoreandretrieveone copy of the work, youmay not decompile,disassemble, reverseengineer, reproduce, modify,createderivativeworksbasedupon, transmit, distribute,disseminate, sell, publish orsublicense the work or anypart of it without McGraw-Hill’spriorconsent.Youmayuse the work for your own
noncommercial and personaluse;anyotheruseoftheworkis strictly prohibited. Yourright touse theworkmaybeterminated if you fail tocomplywiththeseterms.
THEWORK ISPROVIDED“AS IS.” McGRAW-HILLAND ITS LICENSORSMAKE NO GUARANTEESOR WARRANTIES AS TOTHE ACCURACY,ADEQUACY OR
COMPLETENESS OF ORRESULTS TO BEOBTAINED FROM USINGTHE WORK, INCLUDINGANY INFORMATIONTHATCANBEACCESSEDTHROUGH THE WORKVIA HYPERLINK OROTHERWISE, ANDEXPRESSLY DISCLAIMANY WARRANTY,EXPRESS OR IMPLIED,INCLUDING BUT NOTLIMITED TO IMPLIED
WARRANTIES OFMERCHANTABILITY ORFITNESS FOR APARTICULAR PURPOSE.McGraw-Hill and itslicensors do not warrant orguarantee that the functionscontained in the work willmeet your requirements orthat its operation will beuninterrupted or error free.Neither McGraw-Hill nor itslicensors shall be liable toyou or anyone else for any
inaccuracy,errororomission,regardless of cause, in thework or for any damagesresultingtherefrom.McGraw-Hill has no responsibility forthe content of anyinformation accessed throughthe work. Under nocircumstancesshallMcGraw-Hill and/or its licensors beliable for any indirect,incidental, special, punitive,consequential or similardamages that result from the
use of or inability to use thework,evenifanyofthemhasbeen advised of thepossibility of such damages.This limitation of liabilityshall apply to any claim orcause whatsoever whethersuch claimor cause arises incontract,tortorotherwise.
Tomyboys,StephenandMatthew,
fromaveryproudDad.
AbouttheAuthor
Simon Monk has abachelor’s degree incybernetics and computerscience and a doctorate insoftware engineering.He hasbeen an active electronicshobbyist since his schooldays and is an occasionalauthor in hobby electronicsmagazines.He is also authorof30ArduinoProjectsforthe
Evil Genius and 15Dangerously Mad ProjectsfortheEvilGenius.
CONTENTS
Acknowledgments
Introduction
1ThisIsArduino
MicrocontrollersDevelopmentBoards
ATourofanArduinoBoardPowerSupplyPowerConnectionsAnalogInputsDigitalConnectionsMicrocontrollerOtherComponents
TheOriginsofArduino
TheArduinoFamilyUno, Duemilanove, andDiecimilaMega
NanoBluetoothLilypadOther“Official”Boards
ArduinoClonesandVariants
Conclusion
2GettingStarted
PoweringUp
InstallingtheSoftware
UploadingYourFirstSketch
TheArduinoApplication
Conclusion
3CLanguageBasics
Programming
What Is a ProgrammingLanguage?
Blink—Again!
Variables
ExperimentsinCNumeric Variables andArithmetic
Commandsifforwhile
The#defineDirective
Conclusion
4Functions
WhatIsaFunction?
Parameters
Global, Local, and StaticVariables
ReturnValues
OtherVariableTypesfloatsboolean
OtherDataTypes
CodingStyleIndentationOpeningBracesWhitespaceComments
Conclusion
5ArraysandStrings
ArraysMorseCode SOSUsing
Arrays
StringArraysStringLiteralsStringVariables
AMorseCodeTranslatorDataGlobalsandSetupTheloopfunctionThe flashSequenceFunctionThe flashDotOrDashFunction
PuttingItAllTogether
Conclusion
6InputandOutput
DigitalOutputs
DigitalInputsPull-upResistorsInternal Pull-upResistorsDebouncing
AnalogOutputs
AnalogInput
Conclusion
7 The Standard ArduinoLibrary
RandomNumbers
MathFunctions
BitManipulation
AdvancedI/OGeneratingTonesFeedingShiftRegisters
Interrupts
Conclusion
8DataStorage
Constants
ThePROGMEMDirective
EEPROMStoring an int inEEPROMStoring a float inEEPROM(Unions)Storing a String inEEPROMClearing theContentsofEEPROM
CompressionRangeCompression
Conclusion
9LCDDisplays
AUSBMessageBoard
UsingtheDisplay
OtherLCDLibraryFunctions
Conclusion
10 Arduino EthernetProgramming
EthernetShields
Communicating with WebServers
HTTPHTML
ArduinoasaWebServer
SettingArduinoPinsovertheNetwork
Conclusion
11C++andLibraries
ObjectOrientationClassesandMethods
Built-inLibraryExample
WritingLibrariesTheHeaderFileTheImplementationFileCompleting YourLibrary
Conclusion
Index
ACKNOWLEDGMENTS
I thank Linda for givingmethe time, space, and supportto write this book and forputting up with the variousmesses my projects createaroundthehouse.I also thank Stephen and
MatthewMonk for taking aninterest in what their Dad isup to and their generalassistancewithprojectwork.Finally, I would like to
thank Roger Stewart, SapnaRastogi, and everyoneinvolved in theproductionofthis book. It’s a pleasure toworkwithsuchagreatteam.
INTRODUCTION
Arduino interface boardsprovide a low-cost, easy-to-use technology to createmicrocontroller-basedprojects. With a littleelectronics, you can makeyour Arduino do all sorts ofthings,fromcontrollinglightsin an art installation to
managing the power on asolarenergysystem.There are many project-
based books that show youhowtoconnectthingstoyourArduino, including 30ArduinoProjects for theEvilGenius by this author.However, the focus of thisbook is on programming theArduino.Thisbookwillexplainhow
to make programming theArduino simple and
enjoyable, avoiding thedifficulties of uncooperativecode that so often afflict aproject. You will be takenthrough the process ofprogramming the Arduinostepbystep,startingwiththebasicsof theCprogramminglanguagethatArduinosuse.
So, What IsArduino?
Arduino is a smallmicrocontroller board with auniversal serial bus (USB)plug to connect to yourcomputer and a number ofconnection sockets that canbe wired to externalelectronics such as motors,relays, light sensors, laserdiodes, loudspeakers,microphones,andmore.Theycan either be powered
through the USB connectionfromthecomputer,froma9Vbattery, or from a powersupply. They can becontrolled from thecomputeror programmed by thecomputer and thendisconnected and allowed toworkindependently.The board design is open
source. This means thatanyone is allowed to makeArduino-compatible boards.This competition has lead to
lowcostsfortheboards.The basic boards are
supplemented by accessoryshield boards that can beplugged on top of theArduino board. In this book,we will use two shields—anLCD display shield and anEthernet shield—that willallowus to turn ourArduinointoatinywebserver.The software for
programmingyourArduinoiseasy to use and also freely
available forWindows,Mac,andLINUXcomputers.
WhatWillINeed?
This is a book intended forbeginners, but it is alsointendedtobeusefultothosewhohaveusedArduinoforawhileandwanttolearnmoreabout programming the
Arduino or gain a betterunderstanding of thefundamentals.You do not need to have
any programming experienceor a technical background,and the book’s exercises donotrequireanysoldering.Allyou need is the desire tomakesomething.If you want to make the
most of thebook and try outsomeoftheexperiments,thenit is useful to have the
followingonhand:
•Afewlengthsofsolidcorewire
•Acheapdigitalmultimeter
Botharereadilyavailablefora few dollars from a hobbyelectronics shop such asRadio Shack. You will ofcourse also need an ArduinoUnoboard.
If you want to go a step
further and experiment withEthernetandtheliquidcrystaldisplay (LCD) shield, thenyou will need to buy shieldsthatareavailablefromonlinestores.SeeChapters9and10fordetails.
UsingthisBook
Thisbookisstructuredtoget
youstarted ina reallysimpleway and gradually build onwhat you have learned. Youmay, however, find yourselfskipping or skimming someof the early chapters as youfind the right level to enterthebook.Thebookisorganizedinto
thefollowingchapters:
• Chapter 1: This IsArduinoAnintroductiontothe Arduino hardware, this
chapterdescribeswhat it iscapable of, and thevarioustypes of, Arduino boardsthatareavailable.
• Chapter 2: GettingStarted Here you conductyour first experimentswithyour Arduino board:installing the software,powering it up, anduploadingyourfirstsketch.
• Chapter 3: C LanguageBasics This chapter coversthe basics of the C
language; for completeprogramming beginners,the chapters also serves asan introduction toprogrammingingeneral.
•Chapter4:FunctionsThischapter explains the keyconcept of using andwriting functions inArduino sketches. Thesesketches are demonstratedthroughout with runnablecodeexamples.
• Chapter 5: Arrays and
StringsHereyoulearnhowto make and use datastructures that are moreadvanced than simpleinteger variables. AMorsecode example project isslowly developed toillustratetheconceptsbeingexplained.
• Chapter 6: Input andOutput You learn how touse the digital and analoginputs and outputs on theArduino in your programs.
Amultimeterwillbeusefulto show you what ishappeningontheArduino’sinput/outputconnections.
•Chapter 7: The StandardArduino Library Thischapter explains how tomake use of the standardArduino functions thatcome in the Arduino’sstandardlibrary.
• Chapter 8: Data StorageHereyoulearnhowtowritesketches that can savedata
in electrically erasableread-only memory(EEPROM) and make useof the Arduino’s built-inflashmemory.
•Chapter 9: LCDDisplaysIn this chapter, youprogram with the LCDShield library to make asimpleUSBmessageboardexample.
• Chapter 10: ArduinoEthernet ProgrammingYoulearnhowtomakethe
Arduinobehave likeawebserver as you get a littlebackground on HyperTextMarkupLanguage(HTML)andtheHyperTextTransferProtocol(HTTP).
• Chapter 11: C++ andLibraries You go beyondC,lookingataddingobject-orientationandwritingyourownArduinolibraries.
Resources
Thisbook issupportedbyanaccompanyingwebsite:
www.arduinobook.com
There you will find all thesourcecodeusedinthisbookas well as other resources,suchaserrata.
1ThisIsArduino
Arduino is amicrocontrollerplatformthathascapturedtheimagination of electronicsenthusiasts. Its ease of useandopensourcenaturemakeit a great choice for anyone
wanting to build electronicprojects.Ultimately,itallowsyouto
connect electronics throughits pins so that it can controlthings—for instance, turnlightsormotorsonandofforsensethingssuchaslightandtemperature. This is whyArduino is sometimes giventhe description physicalcomputing.BecauseArduinoscan be connected to your
computerbyauniversalserialbus (USB) lead, this alsomeans that you can use theArduinoasaninterfaceboardto control those sameelectronics from yourcomputer.This chapter is an
introduction to the Arduino,including the history andbackground of the Arduino,aswellasanoverviewofthehardware.
Microcontrollers
Theheart ofyourArduino isa microcontroller. Prettymuch everything else on theboard is concerned withproviding the board withpower and allowing it tocommunicate with yourdesktopcomputer.Amicrocontroller really is
alittlecomputeronachip.Ithaseverythingandmorethanthefirsthomecomputershad.It has a processor, a kilobyteor two of random accessmemory (RAM) for holdingdata, a few kilobytes oferasable programmable read-only memory (EPROM) orflash memory for holdingyour programs and it hasinput and output pins. Theseinput/output (I/O) pins linkthemicrocontrollertotherest
ofyourelectronics.Inputscanreadbothdigital
(is theswitchonoroff?)andanalog(whatisthevoltageata pin?). This opens up theopportunity of connectingmany different types ofsensor for light, temperature,sound,andmore.Outputscanalsobeanalog
or digital. So, you can set apintobeonoroff(0voltsor5 volts) and this can turnlight-emitting diodes (LEDs)
on and off directly, or youcan use the output to controlhigherpowerdevicessuchasmotors. They can alsoprovide an analog outputvoltage. That is, you can setthe output of a pin to someparticular voltage, allowingyou to control the speedof amotor or the brightness of alight, rather than simplyturningitonoroff.The microcontroller on an
Arduino board is the 28-pin
chipfittedintoasocketatthecenter of the board. Thissingle chip contains thememoryprocessorandalltheelectronics for theinput/output pins. It ismanufactured by thecompanyAtmel,whichisoneof the major microcontrollermanufacturers. Each of themicrocontrollermanufacturers actuallyproduces dozens of differentmicrocontrollersgroupedinto
different families. Themicrocontrollers are not allcreated for the benefit ofelectronics hobbyists like us.We are a small part of thisvast market. These devicesare really intended forembedding into consumerproducts, including cars,washing machines, DVDplayers, children’s toys, andevenairfresheners.The great thing about the
Arduinoisthatitreducesthis
bewildering array of choicesby standardizing on onemicrocontroller and stickingwithit.(Well,asweseelater,this statement is not quitetrue,butit’scloseenough.)Thismeans thatwhen you
are embarking on a newproject,youdonot firstneedtoweighalltheprosandconsof the various flavors ofmicrocontroller.
DevelopmentBoards
We have established that themicrocontrollerisreallyjustachip. A chip will not justwork on its own withoutsome supporting electronicstoprovide itwitha regulatedand accurate supply ofelectricity (microcontrollersare fussy about this) as wellasameansofcommunicatingwith the computer that is
going to program themicrocontroller.This iswheredevelopment
boards come in. AnArduinoboard is really amicrocontroller developmentboard that happens to be anindependent open sourcehardware design.Thismeansthat the design files for theprinted circuit board (PCB)and the schematic diagramsareallpubliclyavailable,andeveryone is free to use the
designs to make and sell hisorherownArduinoboards.All the microcontroller
manufacturers—includingAtmel, which makes theATmega328 microcontrollerused in an Arduino board—also provide their owndevelopment boards andprogramming software.Although they are usuallyfairly inexpensive, these tendto be aimed at professionalelectronics engineers rather
than hobbyists. This meansthatsuchboardsandsoftwarearearguablyhardertouseandrequire a greater learninginvestmentbeforeyoucangetanythingusefuloutofthem.
A Tour of anArduinoBoard
Figure1-1showsanArduino
board.Let’stakeaquicktourofthevariouscomponentsontheboard.
Figure 1-1 An ArduinoUnoboard
PowerSupply
Referring to Figure 1-1,directly below the USBconnector is the 5-volt (5V)voltage regulator. Thisregulates whatever voltage(between 7V and 12V) is
supplied from the powersocketintoaconstant5V.The 5V voltage regulator
chipisactuallyquitebigforasurface mount component.Thisissothatitcandissipatethe heat required to regulatethe voltage at a reasonablyhigh current. This is usefulwhen driving externalelectronics.
PowerConnections
Next let us look at theconnectors at the bottom ofFigure1-1.You can read theconnectionnamesnext to theconnectors.ThefirstisReset.This does the same thing asthe Reset button on theArduino. Rather likerebooting a PC, using theReset connector resets themicrocontroller so that itbegins its program from thestart. To reset themicrocontroller with the
Reset connector, youmomentarily set this pin low(connectingitto0V).The restof thepins in this
section just provide differentvoltages (3.5V, 5V, GND,and9V), as they are labeled.GND, or ground, just meanszero volts. It is the referencevoltage to which all othervoltages on the board arerelative.
AnalogInputs
The six pins labeled asAnalog In A0 to A5 can beused to measure the voltageconnectedtothemsothatthevaluecanbeusedinasketch.Note that they measure avoltage and not a current.Only a tiny currentwill everflow into them and down toground because they have avery large internal resistance.
Thatis,thepinhavingalargeinternal resistance onlyallows a tiny current to flowintothepin.Although these inputs are
labeled as analog, and areanalog inputs by default,theseconnectionscanalsobeused as digital inputs oroutputs.
DigitalConnections
We now switch to the topconnector and start on theright-handsideinFigure1-1.Here we find pins labeledDigital0 to13.Thesecanbeused as either inputs oroutputs. When used asoutputs, they behave ratherlike the power supplyvoltages discussed earlier inthissection,except that theseare all 5V and can be turnedon or off from your sketch.So, ifyou turn themonfrom
your sketch they will be at5V, and if you turn themoffthey will be at 0V. As withthepower supplyconnectors,you must be careful not toexceed their maximumcurrent capabilities. The firsttwo of these connections (0and 1) are also labeled RXand TX, for receive andtransmit. These connectionsare reserved for use incommunication and areindirectly the receive and
transmitconnectionsforyourUSBlinktoyourcomputer.These digital connections
can supply 40 mA(milliamps) at 5V. That ismore than enough to light astandardLED,butnotenoughto drive an electric motordirectly.
Microcontroller
Continuing our tour of the
Arduino board, themicrocontroller chip itself isthe black rectangular devicewith 28 pins. This is fittedinto a dual inline (DIL)socketsothatitcanbeeasilyreplaced. The 28-pinmicrocontroller chip used ontheArduinoUnoboardistheATmega328. Figure 1-2 is ablock diagram showing themainfeaturesofthisdevice.The heart—or, perhaps
more appropriately, the brain
—of thedevice is thecentralprocessing unit (CPU). Itcontrols everything that goeson within the device. Itfetches program instructionsstored in the flash memoryand executes them. Thismight involve fetching datafrom working memory(RAM),changingit,andthenputting it back. Or, it maymean changing one of thedigital outputs from 0V to5V.
TheEEPROMmemoryisalittleliketheflashmemoryinthat it is nonvolatile.That is,you can turn the device offand on and it will not haveforgotten what is in theEEPROM.Whereas the flashmemory is intended forstoring program instructions(from sketches), theEEPROM is used to storedata that you do notwant toloseintheeventofaresetorthepowerbeingturnedoff.
Figure 1-2 ATmega328blockdiagram
OtherComponents
Above the microcontroller isa small, silver, rectangularcomponent. This is a quartzcrystal oscillator. It ticks 16million times a second, andon each of those ticks, themicrocontroller can perform
one operation—addition,subtraction, or anothermathematicaloperation.To the right of the crystal
is the Reset switch. Clickingon this switch sends a logicpulse to theReset pin of themicrocontroller, causing themicrocontroller to start itsprogram afresh and clear itsmemory. Note that anyprogramstoredon thedevicewill be retained, because thisis kept in non-volatile flash
memory—that is, memorythat remembers even whenthedeviceisnotpowered.To the right of the Reset
button is the SerialProgramming Connector. Itoffers another means ofprogramming the Arduinowithout using the USB port.Because we do have a USBconnection and software thatmakes it convenient to use,wewillnotavailourselvesofthisfeature.
Inthetop-leftcorneroftheboardnexttotheUSBsocketis the USB interface chip.This chip converts the signallevels used by the USBstandard to levels thatcanbeused directly by the Arduinoboard.
The Origins ofArduino
Arduino was originallydeveloped as an aid forteaching students. It wassubsequently (in 2005)developed commercially byMassimo Banzi and DavidCuartielles. It has since goneon to become enormouslysuccessful with makers,students, and artists for itseaseofuseanddurability.Another key factor in its
successis thatall thedesignsfor Arduino are freely
available under a CreativeCommons license. This hasallowed many lower-costalternatives to the boards toappear. Only the nameArduino isprotected,sosuchclones often have “*dunino”names, such as Boarduino,Seeeduino, and Freeduino.However, the official boardsmanufacturedinItalystillsellextremely well. Many bigretailers sell only the officialboards, which are nicely
packagedandofhighquality.Yet another reason for the
successofArduinoisthatitisnotlimitedtomicrocontrollerboards. There are a hugenumber of Arduino-compatible shieldboards thatplug directly into the top ofan Arduino board. Becauseshields are available foralmost every conceivableapplication, you often canavoid using a soldering ironand instead plug together
shields that can be stackedone upon another. Thefollowingarejustafewofthemostpopularshields:
• Ethernet, which gives anArduino web-servingcapabilities
•Motor,whichdriveselectricmotors
• USB Host, which allowscontrolofUSBdevices
• Relays, which switchesrelaysfromyourArduino
Figure 1-3 shows anArduino Uno with anEthernetshieldattached.
Figure1-3ArduinoUnowithanEthernetshield
TheArduinoFamily
It is useful to have a littlebackground on the variousArduino boards. We will beusingtheArduinoUnoasour
standard device. Indeed, thisisbyfarthemostusedoftheArduino boards, but theboards are all programmedusing the same language andlargely have the sameconnections to the outsideworld,soyoucaneasilyuseadifferentboard.
Uno, Duemilanove,andDiecimila
TheArduinoUnoisthelatestincarnation of the mostpopular series of Arduinoboards. The series includesthe Diecimila (Italian for10,000)andtheDuemilanove(Italian for2011).Figure 1-4shows an Arduino clone. Bynow you may have guessedthat Arduino is an Italianinvention.These older boards look
very similar to the ArduinoUno. They both have the
same connectors and a USBsocket and are generallycompatiblewitheachother.The most significant
difference between the Unoand the earlier boards is thattheUnousesadifferentUSBchip. This does not affecthowyouusetheboard,butitdoesmake installation of theArduino software easier andallows higher speeds ofcommunication with thecomputer.
The Uno can also supplymore current on its 3.3Vsupply and always comesequipped with theATmega328. The earlierboards will have either anATmega328 or ATmega168.The ATmega328 has morememory, but unless you arecreating a large sketch, thiswillmakenodifference.
Figure1-4The ArduinoDuemilanove
Mega
TheArduinoMega(Figure1-5) is the muscle car ofArduino boards. It boasts ahuge collection of inputoutput ports, but cleverlyaddstheseasextraconnectors
at one end of the board,allowing it to remain pin-compatible with the ArduinoUno and all the shieldsavailableforArduino.It uses a processor with
more input output pins, theATmega1280, which is asurface mount chip that isfixed permanently to theboard. So, unlike with theUno and similar boards, youcannot replace the processorifyouaccidentallydamageit.
The extra connectors arearranged at the end of theboard. Extra featuresprovidedbytheMegaincludethefollowing:
•54input/outputpins•128KBofflashmemoryforstoring sketches and fixeddata (compared to theUno’s32KB)
• 8KB of RAM and 4KB ofEEPROM
Nano
TheArduinoNano(Figure1-6) isaveryusefuldevice foruse with a solderlessbreadboard. If you fit pins toit, it can just plug into thebreadboard as if it were achip.
Figure 1-5 An ArduinoMegaboard
Figure 1-6 ArduinoNano
Thedownsideof theNano
is that because it is somuchsmallerthananUno,itcannotacceptUno-sizedshields.
Bluetooth
The Arduino Bluetooth(Figure 1-7) is an interesting
device as it includesBluetooth hardware in placeof the USB connector. Thisallows the device to even beprogrammedwirelessly.The Arduino Bluetooth is
not a cheap board, and it isoften cheaper to attach athird-party Bluetooth moduletoaregularArduinoUno.
Lilypad
TheLilypad(Figure1-8) isatiny, thinArduino board thatcan be stitched into clothingfor applications that havebecome known as wearablecomputing.TheLilypaddoesnothave
a USB connection, and youmustuseaseparateadaptortoprogram it. It has anexceptionally beautifuldesign.
Figure 1-7 ArduinoBluetooth
Figure 1-8 ArduinoLilypad
Other “Official”Boards
The previously describedArduino boards are the mostuseful and popular ones.However, the range of
Arduino boards constantlychanges, so for a completeand up-to-date picture of theArduino family, see theofficial Arduino website listatwww.arduino.cc/en/Main/Hardware
Arduino Clones andVariants
Unofficial boards fall intotwo categories. Some justtakethestandardopensourcehardware designs ofArduinoand build a cheaper one.Some names you can searchfor boards of this natureincludethefollowing:
•Roboduino•Freeduino• Seeeduino (yes, with threee’s)More interestingly, some
Arduino-compatible designsare intended to extend orimprovetheArduinoinsomeway. New variants areappearingallthetime,andfartoo many exist to mentionthem all. However, thefollowing are some of themore interesting and popularvariants:
• Chipkit, a high-speedvariant based on a PICprocessor, but which is
fairly compatible withArduino
• Femtoduino, a very smallArduino
• Ruggeduino, with is anArduinoboardwithbuilt-inI/Oprotection
• Teensy, a low-cost nano-typedevice
Conclusion
Now that you have exploredtheArduinohardwarealittle,it’s time to set up yourArduinosoftware.
2GettingStarted
Having introduced theArduino, and learnt a littleabout what it is that we areprogramming, it is time tolearnhowinstallthesoftwarethat we will need on our
computerandtostartworkingonsomecode.
PoweringUp
When you buy an Arduinoboard, it is usuallypreinstalled with a sampleBlinkprogramthatwillmakethe little built-in light-
emittingdiode(LED)flash.The LED marked L is
wireduptooneofthedigitalinput output sockets on theboard. It is connected todigitalpin13.Thislimitspin13tobeingtheoneusedasanoutput. However, the LEDuses only a small amount ofcurrent, so you can stillconnect other things to thatconnector.All you need to do to get
yourArduinoupandrunning
issupplyitwithsomepower.The easiestway to do this istopluginitintotheUSBporton your computer. You willneedatype-A-to-type-BUSBlead.Thisisthesametypeoflead that is normally used toconnect a computer to aprinter.If everything is working
OK, the LED should blink.New Arduino boards comewiththisBlinksketchalreadyinstalled so that you can
verifythattheboardworks.
Installing theSoftware
To be able to install newsketches onto your Arduinoboard, you need to do morethan supply power to it overtheUSB.Youneed to installtheArduino software (Figure
2-1).Full and comprehensive
instructions for installing thissoftwareonWindows,Linux,and Mac computers can befoundat theArduinowebsite(www.arduino.cc).Once you have
successfully installed theArduino software and,depending on your platform,USBdrivers,youshouldnowbe able to upload a programtotheArduinoboard.
Figure2-1The Arduinoapplication
UploadingYourFirstSketch
The blinking LED is theArduino equivalent to the
“HelloWorld” program usedin other languages as thetraditional first program torun when learning a newlanguage. Let’s test out theenvironmentbyinstallingthisprogram on your Arduinoboardandthenmodifyingit.When you start the
Arduino application on yourcomputer, it opens with anempty sketch. Fortunately,the application ships with awide range of useful
examples. So from the Filemenu, open the Blinkexample as shown in Figure2-2.
Figure 2-2 The Blinksketch
You now need to transfer
orupload that sketch toyourArduino board. So plug yourArduino board into yourcomputerusingtheUSBlead.You should see the green“On” LED on the Arduinolight up. The Arduino boardwill probably already be
flashing, as the boards aregenerally shipped with theBlink sketch alreadyinstalled. But let’s install itagainandthenmodifyit.When you plug the board
in, if you are using a Mac,youmaygetthemessage,“Anew network interface hasbeen detected.” Just clickCancel;yourMacisconfusedand thinks that the Uno is aUSBmodem.Before you can upload a
sketch, you must tell theArduino application whattype of board you are usingandwhichserialportyouareconnectedto.Figures2-3and2-4 show how you do thisfromtheToolsmenu.
Figure2-3Selecting theboardtype
Figure2-4Selecting theserialport(inWindows)
On a Windows machine,
the serial port is alwaysCOM3. On Macs and Linuxmachines, you will see amuch longer list of serialdevices (seeFigure2-5).Thedevice will normally be thetopselectioninthelist,withaname similar to
/dev/tty.usbmodem621.Now click on the Upload
icon in the toolbar. This isshown highlighted in Figure2-6.After you click thebutton,
there is a short pause whilethe sketch is compiled andthen the transfer begins. If itisworking,thentherewillbesome furious blinking ofLEDs as the sketch istransferred, after which youshould see the message
“Done Uploading” at thebottom of the Arduinoapplication window and afurther message similar to“Binary sketch size: 1018bytes (of a 14336 bytemaximum).”
Figure2-5Selecting theserialport(onaMac)
Once uploaded, the board
automatically starts runningthe sketch and you will seetheLEDstarttoblink.If this did not work, then
check your serial and boardtypesettings.Now let’s modify the
sketchtomaketheLEDblink
faster. To do this, let’s alterthe two places in the sketchwhere there is a delay for1,000millisecondssothatthedelay is 500 milliseconds.Figure 2-7 shows themodified sketch with thechangeshighlighted.
Figure 2-6 Uploadingthesketch
ClickontheUploadbutton
again. Then, once the sketchhasuploaded,youshouldseeyourLEDstarttoblinktwiceasfastasitdidbefore.Congratulations, you are
now ready to startprogramming your Arduino.First, though, let’s take a
mini-tour of the Arduinoapplication.
Figure 2-7 ModifyingtheBlinksketch
The ArduinoApplication
Sketches in Arduino are likedocuments in a word
processor. You can openthemandcopypartsfromonetoanother.Soyouseeoptionsto Open, Save, and Save AsintheFilemenu.Youwillnotnormally use Open becausethe Arduino application hasthe concept of a Sketchbookwhere all your sketches arekept carefully organized intofolders. You gain access totheSketchbookfromtheFilemenu. As you have justinstalled the Arduino
application for the first time,your Sketchbook will beempty until you create somesketches.As you have seen, the
Arduino application comeswith a selection of examplesketches that can be veryuseful. Having modified theBlink example sketch, if youtry and save it, you get amessage that says, “Somefilesaremarkedread-onlysoyou will need to save this
sketch in a differentlocation.”Try this now. Accept the
default location, but changethe filename to MyBlink, asshowninFigure2-8.Now if you go to the File
menu and then click onSketches, you will seeMyBlink as one of thesketcheslisted.Ifyoulookatyour computer’s file system,onaPC,youwillfindthatthesketch has been written into
MyDocuments\Arduino, andonMacorLinux, theyare inDocuments/Arduino.Allof thesketchesused in
thisbookcanbedownloadedas a zip file(Programming_Arduino.zip)from www.arduinobook.com.Isuggestthatnowisthetimeto download this file andunzip it into the Arduinofolder that contains thesketches. In other words,when you have unzipped the
folder, there should be twofolders in your Arduinofolder: one for the newlysaved MyBlink and onecalled Programming Arduino(see Figure 2-9). TheProgramming Arduino folderwill contain all the sketches,numbered according tochapter,sothatsketch03-01,for example, is sketch 1 ofChapter3.
Figure 2-8 Saving acopyofBlink
These sketches will not
appear in your Sketchbookmenu until you quit theArduino application andrestart it. Do so now. Thenyour Sketchbook menushould look similar to thatshowninFigure2-10.
Figure2-9Installingthe
sketchesfromthebook
Figure 2-10 Sketchbook
with the book’s sketchesinstalled
Conclusion
Your environment is all setupandreadytogo.Inthenextchapter,wewill
look at some of the basicprinciples of the C language
that the Arduino uses andstartwritingsomecode.
3CLanguage
Basics
The programming languageusedtoprogramArduinosisalanguage called C. In thischapter,yougettounderstandthebasicsof theC language.
Youwill use what you learnhere in every sketch youdevelop as an Arduinoprogrammer.Toget themostout of Arduino, you need tounderstand thesefundamentals.
Programming
It is not uncommon forpeople to speak more thanone language. In fact, themore you learn, the easier itseems to learn spokenlanguagesasyoustarttofindcommonpatternsofgrammarand vocabulary. The same istrue of programminglanguages. So, if you haveused any other programminglanguage, you will quicklypickupC.The good news is that the
vocabularyofaprogramminglanguage is far smaller thanthat of a spoken language,and because you write itrather than say it, thedictionary can always be athand whenever you need tolook things up. Also, thegrammar and syntax of aprogramming language areextremely regular, and onceyoucometogripswithafewsimple concepts, learningmorequicklybecomessecond
nature.It is best to think of a
program—or a sketch, asprograms are called inArduino—as a list ofinstructions to be carried outin the order that they arewritten down. For example,supposeyouweretowritethefollowing:
These three lineswouldeachdo something. The first linewouldsettheoutputofpin13toHIGH.Thisisthepinwithan LED built in to theArduino board, so at thispoint the LED would light.Thesecondlinewouldsimplywait for 500 milliseconds(half a second) and then thethirdlinewouldturntheLEDbackoffagain.Sothesethreelines would achieve the goalof making the LED blink
once.You have already seen a
bewildering array ofpunctuation used in strangeways and words that don’thavespacesbetweenthem.Afrustration of many newprogrammers is, “I knowwhatIwanttodo,Ijustdon’tknowwhat I need to write!”Fear not, all will beexplained.First of all, let’s dealwith
the punctuation and the way
the words are formed. Theseare both part of what istermed the syntax of thelanguage. Most languagesrequire you to be extremelypreciseaboutsyntax,andoneof the main rules is thatnamesforthingshavetobeasingle word. That is, theycannot include spaces. So,digitalWrite is the name forsomething.It’sthenameofabuilt-in function (you’ll learnmore about functions later)
thatwilldothejobofsettinganoutputpinon theArduinoboard.Not only do you havetoavoidspacesinnames,butalsonamesarecasesensitive.So you must writedigitalWrite, notDigitalWriteorDigitalwrite.The function digitalWrite
needs to know which pin tosetandwhethertosetthatpinHIGH or LOW. These twopieces of information arecalled arguments, which are
said to be passed to afunction when it is called.Theparametersforafunctionmust be enclosed inparentheses and separated bycommas.The convention is to place
the opening parenthesisimmediately after the lastletter of the function’s nameand to put a space after thecomma before the nextparameter.However,youcansprinkle space characters
within the parentheses if youwant.Ifthefunctiononlyhasone
argument, then there is noneedforacomma.Notice how each line ends
withasemicolon.Itwouldbemore logical if they wereperiods, because thesemicolon marks the end ofone command, a bit like theendofasentence.In the next section, you
willfindoutabitmoreabout
whathappenswhenyoupressthe Upload button on theArduino integrateddevelopment environment(IDE).Thenyouwillbeableto start trying out a fewexamples.
What Is aProgrammingLanguage?
Itisperhapsalittlesurprisingthatwe can get toChapter 3inabookaboutprogrammingwithoutdefiningexactlywhata programming language is.WecanrecognizeanArduinosketch and probably have aroughideaofwhatitistryingto do, butwe need to look abit deeper into how someprogramming language codegoes from being words on a
page to something that doessomething real, like turn anLEDonandoff.Figure3-1 summarizes the
process involved from typingcodeintotheArduinoIDEtorunning the sketch on theboard.
Figure3-1Fromcodetoboard
When you press the
Upload button on yourArduino IDE, it launches achainofeventsthatresultsinyoursketchbeinginstalledonthe Arduino and being run.Thisisnotasstraightforwardas simply taking the text thatyou typed into theeditorandmoving it to the Arduinoboard.
The first step is to dosomethingcalledcompilation.This takes thecodeyouhavewritten and translates it intomachine code—the binarylanguage that the Arduinounderstands. If you click thetriangular Verify button ontheArduinoIDE,thisactuallyattemptstocompiletheCthatyou have written withouttryingtosendthecodetotheArduinoIDE.Aside-effectofcompilingthecodeisthatitis
checked to make sure that itconformstotherulesoftheClanguage.IfyoutypeCiaoBellainto
your Arduino IDE and clickonthePlaybutton,theresultswillbeasshowninFigure3-2.
Figure 3-2 Arduinosdon’tspeakItalian
The Arduino has tried to
compile the words “CiaoBella,” anddespite its Italianheritage, it has no idea whatyou are talking about. ThistextisnotC.So,theresultisthat at the bottom of thescreen we have that crypticmessage“error:Ciaodoesnot
name a type.” What thisactuallymeansisthatthereisa lot wrong with what youhavewritten.Let’s try another example.
This time we will trycompiling a sketch with nocodeatallinit(seeFigure3-3).This time, the compiler is
telling you that your sketchdoes not have setup or loopfunctions.Asyouknowfromthe Blink example that you
raninChapter2,youhavetohavesome“boilerplate”code,asitiscalled,beforeyoucanadd your own code into asketch. In Arduinoprogramming the“boilerplate” code takes theform of the “setup” and“loop” functions that mustalwaysbepresentinasketch.
Figure 3-3No setup orloop
Youwill learnmuchmore
about functions later in thebook, but for now, let’saccept that you need thisboilerplate code and justadapt your sketch so it willcompile(seeFigure3-4).The Arduino IDE has
looked at your efforts at
writing code and found themto be acceptable. It tells youthis by saying “DoneCompiling”andreporting thesizeofthesketchtoyou:450bytes.TheIDEisalsotellingyouthatthemaximumsizeis32,256 bytes, so you stillhave lots of room to makeyoursketchbigger.Let’s examine this
boilerplate code that willform the starting point forevery sketch that you ever
write. There are some newthings here. For example,there is the word void andsomecurlybraces.Let’sdealwithvoidfirst.
Figure3-4Asketchthatwillcompile
The line void setup()
meansthatyouaredefiningafunction called setup. InArduino, some functions arealreadydefinedforyou,suchas digitalWrite and delay,whereas you must or candefine others for yourself.setup and loop are two
functions that you mustdefine for yourself in everysketchthatyouwrite.The important thing to
understand is that here youare not calling setup or looplike you would calldigitalWrite, but you areactually creating thesefunctionsso that theArduinosystem itself can call them.This is a difficult concept tograsp,butonewaytothinkofit is as being similar to a
definition in a legaldocument.Mostlegaldocumentshave
a “definitions” section thatmight say, for example,somethinglikethefollowing:
By defining a term in this
way—for example, simplyusing the word “author” as
shorthand for“Thepersonorpersons responsible forcreating the book”—lawyerscan make their documentsshorter and more readable.Functions work much likesuchdefinitions.Youdefineafunction that you or thesystem itself can then useelsewhereinyoursketches.Going back to void, these
two functions (setup andloop)donotreturnavalueassome functions do, so you
havetosaythattheyarevoid,using the void keyword. Ifyouimagineafunctioncalledsin that performed thetrigonometricfunctionofthatname, then this functionwould return a value. Thevaluereturnedtousefromthecall would be the sin of theanglepassedasitsargument.Rather like a legal
definition uses words todefine a term, we writefunctions in C that can then
becalledfromC.After the special keyword
void comes the name of thefunctionandthenparenthesesto contain any arguments. Inthis case, there are noarguments, but we still haveto include the parenthesesthere. There is no semicolonafter the closing parenthesisbecause we are defining afunctionratherthancallingit,so we need to say what willhappenwhensomethingdoes
callthefunction.Those things that are to
happen when the function iscalled must be placedbetween curly braces. Curlybraces and the code inbetweenthemareknownasablock of code, and this is aconcept that you will meetagainlater.Note that although you do
have to define both thefunctionssetupandloop,youdo not actually have to put
any lines of code in them.However, failing toaddcodewillmakeyoursketcha littledull.
Blink—Again!
The reason that Arduino hasthe two functions setup andloop is to separate the thingsthat only need to be done
once,whentheArduinostartsrunning its sketch, from thethings that have to keephappeningcontinuously.The function setup will
just be run once when thesketch starts. Let’s add somecode to it that will blink theLED built onto the board.Add the lines to your sketchso that it appears as followsandthenuploadthemtoyourboard:
The setup function itself
calls two built-in functions,pinMode and digitalWrite.You already know aboutdigitalWrite,butpinModeis
new. The function pinModesets a particular pin to beeither an input or an output.So, turning the LED on isactually a two-stage process.First, you have to set pin 13to be an output, and second,youneedtosetthatoutputtobehigh(5V).When you run this sketch,
on your board you will seethat the LED comes on andstays on. This is not veryexciting,solet’satleasttryto
makeitflashbyturningitonand off in the loop functionrather than in the setupfunction.You can leave the
pinMode call in the setupfunction because you onlyneed to call it once. Theproject would still work ifyou moved it into the loop,butthereisnoneedanditisagood programming habit todo things only once if youonly need to do them once.
Somodifyyoursketchsothatitlookslikethis:
Run this sketch and seewhat happens. It may not bequite what you wereexpecting. The LED isbasically on all the time.Hmm,whyshouldthisbe?Try stepping through the
sketchalineatatimeinyourhead:
1.Runsetupandsetpin13tobeanoutput.
2.Runloopandsetpin13to
high(LEDon).
3.Delayforhalfasecond.
4. Set pin 13 to low (LEDoff).
5.Runloopagain,goingbacktostep2,andsetpin13 tohigh(LEDon).The problem lies between
steps 4 and 5. What ishappening is that theLED isbeingturnedoff,butthevery
nextthingthathappensisthatit gets turned on again. Thishappens so quickly that itappearsthattheLEDisonallthetime.The microcontroller chip
on the Arduino can perform16 million instructions persecond.That’snot16millionClanguagecommands,but itisstillveryfast.So,ourLEDwill only be off for a fewmillionthsofasecond.To fix the problem, you
need to add another delayafter you turn the LED off.Your code should now looklikethis:
Try again and your LED
should blink away merrilyoncepersecond.Youmay have noticed the
comment at the top of thelisting saying “sketch 3-01.”Tosaveyousometyping,wehave uploaded to the book’swebsite all the sketches withsuch a comment at the top.Youcandownloadthemfromhttp://www.arduinobook.com.
Variables
In this Blink example, youuse pin 13 and have to referto it in three places. If youdecidedtouseadifferentpin,then you would have tochange the code in threeplaces. Similarly, if youwanted to change the rate ofblinking, controlled by theargumenttodelay,youwouldhave to change 500 to someother number in more than
oneplace.Variablescanbethoughtof
asgivinganametoanumber.Actually, they can be a lotmore powerful than this, butfor now, you will use themforthispurpose.When defining a variable
inC,youhave tospecify thetypeofthevariable.Wewantour variables to be wholenumbers, which in C arecalled ints. So to define avariable called ledPin with a
valueof13,youneedtowritethefollowing:
Notice thatbecause ledPin
is a name, the same rulesapply as those of functionnames. So, there cannot beanyspaces.Theconventionisto start variables with alowercase letter and begineach new word with anuppercase letter.
Programmers will often callthis “bumpy case” or “camelcase.”Let’s fit this into your
Blinksketchasfollows:
We have also sneaked inanother variable calleddelayPeriod.Everywhere in the sketch
whereyouusedtoreferto13,younowrefer to ledPin, andeverywhereyouused to referto 500, you now refer todelayPeriod.If you want to make the
sketch blink faster, you canjust change the value of
delayPeriod in one place.Try changing it to 100 andrunning the sketch on yourArduinoboard.There are other cunning
things that you can do withvariables. Let’s modify yoursketch so that the blinkingstartsreallyfastandgraduallygets slower and slower, as ifthe Arduino is getting tired.Todothis,allyouneedtodois to add something to thedelayPeriod variable each
timethatyoudoablink.Modify the sketch by
adding the single line at theend of the loop function sothat it appears, as in thefollowing listing, and thenrunthesketchontheArduinoboard.Press theResetbuttonandseeitstartfromafastrateofflashingagain.
Your Arduino is doing
arithmetic now. Every timethat loop is called, it will dothenormal flashof theLED,butthenitwilladd100tothevariable delayPeriod. Wewill come back to arithmeticshortly, but first you need abetter way than a flashingLEDtoseewhattheArduinoisupto.
ExperimentsinC
You need away to test yourexperimentsinC.Onewayistoput theCthatyouwant totest out into the setupfunction, evaluate them onthe Arduino, and then havethe Arduino display anyoutput back to somethingcalled the Serial Monitor, as
showninFigures3-5and3-6.The SerialMonitor is part
of the Arduino IDE. Youaccess it by clicking on therightmost icon in the toolbar.Its purpose is to act as acommunication channelbetween your computer andtheArduino.You can type amessageinthetextentryareaat the top of the SerialMonitor and when you pressReturn or click Send, it willsend that message to the
Arduino.Also if theArduinohas anything to say, thismessage will appear in theSerialMonitor.Inbothcases,the information is sentthroughtheUSBlink.
Figure3-5WritingC insetup
Figure 3-6 The SerialMonitor
Asyouwouldexpect,there
isabuilt-infunctionthatyoucan use in your sketches tosend a message back to theSerial Monitor. It is calledSerial.println and it expectsa single argument, whichconsists of the informationthat you want to send. Thisinformation is usually avariable.
You will use thismechanism to test out a fewthings that you can do withvariablesandarithmeticinC;frankly,it’stheonlywayyoucan see the results of yourexperimentsinC.
Numeric VariablesandArithmetic
The last thing you did wasaddthefollowinglinetoyour
blinking sketch to increasetheblinkingperiodsteadily:
Looking closely at this
line, it consists of a variablename, then an equals sign,then what is called anexpression (delayPeriod +100). The equals sign doessomething called assignment.Thatis,itassignsanewvaluetoavariable,andthevalueit
is given is determined bywhat comes after the equalssign and before thesemicolon. In this case, thenewvalue to be given to thedelayPeriod variable is theoldvalueofdelayPeriodplus100.Let’s test out this new
mechanism to see what theArduino is up to by enteringthefollowingsketch, runningit, and opening the SerialMonitor:
Figure3-7showswhatyou
should see in the SerialMonitorafterthiscoderuns.
To take a slightly morecomplex example, theformula for converting atemperature in degreesCentigrade into degreesFahrenheitistomultiplyitby5, divide by 9, and then add32.Soyoucouldwritethatinasketchlikethis:
Figure 3-7 Simplearithmetic
There are a few things to
notice here. First, note thefollowingline:
When we write such a line,we are actually doing twothings: We are declaring anintvariablecalleddegC,andwe are saying that its initialvalue will be 20.Alternatively, you couldseparatethesetwothingsandwritethefollowing:
You must declare any
variable justonce,essentiallytellingthecompilerwhattypeofvariableitis—inthiscase,int.However,youcanassignthe variable a value asmanytimesasyouwant:
So, in the Centigrade toFahrenheit example, you aredefining the variable degCand giving it an initial valueof 20, but when you definedegF,itdoesnotgetaninitialvalue. Itsvaluegetsassignedonthenextline,accordingtothe conversion formula,beforebeingsenttotheSerialMonitorforyoutosee.Looking at the expression,
you can see that you use theasterisk(*) formultiplication
and the slash (/) for division.Thearithmeticoperators+,−,*, and / have an order ofprecedence—that is,multiplicationsaredonefirst,thendivisions, thenadditionsand subtractions. This is inaccordancewiththeusualuseof arithmetic. However,sometimes itmakes itclearerto use parentheses in theexpressions.So, forexample,you could write thefollowing:
The expressions that you
write can be as long andcomplexasyouneedthemtobe, and in addition to theusual arithmetic operators,thereareotherlesscommonlyused operators and a bigcollection of variousmathematical functions thatareavailabletoyou.Youwilllearnabouttheselater.
Commands
TheClanguagehasanumberofbuilt-incommands. In thissection, we explore some oftheseandseehowtheycanbeofuseinyoursketches.
if
In our sketches so far, we
have assumed that your linesof programming will beexecuted in order one aftertheother,withnoexceptions.Butwhatifyoudon’twanttodo that? What if you onlywant to execute part of asketch if some condition istrue?Let’s return to our
gradually slowing-downBlinking LED example. Atthemoment, itwillgraduallyget slower and slower until
each blink is lasting hours.Let’s look at how we canchange it so that once it hasslowed down to a certainpoint, it goes back to its faststartingspeed.Todothis,youmustusean
if command; the modifiedsketch is as follows. Try itout.
The if command looks a
little like a functiondefinition, but thisresemblance is onlysuperficial. The word in theparenthesis is not anargument; it iswhat iscalleda condition. So in this case,the condition is that thevariable delayPeriod has avalue that is greater than3,000.If this is true, thenthecommands inside the curly
braces will be executed. Inthis case, the code sets thevalueofdelayPeriodbackto100.Iftheconditionisnottrue,
then the Arduino will justcontinue on with the nextthing. In this case, there isnothing after the “if”, so theArduino will run the loopfunctionagain.Running through the
sequence of events in yourheadwillhelpyouunderstand
what is goingon.So, here iswhathappens:
1. Arduino runs setup andinitializes the LED pin tobeanoutput.
2. Arduino starts runningloop.
3.TheLEDturnson.
4.Adelayoccurs.
5.TheLEDturnsoff.
6.Adelayoccurs.
7. Add 100 to thedelayPeriod.
8. If the delay period isgreater than 3,000 set itbackto100.
9.Gobacktostep2.We used the symbol <,
which means less than. It is
one example of what arecalled comparison operators.These operators aresummarized in the followingtable:
To compare two numbers,
you use the == command.This double equals sign is
easily confused with thecharacter=,which is used toassignvaluestovariables.Thereisanotherformof if
that allows you to do onething if the condition is trueand another if it is false.Wewillusethisinsomepracticalexampleslaterinthebook.
for
In addition to executing
different commands underdifferent circumstances, youalso oftenwillwant to run aseriesofcommandsanumberof times in a program. Youalready know one way ofdoing this, using the loopfunction. As soon as all thecommands in the loopfunctionhavebeenrun,itwillstart again automatically.However, sometimes youneedmorecontrolthanthat.So, for example, let’s say
that you want to write asketch that blinks 20 times,then paused for 3 seconds,and then started again. Youcould do that by justrepeating thesamecodeoverand over again in your loopfunction,likethis:
But this requires a lot oftyping and there are severalmuch better ways to do this.Let’s startby lookingathowyou can use a for loop andthen look at another way ofdoing it using a counter andanifstatement.The sketch to accomplish
thiswithaforloopis,asyoucan see, a lot shorter andeasier to maintain than the
previousexample:
The for loop looks a bit
likeafunctionthattakesthreearguments, although herethoseargumentsareseparatedbysemicolonsratherthantheusual commas. This is just aquirkof theC language.Thecompiler will soon tell youwhenyougetitwrong.The first thing in the
parentheses after for is avariable declaration. Thisspecifiesavariabletobeused
as a counter variable andgives it an initial value—inthiscase,0.The second part is a
condition that must be trueforyoutostayintheloop.Inthiscase,youwillstayintheloop as long as i is less than20, but as soon as i is 20 ormore, the program will stopdoing the things inside theloop.Thefinalpartiswhattodo
every timeyouhavedoneall
thethingsinthe loop. In thiscase,thatistoincrementiby1sothat itcan,after20tripsaround the loop, cease to beless than 100 and cause theprogramtoexittheloop.Try entering this code and
running it. The only way toget familiar with the syntaxandallthatpeskypunctuationis to type it in and have thecompiler tell you when youhave done something wrong.Eventually it will all start to
makesense.One potential downside of
thisapproach is that the loopfunction is going to take along time. This is not aproblem for this sketch,because all it is doing isflashing an LED. But often,the loop function in a sketchwill also be checking thatkeys have been pressed orthat serial communicationshave been received. If theprocessorisbusyinsideafor
loop,itwillnotbeabletodothis. Generally, it is a goodidea to make the loopfunction run as fast aspossible so that it canbe runasfrequentlyaspossible.The following sketch
showshowtoachievethis:
Youmay have noticed the
followingline:
ThisisjustCshorthandfor
thefollowing:
Sonoweachtimethatloopisrun, it will take just a bitmore than 200 milliseconds,
unless it’s the 20th timeroundtheloop,inwhichcaseitwill take thesameplus thethree seconds delay betweeneach batch of 20 flashes. Infact, for some applications,even this is too slow, andpurists would say that youshould not use delay at all.Thebestsolutiondependsontheapplication.
while
Anotherwayof looping inCis to use thewhilecommandinplaceoftheforcommand.Youcanaccomplishthesamething as the preceding forexample using a whilecommandasfollows:
The expression in
parentheses afterwhile mustbe true to stay in the loop.When it is no longer true,then the sketch continues
running the commands afterthefinalcurlybrace.
The#defineDirective
For constant values like pinassignments that do notchangeduring the runningofa sketch, there is analternativetousingavariable.You can use a command
called #define that allowsyou toassociateavaluewithaname.Everywhere that thisnameappears inyour sketch,the value will be substitutedbeforethesketchiscompiled.As an example, you could
defineapinassignment foraLEDlikethis:
Note that the #define
directivedoesnotusean“=”
between the name and thevalue.Itdoesnotevenneeda“;” on the end. This isbecauseit isnotactuallypartoftheClanguageitself;butiscalled a pre-compilerdirective that is run beforecompilation.This approach, in the
author’s opinion, is less easyto read thanusingavariable,butitdoeshavetheadvantagethat you do not use anymemory to store it. It is
something to consider ifmemoryisatapremium.
Conclusion
This chapter has got youstartedwithC.YoucanmakeLEDs blink in variousexciting ways and get theArduino to send results backtoyouovertheUSBbyusing
the Serial.println function.You alsoworked out how touse if and for commands tocontrol the order in whichyourcommandsareexecuted,and learned a little aboutmaking an Arduino do somearithmetic.In the next chapter, you
will look more closely atfunctions. The chapter willalso introduce the variabletypes other than the int typethatyouusedinthischapter.
4Functions
This chapter focusesmostlyon the type of functions thatyou canwrite yourself ratherthan the built-in functionssuch as digitalWrite anddelaythatarealreadydefined
foryou.Thereasonthatyouneedto
be able to write your ownfunctions is that as sketchesstart to get a littlecomplicated, thenyour setupand loop functionswill growand grow until they are longand complicated and itbecomes difficult to see howtheywork.The biggest problem in
software development of any
sort ismanaging complexity.The best programmers writesoftware that is easy to lookat and understand andrequiresverylittleinthewayofexplanation.Functionsareakeytool in
creating easy-to-understandsketches that can be changedwithout difficulty or risk ofthewhole thingfalling intoacrumpledmess.
WhatIsaFunction?
A function is a little like aprogram within a program.You can use it to wrap upsome little thing that youwant to do. A function thatyoudefinecanbecalledfromanywhere in your sketch andcontainsitsownvariablesandits own list of commands.
When the commands havebeenrun,executionreturnstothepointjustafterwhereveritwasinthecodethatcalledthefunction.By way of an example,
code that flashes a light-emitting diode (LED) is aprime example of some codethat should be put in afunction.So let’smodifyourbasic“blink20times”sketchtouseafunctionthatwewillcreatecalledflash:
So,allwehavereallydone
hereistomovethefourlinesof code that flash the LEDfrom the middle of the forloop to be in a function oftheir own called flash. Nowyou canmake theLED flashany time you like by justcalling the new function bywriting flash(). Note theempty parentheses after thefunctionname.Thisindicatesthatthefunctiondoesnottake
any parameters. The delayvaluethatitusesissetbythesame delayPeriod functionthatyouusedbefore.
Parameters
When dividing your sketchup into functions, it is oftenworth thinking about whatservice a function could
provide. In the caseof flash,thisisfairlyobvious.Butthistime, let’s give this functionparameters that tell it both,howmany times to flashandhowshortor long theflashesshould be. Read through thefollowingcodeandthenIwillexplain just how parametersworkinalittlemoredetail.
Now, if we look at our
loopfunction,ithasonlytwolines in it. We have movedthebulkoftheworkofftotheflash function. Notice howwhen we call flash we nowsupply itwith twoargumentsinparentheses.Where we define the
function at the bottomof thesketch,wehavetodeclarethetype of variable in theparameters. In thiscase, they
are both ints.We are in factdefining new variables.However, these variables(numFlashesandd)canonlybe used within the flashfunction.This is a good function
because it wraps upeverything you need in orderto flash an LED. The onlyinformationthatitneedsfromoutside of the function is towhich pin the LED isattached. If you wanted, you
could make this a parametertoo—something that wouldbe well worth doing if youhad more than one LEDattachedtoyourArduino.
Global, Local, andStaticVariables
As was mentioned before,parameters to a function can
be used only inside thatfunction.So,ifyouwrotethefollowing code, you wouldgetanerror:
Ontheotherhand,suppose
youwrotethis:
Thiscodewouldnotresultinacompilationerror.However,you need to be careful,because you now actuallyhave two variables called xand they can each havedifferentvalues.Theonethat
youdeclaredon the first lineis calledaglobalvariable. Itiscalledglobalbecauseitcanbeusedanywhereyoulikeintheprogram, including insideanyfunctions.However, because you use
the same variable name xinside the function, as aparameter,youcannotusetheglobal variable x simplybecause whenever you referto x inside the function, the“local” version of x has
priority. The parameter x issaid to shadow the globalvariable of the same name.This can lead to someconfusion when trying todebugaproject.In addition to defining
parameters, you can alsodefine variables that are notparametersbutarejustforusewithin a function. These arecalled local variables. Forexample:
The local variabletimesToFlashwillonlyexistwhilethefunctionisrunning.As soon as the function hasfinished its last command, itwill disappear. This meansthat local variables are not
accessible from anywhere inyour program other than inthefunctioninwhichtheyaredefined.So, for instance, the
followingexamplewillcauseanerror:
Seasoned programmersgenerally treat globalvariableswith suspicion.Thereason is that theygoagainstthe principal ofencapsulation. The idea ofencapsulation is that youshouldwrap up in a packageeverythingthathastodowitha particular feature. Hencefunctions are great forencapsulation. The problemwith “globals” (as globalvariables are often called) is
that they generally getdefinedat thebeginningof asketch andmay thenbeusedall over the sketch.Sometimes there is aperfectlylegitimatereasonforthis. Other times, people usethem in a lazy way when itwould be far moreappropriate to passparameters. In our examplessofar,ledPinisagooduseofa global variable. It’s alsovery convenient and easy to
find up at the top of thesketch, making it easy tochange. Actually, ledPin isreally a constant, becausealthough you may change itand then recompile yoursketch, you are unlikely toallow the variable to changewhile the sketch is actuallyrunning.For this reason, youmayprefertousethe#definecommand we described inChapter3.Another feature of local
variablesisthattheirvalueisinitialized every time thefunction is run. This isnowheremoretrue(andofteninconvenient)thanintheloopfunction of an Arduinosketch. Let’s try and use alocal variable in place ofglobal variable in one of theexamples from the previouschapter:
Sketch4-03isbasedonthe
sketch 3-09, but attempts tousealocalvariableinsteadofthe global variable to countthenumberofflashes.This sketch is broken. It
will notwork, because everytime loop is run, thevariablecountwillbegiventhevalue0 again, so count will neverreach 20 and the LED willjust keep flashing forever.The whole reason that we
made count a global in thefirst place was so that itsvaluewouldnotbereset.Theonlyplace thatweusecountisintheloopfunction,sothisiswhereitshouldbeplaced.Fortunately, there is a
mechanism in C that getsaround this conundrum. It isthe keyword static. Whenyouusethekeywordstaticinfrontofavariabledeclarationinafunction,ithastheeffectof initializing the variable
only the first time that thefunction is run. Perfect!That’sjustwhatisrequiredinthis situation. We can keepour variable in the functionwhere it’s used without itgetting set back to 0 everytimethefunctionruns.Sketch4-04showsthisinoperation:
ReturnValues
Computer science, as anacademicdiscipline,hasasitsparents mathematics andengineering. This heritagelingers on in many of thenames associated withprogramming. The word
function is itself amathematical term. Inmathematics, the input to thefunction (the argument)completely determines theoutput. We have writtenfunctions that take an input,but none that give us back avalue.Allour functionshavebeen “void” functions. If afunctionreturnsavalue, thenyouspecifyareturntype.Let’s look at writing a
function that takes a
temperature in degreesCentigrade and returns theequivalent in degreesFahrenheit:
The function definition nowstarts with int rather thanvoid to indicate that the
functionwill return an int towhatever calls it. Thismightbeabitofcodethatlookslikethis:
Anynon-void functionhas
tohaveareturnstatementinit. If you do not put one in,thecompilerwilltellyouthatit is missing. You can havemore than one return in thesame function. This might
arise if you have an ifstatement with alternativeactions based on somecondition. Someprogrammers frown on this,butifyourfunctionsaresmall(as all functions should be),thenthispracticewillnotbeaproblem.Thevalueafterreturncan
be an expression; it does nothavetojustbethenameofavariable. So you couldcompress the preceding
exampleintothefollowing:
If the expression being
returned is more than just avariable name, then it shouldbeenclosedinparenthesesasintheprecedingexample.
Other Variable
Types
Allourexamplesofvariablessofarhavebeenintvariables.This is by far the mostcommonlyusedvariabletype,buttherearesomeothersthatyoushouldbeawareof.
floats
One such type, which isrelevant to the previoustemperature conversionexample, is float. Thisvariable type representsfloating point numbers—thatis, numbers that may have adecimal point in them, suchas 1.23. You need thisvariable type when wholenumbers are just not preciseenough.Note the following
formula:
If you give c the value 17,thenfwillbe17*9/5+32or62.6.Butiffisanint,thenthevaluewillbetruncatedto62.Theproblembecomeseven
worseifwearenotcarefulofthe order in which weevaluate things. For instance,suppose that we did thedivisionfirst,asfollows:
Then in normal math terms,theresultwouldstillbe62.6,butifallthenumbersareints,then the calculation wouldproceedasfollows:
1. 17 is divided by 5, whichgives 3.4, which is thentruncatedto3.
2. 3 is then multiplied by 9
and 32 is added to give aresultof59—whichisquitealongwayfrom62.6.Forcircumstanceslikethis,
we can use floats. In thefollowing example, ourtemperature conversionfunction is rewritten to usefloats:
Noticehowwehaveadded.0to the end of our constants.Thisensuresthatthecompilerknows to treat themas floatsratherthanints.
boolean
Boolean values are logical.They have a value that iseithertrueorfalse.IntheClanguage,Boolean
isspelledwithalowercaseb,but in general use, Booleanhasanuppercaseinitialletter,as it is named after themathematicianGeorgeBoole,who invented the Booleanlogic that is crucial tocomputerscience.Youmaynotrealizeit,but
you have already met
Boolean values when wewere looking at the ifcommand. The condition inan if statement, such as(count==20), is actually anexpression that yields aboolean result. The operator== is called a comparisonoperator. Whereas + is anarithmetic operator that addstwonumberstogether,==isacomparison operator thatcompares two numbers andreturns a value of either true
orfalse.You can define Boolean
variables and use them asfollows:
Boolean values can be
manipulated using Booleanoperators. So, similar to how
you can perform arithmeticon numbers, you can alsoperform operations onBoolean values. The mostcommonly used Booleanoperators are and, which iswrittenas&&,andor,whichiswrittenas||.Figure 4-1 shows truth
tables for the and and oroperators.From the truth tables in
Figure 4-1, you can see thatforand, if bothAandB are
true, then the result will betrue;otherwise,theresultwillbefalse.Ontheotherhand,withthe
or operator, if either A or BorbothAandBaretrue,thenthe result will be true. Theresult will be false only ifneitherAnorBistrue.In addition toand andor,
there is the not operator,written as !. Youwill not besurprised to learn that “nottrue” is false and “not false”
istrue.
Figure4-1Truthtables
You can combine theseoperators into Booleanexpressions in your ifstatements, as the followingexampleillustrates:
OtherDataTypes
Asyouhaveseen,theintandoccasionally the float datatypes are fine for most
situations; however, someother numeric types can beuseful under somecircumstances. InanArduinosketch, the int type uses 16bits (binary digits). Thisallowsittorepresentnumbersbetween−32767and32768.Other data types available
to you are summarized inTable 4-1. This table isprovided mainly forreference.Youwillusesomeof these other types as you
progressthroughthebook.
Table4-1DataTypesinC
One thing to consider is
thatifdatatypesexceedtheirrange, then strange thingshappen. So, if you have abyte variable with 255 in itandyouadd1toit,youget0.Morealarmingly, ifyouhavean int variable with 32767andyouadd1 to it, youwill
endupwith−32768.Until you are completely
comfortable with thesedifferent data types, I wouldrecommendstickingtoint,asit works for pretty mucheverything.
CodingStyle
The C compiler does not
reallycareabouthowyoulayoutyourcode.Forallitcares,youcanwriteeverythingonasingle line with semicolonsbetween each statement.However, well-laid-out, neatcode is much easier to readand maintain than poorlylaid-out code. In this sense,reading code is just likereadingabook:Formattingisimportant.Tosomeextent,formatting
is a matter of personal taste.
Noone likes to think that hehas bad taste, so argumentsabout how code should lookcanbecomepersonal.Itisnotunknown for programmers,on being required to dosomething with someoneelse’s code, to start byreformattingall thecode intotheir preferred style ofpresentation.As an answer to this
problem,codingstandardsareoften laiddowntoencourage
everyonetolayouthisorhercode in the same way andadopt “good practice” whenwritingprograms.The C language has a de
facto standard that hasevolved over the years, andthisbookisgenerallyfaithfultothatstandard.
Indentation
In the example sketches that
you have seen, you can seethat we often indent theprogram code from the leftmargin. So, for examplewhen defining a voidfunction,thevoidkeywordisat the left margin, as is theopening curly brace on thenextline,butthenallthetextwithin the curly braces isindented. The amount ofindentation does not reallymatter.Somepeople use twospaces, some four. You can
also press Tab to indent. Inthisbook,weuse twospacesforindentation.If you were to have an if
statement inside a functiondefinition, then once againyou would add two morespacesforthelineswithinthecurly braces of the ifcommand,asinthefollowingexample:
Youmight includeanother
if inside the first if, whichwould add yet another levelof indentation, making six
spacesfromtheleftmargin.All of this might sound a
bittrivial,butifyoueversortthroughsomeoneelse’sbadlyformatted sketches, you willfinditverydifficult.
OpeningBraces
There are two schools ofthoughtastowheretoputthefirstcurlybraceinafunctiondefinition,ifstatement,orfor
loop.Onewayistoplacethecurly brace on the line afterthe rest of the command, aswe have in all the examplesso far, or put it on the sameline,likethis:
This style ismost commonlyusedintheJavaprogramminglanguage,whichsharesmuchof the same syntax as C. Iprefer the first form, whichseems to be the form mostcommonly used in theArduinoworld.
Whitespace
The compiler ignores spacestabsandnewlines,apartfromusing them as a way ofseparating the “tokens” orwords in your sketch. Thusthe following example willcompilewithoutaproblem:
Thiswillwork,butgoodlucktryingtoreadit.Where assignments are
made,somepeoplewillwritethefollowing:
But others will write thefollowing:
Whichofthesetwostylesyouusereallydoesnotmatter,butit is a good idea to beconsistent. I use the firstform.
Comments
Comments are text that iskept in your sketch alongwith all the real programcode, but which actuallyperforms no programming
functionwhatsoever.Thesolepurposeofcommentsistobearemindertoyouorothersastowhy thecode iswrittenasit is. A comment line mayalsobeusedtopresentatitle.The compiler will
completely ignore any textthat is marked as being acomment. We have includedcomments as titles at the topofmanyofthesketchesinthebooksofar.There are two forms of
syntaxforcomments:
• The single line commentthat starts with // andfinishes at the end of theline
•Themultilinecommentthatstarts with a /* and endswitha*/The following is an
example using both forms ofcomments:
Inthisbook,Imostlystick
to the single-line comment
format.Good comments help
explainwhat is happening ina sketch or how to use thesketch. They are useful ifothers are going to use yoursketch, but equally useful toyourself when you arelooking at a sketch that youhavenotworkedonforafewweeks.Some people are told in
programmingcoursesthatthemore comments, the better.
Most seasoned programmerswill tellyouthatwell-writtencoderequiresverylittleintheway of comments because itis self-explanatory. Youshould use comments for thefollowingreasons:
• To explain anything youhave done that is a littletricky or not immediatelyobvious
• To describe anything thattheuserneeds todo that is
notpartoftheprogram;forexample,//thispinshouldbe connected to thetransistor controlling therelay
•Toleaveyourselfnotes;forexample,//todo:tidythis-it’samessThis last point illustrates a
useful technique of todos incomments. Programmersoftenput todos in their codeto remind themselves ofsomething they need to do
later.Theycanalwaysusethesearch facility in theirintegrated developmentenvironment(IDE)tofindalloccurrencesof//todointheirprogram.Thefollowingarenotgood
examples of reasons youshouldusecomments:
• To state the blatantlyobvious;forexample,a=a+1;//add1toa.
• To explain badly written
code.Don’tcommentonit;just write it clearly in thefirstplace.
Conclusion
This has been a bit of atheoreticalchapter.Youhavehad to absorb some newabstract concepts concernedwith organizing our sketches
into functionsandadoptingastyle of programming thatwillsaveyoutimeinthelongrun.In the next chapter, you
can start to apply some ofwhat you have learned andlook at better ways ofstructuring your data andusingtextstrings.
5ArraysandStrings
AfterreadingChapter4,youhave a reasonableappreciation as to how tostructure your sketches tomakeyourlifeeasier.Ifthere
is one thing that a goodprogrammerlikes,it’saneasylife. Now our attention isgoing to turn to thedata thatyouuseinyoursketches.The book Algorithms +
Data Structures = Programsby Niklaus Wirth has beenaroundforagoodwhilenow,but still manages to capturethe essences of computerscience and programming inparticular. I can strongly
recommend it toanyonewhofindsthemselvesbittenbytheprogramming bug. It alsocapturestheideathattowriteagoodprogram,youneed tothink about both thealgorithm (what you do) andthe structure of the data youuse.You have looked at loops,
if statements, and what iscalled the “algorithmic” sideof programming an Arduino;youarenowgoing to turn to
howyoustructureyourdata.
Arrays
Arrays are a way ofcontaining a list of values.The variables that you havemet so far have containedonly a single value, usuallyan int. By contrast, an arraycontains a list of values, and
you can access any one ofthosevaluesbyitspositioninthelist.C, in common with the
majority of programminglanguages, begins its indexpositions at 0 rather than 1.This means that the firstelement is actually elementzero.To illustrate the use of
arrays, we could create anexample application thatrepeatedly flashes “SOS” in
Morse code using theArduino board’s built-inLED.Morse code used to be a
vital method ofcommunication in the 19thand 20th centuries. Becauseof its coding of letters as aseriesof longand short dots,Morse code can be sent overtelegraphwires, over a radiolink, and using signalinglights. The letters “SOS” (anacronymfor“saveoursouls”)
is still recognized as aninternational signal ofdistress.The letter “S” is
represented as three shortflashes (dots) and the letter“O” by three long flashes(dashes). You are going touse an array of ints to holdthedurationofeachflashthatyou are going to make. Youcanthenuseaforlooptostepthrough each of the items inthe array, making a flash of
theappropriateduration.First let’s have a look at
how you are going to createanarrayofintscontainingthedurations.
Youindicatethatavariable
contains an array by placing[]afterthevariablename.In this case, youaregoing
to set the values for thedurationsatthetimethatyou
create the array. The syntaxfor doing this is to use curlybraces and then values eachseparated by commas. Don’tforget the semicolon on theendoftheline.You can access any given
elementofthearrayusingthesquarebracketnotation.So,ifyou want to get the firstelementofthearray,youcanwritethefollowing:
To illustrate this, let’s
createanarrayandthenprintoutallitsvaluestotheSerialMonitor:
Upload the sketch to your
board and then open theSerialMonitor. If all iswell,you will see something likeFigure5-1.
This is quite neat, becauseif you wanted to add moredurationstothearray,allyouwouldneedtodoisaddthemto the list inside the curlybraces andchange“9” in theforlooptothenewsizeofthearray.
Figure 5-1 The SerialMonitor Showing theOutputofSketch5-01
You have to be a little
careful with arrays, becausethe compilerwill not try andstop you from accessingelements of data that arebeyond the end of the array.This is because the array isreallyapointer toanaddress
in memory, as shown inFigure5-2.Programs keep their data,
both ordinary variables andarrays, inmemory. Computermemory is arranged muchmore rigidly than the humankind ofmemory. It is easiestto thinkof thememory inanArduino as a collection ofpigeonholes. When youdefine an array of nineelements, for example, thenext available nine
pigeonholes are reserved foritsuseandthevariableissaidtopointatthefirstpigeonholeorelementofthearray.Going back to our point
about access being allowedbeyond the bounds of yourarray, if you decided toaccess durations[10], thenyou would still Memory getback an int, but the value ofthis int could be anything.This is in itself fairlyharmless, except that if you
accidentally get a valueoutside of the array, you arelikelytogetconfusingresultsinyoursketch.
Figure 5-2 Arrays andPointers
However,whatisfarworse
isifyoutrychangingavalueoutside of the size of thearray. For instance, if youwere to include somethinglike the following in yourprogram, the results couldsimply make your sketchbreak:
The pigeonhole
durations[10]may be in useas some completely differentvariable. So always makesure that you do not gooutside of the size of thearray. If your sketch startsbehaving strangely, thencheck for this kind ofproblem.
Morse Code SOS
UsingArrays
Sketch 5-02 shows how youcanuseanarraytomakeyouremergencysignalofSOS:
An obvious advantage of
thisapproachisthatitisveryeasy to change the messageby simply altering thedurations array. In sketch5-05, you will take the use ofarraysastagefurthertomakea more general-purposeMorsecodeflasher.
StringArrays
In the programming world,thewordstringhasnothingtodo with long thin stuff thatyoutieknotsin.Astringisasequence of characters. It’sthe way you can get yourArduinotodealwithtext.Forexample,thesketch5-03willrepeatedly send the text“Hello”totheSerialMonitoronetimepersecond:
StringLiterals
String literalsareenclosed indoublequotationmarks.Theyareliteralinthesensethatthestringisaconstant,ratherliketheint123.As youwould expect, you
can put strings in a variable.There is also an advancedstring library, but for nowyou will use standard Cstrings, such as the one insketch5-03.In C, a string literal is
actually an array of the type
char. The type char is a bitlikeintinthatitisanumber,but thatnumber isbetween0and 127 and represents onecharacter. The character maybe a letter of the alphabet, anumber, a punctuation mark,oraspecialcharactersuchasa tab or a line feed. Thesenumbercodesforlettersuseastandard calledASCII; Someof the most commonly usedASCII codes are shown inTable5-1.
Table 5-1 CommonASCIICodes
Thestringliteral“Hello”is
actually an array ofcharacters, as shown inFigure5-3.
Note that the string literalhasaspecialnullcharacteratthe end. This character isusedtoindicatetheendofthestring.
StringVariables
As you would expect, stringvariables are very similar toarray variables, except thatthere is a useful shorthandmethod for defining their
initialvalue.
This defines an array of
charactersandinitializesit totheword“Hello.”Itwillalsoaddafinalnullvalue(ASCII0) to mark the end of thestring.
Figure 5-3 The StringLiteral“Hello”
Although the precedingexample is most consistentwith what you know aboutwriting arrays, it would bemore common to write thefollowing:
This is equivalent, and the
*indicatesapointer.Theideaisthatnamepointstothefirstchar element of the chararray. That is the memory
location that contains theletterH.You can rewrite sketch 5-
03touseavariableaswellasastringconstant,asfollows:
A Morse CodeTranslator
Let’s put together what youhavelearnedaboutarraysandstrings to build a morecomplex sketch that willaccept anymessage from theSerialMonitorandflashitoutonthebuilt-inLED.The letters in Morse code
areshowninTable5-2.SomeoftherulesofMorse
code are that a dash is threetimes as long as a dot, thetime between each dash ordotisequaltothedurationofadot, the spacebetween twolettersisthesamelengthasadash, and the space betweentwo words is the samedurationassevendots.For this project, we will
notworry about punctuation,although it would be an
interestingexerciseforyoutotry adding this to the sketch.ForafulllistofalltheMorsecharacters, seeen.wikipedia.org/wiki/Morse_code
Table 5-2 Morse CodeLetters
Data
You are going to build thisexample a step at a time,starting with the datastructurethatyouaregoingtousetorepresentthecodes.It is important to
understand that there is noone solution to this problem.Different programmers willcome up with different waystosolveit.So,itisamistaketothinktoyourself,“Iwouldnever have come up withthat.”Well,no,quitepossiblyyou would come up withsomething different andbetter. Everyone thinks indifferent ways, and thissolution happens to be theone that firstpopped into the
author’shead.Representingthedataisall
about finding a way ofexpressingTable5-2 inC. Infact,youaregoingtosplitthedata into two tables: one forthe letters, and one for thenumbers. The data structureforthelettersisasfollows:
What you have here is an
array of string literals. So,because a string literal isactually an array of char,what you actually have hereis an array of arrays—
something that is perfectlylegalandreallyquiteuseful.This means that to find
Morse for A, you wouldaccess letters[0], whichwould give you the string .-.This approach is not terriblyefficient, because you areusing a whole byte (eightbits)ofmemorytorepresentadashoradot,whichcouldberepresentedinabit.However,you can easily justify thisapproach by saying that the
total number of bytes is stillonlyabout90andwedohave2K to play with. Equallyimportantly, it makes thecodeeasytounderstand.Numbers use the same
approach:
GlobalsandSetup
You need to define a coupleof global variables: one forthedelayperiodforadot,andone to define which pin theLEDisattachedto:
The setup function is
pretty simple; you just needtosettheledPinasanoutputandsetuptheserialport:
Theloopfunction
Youarenowgoingtostartonthe real processing work inthe loop function. Thealgorithm for this function isasfollows:
•IfthereisacharactertoreadfromUSB:
•If it’saletter,flashitusingthelettersarray
• If it’s a number, flash itusingthenumbersarray
• If it’s a space, flash fourtimesthedotdelayThat’s all. You should not
think too far ahead. Thisalgorithm represents whatyouwanttodo,orwhatyourintention is, and this style ofprogramming is called
programmingbyintention.If youwrite this algorithm
inC,itwilllooklikethis:
Thereareafewthingshere
that need explaining. First,thereisSerial.available().Tounderstandthis,youfirstneedtoknowalittleabouthowanArduino communicates withyour computer over USB.Figure 5-4 summarizes thisprocess.In the situation where the
computer is sending datafromtheSerialMonitortotheArduinoboard, thentheUSB
is converted from the USBsignal levels and protocol tosomething that themicrocontroller on theArduino board can use. Thisconversion happens in aspecial-purpose chip on theArduino board. The data isthenreceivedbyapartofthemicrocontroller called theUniversal AsynchronousReceiver/Transmitter(UART). The UART placesthe data it receives into a
buffer.Thebufferisaspecialarea of memory (128 bytes)that can hold data that isremovedassoonasitisread.
Figure 5-4 Serialcommunication with anArduino
This communication
happens regardless of whatyoursketchisdoing.So,eventhough you may be merrilyflashingLEDs, datawill stillarrive in the buffer and sitthere until you are ready toread it.You can think of thebufferasbeingabitlikeane-mailinbox.
Theway thatyoucheck toseewhether you “havemail”is to use the functionSerial.available(). Thisfunction returns the numberofbytesofdata in thebufferthat are waiting for you toread.Iftherearenomessageswaiting to be read, then thefunction returns 0. This iswhy the if statement checkstoseethattherearemorethanzero bytes available to read,and if they are, then the first
thing that the statement doesis read the next availablechar, using the functionSerial.read(). This functiongets assigned to the localvariablech.Nextisanotheriftodecide
what kind of thing it is thatyouwanttoflash:
At first, thismight seem a
bitstrange.Youareusing<=and >= to comparecharacters. You can do thatbecause each character isactually represented by anumber(itsASCIIcode).So,ifthecodeforthecharacterissomewhere between a and z(97and122), thenyouknowthat the character that hascome from the computer is alowercase letter. You then
call a function that you havenot written yet calledflashSequence, towhichyouwillpassa stringofdotsanddashes; for example, to flasha, youwould pass it .- as itsargument.You are devolving
responsibility to this functionfor actually doing theflashing. You are not tryingto do it inside the loop. Thislets us keep the code easy toread.
Here is the C thatdetermines the string ofdashesanddotsthatyouneedtosend to the flashSequencefunction:
Once again, this looks a
little strange. The functionappears tobesubtractingonecharacter from another. Thisis actually a perfectlyreasonable thing to do,
because the function isactually subtracting theASCIIvalues.Remember that you are
storing the codes for thelettersinanarray.Sothefirstelementof thearraycontainsastringofdashesanddotsforthe letter A, the secondelementincludesthedotsanddashes for B, and so on. Soyou need to find the rightposition in the array for theletter that you have just
fetched from the buffer. Theposition for any lowercaseletter will be the charactercode for the letter minus thecharacter code for a. So, forexample,a–a isactually97– 97 = 0. Similarly, c –a isactually 99 – 97 = 2. So, inthefollowingstatement, ifchis the letter c, then the bitinside the square bracketswouldevaluate to2,andyouwouldgetelement2fromthearray,whichis-.-:
What this section has justdescribed is concerned withlowercase letters. You alsohave to deal with uppercaseletters and numbers. Theseare both handled in a similarmanner.
The flashSequenceFunction
We have assumed a functioncalled flashSequence and
made use of it, but now youneed to write it. We haveplannedfor it to takeastringcontaining a series of dashesand dots and to make thenecessary flashes with thecorrecttimings.Thinking about the
algorithm for doing this, youcanbreakitintothefollowingsteps:
• For each element of thestring of dashes and dots
(suchas.-.-)•flashthatdotordashUsingthe concept ofprogramming by intention,let’s keep the function assimpleasthat.The Morse codes are not
thesamelengthforallletters,so you need to loop aroundthestringuntilyouencounterthe endmarker, \0.You alsoneedacountervariablecalledi that starts at 0 and isincrementedastheprocessing
looksateachdotanddash:
Again, you delegate the
actual job of flashing an
individual dot or dash to anew method calledflashDotOrDash, whichactuallyturnstheLEDonandoff. Finally, when theprogram has flashed the dotsanddashes, it needs topauseforthreedotsworthofdelay.Note the helpful use of acomment.
The flashDotOrDashFunction
The last function in yourchain of functions is the onethatactuallydoestheworkofturning the LED on and off.As its argument, the functionhas a single character that iseitheradot(.)oradash(–).All the function needs to
do is turn the LED on anddelayforthedurationofadotif it’s a dot and three timesthe duration of a dot if it’s adash, then turn the LED offagain. Finally it needs to
delay for theperiodofadot,to give the gap betweenflashes.
Putting It AllTogether
Putting all this together, thefulllistingisshowninsketch5-05. Upload it to yourArduinoboard and try it out.Remember that touse it,youneed to open the SerialMonitor and type some textinto the area at the top and
click Send. You should thensee that textbeing flashedasMorsecode.
Thissketchincludesaloopfunction that is calledautomatically and repeatedlycalls a flashSequencefunction that you wrote,whichitselfrepeatedlycallsaflashDotOrDashfunction thatyou wrote, which callsdigitalWrite and delayfunctionsthatareprovidedbyArduino!This is how your sketches
should look. Breaking thingsup into functions makes it
mucheasier togetyourcodeworking and makes it easierwhen you return to it after aperiodofnotusingit.
Conclusion
In addition to looking atstrings and arrays in thischapter, you have also builtthis more complex Morse
translatorthatIhopewillalsoreinforce the importance ofbuilding your code withfunctions.In the next chapter, you
learn about input and output,bywhichwemean inputandoutput of analog and digitalsignalsfromtheArduino.
6InputandOutput
The Arduino is aboutphysical computing, and thatmeansattachingelectronicstothe Arduino board. So youneed to understand how to
use the various options foryourconnectionpins.Outputs can be digital,
which just means switchedbetweenbeingat0Vorat5V,or analog, which allows youto set the voltage to anyvoltage between 0V and 5V—although it’s not quite assimple as that, as we shallsee.Likewise, inputscaneither
be digital (for example,
determiningwhetherabuttonpressed or not) or analog(suchasfromalightsensor).Inabookthatisessentially
about software rather thanhardware,wearegoingtotryandavoidbeingdragged intotoo much discussion ofelectronics. However, it willhelp you to understand whatishappeninginthischapterifyou can find yourself amultimeterandashortlengthofsolidcorewire.
DigitalOutputs
In earlier chapters, you havemadeuseoftheLEDattachedto digital pin 13 of theArduino board. For example,inChapter5,youuseditasaMorse code signaler. TheArduino board has a wholeloadofdigitalpinsavailable.Let’s experiment with one
of the other pins on theArduino.Youwillusedigitalpin 4, and to see what isgoing on, you will fix somewiretoyourmultimeterleadsand attach them to yourArduino. Figure 6-1 showsthe arrangement. If yourmultimeter has crocodileclips, strip the insulation offthe ends of some shortlengthsofsolidcorewireandattach the clip to one end,fitting the other end into the
Arduino socket. If yourmultimeter does not havecrocodileclipsthenwraponeof the stripped wire endsaroundtheprobe.
Figure 6-1 Measuringoutputs with amultimeter
Themultimeterneedstobe
settoits0–20Vdirectcurrent(DC) range. The negativelead (black) should beconnected to the ground(GND)pinandthepositivetoD4. The wire is justconnected to the probe lead
and poked into the socketheaders on the Arduinoboard.Loadsketch6-01:
At the top of the sketch,
you can see the commandpinMode. You should usethis command for every pinthatyouareusinginaprojectsothatArduinocanconfigurethe electronics connected tothat pin to be either an inputor an output, as in thefollowingexample:
As you might haveguessed,pinMode is a built-infunction.Itsfirstargumentis thepinnumberinquestion(an int), and the secondargument is themode,whichmust be either INPUT orOUTPUT. Note that themode name must be alluppercase.This loop waits for a
command of either1 or0 tocomefromtheSerialMonitoronyourcomputer. It it’sa1,
thenpin4will be turnedon;otherwise, it will be turnedoff.Upload the sketch to your
Arduino and then open theSerial Monitor (shown inFigure6-2).So, with the multimeter
turned on and plugged intothe Arduino, you should beabletoseeitsreadingchangebetween0Vandabout5Vasyou send commands to theboardfromtheSerialMonitor
byeitherpressing1 and thenReturn or pressing 0 andthen Return. Figure 6-3showsthemultimeterreadingafter a 1 has been sent fromtheSerialMonitor.Iftherearenotenoughpins
labeled “D” for your project,youcanactuallyuse thepinslabeled “A” (for analog) asdigitaloutputstoo.Todothis,youjusthavetoadd14totheanalog pin number. Youcould try this out by
modifying the first line insketch6-01tousepin14andmoving your positivemultimeter lead topinA0ontheArduino.Thatisreallyallthereisto
digital outputs, so let’smoveonswiftlytodigitalinputs.
Figure 6-2 The Serial
Monitor
Figure 6-3 Setting theoutputtoHigh
DigitalInputs
The most common use ofdigital inputs is to detectwhen a switch has beenclosed. A digital input can
either be on or off. If thevoltage at the input is lessthan2.5V(halfwayto5V), itwill be 0 (off), and if it isabove2.5V,itwillbe1(on).Disconnect your
multimeter and upload thesketch 6-02 onto yourArduinoboard:
As with using an output,
you need to tell the Arduinointhesetupfunctionthatyouare going to use a pin as aninput.Youget thevalueofadigital input using thedigitalRead function. Thisreturns0or1.
Pull-upResistors
Thesketchreadstheinputpin
and writes its value to theSerial Monitor once persecond.Soupload the sketchand open the SerialMonitor.You should see a valueappearoncepersecond.Pushone end of your bit of wireinto the socket for D5 andpinch the end of the wirebetween your finger, asshowninFigure6-4.Continue pinching for a
few seconds and watch thetext appear on the Serial
Monitor. You should see amixture of ones and zerosappear in the SerialMonitor.Thereasonforthisisthattheinputs to the Arduino boardare very sensitive. You areacting as an antenna, pickingupelectricalinterference.Take the end of the wire
that you were holding andpush it into the socket for+5Vas shown inFigure 6-5.The stream of text in theSerialMonitorshouldchange
toones.
Figure 6-4 A digitalinput with a humanantenna
Figure 6-5 Pin 5connectedto+5V
Nowtake theend thatwas
in+5Vandput it intooneofthe GND connections on theArduino. As you wouldexpect, the Serial Monitorshouldnowdisplayzeros.A typical use for an input
pin is to connect a switch toit.Figure6-6showshowyou
mightbeexpectingtoconnectyourswitch.The problem with this is
that if the switch is notclosed, then the input pin isnot connected to anything. Itis said to be floating, andcould easily give you a falsereading.Youneedyourinputto be more predictable, andthe way to do this is withwhat is called a pull-upresistor.Figure6-7showsthestandard use of a pull-up
resistor. It has the effect thatiftheswitchisopen,thentheresistor pulls up the floatinginput to5V.Whenyoupressthe switch and close thecontact, the switch overridesthe effect of the resistor,forcing the input to 0V.Oneside-effect of this is, whilethe switch is closed, 5Vwillbeacrosstheresistor,causinga current to flow. So, thevalue of the resistor isselected to be low enough to
make it immune from anyelectrical interference, but atthesametimehighenoughtoprevent excessive currentdrain when the switch isclosed.
Figure6-6Connectingaswitch to an Arduinoboard
Figure6-7Switchwithapull-upresistor
Internal Pull-upResistors
Fortunately, the Arduinoboard has software-configurable pull-up resistorsbuilt into thedigital pins.By
default, they are turned off.So all you need to do toenable thepull-upresistoronpin5forsketch6-02istoaddthefollowingline:
This linegoesinthesetup
functionrightafteryoudefinethe pin as an input. It mayseem a little strange to do adigitalWrite to an input, butthisisjustthewayitworks.
Sketch6-03isthemodifiedversion. Upload it to yourArduino board and test it byacting like an antenna again.Youshouldfindthatthistimethe input stays at 1 in theSerialMonitor.
Debouncing
Whenyoupressapushbutton,you would expect that youwouldjustgetasinglechangefrom 1 (with a pull-upresistor) to 0 as thebutton isdepressed. Figure 6-8 showswhat can happen when youpress a button. The metalcontactsinthebuttonbounce.
So a single button pressbecomes a series of pressesthateventuallystabilize.All this happens very
quickly;thetotaltimespanofthe button press on theoscilloscopetraceisonly200milliseconds. This is a very“ropey” old switch. A newtactile, click-typebuttonmaynotevenbounceatall.Sometimes bouncing does
notmatteratall.Forinstance,sketch 6-04 will light the
LED while the button ispressed.Inreality,youwouldnotuseanArduinotodothis;wearefirmlyintherealmsoftheory rather than practicehere.
Figure6-8Oscilloscopetraceofabuttonpress
Looking at the loop
function of sketch 6-04, thefunction reads the digitalinputandassigns itsvalue toa variable switchOpen. Thisisa0 if thebuttonispressedand a 1 if it isn’t (rememberthat the pin is pulled up to 1when the button is notpressed).When you program
digitalWritetoturntheLEDonoroff,youneedtoreverse
this value.Youdo this usingthe!ornotoperator.If you upload this sketch
and connect your wirebetween D5 and GND (seeFigure 6-9), you should seetheLEDlight.Bouncingmaybe going on here, but it isprobably too fast for you toseeanddoesnotmatter.One situation where key
bouncing would matter is ifyouweremakingyourswitchtoggle the LED on and off.
That is, if you press thebutton, the LED comes onand stays on, and when youpressthebuttonagain,itturnsoff. If you had a button thatbounced, then whether theLEDwasonoroffwouldjustdepend on whether you hadan odd or even number ofbounces.Sketch 6-05 just toggles
theLEDwithoutanyattemptat “debouncing.” Try it outusing your wire as a switch
betweenpinD5andGND:
Youwillprobablyfindthat
sometimes the LED toggles,butother timesitappearsnottotoggle.Thisisbouncinginaction!Asimplewaytotacklethis
problem is simply to add adelayafteryoudetectthefirstbutton press, as shown insketch6-06:
Figure6-9Usingawireasaswitch
By putting a delay here,
nothing else can happen for500 milliseconds, by whichtime any bouncing will havesubsided. You should findthat this makes the togglingmuch more reliable. Aninteresting side-effect is thatif you hold the button down,
theLEDjustkeepsflashing.If that is all there is to the
sketch,thenthisdelayisnotaproblem.However, ifyoudomoreintheloop,thenusingadelay can be a problem; forexample, the program wouldbe unable to detect the pressof any other button duringthat500milliseconds.So, this approach is
sometimes not good enoughandyouwillneed tobeabitmore sophisticated. You can
write your own advanceddebouncingcodebyhand,butdoing so gets complicatedand fortunately some finefolks have done all theworkforyou.
Figure 6-10 Adding theBounce library inWindows
Afterdownloadingthefile,
unzip it and place theunzipped folder, calledBounce, into the librariessubfolder in the folderwhereall your sketches are saved.On Windows, this folder isMy Documents\Arduino, and
on Mac and Linux, it isDocuments/Arduino. If thereisno librariessubfolder, thenyou will need to create one.Figure6-10 shows the folderstructure inWindows after alibraryhasbeenadded.After adding the library,
you need to restart theArduino application for thechanges to take effect. Onceyou do so, you can use theBounce library in anysketchesthatyouwrite.
Sketch 6-07 shows howyou can use the Bouncelibrary. Upload it to yourboard and see how reliablethe LED toggling hasbecome.
Using the library is pretty
straightforward. The firstthing that you will notice isthisline:
This is necessary to tell thecompiler to use the Bouncelibrary.You then have the
followingline:
Do not worry about thesyntax of this line at themoment; it is actually C++ratherthanCsyntax,andyouwillnotbemeetingC++untilChapter11.Fornow,youwilljust have to be content toknow that this sets up abouncer object for the pinspecified, with a debounceperiodof5milliseconds.
Fromnowon,youusethatbouncer object to find outwhat the key is doing ratherthan reading the digital inputdirectly. It has put a kind ofdebouncing wrapper aroundyour input pin. So, decidingwhether a button has beenpressed iswrappedup in thisline:
The function update returnstrueifsomethinghaschangedwith the bouncer object andthe second part of thecondition checkswhether thebuttonwentLOW.
AnalogOutputs
A few of the digital pins—namelydigitalpins3,5,6,9,
10, and 11—can providevariableoutputotherthanjust5Vor nothing.These are thepinsontheboardwitha~or“PWM” next to them. PWMstands for Pulse WidthModulation, which refers tothe means of controlling theamount of power at theoutput. It does so by rapidlyturningtheoutputonandoff.The pulses are always
delivered at the same rate(roughly500persecond),but
the length of the pulses isvaried. If you were to usePWM to control thebrightnessofanLED,thenifthe pulse were long, yourLED would be on all thetime. If, however, the pulsesare short, then the LED isactually lit only for a smallportion of the time. Thishappens too fast for theobserver even to tell that theLED is flickering, and it justappears that the LED is
lighterordimmer.Before you try using an
LED, you can test this outwithyourmultimeter.Set themultimeteruptomeasurethevoltage between GND andpinD3(seeFigure6-11).Nowuploadsketch6-08to
your board and open theSerialMonitor (seeFigure6-12). Enter the single digit 3andpressReturn.Youshouldsee your volt meter registerabout 3V. You can then try
any other number between 0and5.
Figure 6-11 Measuringtheanalogoutput
Figure 6-12 Setting the
voltage at an analogoutput
The program determines
the value of PWM outputbetween 0 and 255 bymultiplying the desiredvoltage (0 to 5) by 51.(ReadersmaywishtorefertoWikipedia for a fullerdescriptionofPWM.)You can set the value of
the output by using thefunctionanalogWrite,which
requires an output valuebetween 0 and 255, where 0is off and 255 is full power.Thisisactuallyagreatwaytocontrol the brightness of anLED. If you were to try tocontrol the brightness byvaryingthevoltageacrosstheLED, you would find thatnothing would happen untilyougottoabout2V;thentheLEDwould very quickly getquite bright. By controllingthe brightness using PWM
and varying the averageamountof time that theLEDison,youachievemuchmorelinear control of thebrightness.
AnalogInput
Digitalinputsjustgiveyouanon/off answer as to what ishappening at a particular pin
ontheArduinoboard.Analoginputs, however, give you avalue between 0 and 1023depending on the voltage attheanaloginputpin.The program reads the
analog input using theanalogRead function.Sketch6-09displaysthereadingandactual voltage at the analogpinA0 in the SerialMonitorevery half second, so opentheSerialMonitorandwatchthereadingsappear.
When you run this sketch,
you will notice that thereadings change quite a bit.Aswiththedigitalinputs,thisis because the input isfloating.Take one end of the wire
andput it intoaGNDsocketso that A0 is connected toGND. Your readings shouldnow stay at 0.Move the endof the lead thatwas inGNDand put it into 5V and you
should get a reading ofaround 1023, which is themaximumreading.So, ifyouwere to connect A0 to the3.3V socket on the Arduinoboard,theArduinovoltmetershould tellyou thatyouhaveabout3.3V.
Conclusion
Thisconcludesourchapteronthe basics of getting signalsinto and out of the Arduino.In the next chapter, we willlook at some of the featuresprovided in the standardArduinolibrary.
7TheStandard
ArduinoLibrary
This library iswhere all thegoodies live. You can onlyget so far with the core Clanguage; what you reallyneed is a big collection of
functions that youcanuse inyoursketches.You have already met a
fair few of these, such aspinMode, digitalWrite, andanalogWrite. But actually,there are many more. Therearefunctionsthatyoucanusefor doing math, makingrandom numbers,manipulating bits, detectingpulses on an input pin, andusing something called
interrupts.The Arduino language is
based on an earlier librarycalled Wiring and itcomplements another librarycalled Processing. TheProcessing library is verysimilar to Wiring, but it isbased on the Java languagerather thanC and is used onyour computer to link toAndroid over USB. In fact,the Arduino application thatyou run on your computer is
based on Processing. If youfindyourselfwantingtowritesomefancy interfaceonyourcomputer to talk to anArduino, then take a look atProcessing(www.processing.org).
RandomNumbers
Despite the experience of
anyone using a PC,computers are in actual factvery predictable.Occasionallyitisusefultobeable to deliberately makeyour Arduino unpredictable.Forexample,youmightwantto make a robot take a“random” path around aroom, heading for a randomamount of time in onedirection, turning a randomnumber of degrees, and thensetting off again. Or, you
might be contemplatingmakinganArduino-baseddiethat gives you a randomnumberbetweenoneandsix.The Arduino standard
library provides you with afeaturetodojustthis.Itisthefunction called random.random returnsan int and itcan take either one argumentor two. If it just takes oneargument,thenitwillreturnarandomnumberbetweenzeroandtheargumentminusone.
The two argument versionproduces a random numberbetween the first argument(inclusive) and the secondargument minus one. Thusrandom(1, 10) produces arandom number between oneandnine.Sketch 7-01 pumps out
numbersbetweenoneandsixtotheSerialMonitor.
Ifyouuploadthissketchto
your Arduino and open theSerial Monitor, you will seesomethinglikeFigure7-1.Ifyourunthisafewtimes
you will probably besurprised to see that, everytime you run the sketch, youget the same series of‘random’numbers.The output is not really
random; the numbers arecalled pseudo-randomnumbersbecause theyhavearandom distribution. That is,
if you ran this sketch andcollected a million numbers,you would get pretty muchthe same number of ones,twos, threes, and so on. Thenumbers are not random inthe sense of beingunpredictable.Infact, it issoagainst the workings of amicrocontroller tobe randomthat it just plain can’t do itwithout some interventionfromtherealworld.
Figure 7-1 Randomnumbers
You can provide this
intervention to make yoursequence of numbers lesspredictable by seeding therandom number generator.This basically just gives it astarting point for thesequence. But, if you thinkabout it, you cannot just userandom to seed the randomnumber generator. Acommonlyusedtrickistousethe fact that (as discussed in
the previous chapter) ananalog input will float. Soyou can use the value readfroman analog input to seedthe random numbergenerator.Thefunction thatdoes this
is called randomSeed.Sketch 7-02 shows how youcan add a bit morerandomness to your randomnumbergenerator.
Try pressing the Resetbutton a few times. Youshould now see that yourrandom sequence is differenteverytime.This type of random
number generation could notbe used for any kind oflottery. For much betterrandom number generation,you would need hardwarerandom number generation,which issometimesbasedonrandom events, such as
cosmicrayevents.
MathFunctions
On rare occasions, you willneedtodoalotofmathonanArduino, over and above theodd bit of arithmetic. But,shouldyouneedto,thereisabig library ofmath functionsavailable to you. The most
useful of these functions aresummarized in the followingtable:
BitManipulation
A bit is a single digit ofbinary information, that is,either0or1.Thewordbit isa contraction of binary digit.Mostofthetime,youuseintvariables that actuallycomprise16bitsThis isabit
wasteful if you only need tostoreasimpletrue/falsevalue(1or0).Actually,unlessyouarerunningshortofmemory,being wasteful is less of aproblem than creatingdifficult-to-understand code,but sometimes it is useful tobe able to pack your datatightly.Each bit in the int can be
thought of as having adecimal value, and you canfind thedecimalvalueof the
intbyaddingupthevaluesofallthebitsthatarea1.SoinFigure7-2, thedecimalvalueof the int would be 38.Actually, it gets morecomplicated to deal withnegative numbers, but thatonly happens when theleftmostbitbecomesa1.When you are thinking
aboutindividualbits,decimalvalues do not really workverywell. It is very difficulttovisualizewhichbitsareset
in a decimal number such as123. For that reason,programmers often usesomething calledhexadecimal, or, morecommonly, just hex. Hex isnumberbase16.Soinsteadofhavingdigits0to9,youhavesix extra digits,A to F. Thismeans that each hex digitrepresents four bits. Thefollowing table shows therelationship among decimal,hex, and binary with the
numbers0to15:
So, in hex, any int can be
represented as a four-digithexnumber.Thus,thebinarynumber 10001100 would inhex be 8C. The C languagehasaspecialsyntaxforusinghexnumbers.Youcanassign
a hex value to an int asfollows:
The Arduino standard
library provides somefunctions that let youmanipulate the16bitswithinan int individually. Thefunction bitRead returns thevalueofaparticularbit inanint; so, for the followingexample would assign the
value0 to thevariablecalledbit:
In the second argument, thebit position starts at 0 andgoes up to 15. It starts withthe least significant bit. Sothe rightmost bit is bit 0, thenextbittotheleftisbit1,andsoon.
As you would expect, thecounterpart to bitRead isbitWrite, which takes threearguments. The first is thenumber to manipulate, thesecondisthebitposition,andthethirdis thebitvalue.Thefollowing example changesthevalueoftheintfrom2to3(indecimalorhex):
Figure7-2Anint
AdvancedI/O
There are some useful littlefunctions that youcanuse tomake your life easier when
performing variousinput/outputtasks.
GeneratingTones
Thetonefunctionallowsyouto generate a square-wavesignal(seeFigure7-3)ononeofthedigitaloutputpins.Themost common reason to dothis is to generate an audibletone using a loudspeaker orbuzzer.
The function takes eithertwo or three arguments. Thefirst argument is always thepinnumberonwhichthetoneistobegenerated,thesecondargument is the frequency ofthetoneinhertz(Hz),andtheoptionalfinalargumentistheduration of the tone. If nodurationisspecified,thenthetone will continue playingindefinitely, as is the case insketch 7-03. This is why wehave put the tone function
callinsetupratherthanintheloopfunction.
Figure 7-3 A square-wavesignal
To stop a tone that is
playing,youuse the function
noTone. This function hasjust one argument, which isthe pin on which the tone isplaying.
Feeding ShiftRegisters
Sometimes the Arduino Unojust doesn’t have enoughpins. When driving a largenumber of LEDs, forexample, a common
technique is to use a shiftregister chip.This chip readsdata one bit at a time, andthen when it has enough, itlatches all those bits onto asetofoutputs(oneperbit).To help you use this
technique, there is a handyfunction called shift-Out.This function takes fourarguments:
• The number of the pin onwhichthebittobesentwill
appear.•Thenumberofthepintobeused as a clock pin. Thistoggles every time a bit issent.
•Aflagtodeterminewhetherthebitswillbesentstartingwiththeleastsignificantbitorthemostsignificant.Thisshould be one of theconstants MSBFIRST orLSBFIRST.
•Thebyteofdatatobesent.
Interrupts
Oneofthethingsthattendtofrustrateprogrammersusedto“programminginthelarge”isthat theArduinocandoonlyone thing at a time. If youliketohavelotsofthreadsofexecution all running at thesame time in your programs,then you are out of luck.
Although a few people havedeveloped projects that canexecute multiple threads inthis way, generally thiscapability is unnecessary forthe type of uses that anArduino is normally put to.The closest an Arduino getstosuchexecutionistheuseofinterrupts.Two of the pins on the
Arduino (D2 and D3) canhave interrupts attached tothem. That is, these pins act
as inputs that, if the pinsreceiveasignalinaspecifiedway, theArduino’sprocessorwill suspendwhatever itwasdoing and run a functionattachedtothatinterrupt.Sketch 7-04 blinks an
LED, but then changes theblink period when aninterruptisreceived.Youcansimulate an interrupt byconnectingyourwirebetweenpin D2 and GND and usingtheinternalpull-upresistorto
keep the interrupt high mostofthetime.
The following is the key
line in the setup function ofthissketch:
Figure 7-4 Types ofinterruptsignals
The first argument
specifies which of the twointerrupts you want to use.Rather confusingly, a 0 heremeans you are using pin 2,while a 1 means you areusingpin3.The next argument is the
nameofthefunctionthatistobe called when there is aninterrupt, and the finalargument is a constant thatwill be one of CHANGE,
RISING, or FALLING.Figure 7-4 summarizes theseoptions.If the interrupt mode is
CHANGE, then either aRISING from 0 to 1 or aFALLING from 1 to 0 willbothtriggeraninterrupt.You can disable interrupts
using the functionnoInterrupts. This stops allinterrupts fromboth interruptchannels. You can resumeusing interrupts again by
calling the functioninterrupts.
Conclusion
In this chapter, you havelooked at some of the handyfeatures that the Arduinostandard library provides.These features will save yousome programming effort,
andifthereisonethingthatagood programmer likes, it isbeingabletousehigh-qualityworkdonebyotherpeople.Inthenextchapter,wewill
extendwhatwelearnedaboutdata structures in Chapter 5andlookathowyougoaboutremembering data on theArduinoafter thepowergoesoff.
8DataStorage
When you give values tovariables, the Arduino boardwill remember those valuesonly as long as the power ison.Themomentthatyouturnthe power off or reset the
board,allthatdataislost.In this chapter,we look at
somewaystohangontothatdata.
Constants
If the data that you want tostore does not change, thenyou can just set the data up
each time that the Arduinostarts. An example of thisapproach is the case in theletters array in your Morsecode translator of Chapter 5(sketch5-05).You used the following
code to define a variable ofthecorrectsizeandfillitwiththedatathatyouneeded:
You may remember that
you did the calculation anddecided that you had plentyof your meager 2K to spare.However, if memory was abittight,itwouldbefarbetter
tobeabletostorethisdatainthe 32K of flash memoryusedtostoreprograms,ratherthanthe2KofRAM.Thereisameansofdoing this. It is adirectivecalledPROGMEN;itlivesinalibraryandisabitawkwardtouse.
The PROGMEMDirective
To store your data in flashmemory,youhave to includethe PROGMEM library asfollows:
Thepurposeofthiscommandis to tell the compiler to usethepgmspace libraryfor thissketch. In this case, a libraryis a set of functions thatsomeoneelsehaswrittenand
that you can use in yoursketches without having tounderstand all the details ofhowthosefunctionswork.Becauseyouareusing this
library, the PROGMEMkeyword and thepgm_read_word functionare available. You will useboth in the sketches thatfollow.This library is included as
part of the Arduino softwareand isanofficiallysupported
Arduino library. A goodcollection of such officiallibraries is available, andmany unofficial libraries,developedbypeoplelikeyouand made for others to use,are also available on theInternet. Such unofficiallibraries must be installedinto your Arduinoenvironment. You will learnmoreabout these libraries,aswell as how to write yourownlibraries,inChapter11.
When usingPROGMEM,you have to make sure thatyou use specialPROGMEM-friendly datatypes. Unfortunately, thatdoesnot include an array ofchar arrays. You actuallyhave to define a variable foreach string using aPROGMEM string type andthen put them all in aPROGMEM array type, likethis:
I have not listed sketch 8-
01 here, as it is a littlelengthy,butyoumaywishtoload it and verify that itworks the same way as theRAM-basedversion.
In addition to creating thedata in a special way, youalso have to read the databack a special way. YourcodetogetthecodestringforaMorse letter from thearrayhas to be modified to looklikethis:
Thisusesabuffervariable
into which the PROGMEMstringiscopied,sothatitcan
be used as a regular chararray. This needs to bedefinedasaglobalvariableasfollows:
This approach works only
if the data is constant—thatis, you are not going tochange it while the sketch isrunning. In the next section,youwilllearnaboutusingtheEEPROM memory that is
intendedforstoringpersistentdatathatcanbechanged.
EEPROM
TheATMega328at theheartof an Arduino Uno has akilobyte of electricallyerasable read-only memory(EEPROM). EEPROM isdesigned to remember its
contents for many years.Despite its name, it is notreally read-only. You canwritetoit.The Arduino commands
for reading and writing toEEPROM are just asawkward to use as the onesfor using PROGMEM. YouhavetoreadandwritetoandfromEEPROMonebyteatatime.The example of sketch 8-
02 allows you to enter a
single-digit letter code fromthe Serial Monitor. Thesketch then remembers thedigit and repeatedly writes itoutontheSerialMonitor.
Totrythissketch,openthe
Serial Monitor and enter anew character. Then unplugtheArduinoandplug it backin. When you reopen theSerial Monitor, you will seethat the letter has beenremembered.The function
EEPROM.write takes twoarguments. The first is theaddress,whichisthememorylocation in EEPROM and
should be between 0 and1023.Thesecondargumentisthe data to write at thatlocation. This must be asingle byte. A character isrepresented as eight bits, sothis is fine, but you cannotdirectlystorea16-bitint.
Storing an int inEEPROM
To store a two-byte int in
locations 0 and 1 of theEEPROM,youwouldhavetodothis:
The functions highByte
and lowByte are useful forseparating an int into twobytes.Figure 8-1 shows howthis int is actually stored intheEEPROM.
Figure8-1Storinga16-bitintegerinEEPROM
Toreadtheintbackoutof
EEPROM, you need to readthe two bytes from theEEPROMandreconstructtheint,asfollows:
The << operator is a bit
shift operator that moves theeighthighbytes to the topofthe int and then adds in thelowbyte.
Storing a float inEEPROM(Unions)
StoringafloatinEEPROMisa little more tricky. To dothis,youcanusea featureofC called unions. These datastructures are interesting inthattheycanbethoughtofasaway tomake thesameareaofmemoryaccessibletomorethan one variable. What ismore, these variables are
allowed to be of differenttypes as long as they are thesamesizeinbytes.The following union
definitionallowsbotha floatandaninttorefertothesametwobytesofmemory:
You can then put a floatintotheunionasfollows:
Then you can separate an
integer into its two bytes forstorage in EEPROM asfollows:
Reading the floatbackout
again requires you to do thereverse. First you assemblethe two bytes into a singleint, thenyouput the int intothe union and pull it outagainasafloat.
Storing a String in
EEPROM
WritingandreadingcharacterstringsintotheEEPROMarepretty straightforward; youjust have to write eachcharacter at a time, as in thefollowingexample:
Toreadthestringbackinto
acharacterarray,youcandosomethinglikethis:
Clearing theContents of
EEPROM
When writing to EEPROM,remember that evenuploading a new sketch willnot clear the EEPROM, soyoumayhaveleftovervaluesin there from a previousproject.Sketch8-03resetsallthe contents of EEPROM tozeros:
Alsobeawarethatyoucan
writetoanEEPROMlocationonly about 100,000 timesbefore it will becomeunreliable. So only write avaluebacktoEEPROMwhenyoureallyneedto.EEPROMis also quite slow, takingabout3milliseconds towriteabyte.
Compression
When saving data toEEPROM or when usingPROGMEM, you willsometimesfindthatyouhavemore to save than you haveroom to save it. When thishappens, it is worth findingthe most efficient way ofrepresentingthedata.
RangeCompression
You may have a value forwhich on the face of it youneedanintorafloatthatareboth 16-bit. For example, torepresent a temperature indegrees Celsius, you mightuse a float value such as20.25.When you are storingthat into EEPROM, lifewould be so much easier ifyou could fit it into a singlebyte, and you could storetwiceasmuchas ifyouusedafloat.
One way that you can dothis is to change the databefore you store it.Remember that a byte willallow you to store a positivenumber between 0 and 255.Soifyouonlycaredaboutthetemperature to the nearestdegree Celsius, then youcould simply convert thefloattoanintanddiscardthepart after the decimal point.Thefollowingexampleshowshowtodothis:
The variable tempFloat
contains the floating pointvalue. The (int) command iscalledatypecastand isusedtoconvertavariablefromonetype to another compatibletype. In this case, the typecastconvertsthefloatof (forexample)20.25toan int thatwill simply truncate thenumberto20.If you know that the
highest temperature that youcare about is 60 degreesCelsiusandthat thelowest is0 degrees Celsius, then youcould multiply everytemperature by 4 beforeconverting it to a byte andsaving it. Then when youread the data back fromEEPROM,youcandivideby4 to get a value that has aprecisionof0.25ofadegree.The following code
example (sketch 8-04) saves
such a temperature intoEEPROM, then reads it backand displays it in the SerialMonitorasproof:
There are other means of
compressing data. Forinstance, if you are takingreadings that change slowly—again, changes intemperature are a goodexample of this—then youcan record the firsttemperature at full resolutionand then just record thechanges in temperature fromthe previous reading. Thischange will generally be
small and occupy fewerbytes.
Conclusion
Younowknowa little abouthow tomake your data hangaround after the power hasgoneoff. In thenextchapter,you will look at LCDdisplays.
9LCDDisplays
In this chapter, you look athow to write software tocontrolLCDdisplays.Figure9-1 shows the kind of LCDdisplayused.
This is a book aboutsoftware,nothardware,butinthis chapter, wewill have toexplaina littleabouthowtheelectronics of these displayswork so that you understandhowtodrivethem.The LCD module that we
use is a prebuilt Arduinoshield that can just bepluggedontopofanArduinoboard. In addition to itsdisplay, it also has somebuttons. There are a number
ofdifferentshields,butnearlyallofthemusethesameLCDcontroller chip (theHD44780), so look for ashieldthatusesthiscontrollerchip.I used the DFRobot LCD
Keypad Shield for Arduino.This module supplied byDFRobot(www.robotshop.com) isinexpensive and provides anLCD display that is 16charactersby2rowsandalso
hassixpushbuttons.The shield comes
assembled,sonosoldering isrequired; you just plug it ontop of your Arduino board(seeFigure9-2).TheLCDshieldusesseven
oftheArduinopinstocontrolthe LCD display and oneanalogpinforthebuttons.Sowe cannot use theseArduinopinsforanyotherpurpose.
Figure 9-1 AnAlphanumeric LCDshield
Figure 9-2 LCD shieldattached to an Arduinoboard
A USB MessageBoard
For a simple example of a
simpleuseof thedisplay,weare going to make a USBmessage board. This willdisplay messages sent fromtheSerialMonitor.The Arduino IDE comes
with an LCD library. Thisgreatly simplifies the processofusinganLCDdisplay.Thelibrary gives you usefulfunctionsthatyoucancall:
• clear clears the display ofanytext.
•setCursor sets the positionin row and column wherethenextthingthatyouprintwillappear.
•printwrites a string at thatposition.This example is listed in
sketch9-01:
As with all Arduino
libraries,youhavetostartbyincluding the library tomakethecompilerawareofit.The next line defines
whichArduino pins are usedby the shield and for whatpurpose. If you are using adifferentshield,thenyoumaywell find that the pinallocations are different, socheck in the documentationfortheshield.
In this case, the six pinsusedtocontrolthedisplayareD4,D5,D6,D7,D8,andD9.Thepurposeofeachof thesepinsisdescribedinTable9-1.
Table 9-1 LCD shield
pinassignmentsThe setup function is
straightforward. You startserialcommunicationssothatthe Serial Monitor can sendcommands and initialize theLCD library with thedimensions of the displaybeing used.You also displaythemessage“ArduinoRules”on two lines by setting thecursor to top-left, printing“Arduino,” then moving the
cursor to the start of thesecond row and printing“Rules.”Most of the action takes
place in the loop function,which checks for anyincomingcharacters from theSerial Monitor. The sketchdealswithcharactersoneatatime.Apart from ordinary
charactersthatthesketchwillsimplydisplay, therearealsoacoupleofspecialcharacters.
If the character is a #, thenthe sketch clears the wholedisplay,andifthecharacterisa /, the sketch moves to thesecond line. Otherwise, thesketch simply displays thecharacteratthecurrentcursorposition using write. Thefunctionwrite is like print,but it prints only a singlecharacter rather than a stringofcharacters.
UsingtheDisplay
Try out sketch 9-01 byuploading it to theboardandthen attaching the shield.Note that you should alwaysunplug theArduino board sothat it is off before you pluginashield.OpenuptheSerialMonitor
and try typing in the text
showninFigure9-3.
Figure 9-3 Sending
commandstothedisplay
Other LCD LibraryFunctions
In addition to the functionsthat you have used in thisexample, there are a numberof other functions that youcanuse:
• home is the same assetCursor(0,0): it movesthecursortotop-left.
•cursordisplaysacursor.• noCursor specifies not todisplayacursor.
• blink makes the cursorblink.
• noBlink stops the cursorfromblinking.
• noDisplay turns off thedisplay without removingthecontent.
• display turns the display
backonafternoDisplay.•scrollDisplayLeftmovesallthe text on the display onecharacter position to theleft.
• scrollDisplayRight movesall the text on the displayone character position totheright.
•autoscrollactivatesamodeinwhich,asnewcharactersareaddedat thecursor, theexisting text is pushed inthedirectiondeterminedby
the functions leftToRightandrightToLeft.
• noAutoscroll turnsautoscrollmodeoff.
Conclusion
You can see thatprogramming shields is nothard, particularly when thereisalibrarythatcandoalotof
thework.In the next chapter, you
will use an Ethernet shieldthatwillallowyoutoconnecttheArduinototheInternet.
10ArduinoEthernet
Programming
In this chapter, youwill usean Ethernet shield to enableyour Arduino to work over
your home network (seeFigure10-1).
Figure 10-1 ArduinowithEthernet
EthernetShields
When buying an Ethernetshield, you need to take alittlecare,asyouneedtousean “official” shield based on
the Wiznet chipset and notone of the cheaper but moredifficult to use unofficialboards based on theENC28J60 Ethernetcontrollerchip.The Ethernet shields are
quite power hungry, so youwill also need a 9V or 12Vpower supply rated at 1A ormore. This supply will beattached to the Arduinopowersocket.
Communicating withWebServers
Before looking at how theArduino deals withcommunication between abrowser and the web serverthat it uses, you need someunderstanding of theHyperText Transfer Protocol(HTTP) and the HyperText
MarkupLanguage(HTML).
HTTP
The HyperText TransportProtocol is the method bywhich web browserscommunicate with a webserver.When you go to a page
using a web browser, thebrowsersendsarequesttotheserver hosting that page,
saying what it wants. Whatthe browser asks for may besimplythecontentsofapageinHTML.Theweb server isalways listening for suchrequests,andwhenitreceivesone, it processes it. In thissimple case, processing therequest just means sendingback HTML that you havespecified in the Arduinosketch.
HTML
The HyperText MarkupLanguage isawayofaddingformattingtoordinarytextsothat it looks good when thebrowser displays it. Forexample, the following codeis HTML that displays on abrowser page as shown inFigure10-2:
The HTML contains tags.
Tagshave a start and an endand usually contain othertags.Thestartofataghasa<and then the tag name, andthen a >; for example,<html>. The end of a tag is
similar except that it has a /after the <. In the precedingexample, theoutermosttagis<html> that contains a tabcalled <body>. All webpages should start with suchtags, and you can see thecorresponding ends for thosetags at the end of the file.Notethatyouhavetoputtheendtagsintherightorder,sothebody tag must be closedbeforethehtmltag.Now we get to the
interesting bit in the middle,theh1 andp tags. These arethe parts of the example thatareactuallydisplayed.Theh1tagindicatesalevel
1 header. This has the effectof displaying the text that itcontains in a large bold font.Thep tag isaparagraph tag,and so all the text containedwithin it is displayed as aparagraph.This really just scratches
the surface of HTML.Many
books and Internet resourcesare available for learningaboutHTML.
Figure 10-2 An HTMLexample
Arduino as a WebServer
The first example sketchsimply uses the Arduino andEthernet shield to make asmall web server. It’s
definitelynotaGoogleserverfarm,but itwillallowyoutosend a web request to yourArduino and view the resultsin a browser on yourcomputer.Before uploading the
sketch 10–01, there are acouple of changes that youneed tomake. If you look atthetopofthesketch,youwillseethefollowinglines:
The firstof these, themac
address, must be uniqueamong all the devicesconnected to your network.The second one is the IPaddress. Whereas mostdevices that you connect toyourhomenetworkwillhaveIPaddressesassignedtothemautomatically by a protocolcalled Dynamic Host
Configuration Protocol(DHCP), this is not true forthe Ethernet shield. For thisdevice,youhavetodefineanIP address manually. Thisaddress cannot be any fournumbers; they must benumbersthatqualifyasbeinginternal IP addresses and fitin the range of IP addressesexpected by your homerouter. Typically, the firstthree numbers will besomething like 10.0.1.x or
192.168.1. x, where x is anumber between 0 and 255.Some of these IP addresseswill be in use by otherdevices on your network. Tofind an unused but valid IPaddress, connect to theadministration page for yourhome router and look for anoption that says “DHCP.”You should find a list ofdevices and their IPaddresses, similar to thatshown inFigure 10-3. Select
a final number to use in youIP address. In this case,192.168.1.30 looked like agood bet, and indeed itworkedfine.AttachtheArduinotoyour
computerusingtheUSBleadand upload the sketch. Youcan nowdisconnect theUSBlead and attach the powersupplytotheArduinoandtheEthernetlead.Openaconnectiononyour
computer’sbrowser to the IP
address thatyouassigned forthe Ethernet shield.Something very much likeFigure10-4shouldappear.
Figure 10-3Finding anunusedIPaddress
Figure 10-4 A Simple
ArduinoserverexampleThe listing for sketch 10-
01isasfollows:
As with the LCD library
discussed in Chapter 9, astandard Arduino librarytakescareof interfacingwiththeEthernetshield.The setup function
initializestheEthernetlibraryusing the mac and IPaddressesthatyousetearlier.The loop function is
responsible for servicing anyrequeststhatcometothewebserver from a browser. If a
request is waiting for aresponse, then callingserver.availablewillreturnaclient. A client is an object;you will learn a bit moreabout what this means inChapter 11. But for now, allthatyouneedtoknowis thatwhetheraclientexists(testedbythefirstifstatement);thenyou can then determinewhetheritisconnectedtotheweb server by callingclient.connected.
The next three lines ofcodeprintoutareturnheader.This just tells the browserwhat type of content todisplay. In this case, thebrowser is to display HTMLcontent.Once the header has been
written, all that remains is towrite the remaining HTMLback to the browser. Thismust include the usual<html> and <body> tags,and also includes a <h1>
header tag and two<p> tagsthatwilldisplay thevalueonthe analog input A0 and thevalue returned by the millisfunction; that value is thenumberofmilliseconds sincetheArduinowaslastreset.Finally,client.stoptellsthe
browser that the message iscomplete. The browser thendisplaysthepage.
Setting Arduino Pins
overtheNetwork
ThissecondexampleofusinganEthernetshieldallowsyouto turn the Arduino pins D3toD7onandoffusingawebform.Unlike the simple server
example, you are going tohavetofindawaytopassthepinsettingstotheArduino.
Themethod for doing thisis called posting data and ispart of the HTTP standard.Forthismethodtowork,youhave to build the postingmechanismintotheHTMLsothat the Arduino returnsHTMLtothebrowser,whichrenders a form. This form(showninFigure10-5) has aselection of On and Off foreach pin and an Updatebutton that will send the pinsettingstotheArduino.
Figure 10-5 Themessagesendingform
WhentheUpdatebuttonis
pressed, a second request issenttotheArduino.Thiswillbe just like the first request,except that the request willcontain request parametersthatwillcontainthevaluesofthepins.A request parameter is
similar in concept to afunction parameter. Afunction parameter enablesyou to get information to afunction, such as the numberof times to blink, and arequest parameter enablesyou to pass data to theArduino that is going tohandlethewebrequest.WhentheArduinoreceivesthewebrequest, it canextract thepinsettings from the requestparameter and change the
actualpins.The code for the second
examplesketchfollows:
Thesketchusestwoarrays
to control the pins.The first,
pins,justspecifieswhichpinsare to be used. ThepinStatearray holds the state of eachpin:either0or1.To get the information
coming from the browserformaboutwhichpinsshouldbe on and which should beoff,itisnecessarytoreadtheheader coming from thebrowser.Infact,allyouneediscontainedinthefirstlineofthe header. You will use acharacter array line1 to
contain the first line of theheader.Whentheuserclicksonthe
Update button and submitsthe form from the browser,the URL for the page willlooksomethinglikethis:
The request parameters
comeafterthe?andareeachseparated by an&. Lookingat the first parameter (0=1),
thismeansthatthefirstpininthe array (pins[0]) shouldhavethevalue1.Ifyouweretolookat thefirst lineof theheader, you would see thosesame request parametersthere:
Before the parameters,
there is the textGET/. Thisspecifies the page requestedbythebrowser.Inthiscase,/
indicatestherootpage.In the loop of the sketch,
you call the readHeaderfunction to read the first lineof the header. You then usethe pageNameIs function tocheckthatthepagerequestisfortherootpage/.The sketch then generates
theheaderandthestartoftheHTML form that is to bedisplayed.Beforewriting theHTML for each of the pins,the sketch calls the
setValuesFromParamsfunction to read each of therequestparametersandsettheappropriate values in thepinStatesarray.Thisarrayisthenusedtoset thevaluesofthe pin outputs before thewriteHTMLforPin functioniscalledforeachof thepins.This function generates aselection list for each pin. Ithas to build this list part bypart.Theifstatementsensurethat the appropriate options
areselected.The functions
readHeader, pageNameIs,and valueOfParam areuseful general-purposefunctions that you can makeuseofinyourownsketches.You can use your
multimeter as you did inChapter 6 to verify that thepins are indeed turning onand off. If you are feelingmore adventurous, you couldattach LEDs or relays to the
pinstocontrolthings.
Conclusion
Having used shields andassociatedlibrariesinthelasttwochapters,itisnowtimetoinvestigate the features thatenable libraries to be writtenand learn how to writelibrariesofyourown.
11C++andLibraries
Arduinos are simplemicrocontrollers.Mostof thetime, Arduino sketches arequite small, so using the Cprogramminglanguageworks
just fine. However, theprogramming language forArduino is actually C++rather than C. C++ is anextension to the Cprogramming language thatadds something called objectorientation.
ObjectOrientation
This is only a short book, soanin-depthexplanationoftheC++ programming languageisbeyonditsscope.Thebookcan, however, cover thebasics of C++ and objectorientation.Butthemaingoalis to increase theencapsulation of yourprograms. Encapsulationkeeps relevant thingstogether, something thatmakes C++ very suitable forwritinglibrariessuchasthose
that you have used for theEthernetandLCDsketchesinearlierchapters.There are many good
books on the topics of C++and object-orientedprogramming. Look for thehigher-rated books on thetopic in your favorite onlinebookstore.
ClassesandMethods
Object orientation uses aconcept called classes to aidencapsulation. Generally, aclass is like a section of aprogram that includes bothvariables—called membervariables—and methods,which are like functions butapply to the class. Thesefunctionscaneitherbepublic,in which case the methodsandfunctionsmaybeusedbyother classes, or private, inwhich case the methods can
be called only by othermethods within the sameclass.WhereasanArduinosketch
is contained in a single file,when you are working inC++, you tend to use morethanonefile.Infact,therearegenerally two files for everyclass: A header file, whichhas the extension .h, and theimplementation file, whichhastheextension.cpp.
Built-in LibraryExample
The LCD library has beenused in the two previouschapters, so let’s look morecloselyandseewhatisgoingoninalittlemoredetail.Referringbacktosketch9-
01(openthisinyourArduinoIDE), you can see that the
include command includesthefileLiquidCrystal.h:
Thisfileistheheaderfileforthe class calledLiquidCrystal.Thisfiletellsthe Arduino sketch what itneeds to know to be able touse the library. You canactually retrieve this file ifyou go to your Arduino
installationfolderandfileandfind the filelibraries/LiquidCrystal. Youwillneedtoopenthefileinatexteditor.IfyouareusingaMac, then right-click on theArduino app itself and selectthe menu option ShowPackage Contents. Thennavigate toContents/Resources/Java/libraries/LiquidCrystal.The file LiquidCrystal.h
contains lots of code, as thisis a fairly large library class.
The code for the actual classitself, where the nuts andboltsofdisplayingamessageactually reside,are in thefileLiquidCrystal.cpp.In the next section, a
simple example library willbecreatedthatshouldputtheconceptsbehindalibraryintocontext.
WritingLibraries
Creating an Arduino librarymight seem like the kind ofthing that only a seasonedArduino veteran shouldattempt, but actually it ispretty straight-forward tomake a library. For example,youcanconvertintoalibrarythe flash function fromChapter4thatcausesanLEDto flash for a specifiednumberoftimes.
TocreatetheC++filesthatareneededtodothis,youwillneed a text editor for yourcomputer—something likeTextPad on Windows orText-MateonMac.
TheHeaderFile
Start by creating a folder tocontain all the library files.Youshouldcreate this folderinside the libraries folder of
your Arduino documentsfolder. In Windows, yourlibraries folderwillbe inMyDocuments\Arduino. On theMac,youwill find it inyourhome directory,Documents/Arduino/, and onLinux, it will be in thesketchbook directory of yourhomedirectory.Ifthereisnolibraries folder in yourArduino,thencreateone.This libraries folder is
whereanylibrariesyouwrite
yourself, or any “unofficial”contributed libraries,mustbeinstalled.Call the folder Flasher.
Start the text editor and typethefollowingintoit:
SavethisfileintheFlasher
folder with the nameFlasher.h. This is the headerfilefor thelibraryclass.Thisfile specifies the differentpartsoftheclass.Asyoucansee, it is divided into publicandprivateparts.The public part contains
what looks like the start oftwo functions. These arecalled methods and differfromfunctionsonlyinsofarasthey are associated with aclass.They can be used only
as part of the class. Unlikefunctions, they cannot beusedontheirown.The firstmethod,Flasher,
begins with an uppercaseletter,whichissomethingyouwouldnotusewithafunctionname. It also has the samename as the class. Thismethod is called aconstructor, which you canapplytocreateanewFlasherobjecttouseinasketch.Forexample,youcouldput
thefollowinginasketch:
This would create a newFlasher called slowFlasherthat would flash on pin D13with a duration of 500milliseconds.The second method in the
class is called flash. Thismethod takes a singleargument of the number of
times to flash. Because it isassociatedwithaclass,whenyouwant to call it, youhavetorefertotheobjectthatyoucreatedearlier,asfollows:
ThiswouldcausetheLEDtoflash ten times at the periodthat you specified in theconstructor to the Flasherobject.
The private section of theclass contains two variabledefinitions: one for the pin,and one for the duration,which is simply called d.EverytimethatyoucreateanobjectofclassFlasher,itwillhavethesetwovariables.Thisenables it to remember thepinanddurationwhenanewFlasherobjectiscreated.These variables are called
member variables becausethey are members of the
class. Their names generallyare unusual in that they startwithanunderscorecharacter;however, this is just acommon convention, not aprogramming necessity.Another commonly usednamingconventionistousealowercasem (formember)asthe first letter of the variablename.
The Implementation
File
The header file has justdefined what the class lookslike.Younowneedaseparatefile that actually does thework. This is called theimplementation file and hastheextension.cpp.So, create a new file
containing the following andsave it as Flasher.cpp in theFlasherfolder:
There is some unfamiliar
syntax in this file. Themethod names are bothprefixed by Flasher::. Thisindicates that the methodsbelongtotheFlasherclass.The constructor method
(Flasher)justassignseachofits parameters to theappropriate private membervariable. The durationparameter is divided by twobefore being assigned to the
member variable _d. This isbecause the delay is calledtwice, and it seems morelogical for the duration to bethe totaldurationof theflashandthegapbetweenflashes.Theflashfunctionactually
carries out the business offlashing; it loops for theappropriate number of times,turning the LED on and offfortheappropriatedelay.
Completing YourLibrary
Youhavenowseenalloftheessentials for completing thelibrary. You could nowdeploy this library and itwould work just fine.However, there are twofurther steps that you shouldtaketocompleteyourlibrary.Oneistodefinethekeywordsusedinthelibrarysothatthe
Arduino IDE can show themintheappropriatecolorwhenusers are editing code. Theother is to include someexamples of how to use thelibrary.
Keywords
To define the keywords, youhave to create a file calledkeywords.txt,whichgoesintothe Flasher directory. This
file contains just the twofollowinglines:
This is essentially a two-column table in a text file.The left column is thekeywordandtherightcolumnan indication of the type ofkeyword it is. Class namesshould be a KEYWORD1
and methods should beKEYWORD2. It does notmatter how many spaces ortabs you put between thecolumns, but each keywordshouldstartonanewline.
Examples
Theotherthingthatyou,asagoodArduino citizen, shouldinclude as part of the libraryis a folder of examples. In
this case, the library is sosimple that a single examplewillsuffice.The examples must all be
placed in a folder calledexamples inside the Flasherfolder.Theexampleisinfactjust an Arduino sketch, soyou can create the exampleusing the Arduino IDE. Butfirst, you have to quit andthenreopen theArduinoIDEtomake it aware of the newlibrary.
After restarting theArduino IDE, from theArduino IDE’s menu, selectFileandthenNewtocreateanew sketch window. ThenfromtheMenu,selectSketchand the Import Libraryoption. The Options shouldlook something like Figure11-1.Thelibrariesabovetheline
in the submenu are theofficial libraries; below thisline are the “unofficial”
contributedlibraries.Ifallhasgone well, you should seeFlasherinthelist.IfFlasher isnot in thelist,
it is very likely that theFlasher folder is not in thelibraries folder of yoursketches folder, so go backandcheck.
Figure 11-1 ImportingtheFlasherlibrary
Type the flowing into the
sketch window that has justbeencreated:
The Arduino IDE will not
allow you to save theexample sketch directly intothelibrariesfolder,sosaveitsomewhere else under thename Simple FlasherExample and then move thewhole Simple FlasherExample folder that you justsaved into the examplesfolderinyourlibrary.IfyourestartyourArduino
IDE,youshouldnowseethat
you are able to open theexample sketch from themenuasshowninFigure11-2.
Figure11-2Openingtheexamplesketch
Conclusion
There ismore toC++and towriting libraries, but thischapter should get youstarted. It should also be
sufficient for most of whatyou are likely to do with anArduino.TheseArduinos aresmall devices and thetemptation is often tooverengineer solutions thatcould otherwise be verysimpleandstraightforward.That concludes the main
bodyofthisbook.Forfurtherinformation on Arduino andwhere to go next, a goodstarting point is always theofficial Arduino website at
www.arduino.cc.Also,pleaserefer tothebook’swebsiteatwww.arduinobook.com,whereyouwillfinderrataandotherusefulresources.Ifyouare lookingforhelp
or advice, the Arduinocommunity onwww.arduino.com/forum isextremely helpful. You willalso find the author on therewiththeusernameSi.
Index
Please note that index linkspointtopagebeginningsfromthe print edition. Locationsareapproximateine-readers,and you may need to pagedownoneormoretimesafterclicking a link to get to theindexedmaterial.
Symbols
>= (greater than or equal to)comparisonoperator,44<= (less than or equal to)comparisonoperator,44−(minus)operator,42!= (not equal to) comparisonoperator,44/ (slash), as divisionoperators,42; (semicolon), in
programmingsyntax,29||(or)operator,60+(plus),asadditionoperator,42= (assignment) operator,assigningvalues tovariables,40== (equal to) comparisonoperator,44,60&& (and) operator,manipulatingvalues,60* (asterisk), asmultiplicationoperator,42[] (square brackets), in array
syntax,68<<(bitshiftoperator),119< (less than) comparisonoperator,44> (greater than) comparisonoperator,44
Aabs function, math functionsinlibrary,108addition(+)operator,42Algorithms+DataStructures=Programs(Wirth),67
alphanumeric LCD Shield,126analoginputs,4–5,102–103analogoutputs,100–102analogReadfunction,102analogWritefunction,102and (&&) operator,manipulatingvalues,60ArduinoBluetooth,11–12ArduinoDiecimila,9ArduinoDuemilanove,9ArduinoLilypad,11–12ArduinoMega,10ArduinoNano,10–11
Arduino,originsof,7ArduinoUno
in Arduino family ofdevelopmentboards,9ATMega328 processorin,117
argumentspassingtofunctions,28–29ofrandomfunction,106oftonefunction,111
arithmeticnumeric variables and,40–42
operators,42arrays
overviewof,67–71PROGMEM and, 116–117SOS signal example,71–72stringarrays.Seestringsfor translating Morsecode. See Morse codetranslator
ASCIIcode,73assignment (=) operator,assigningvalues tovariables,
40asterisk (*), asmultiplicationoperator,42ATmega1280,Megaand,10ATmega168,Unoand,9ATmega328
Unoand,9,117useonArduinoboards,3
autoscroll function, LCDlibrary,130
Bbinary language, compiling
codeinto,30binary values, hexadecimaland decimal equivalents,109–110bit manipulation functions,108–110bitshiftoperator(<<),119bitReadfunction,110bits,109bitWritefunction,110blink function, LCD library,130Blinksketch
default,17–18
LEDsand,15modifying,20–22running,35–36setupandloopfunctionsin,34–35
blocks,ofcode,34Bluetooth,11–12bodytags,HTML,137Booleans
datatypesinClanguage,61manipulatingvalues,59–61
buffer variables, when using
char arraywith PROGMEM,117bytedatatype,61
CC++language
classes and methods,143–144creating examples forlibrary,148–150creating header file forlibraryclass,145–146creating implementation
file for library class,146–147defining keywords forlibrary,148example using built inlibrary,144objectorientationin,143writing libraries, 144–145
ClanguageC++asextensionto,143codingstyles,62forcommand,45–48commands,42
compilationprocess,30–32datatypesin,61–62#definedirective,48–49examining functions inboilerplatecode,32–34ifcommand,42–44numeric variables andarithmetic processes in,40–42running Blink sketch,35–36setupandloopfunctionsinBlinksketch,34–35
testing experiments in,38–40variables,36–38whilecommand,48zeroasindexin,68
callingfunctions,28case sensitivity, syntax ofprogramming languages and,28CHANGE constant, types ofinterruptsignals,114char
datatypesinClanguage,61
PROGMEM and, 116–117stringliteralsand,72
character sequences. SeestringsChipkitboard,13classes,C++,143–144clear function, LCD library,127code
blocksof,34compilationof,30–32formatting styles orstandards,62
translating toboard,29–30
COM3ports,asserialportforWindowscomputers,18–19commands,Clanguage
forcommand,45–48ifcommand,42–44overviewof,42whilecommand,48
commentscodeformattingstylesorstandards,64–65reasons for using or notusing,65–66
comparisonoperatorscomparing values withequalto(==),60typesof,44
compilationprocessarraysand,70translating code intomachinecode,30–32
compression, data storageand,121–123computermemory,datain,70conditions, if command and,43constants
defining,55storing,115–116
constrain function, mathfunctionsinlibrary,108constructor methods, 146–147controller chip, for use withLCDshield,125cos,mathfunctionsinlibrary,108Creative Commons license,forArduinodesigns,7curlybraces({})
codeformattingstylesor
standards,63in syntax of blocks ofcode,34
cursor function,LCD library,130
Ddata, representation ofnumbersandletters,75–76datastorage
clearing EEPROMcontents,121compression and, 121–
123constants,115–116EEPROM,117–118overviewof,115PROGMEM directive,116–117storing floats inEEPROM,119–120storingintsinEEPROM,118–119storing strings inEEPROM,120
datatypes,inClanguage,61–62
debouncing, button pressesand,94–100decimal value, hexadecimaland binary equivalents, 109–110#definedirective
for associating a valuewithaname,48–49for defining constants,55
delayPeriodvariableconditionsusedwith,43example of use of, 37–38
developmentboardsanalog and digitalconnections,4–5inArduinofamily,8Bluetooth,11–12componentson,3crystal, Reset switch,Serial ProgrammingConnector, and USBconnection,6–7Lilypad,11–13Mega,10microcontrollerson,5–6Nano,10–11
overviewof,2–3powerconnections,4powersupply,4selectingtypeof,18Uno, Duemilanove, andDiecimila,9
DFRRobot LCD KeypadShield,125DHCP (Dynamic HostConfigurationProtocol),134Diecimila,9digital connections, onArduinoboards,4–5digitalinputs
button presses anddebouncing,94–100internalpull-upresistors,93–94overviewof,89–90pull-up resistors and,90–93
digitaloutputsmeasuring withmultimeter,85–87,89overviewof,85pinMode function forconfiguring pinelectronics,87–88
digitalReadfunction,90digitalWrite function, 34–35,93DIL(dualinline)socket,4display function, LCDlibrary,130division(/)operator,42doubles, data types in Clanguage,61dualinline(DIL)socket,4Duemilanove,9Dynamic Host ConfigurationProtocol(DHCP),134
EEEPROM (electricallyerasableread-onlymemory)
clearingcontentsof,121compressing data and,121floatsstoredin,119–120intsstoredin,118–119reading to/writing from,117–118stringsstoredin,120
elements,ofarrays,70ENC28J60 Ethernetcontrollerchip,132
encapsulationglobalvariablesand,55object orientationincreasing,143
EPROM (erasableprogrammable read-onlymemory),1equal to (==) comparisonoperator,44,60Ethernet
Arduino shields, 7–8,131communicating withwebservers,132–133
passingpinsettingsoverthenetwork,137–142selecting officialWiznet-based shield,132using Arduino as webserver,134–137
examples, creating for C++library,148–150
FFALLING constant, types ofinterruptsignals,114
Femtoduino, unofficialArduinoboards,13File menu, accessingSketchbookfrom,22–23flashmemory
onmicrocontroller,1storingdatain,116–117
flashDotOrDashfunction,81flashSequence function, 79–80floating point numbers. Seefloatsfloats
datatypesinClanguage,
61overviewof,59range compression and,121–122storing in EEPROM,119–120
forcommand,45–48Freeduino,unofficialArduinoboards,13functions
Booleansand,59–61calling and passingargumentsto,28–29coding styles or
standardsforformatting,62collection of. Seelibraries,Arduinocommenting,64–66datatypesinClanguage,61–62defining vs. predefined,51examining in boilerplatecode,32–34floats,59global, local, and staticvariablesand,54–57
indentation,62–63openingbraces,63overviewof,51–52parameters,53–54pre-definedvs. defining,33returningvalues,57–58setupandloopfunctionsinBlinksketch,34–35for use with LCDdisplays,130variabletypes,58whitespaces,64
Gglobalvariables,54–56,76greater than (>) comparisonoperator,44greater than or equal to (>=)comparisonoperator,44
HHD44780, controller chipusedwithLCDshield,125header(.h)files
creatingforlibraryclass,145–146
needed for each C++class,144
headertags,HTML,133,137hexadecimal values, decimaland binary equivalents, 109–110highBytefunction,118home function, LCD library,130HTML (HyperText MarkupLanguage),132,137,142HTTP (HyperText TransportProtocol),132,137
II/O(input/output)
advanced functions for,111–114analoginputs,102–103analogoutputs,100–102button presses anddebouncing,94–100digitalinputs,89–90digitaloutputs,85–89internalpull-upresistors,93–94overviewof,85pins on microcontroller,
1–2pull-up resistors and,90–93
ifcommand,42–44,60implementation(.cpp)file
creatingforlibraryclass,146–147needed for each C++class,144
indentation, code formattingstylesorstandards,62–63input/output. See I/O(input/output)interference, pull-up resistors
and,90interrupts,112–114ints
16 bits used in numericrepresentation,61datatypesinClanguage,61decimalvalueof,109declaring,53–54hexvalueof,110random functionreturning,106range compression and,121–122
returnvaluesand,58storing in EEPROM,118–119
IP addresses, using Arduinoaswebserverand,134–136
Kkeywords, defining for C++library,148
LLCDdisplays
functions that can beusedwith,130overviewof,125–126sending messages to,129USB message board,127–129
ledPinvariable,37LEDs(light-emittingdiodes),15–16less than (<) comparisonoperator,44less than or equal to (<=)comparisonoperator,44
letters, data representation inMorsecodetranslator,75–76libraries,Arduino
bit manipulationfunctionsin,108–110interrupts,112–114mathfunctions,108overviewof,105PROGMEM library,116–117random numbers, 105–108shift-Outfunction,112tonefunction,111–112
libraries,C++creating examples forlibrary,148–150creating header file forlibraryclass,145–146creating implementationfile for library class,146–147defining keywords for,148example using built in,144writing,144–145
light-emittingdiodes(LEDs),
15–16Lilypad,11–12localvariables,55–56log,mathfunctionsinlibrary,108longdatatype,inClanguage,61loopfunction
inBlinksketchexample,34–35defining,33forEthernetshield,137ifcommandand,43–44forLCDshield,129
forloops,45–48for Morse codetranslator,76–80required in all sketches,31whileloops,48
lowBytefunction,118LSBFIRSTconstant,112
Mmacaddresses,usingArduinoaswebserverand,134Maccomputers
creating C++ librariesand,145TextMate as text editor,145
map, math functions inlibrary,108math functions, in Arduinolibrary,108max, math functions inlibrary,108Mega,10member variables,C++, 143,146memory
data in computermemory,70flash memory, 1, 116–117
methods,C++,143–144microcontrollers
onArduinodevelopmentboard,2–3overviewof,1–2processingspeedof,35
min, math functions inlibrary,108minus(−)operator,42Morsecode
historyof,68SOS example usingarrays,71–72
Morsecodetranslatordata representation, 75–76flashDotOrDashfunction,81flashSequence function,80global variables andsetupfunctionfor,76loopfunctionfor,76–80overviewof,74–75
storing constants usedin,115–116testinginSerialMonitor,81–83
Motorshield,7MSBFIRSTconstant,112multimeter, measuringoutputswith,85–87,100–102multiplication operator (*),42
Nnaming conventions, for
variables,146Nano,10–11noAutoscroll function, LCDlibrary,130noBlink function, LCDlibrary,130noCursor function, LCDlibrary,130noDisplay function, LCDlibrary,130noInterruptsfunction,114not equal to (!=) comparisonoperator,44numbers, data representation
inMorsecodetranslator,75–76numericvariables,40–42
Oobject orientation, in C++,143objects,creating,146operators,59–61
arithmetic,42assignment(=),40bitshift(<<),119comparison,44
or(||)operator,60output.SeeI/O(input/output)
PpageNameIsfunction,142paragraph tags, HTML, 133,137parameters
adding to functions,53–54globalvariablesand,54–55syntax of programming
languages,28PCB(printedcircuitboard),3pgm_read_word function,116physical computing, Arduinodescribedas,1pinModefunction
for configuring pinelectronics,87–88setup function calling,34–35
pinscontrollingLCDdisplay,125
I/O pins onmicrocontroller,1–2interrupts attached to,113LCD shield pinassignments,128passingpinsettingsoverthenetwork,137–142shift-Out functionfeeding shift registers,112
pinStatearrays,141–142plus(+),asadditionoperator,42
postingdata,HTTPand,137pow, math functions inlibrary,108powerconnections,4powersupply
onArduinoboard,4required by Ethernetshield,132
poweringupArduinoboards,15–16print function, LCD library,127printedcircuitboard(PCB),3privatemethods,C++,144
Processinglibrary,105PROGMEMdirective
compressing data and,121storing data in flashmemory,116–117
programmingbyintention,77programminglanguages
C++ language.See C++languageC language. See Clanguagesyntaxof,28–29translating code to
board,29–30vocabularyof,27
programs.Seesketchespseudo-randomnumbers,106publicmethods,C++,144pull-upresistors
enablinginternal,93–94overviewof,90–93simulation of interruptusing,113
Pulse Width Modulation(PWM),100–102punctuation, syntax ofprogramminglanguages,28
pushbuttons,debouncing,94PWM (Pulse WidthModulation),100–102
Qquartz crystal oscillator, onArduinoboards,6–7
RRAM (random accessmemory),1randomfunction,105–108
random number generator,107–108randomSeedfunction,107rangecompression,121–123readHeaderfunction,142relays,Arduinoshields,7Reset connector, powerconnections,4Reset switch, on Arduinoboard,6resistors,pull-up.See pull-upresistorsreturn values, functions and,57–58
RISING constant, types ofinterruptsignals,114Roboduino, unofficialArduinoboards,13Ruggeduino, unofficialArduinoboards,13
SscrollDisplayLeft function,LCDlibrary,130scrollDisplayRight function,LCDlibrary,130Seeeduino, unofficial
Arduinoboards,13SerialMonitor
displayingmessagessentfrom,127example using numericvariablesandarithmetic,40–41reading electricalinterference,90–92testingexperimentsinC,38–40testing Morse codetranslatorin,81–83viewingarrayin,68–69
serial port, selecting fromToolmenu,18–20Serial ProgrammingConnector,6Serial.available(),77–78setCursor function, LCDlibrary,127setupfunction
inBlinksketchexample,34–35defining,33forEthernetshield,137forLCDshield,129inMorsecodetranslator,
76required in all sketches,31
setValuesFromParamsfunction,142shieldboards
forEthernet,131forLCDdisplay,125listofpopular,7selecting officialWiznet-based shield,132
shift-Outfunction,112shiftregisters,112
sin,mathfunctionsinlibrary,108Sketchbook,22–25sketches
accessing from Filemenu,22–23boilerplatecodefor,31collection of functionsfor. See libraries,Arduinodownloading,23–25asprograms,28uploadingfirst,17–22
slash (/), as division
operators,42software,installing,16sqrt, math functions inlibrary,108square brackets ([]), in arraysyntax,68staticvariables,56–57stringarrays.Seestringsstringliterals,72–73,76stringvariables,73–74strings
overviewof,72storing in EEPROM,120
stringliterals,72–73stringvariables,73–74for translating Morsecode. See Morse codetranslator
subtraction(–)operator,42switches
connecting to input pinonboard,92pull-upresistorsand,93usingwireas,95,97
syntax, of programminglanguages,28–29
Ttags,HTML,133,137tan,mathfunctionsinlibrary,108Teensy, unofficial Arduinoboards,13tempFloatvariable,122texteditors, forcreatingC++files,145text,HTMLformatting,132–133TextMate (Mac computers),145TextPad (Windows
computers),145threads, executing single,112–113todos, commenting on code,65–66tonefunction,111–112Toolsmenu,18–20truth tables, using withvalues,60typecasts,convertingfloattoint,122
U
UART (UniversalAsynchronousReceiver/Transmitter),78unions, storing floats inEEPROM,119–120Universal AsynchronousReceiver/Transmitter(UART),78Uno
in Arduino family ofdevelopmentboards,9ATMega328 processorin,117
unsigned int, data types inC
language,61unsigned long, data types inClanguage,61USB
communicating via, 77–78component on Arduinodevelopmentboards,6–7connectingvia,1installingdriversfor,16plugging Arduino boardintoUSBport,15
USBHostshield,7USB message board, 127–
129
VvalueOfParamfunction,142values
assigning to variables,40#define directive forassociatingwithaname,48–49functions returning, 57–58list of values in arrays,
67manipulatingvalues,59–61storing.Seedatastorage
variablesBooleansand,59–61C++ member variables,143datatypesinClanguage,61–62defining in C language,36–38forFlasherobject,146floats,59
global,54–55local,55–56numeric,40–42static,56–57typesof,58
Verify button, for checkingcode,30vocabulary, of programminglanguages,27voidkeyword,32–33
Wwebbrowsers
communicating viaHTTP,132text formatted usingHTML,132–133
webserverscommunicating with,132–133using Arduino as, 134–137
whilecommand,48whitespace, code formattingstylesorstandards,64Windowscomputers
creating C++ libraries,
145serialportfor,18–19TextPad as text editor,145
Wiring library, Arduinolibrarybasedon,105Wiznetchipset,132write function, LCD library,129writeHTMLforPin function,142