Professional Documents
Culture Documents
Chapter 2. Exploring The Arduino Board and The IDE: Enjoy Safari?
Chapter 2. Exploring The Arduino Board and The IDE: Enjoy Safari?
Chapter 2. Exploring The Arduino Board and The IDE: Enjoy Safari?
NEXT
PREV
1. Getting Started
3. First Steps
Recent
Topics
Tutorials
Highlights
Settings
Feedback(http://community.safaribooksonline.com)
Sign Out
InthischapteryoullexploretheArduinoboardaswellastheIDEsoftwarethat
youllusetocreateanduploadArduinosketches(Arduinosnameforits
programs)totheArduinoboarditself.Youlllearnthebasicframeworkofa
Settings
sketchandsomebasicfunctionsthatyoucanimplementinasketch,andyoull
createanduploadyourfirstsketch.
Feedback(http://community.safaribooksonline.com/)
WhatexactlyisArduino?AccordingtotheArduinowebsite
(http://www.arduino.cc/(http://www.arduino.cc/)),itis
anopensourceelectronicsprototypingplatformbasedonflexible,easy
tousehardwareandsoftware.Itsintendedforartists,designers,
hobbyists,andanyoneinterestedincreatinginteractiveobjectsor
environments.
Insimpleterms,theArduinoisatinycomputersystemthatcanbeprogrammed
withyourinstructionstointeractwithvariousformsofinputandoutput.The
currentArduinoboardmodel,theUno,isquitesmallinsizecomparedtothe
averagehumanhand,asyoucanseeinFigure21.
Figure21.AnArduinoUnoisquitesmall.
Althoughitmightnotlooklikemuchtothenewobserver,theArduinosystem
allowsyoutocreatedevicesthatcaninteractwiththeworldaroundyou.By
usinganalmostunlimitedrangeofinputandoutputdevices,sensors,indicators,
displays,motors,andmore,youcanprogramtheexactinteractionsrequiredto
createafunctionaldevice.Forexample,artistshavecreatedinstallationswith
patternsofblinkinglightsthatrespondtothemovementsofpassersby,high
schoolstudentshavebuiltautonomousrobotsthatcandetectanopenflameand
extinguishit,andgeographershavedesignedsystemsthatmonitortemperature
andhumidityandtransmitthisdatabacktotheirofficesviatextmessage.Infact,
youllfindanalmostinfinitenumberofexampleswithaquicksearchonthe
Internet.
NowletsmoveonandexploreourArduinoUnohardware(inotherwords,the
physicalpart)inmoredetailandseewhatwehave.Dontworrytoomuch
aboutunderstandingwhatyouseehere,becauseallthesethingswillbediscussed
ingreaterdetailinlaterchapters.
LetstakeaquicktouroftheUno.Startingattheleftsideoftheboard,youllsee
twoconnectors,asshowninFigure22.
Subscribe.
Sign Out
Figure22.TheUSBandpowerconnectors
OnthefarleftistheUniversalSerialBus(USB)connector.Thisconnectsthe
boardtoyourcomputerforthreereasons:tosupplypowertotheboard,toupload
yourinstructionstotheArduino,andtosenddatatoandreceiveitfroma
computer.Ontherightisthepowerconnector.Throughthisconnector,youcan
powertheArduinowithastandardmainspoweradapter.
Atthelowermiddleistheheartoftheboard:themicrocontroller,asshownin
Figure23.
Figure23.Themicrocontroller
ThemicrocontrolleristhebrainsoftheArduino.Itisatinycomputerthat
containsaprocessortoexecuteinstructions,includesvarioustypesofmemoryto
holddataandinstructionsfromoursketches,andprovidesvariousavenuesof
sendingandreceivingdata.Justbelowthemicrocontrolleraretworowsofsmall
sockets,asshowninFigure24.
Figure24.Thepowerandanalogsockets
ThefirstrowofferspowerconnectionsandtheabilitytouseanexternalRESET
button.Thesecondrowofferssixanaloginputsthatareusedtomeasure
electricalsignalsthatvaryinvoltage.Furthermore,pinsA4andA5canalsobe
usedforsendingdatatoandreceivingitfromotherdevices.Alongthetopofthe
boardaretwomorerowsofsockets,asshowninFigure25.
Figure25.Thedigitalinput/outputpins
Sockets(orpins)numbered0to13aredigitalinput/output(I/O)pins.Theycan
eitherdetectwhetherornotanelectricalsignalispresentorgenerateasignalon
command.Pins0and1arealsoknownastheserialport,whichisusedtosend
andreceivedatatootherdevices,suchasacomputerviatheUSBconnector
circuitry.Thepinslabeledwithatilde(~)canalsogenerateavaryingelectrical
signal,whichcanbeusefulforsuchthingsascreatinglightingeffectsor
controllingelectricmotors.
Nextaresomeveryusefuldevicescalledlightemittingdiodes(LEDs)these
verytinydeviceslightupwhenacurrentpassesthroughthem.TheArduino
boardhasfourLEDs:oneonthefarrightlabeledON,whichindicateswhenthe
boardhaspower,andthreeinanothergroup,asshowninFigure26.
TheLEDslabeledTXandRXlightupwhendataisbeingtransmittedorreceived
betweentheArduinoandattacheddevicesviatheserialportandUSB.TheL
LEDisforyourownuse(itisconnectedtothedigitalI/Opinnumber13).The
littleblacksquareparttotheleftoftheLEDsisatinymicrocontrollerthat
controlstheUSBinterfacethatallowsyourArduinotosenddatatoandreceiveit
fromacomputer,butyoudontgenerallyhavetoconcernyourselfwithit.
Figure26.TheonboardLEDs
And,finally,theRESETbuttonisshowninFigure27.
Figure27.TheRESETbutton
Aswithanormalcomputer,sometimesthingscangowrongwiththeArduino,
andwhenallelsefails,youmightneedtoresetthesystemandrestartyour
Arduino.ThissimpleRESETbuttonontheboard(Figure27)isusedtorestart
thesystemtoresolvetheseproblems.
OneofthegreatadvantagesoftheArduinosystemisitseaseofexpandability
thatis,itseasytoaddmorehardwarefunctions.Thetworowsofsocketsalong
eachsideoftheArduinoallowtheconnectionofashield,anothercircuitboard
withpinsthatallowittoplugintotheArduino.Forexample,theshieldshownin
Figure28containsanEthernetinterfacethatallowstheArduinotocommunicate
overnetworksandtheInternet,withplentyofspaceforcustomcircuitry.
NoticehowtheEthernetshieldalsohasrowsofsockets.Theseenableyouto
insertoneormoreshieldsontop.Forexample,Figure29showsthatanother
shieldwithalargenumericdisplay,temperaturesensor,extradatastoragespace,
andalargeLEDhasbeeninserted.
Notethatyoudoneedtorememberwhichshielduseswhichindividualinputs
andoutputstoensurethatclashesdonotoccur.Youcanalsopurchase
completelyblankshieldsthatallowyoutoaddyourowncircuitry.Thiswillbe
explainedfurtherinChapter8.
Figure28.ArduinoEthernetinterfaceshield
Figure29.Numericdisplayandtemperatureshield
ThecompaniontotheArduinohardwareisthesoftware,acollectionof
instructionsthattellthehardwarewhattodoandhowtodoit.Twotypesof
softwarecanbeused:Thefirstistheintegrateddevelopmentenvironment(IDE),
whichisdiscussedinthischapter,andthesecondistheArduinosketchyou
createyourself.
TheIDEsoftwareisinstalledonyourpersonalcomputerandisusedtocompose
andsendsketchestotheArduinoboard.
Figure210.TheArduinoIDE
Open.Clickthistoopenasavedsketch.
Save.Clickthistosavetheopensketch.Ifthesketchdoesnthaveaname,
youwillbepromptedtocreateone.
SerialMonitor.Clickthistoopenanewwindowforuseinsendingand
receivingdatabetweenyourArduinoandtheIDE.
Figure211.TheLEDontheArduinoboard,nexttothecapitalL
NOTE
Dontworrytoomuchaboutthespecificcommandsinthe
sketchwerecreatinghere.Thegoalistoshowyouhow
easyitistogettheArduinotodosomethingsothatyoull
keepreadingwhenyougettotheharderstuff.
Tobegin,connectyourArduinotothecomputerwiththeUSBcable.Thenopen
theIDE,chooseToolsSerialPort,andmakesuretheUSBportisselected.
ThisensuresthattheArduinoboardisproperlyconnected.
Comments
First,enteracommentasareminderofwhatyoursketchwillbeusedfor.A
commentisanoteofanylengthinasketch,writtenfortheusersbenefit.
Commentsinsketchesareusefulforaddingnotestoyourselforothers,for
enteringinstructions,orfornotingmiscellaneousdetails.Whenprogramming
yourArduino(creatingsketches),itsagoodideatoaddcommentsregarding
yourintentionsthesecommentscanproveusefullaterwhenyourerevisitinga
sketch.
Toaddacommentonasingleline,entertwoforwardslashesandthenthe
comment,likethis:
//BlinkLEDsketchbyMarySmith,created09/09/12
ThetwoforwardslashestelltheIDEtoignorethetextthatfollowswhen
verifyingasketch.(Asmentionedearlier,whenyouverifyasketch,youre
askingtheIDEtocheckthateverythingiswrittenproperlywithnoerrors.)
Toenteracommentthatspanstwoormorelines,enterthecharacters/*ona
linebeforethecomment,andthenendthecommentwiththecharacters*/onthe
followingline,likethis:
/*
ArduinoBlinkLEDSketch
byMarySmith,created09/09/12
*/
Aswiththetwoforwardslashesthatprecedeasinglelinecomment,the/*and
*/telltheIDEtoignorethetextthattheybracket.
EnteracommentdescribingyourArduinosketchusingoneofthesemethods,
andthensaveyoursketchbychoosingFileSaveAs.Enterashortnamefor
yoursketch(suchasblinky),andthenclickOK.
ThedefaultfilenameextensionforArduinosketchesis.ino,andtheIDEshould
addthisautomatically.Thenameforyoursketchshouldbe,inthiscase,
blinky.ino,andyoushouldbeabletoseeitinyourSketchbook.
pinMode(13,OUTPUT);//setdigitalpin13tooutput
Thenumber13inthelistingrepresentsthedigitalpinyoureaddressing.Youre
settingthispintoOUTPUT,whichmeansitwillgenerate(output)anelectrical
signal.Ifyouwantedittodetectanincomingelectricalsignal,thenyouwould
useINPUTinstead.NoticethatthefunctionpinMode()endswithasemicolon
(;).EveryfunctioninyourArduinosketcheswillendwithasemicolon.
Saveyoursketchagaintomakesurethatyoudontloseanyofyourwork.
/*
ArduinoBlinkLEDSketch
byMarySmith,created09/09/12
*/
voidsetup()
{
pinMode(13,OUTPUT);//setdigitalpin13tooutput
}
voidloop()
{
//placeyourmainloopcodehere:
}
WARNING
TheArduinoIDEdoesnotautomaticallysavesketches,so
saveyourworkfrequently!
Next,entertheactualfunctionsintovoidloop()fortheArduinotoexecute.
Enterthefollowingbetweentheloopfunctionsbraces,andthenclickVerifyto
makesurethatyouveenteredeverythingcorrectly:
digitalWrite(13,HIGH);//turnondigitalpin13
delay(1000);//pauseforonesecond
digitalWrite(13,LOW);//turnoffdigitalpin13
delay(1000);//pauseforonesecond
Letstakethisallapart.ThedigitalWrite()functioncontrolsthevoltagethat
isoutputfromadigitalpin:inthiscase,pin13totheLED.Bysettingthesecond
parameterofthisfunctiontoHIGH,ahighdigitalvoltageisoutputthen
currentwillflowfromthepinandtheLEDwillturnon.(Ifyouweretosetthis
parametertoLOW,thenthecurrentflowingthroughtheLEDwouldstop.)
WiththeLEDturnedon,thelightpausesfor1secondwithdelay(1000).The
delay()functioncausesthesketchtodonothingforaperiodoftimeinthis
case,1,000milliseconds,or1second.
Next,weturnoffthevoltagetotheLEDwithdigitalWrite(13,LOW);.
Finally,wepauseagainfor1secondwhiletheLEDisoff,withdelay(1000);.
Thecompletedsketchshouldlooklikethis:
/*
ArduinoBlinkLEDSketch
byMarySmith,created09/09/12
*/
voidsetup()
{
pinMode(13,OUTPUT);//setdigitalpin13tooutput
}
voidloop()
{
digitalWrite(13,HIGH);//turnondigitalpin13
delay(1000);//pauseforonesecond
digitalWrite(13,LOW);//turnoffdigitalpin13
delay(1000);//pauseforonesecond
}
Beforeyoudoanythingfurther,saveyoursketch!
Figure212.Thesketchhasbeenverified.
ThisDonecompilingmessagetellsyouthatthesketchisokaytouploadto
yourArduino.Italsoshowshowmuchmemoryitwilluse(1,076bytesinthis
case)ofthetotalavailableontheArduino(32,256bytes).
Butwhatifyoursketchisntokay?Say,forexample,youforgottoadda
semicolonattheendoftheseconddelay(1000)function.Ifsomethingis
brokeninyoursketch,thenwhenyouclickVerify,themessagewindowshould
displayaverificationerrormessagesimilartotheoneshowninFigure213.
Figure213.Themessagewindowwithaverificationerror
Themessagetellsyouthattheerroroccursinthevoidloopfunction,liststhe
linenumberofthesketchwheretheIDEthinkstheerrorislocated(blinky:16,
orline16ofyourblinkysketch),anddisplaystheerroritself(themissing
semicolon,error:expected';'before'}'token).Furthermore,the
IDEshouldalsohighlightinyellowthelocationoftheerrororaspotjustafterit.
Thishelpsyoueasilylocateandrectifythemistake.
thensaveyoursketchagainanduploadittotheArduino.Forexample,to
increasetherateofblinking,changebothdelayfunctionstomaketheLEDs
blinkforonequarterofasecondbyadjustingthedelayto250likethis:
delay(250);//pauseforonequarterofonesecond
Thenuploadthesketchagain.TheLEDshouldnowblinkfaster,foronequarter
ofasecondeachtime.
Looking Ahead
Armedwithyournewfoundknowledgeofhowtoenter,edit,save,andupload
Arduinosketches,yourereadyforthenextchapter,whereyoulllearnhowto
usemorefunctions,implementgoodprojectdesign,constructbasicelectronic
circuits,anddomuchmore.