Chapter 2. Exploring The Arduino Board and The IDE: Enjoy Safari?

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Arduino Workshop

NEXT

PREV

1. Getting Started

3. First Steps

Recent

Topics
Tutorials

Chapter2.Exploring the Arduino


Board and the IDE

Highlights

Settings
Feedback(http://community.safaribooksonline.com)
Sign Out

InthischapteryoullexploretheArduinoboardaswellastheIDEsoftwarethat
youllusetocreateanduploadArduinosketches(Arduinosnameforits
programs)totheArduinoboarditself.Youlllearnthebasicframeworkofa

Settings

sketchandsomebasicfunctionsthatyoucanimplementinasketch,andyoull
createanduploadyourfirstsketch.

The Arduino Board

10 days left in your trial.

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.

Enjoy Safari? Subscribe Today

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.

Taking a Look Around the IDE


AsshowninFigure210,theArduinoIDEresemblesasimplewordprocessor.
TheIDEisdividedintothreemainareas:thecommandarea,thetextarea,and
themessagewindowarea.

Figure210.TheArduinoIDE

The Command Area


ThecommandareaisshownatthetopofFigure210andincludesthetitlebar,
menuitems,andicons.Thetitlebardisplaysthesketchsfilename
(sketch_mar22a),aswellastheversionoftheIDE(Arduino1.0).Belowthisisa
seriesofmenuitems(File,Edit,Sketch,Tools,andHelp)andicons,asdescribed
next.
Menu Items
Aswithanywordprocessorortexteditor,youcanclickoneofthemenuitemsto
displayitsvariousoptions.
File.Containsoptionstosave,load,andprintsketchesathoroughsetof
examplesketchestoopenaswellasthePreferencessubmenu
Edit.Containstheusualcopy,paste,andsearchfunctionscommontoany
wordprocessor
Sketch.Containsthefunctiontoverifyyoursketchbeforeuploadingtoa
board,andsomesketchfolderandimportoptions
Tools.Containsavarietyoffunctionsaswellasthecommandstoselectthe
ArduinoboardtypeandUSBport
Help.ContainslinkstovarioustopicsofinterestandtheversionoftheIDE
The Icons
Belowthemenutoolbararesixicons.Mouseovereachicontodisplayitsname.
Theicons,fromlefttoright,areasfollows:
Verify.ClickthistocheckthattheArduinosketchisvalidanddoesnt
containanyprogrammingmistakes.
Upload.ClickthistoverifyandthenuploadyoursketchtotheArduino
board.
New.Clickthistoopenanewblanksketchinanewwindow.

Open.Clickthistoopenasavedsketch.
Save.Clickthistosavetheopensketch.Ifthesketchdoesnthaveaname,
youwillbepromptedtocreateone.
SerialMonitor.Clickthistoopenanewwindowforuseinsendingand
receivingdatabetweenyourArduinoandtheIDE.

The Text Area


ThetextareaisshowninthemiddleofFigure210thisiswhereyoullcreate
yoursketches.Thenameofthecurrentsketchisdisplayedinthetabattheupper
leftofthetextarea.(Thedefaultnameisthecurrentdate.)Youllenterthe
contentsofyoursketchhereasyouwouldinanytexteditor.

The Message Window Area


ThemessagewindowareaisshownatthebottomofFigure210.Messagesfrom
theIDEappearintheblackarea.Themessagesyouseewillvaryandwill
includemessagesaboutverifyingsketches,statusupdates,andsoon.
Atthebottomrightofthemessagearea,youshouldseethenameofyour
ArduinoboardtypeaswellasitsconnectedUSBportArduinoDuemilanove
w/ATmega328onCOM6inthiscase.

Creating Your First Sketch in the IDE


AnArduinosketchisasetofinstructionsthatyoucreatetoaccomplisha
particulartaskinotherwords,asketchisaprogram.Inthissectionyoullcreate
anduploadasimplesketchthatwillcausetheArduinosLED(shownin
Figure211)toblinkrepeatedly,byturningitonandthenofffor1second
intervals.

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.

The Setup Function


Thenextstageincreatinganysketchistoaddthevoidsetup()function.This
functioncontainsasetofinstructionsfortheArduinotoexecuteonceonly,each
timeitisresetorturnedon.Tocreatethesetupfunction,addthefollowing
linestoyoursketch,afterthecomments:
voidsetup()
{
}

Controlling the Hardware


OurprogramwillblinktheuserLEDontheArduino.TheuserLEDisconnected
totheArduinosdigitalpin13.Adigitalpincaneitherdetectanelectricalsignal
orgenerateoneoncommand.Inthisproject,wellgenerateanelectricalsignal
thatwilllighttheLED.Thismayseemalittlecomplicated,butyoulllearnmore
aboutdigitalpinsinfuturechapters.Fornow,justcontinuewithcreatingthe
sketch.
Enterthefollowingintoyoursketchbetweenthebraces({and}):

pinMode(13,OUTPUT);//setdigitalpin13tooutput

Thenumber13inthelistingrepresentsthedigitalpinyoureaddressing.Youre
settingthispintoOUTPUT,whichmeansitwillgenerate(output)anelectrical
signal.Ifyouwantedittodetectanincomingelectricalsignal,thenyouwould
useINPUTinstead.NoticethatthefunctionpinMode()endswithasemicolon
(;).EveryfunctioninyourArduinosketcheswillendwithasemicolon.
Saveyoursketchagaintomakesurethatyoudontloseanyofyourwork.

The Loop Function


RememberthatourgoalistomaketheLEDblinkrepeatedly.Todothis,well
createaloopfunctiontotelltheArduinotoexecuteaninstructionoverandover
untilthepowerisshutofforsomeonepressestheRESETbutton.
Enterthecodeshowninboldfaceafterthevoidsetup()sectioninthe
followinglistingtocreateanemptyloopfunction.Besuretoendthisnew
sectionwithanotherbrace(}),andthensaveyoursketchagain.

/*
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!

Verifying Your Sketch


Whenyouverifyyoursketch,youensurethatithasbeenwrittencorrectlyina
waythattheArduinocanunderstand.Toverifyyourcompletesketch,click
VerifyintheIDEandwaitamoment.Oncethesketchhasbeenverified,anote
shouldappearinthemessagewindow,asshowninFigure212.

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.

Uploading and Running Your Sketch


Onceyouresatisfiedthatyoursketchhasbeenenteredcorrectly,saveit,ensure
thatyourArduinoboardisconnected,andclickUploadintheIDE.TheIDE
mayverifyyoursketchagainandthenuploadittoyourArduinoboard.During
thisprocess,theTX/RXLEDsonyourboard(showninFigure26)shouldblink,
indicatingthatinformationistravelingbetweentheArduinoandyourcomputer.
Nowforthemomentoftruth:YourArduinoshouldstartrunningthesketch.If
youvedoneeverythingcorrectly,thentheLEDshouldblinkonandoffonce
everysecond!
Congratulations.Younowknowthebasicsofhowtoenter,verify,anduploadan
Arduinosketch.

Modifying Your Sketch


Afterrunningyoursketch,youmaywanttochangehowitoperates,by,for
example,adjustingtheonoroffdelaytimefortheLED.BecausetheIDEisalot
likeawordprocessor,youcanopenyoursavedsketch,adjustthevalues,and

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.

Recommended / Queue / Recent / Topics / Tutorials / Settings / Blog(http://blog.safaribooksonline.com) /


Feedback(http://community.safaribooksonline.com/) / Sign Out
2015 Safari(http://www.safaribooksonline.com/).
Terms of Service / Privacy Policy

You might also like