Tải bản đầy đủ (.pdf) (57 trang)

Arduino complete beaginner guie for arduno everything you need to know to get started

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.36 MB, 57 trang )








ARDUINO
CompleteBeginnersGuideForArduino-EverythingYou
NeedToKnowToGetStarted



MatthewMckinnon


TableofContents
Introduction
Chapter1:WhatisArduino?
Chapter2:Arduinoboards
Chapter3:ArduinoTerminologies
Chapter4:ArduinoIDE
Chapter5:UnderstandingArduinoSyntax
Chapter6:Programmingexpressions
Chapter7:ArduinoProjectcreationProcess
Chapter8:DownloadandinstalltheArduinoIDE
Chapter9:Hardwareoverview
Chapter10:Arduinocommands
Chapter11:AdvancedProgrammingConcepts
Chapter12:Samplecodesforstudy





INTRODUCTION
AreyoueagertoopenuptotheniftyworldofArduinoboards?Doyouhaveacoolideain
your mind and looking for something to realize your ideas? Have you just bought an
Arduinoboard,andwanttomakesureyougetarunningstart?Thenthisbookmayhelp
youinyourendeavor.
Itcoverstheinformationyouneedtojumpinfeetfirst:
·ArduinoterminologiesanddifferenttypesofArduinoboards
·ArduinoIDE
·ArduinosyntaxandProgrammingexpressions
·HardwareoverviewandArduinocommands
·Advancedprogrammingconcepts–Interrupts,Array,Arduinolibrary
·Samplecodesforstudyandmore
IfyouareeagertojoininontheadventureofdesigningcoolprojectsbyusingArduino
Boards,thisbookwillhelpyouaccomplishit.
Thanksagainfordownloadingthisbook.Ihopeyouenjoyit!


CHAPTER1:WHATISARDUINO?
Arduino is a type of open-source platform, which may be used to develop electronic
projects.Arduinoplatformismadeupoftwoseparatecomponents–microcontrollerand
anIDE.Microcontrollerisalsoknownasprogrammablecircuitboard,whichconstitutes
the hardware of Arduino. IDE is a software which runs on your system and it lets you
write and upload code to microcontroller. Arduino is known as a physical or embedded
computingplatform,whichimpliesthatArduinohelpstosensethephysicalworldbetter
compared to our current computers. Arduino helps in the development of interactive
objectsbyusingtheinputsfromswitchesandsensorstoregulatephysicaloutputs.
Arduino can be considered as a tiny computer, which enables to process inputs and

outputsbetweenthegadgetandexternalmodulesyouattachtoit.Forinstance,youmay
useArduinototurnonlightforapre-definedtime,maybe10secondsafterwepressa
button. You may use this concept for a variety of purposes like creating digital clocks,
temperature and humidity sensors etc. All the design files for Arduino board have been
madepublic.AnypersoncanmakeclonesofArduinosinceitisanopen-sourcehardware.
OnlineResource:
ArduinoProducts: />ArduinoBoardSpecifications: />ArduinoUno: />
AdvantagesofArduino
· Affordable–Arduinoboardisavailableataffordableratescomparedtoother
microcontrollerplatforms.
·Cross-platformsupport–ArduinobacksWindows,LinuxandMacintoshOSX.
·Easytofollowprogrammingenvironment–Programmingenvironmentissimple
and easy to follow. Moreover, the platform is simple and flexible which assists in
accomplishingcomplexprojects.
·Extensiblesoftwareandhardware–Arduinoiscompletelyopen-sourceandhelps
toexpandthecapabilitiesbyusinglanguageslikeC++,AVRC.Itenablesprogrammersto
makemoduleversions,enhancing,extendingandthelike.


· ProgramitviaUSBcable–MostofthemoderndaycomputerssupportUSB
cableandhencethisisareallygoodfeature.
· Activecommunityofusers–Youcanalsogetsupportfromlike-mindedusers
whoareexpertsinthisfield
AtmelMicrocontroller
MainunitofArduinoisanAtmelmicrocontrollerunit,whichisaccountableforexecuting
thecommandsyouspecify.ArduinoUnousesanAVRATMegamicrocontrollerwhereas
the Arduino Due uses an ARM Cortex microcontroller. A 16 Mhz ceramic resonator is
attached to the clock pins which functions as the reference to execute your program
commands.Usercanuseresetbuttontorestartprogramexecution.



CHAPTER2:ARDUINOBOARDS
ThereisawidevarietyofArduinoboardscurrentlyavailableinmarketandnewboards
are released with improved aspects regularly. Hence, let us concentrate on some of the
leadingofficialArduinoboards.

ArduinoUNO
ArduinoUNOisthewidely-usedmicrocontrollerboardandisbasedontheATmega328P.
ArduinoUNOencompasses14digitalI/Opins,6analoginputs,32Kbflashmemoryand
clockspeedof16Mhz.Operatingvoltageis5Vwhereasrecommendedinputvoltageis712V.

Fig2.1ArduinoUNO

ArduinoLeonardo
Arduino Leonardo uses ATmega32u4 and includes 20 digital I/O pins, 32 Kb flash
memoryandclockspeedof16Mhz.Operatingvoltageis5Vwhereasrecommendedinput
voltageis7-12V.


Fig2.2ArduinoLeonardo

ArduinoMega2560
ArduinoMega2560usesATmega2560asthemainmicrocontrollerunit.ArduinoMega
2560isconceivedforcomplexprojectslikerapidprototyping.Itincludes54digitalI/O
pins,16analoginputpins,flashmemoryof256kbandclockspeedof16Mhz.Ithelps
youtointerfacewithmultipledevicesasithas54GPIOpins.

Fig2.3ArduinoMega2560

ArduinoDue

Arduino Due employs Atmel SAM3X8E ARM Cortex-M3 CPU as microcontroller. It
encompasses54digitalI/Opins,12analoginputs,2analogoutputsandflashmemoryof
512kb.Operatingvoltageis3.3Vwhereasrecommendedinputvoltageis7-12V.


Fig2.4ArduinoDue

ArduinoNano
ArduinoNanoemploysATmega328asthemicrocontrollerunit.Asthenameimplies,its
smallformfactormakesittheidealoptionformorefinishedprojects.

Fig2.5ArduinoNano

ArduinoMegaADK
ArduinoMegaADKusesATmega2560asthemainmicrocontrollerunit.Itincludes54
digitalI/Opins,16analoginputpins,flashmemoryof256kbandclockspeedof16Mhz.
Ithelpsyoutointerfacewithmultipledevicesasithas54GPIOpins.


Fig2.6ArduinoMegaADK


CHAPTER3:ARDUINOTERMINOLOGIES
Havinggoodunderstandingoftheterminologiesandjargonsisinevitabletogetthemost
outofthisbook.
Breadboard–Breadboardsareextremelyusefulforprototyping,whichisareusabletool
fordevelopingcircuits.Itenablesyoutojoincircuitswithoutpermanentlysolderingthem,
whichservesasastablesurfaceforlinkingtogethermodules.
Compiler – Compiler translates code that you have written into a form that Arduino
microcontrollercanperceive.

Devicedriver–Devicedriverisresponsibleforthecommunicationbetweencomputerand
gadgetthatyouhavelinkedtothesystem.
EEPROM–Itstandsforelectricallyerasableprogrammableread-onlymemory.Electric
currenthastobeusedtoerasethechipcontent.
Externalinterrupt–Anexternalinterruptimpliesthatsomeeventhasoccurredoutsidethe
processor,whichdemandsattention.
Flash Memory – It is a type of memory, which helps to retain data even if power is
providedornot.
DigitalInput/output–Digitalpinscanhaveeitherhighorlowvalue,wherelowmeans0
orfalseandhighmeans1ortrue.Thenumberofdigitalpinscanvarybetweendifferent
Arduinoboards.
AnalogInput/output–Analogsignalmeanscontinuouselectricalsignal.Inputforanalog
i/ppinisanalogsignal.
Processor – Computer instructions are fed into the processor, after which they are
executed.
PWMpins–InPWMpin,dataistransmittedbymeansofpulse–widthmodulation.
Serialcommunication–Serialcommunicationoccurswhentwosystemstransmitdigital
pulsesbetweenthematapre-definedrate.
Sketch–SketchisanalogoustocodethatwerefertoinJAVA/Cprogramming.Sketch
encompassestheinstructions,whichenabletheArduinotorun.


SPI–SPIorserialperipheralinterfacewhichisusedascommunicationprotocolinshort
distancecommunication.
SRAM–SRAMstandsforStaticRandomAccessMemorywhichimpliesthatitdoesnot
havetoberefreshedfromtimetotime.
UART–UARTstandsforUniversalAsynchronousReceiver/Transmitterwhichisusedto
transformbetweenserialandparalleldata.



CHAPTER4:ARDUINOIDE
ArduinoIDEisalsoknownasArduinoIntegratedDevelopmentEnvironment,whichisa
texteditorlikeprogram.IthelpsyoutowriteArduinocode,verifythecodeandupload
thesametoArduinoboard.WhenyousaveafileonArduino,thefileiscalledasketch
and a sketch is where you save all the computer code that you’ve written. Coding
languagethatArduinousesisverymuchlikeC++whichisacommonlanguageinthe
worldofcomputing.ThecodeyoulearntowriteforyourArduinowillbeverysimilarto
codeyouwriteinanyothercomputerlanguage.Allthebasicconceptsremainthesame
anditisreallyjustamatteroflearninganewdialectshouldyoupursueotherventuresand
programming.Thecodethatyouwillbewritingiscalledhumanreadable,whichimplies
thatitwillbeorganizedforahumantofollow.PartofthejobisoftheIDEistotakethe
human-readablecodethatwewriteandthentranslatethatintomachine-readablecodethat
canbeexecutedbyArduino.Thisprocessiscalledcompiling.
FileextensionforsketchisdotINO.ItusedtobedotPDEforolderIDEversion.
ArduinoIDEcanbedividedintofourparts:
1.FileMenu–whichcanbeseeninthetoppartofArduinoIDE
2.Toolbar
3.CodeorSketchwindow
4.Messageswindow
Buttonsintoolbaroffereasyaccesstofunctionswhicharecommonlyused.Theyare:
1.Verify–Thisbuttonverifiesifthecodeiscorrectanderror-freesothatitcould
beuploadedtotheArduinoboard.ShortcutkeyforverifyisControlR.Itwouldshowan
errormessageatthebottomofthescreenifthereisanyissue.
2.Stop–Usermayclickonthestopbutton(tostoptheoperationofserialmonitor)
to receive snapshot of serial data to check it. Once the stop button is clicked, other
selectedbuttonswillbeun-highlighted.
3. New–Usercanclickonthenewbuttontodevelopablanksketchwhichhelps
youtokeyinthecode.Inordertocreateablanksketch,Arduinoneedsnameandlocation
ofthesketch.Givingdefaultlocationisconsideredasthebestpracticeforgivinglocation



ofthesketch.
4. Open–Openbuttonoffersasetofsketches,whichissavedinyoursketchbook
andalsoasetofsamplesketchesthatyoucouldusewithmultipleperipherals.Fornovice
Arduinousers,thiswilldefinitelyprovetobeavaluableasset.Usermayeditthesample
codestosuittheirrequirements.
5.Save–Savebuttonhelpstosavethecodethatyouhavewritteninsidethesketch
window.
6. Upload–Thisbuttonhelpstouploadthecodethatyouhavewritteninsidethe
sketch window to Arduino. Short cut key for upload is control U. If you have got your
ArduinohookeduptoyourcomputerwithyourUSBcable,you’llseethat2LED`sare
goingtoblinkreallyfast.TheLEDsareTXandtheRXLED`sthatstandfortransmit
andreceive.
7. Monitor–Itdisplaysserialdata,whichissentfromArduino.Italsohelpsto
transmitserialdatatoArduino.Short-cutkeyforserialdatamonitorisshiftcontrolN.
Baud rate is defined as the rate at which bits are sent to or from the Arduino board.
Defaultsettingsforbaudrateis9600baud,usermaychangethebaudsettingsifrequired.
You may view error messages (if any) in red text at the bottom of IDE window. At the
bottom left side, you may see a number, which refers to the cursor location inside the
code.Ifyounavigatedownthecodelines,youcouldseethatthisnumberincreases,this
helpstopinpointdefects,whicharehighlightedintheerrormessage.
BestpracticeswhiledealingwithArduinoIDEareasfollowing:
1. Givingdefaultlocationisconsideredasthebestpracticeforgivinglocationof
thesketch
2. MakesurethatyousavethesketchbeforeyouuploadittoArduinoboard.This
willhelptoretaincodeenteredincasesystemhangsorIDEcrashes.
3.ClickonVerify/Completebuttontoconfirmthatyourcodeiserror-free.

IDEMenus
Now,letuslearnaboutIDEMenus.ThefirstmenuistheArduinomenu.AboutArduino

displays the present version number and some additional details. Preference option
enablesusertochangedifferentIDEchoiceslikesketchbooklocation.QuitArduinohelps
toquittheIDE.


Fig4.1ArduinoMenu
FileMenu
FileMenuenablesyoutodevelopanewsketch,viewsketchesthatyouhavesavedinthe
sketchbook,savethesketch,uploadthesketchandalsotoprintoutthecode.

Fig4.2FileMenu
Editmenu
Editmenuenablesyoutoperformeditoperationsonthecode–cut,copyandpastecode
sections. You can also increase or decrease the indents with the help of edit menu. This
menu also helps to select the complete code or find specific codes or phrases inside the
code.


Fig4.3EditMenu
Sketchmenu
It encompasses Verify/Compile functions, which helps to verify or compile the code.
Importlibraryfeaturedisplayslistofavailablelibrariessavedinsidelibrariesfolder.Add
File feature enables user to incorporate another source file to sketch which helps to
separatebiggersketchesintosmallerunits,whichcanbethenincludedinthemainsketch.

Fig4.4SketchMenu

Toolsmenu
ToolsMenuoffersagaloreofoptions.Autoformatfunctionrendersyourcodecrispand
nicer. Archive Sketch feature enables you to compress the sketch into a ZIP file format

andasksyouthelocationwhereyouwouldliketostoreit.BurnBootloaderfeatureburns
the Arduino Bootloader, which is the piece of code on the chip conceived to make it
compatiblewithIDE.


Fig4.5ToolsMenu
Dropdownmenu
Dropdownmenuallowsyoutomakenewtabs,renameyourtab,deleteatabandyoucan
alsonavigatethroughthetabsdownatthebottom.
Helpmenu
You can find valuable information pertaining to Arduino IDE and links to other useful
pages.


CHAPTER5:UNDERSTANDINGARDUINOSYNTAX
Syntax is to computer language as grammar is to written language. When we write a
sentence, it might have a period, a semi colon or a dash and all those grammatical
instruments to convey information to the reader. Computer programming languages also
followthesameformatanditiscalledsyntax.
Now,clickonfileàexamplesàbasicsandopenupdigitalreadserial.Letuslearnstepby
stepabouttheArduinosyntax.

Fig5.1SampleCode
In the above image, you could see two forward slashes. You could also see that all the
words on the line following the forward slashes are grayed out. Comment tells the
compilertoignorethatlineofcode.Commentsallowyoutoexplaintoyourself,ormore
importantlyafutureversionofyourself,whatexactlyyouweredoingwhenyouwrotea
pieceofcode.
Now,letusanalyzeintpushButton=2;
Here,INTstandsforinteger.Ithasgotanamepushbuttonandisassignedvalueas2.If

commentisnotwritten,youwouldbewonderingwhatthecodemeans.Here,authorhas
writtenexplicitlythatdigitalpin2hasapushbuttonattachedtoitgiveitaname.
Comments provide information to you when you forget what you wrote and it will be
helpfultootheruserswhoviewyourcode.Commentscanbeclassifiedintotwo–single
linecommentsandmulti-linecomments.
Semicolonistogrammarwhataperiodis[KIT1] .Theendofeverystatementofcodeneed
tohaveasemicolonthatletsthecompilerknowthatyouaredonewiththatstatementof
code.Youwillgetanerrorifyouforgetasemicolonsoeverysinglelineofcodethatyou


writeotherthanfunctionneedtohaveasemi-colon.
TherearetwoverycommonfunctionsthatyouuseinalmosteveryArduinoprogram-they
are called as set up and loop functions. Function basically encapsulates an extremely
usefulpieceofcodeandthenreducesittoasinglekeywordwhichallowsyoutorapidly
implementthatpieceofcode.So“setup”itisonlyonewordbutbehindthescenessetup
isabigfunctionthatdoeslotsofstuff.
Weputtheopeningandclosingparentheses.Foreachopeningparenthesis,thereshouldbe
aclosingparenthesis.Weputouropeningcurlybracketandnowwecanuseallthepower
setup.Setupbasicallysetsuptheprogram.Thisiswhereyou’regoingtoinitializeapin
asaninputoroutputonyourArduino.Youmightsetsomebaselineparametersforyour
programandstartserialcommunication.
Nowtheloopisafunctionjustlikesetupfunction.Loopisreallythemeatandpotatoesof
thefunctionandthelooprunsoverandoveragain.Codegetsexecutedfromfirstlinetill
itgetstothebottomanditgetstothatcurlyclosingbracket.Thisprocessrepeatsandthat
iswhywecallitaloop.
Whatvoidbasicallysaysisthatthisfunctiondoesnotreturnanyinformationbacktothe
program.Soit’sbasicallyperformingafunctionandthatfunctioninandofitselfisallyou
need.You’renotgettinglikeanumberbackfromsetup.



CHAPTER6:PROGRAMMINGEXPRESSIONS
Expressions are combinations of variables, constants, mathematical operators, logical
operatorsetc.

Variablesanddatatypes
VariablesarefundamentaltoallprogramminglanguagesandtheArduinoisnoexception.
Variablesareprogrammingtoolsthatallowustocarryaroundinformationfromonepart
ofaprogramtoanotherpartofaprogram.Contentsofthevariablechangeandvariable
stays as such. When you make a variable, you need to specify what type of stuff that
you’re going to put inside the variable. In programming terminology, the stuff that you
specifyiscalledthedatatype.Someexamplesofdatatypesareintegers,charactersand
arrays.Avariablewillonlyholdthedatatypethatyouspecify.Theprocessofmakinga
variable is called declaring or declaration. When you declare a variable, there are two
thingsthatyouneedtotelltheprogram.Firstisthedatatypeandsecondisthenameof
thevariable.
To declare a variable, you need to write the type of contents it will hold (data type)
followedbythenameandthereshouldbespaceinbetween.
For example, if you are going to write a program to blink an LED, we need to declare
variableas
intled;
Here, int is data type, led is the variable and then it ends with a semi colon. When you
declarevariableinArduino,youcouldnoticeisthatthedatatypeisadifferentcolorand
that’sbecauseArduinoknowsvariabledatatypesandgivesthemaspecialcolortoreduce
confusion. When we specify data types, what we’re telling the compiler is to set aside
muchspacefortheinformationforthisvariable.
Therearecertainrestrictionsforvariablenaming.Forexample,avariablenamecannot
have spaces or special characters in it. You may use upper and lowercase letters and
numbersfornamingthevariable.However,variablenamecan’tjustbeanumberandyour
variable must start with a letter, not a number. Variable names cannot be the name of
Arduino keyword. It is good to give the variable name as descriptive of X function as

possible.


You should always start your variables with lowercase letters and then if your variable
name is two words connected together, then you should capitalize the first letter of the
secondwordandthenifyouhavemultiplewordsjustkeepcapitalizingthefirstletterof
theofthewordsasyougo,forexample,ledPinandholdPinValues.
Processofputtingsomethinginvariableisinitialization.
Forexample,
Declarationisintled;
Initializationisled=10;
Wecancoupletogetherdeclarationandinitializationasintled=10;
Thereareseveraltypesofdatathatyoucandeclare.Forexample,
Integerdatatype-anintegerisawholenumberandawholenumberisjustanumberwith
nodecimals(forexample,10and1500arewholenumbersbutnumberslike1.5eisnota
wholenumber).ForArduino,anintegerisanumberfrom-32,768to+32,768.
Booleandatatype-itcantaketwovalues,eithertrueorfalse
Characterdatatype-itcantakevaluessuchas‘a’or‘X’etc.
Longdatatype–thisdatatypecanbeconsideredasanextensionofintegerdatatypeand
itcouldtakevaluesbetween-2157483648to2157483647.
Floatdatatype–thisdatatypecantakevaluesbetween-3.4028e+38to3.4028e+38.

Operators
Variablesaremanipulatedbyusingoperators.Operatorscanbebroadlyclassifiedintofour
categories:
1.Assignment
2.Mathematical
3.Logical
4.Boolean
Assignmentoperator–itisalsoknownasequalsign,whichcomputesthevalueinRHS

andassignsthevaluewiththevariableinLHS.
Mathematicaloperator–theyperformmathematicaloperations,


Forexample.,+(addition),-(subtraction),*(multiplication),/(division)
Logicaloperator–
==equalto
!=notequalto
>greaterthan
<=lessthanorequalto
>=greaterthanorequalto
Booleanoperator–Itworksonbooleandatatypes
&&and
||or
!not
Incrementanddecrementoperators
Incrementoperator–Valueofvariableisincrementedby1
Decrementoperator–Valueofvariableisdecrementedby1


CHAPTER7:ARDUINOPROJECTCREATION
PROCESS
Now,letusseewhatarethedifferentstepsinvolvedinArduinoprojectcreation.
DifferentstepsinvolvedinArduinoprojectcreationareasfollows:
1.Specify
2.Design
3.Prototype
4.Algorithm
5.Sketch

6.CompileandUpload
7.TestandDebug
Specify
Before you have to start with Arduino project creation, you need to be clear of the
objectivemeaning,whatisthenatureandrangeofinputgiven,howtheoutputwouldbe
andhowitcouldbegenerated?Whatprocessyouneedtogothroughtoconvertinputinto
output?Onlywhenthisphaseisclear,youcouldproceedtonextstep.
Design
Onceyouareclearwithinputtype,outputtypeandthetransformationprocess,youmay
start working on the second phase, which is design phase. You need to design circuit
withintherestrictionsoftheArduinoboardtoachievethisgoal.Youshouldbeclearofthe
electronic components that you need to start working on the project. Electronic
componentsmayberesistors,capacitors,LEDs,sensorsetc.Youshouldalsobeawareof
thespecsofthecomponents.Youalsoneedtohavegoodunderstandingofthepinsthat
areusedasinput,outputorthepinsthatarenotneeded.
Prototype
Now,youhavetocreateprototypeofthecircuit.Thiscouldbedoneeitherinbreadboard
oryoucanalsomakeuseofanonlineprototypingtool.


Algorithm
ThispartisoftenneglectedbyArduinodevelopers,butneedtobegivenproperfocusto
ensuresuccessfulcompletionoftheArduinoproject.
Sketch
SketchisanalogoustocodethatwerefertoinJAVA/Cprogramming.Sketchencompasses
theinstructions,whichenablestheArduinotorun.WhenyousaveafileonArduino,the
fileiscalledasketchandasketchiswhereyousaveallthecomputercodethatyou’ve
written.
Compileandupload
CompilertranslatescodethatyouhavewrittenintoaformthatArduinomicrocontroller

canperceive.Oncethecodeiscompiled,ithastobeuploaded.
Testanddebug
ThisisoneofthemosttimeconsumingpartsofArduinoprogramming.Ifyourcodedoes
notrun,youneedtodebugthecode,findtheissueandfixit.Youalsoneedtocheckthe
circuitandensurethatitisproper.


CHAPTER8:DOWNLOADANDINSTALLTHE
ARDUINOIDE
OneoftheabsolutebestthingsabouttheArduinoplatformisthatitiseasytogetstarted.
The software that it installs in your computer is completely free and it is designed
specificallyforeaseofuse.
GotoyourfavoritebrowserandgototheArduinohomepage:www.arduino.cc

Fig7.1ArduinoHomepage
Gotothedownloadtabandfindyouroperatingsystem.WewillinstallontheMacforthis
tutorial.

Fig7.2Arduinodownload
Now,youhavetomentionwhereyouwanttosaveit.


×