Practical Arduino Engineering free ebook download
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
Contents at a Glance
iv
AbouttheAuthor...................................................................................................
AbouttheTechnicalReviewer .............................................................................
Preface..................................................................................................................
Chapter2:UnderstandingtheArduinoSoftware .................................................. Chapter4:AddingComplexitytotheRobot:WorkingwithLCDs.......................... Chapter6:Interlude:HomeEngineeringfromRequirementstoImplementation133
Chapter7:RobotPerception:ObjectDetectionwiththeArduino.......................
Chapter8:MatureArduinoEngineering:MakinganAlarmSystemUsingthe Arduino ................................................................................................................... Chapter9:ErrorMessagesandCommands:UsingGSMTechnologywithYour
Arduino ................................................................................................................... Chapter10:ControlandInstrumentation:TheXboxControllerandtheLabVIEW
Process................................................................................................................... Chapter11:ControllingYourProject:BluetoothArduino ................................... Index ...................................................................................................................
C H A P T E R 1 The Process of Arduino Engineering
Inthischapter,wewilldiscusstheengineeringprocessandhowyoucanuseitstreamlineyour prototypesbyavoidingproblemswithhardwareandsoftwareandkeepingtoafixedschedule. Throughoutthisbook,youwillhaveprojectsthatwillbeorganizedintoasequenceIliketocallthe “engineeringprocess.”Here’saquicksummaryofthesequence:
1. RequirementsGathering
2. Creatingtherequirementsdocument
3. Gatheringhardware
4. Configuringthehardware
5. Writingthesoftware
6. DebuggingtheArduinosoftware
7. Troubleshootingthehardware
8. Finishedprototype Asyoucanimagine,eventhissummaryofengineeringprocessisveryeffectivewhenprototyping, whichiswhywewilluseitwiththeArduinointhisbook.WhatistheArduino?TheArduinoisavery customizablemicrocontrollerusedbyhobbyistsandengineersalike.Also,itisopensource,which meansthatthesourcecodeisavailabletoyouforyourprogrammingneeds;theintegrateddevelopment environment(IDE)(whereyouwillbewritingyoursoftware)isfree,andmosttheresourcesyoucanfind areopensource.TheonlythingyouhavetobuyistheArduinomicrocontrolleritself.TheArduinois supportedverywellontheWebandinbooks,whichmakesitveryeasytoresearchhow-totopics;afew sitesthatwillhelpyougetstartedare
thisbookismorethansimplyahow-toreference;
thisbookisgoingtoteachyoutheengineeringprocess—askillthatisusefulformakingprojectsmore readable,efficient,andreliable.
Gathering Your Hardware
Beforeweexaminetheengineeringprocesssteps,it’simportanttoknowsomeofthepartsandmaterials you’llneed.Throughoutthisbook,youwillneedthefollowingpiecesofhardwaretocompletethe variousprojectswe’llbeworkingon(foracompletelistofhardwareusedinthisbook,pleasesee AppendixA):
- Arduino Duemilanove or UNO:YoucanuseeithertheDuemilanoveortheUNO micro-controllerforthisbook(seeFigure1-1).TheyhavemultipleI/Oportsfor sensorsandmotors.WewillbeusingtheseI/Opointstocontrolandkeeptrackof thevariousprojectsinthisbook.
Figure 1-1. Arduino UNO (left) and Duemilanove (right)
- ArduinoBT or Bluetooth Mate Silver:IsuggestusingtheBluetoothMateSilver modemforthisbookbecauseitcanmakeyourArduinoDuemilanoveorUNO behavelikeanArduinoBTathalfthecost.Also,theArduinoBTdoesnothavea3.3V outputpoint,soyouwouldneedtoaddcircuitrytotheArduinoinordertoget3.3V, whichyouneedinChapter6ofthisbook.Figure1-2illustratesthesetwopiecesof hardware.
Figure 1-2. ArduinoBT (left) and Bluetooth Mate Silver (right)
- Solderless breadboard:Anotherveryimportantpieceofhardwareisthesolderless breadboard(seeFigure1-3),whichisusedtoimplementyourcircuitry.Forthis book,youneedtohaveamidsizesolderlessbreadboard.Itwillbeusedinboththe designandtroubleshootingphasesoftheprojects.
Figure 1-3. An example of a solderless breadboard
- Wire:Wewillusealargequantityofwireinthisbook;youcangetawirejumper kitatalmostanyelectronicsstore.
- Arduino shields:Wewillbeusingseveralshieldsinthisbook,includingtheMotor,
GPS,GSM,andLCDshields(seeFigure1-4).
Figure 1-4. A couple of Aeduino Shields the GPS Shield on the left and the motor shield on the right.
- Motor shield:Thisshieldisusedtocontrolmotorsupto18V.Itincludesasurface- mountH-bridge,whichallowsforahighervoltagemotortobeusedaswellasfor controloftwomotors.FormoreinformationonH-bridges,pleaseseeChapter3.
- GPS shield:ThisshieldisusedtogetpositioninginformationfromGPSsatellites.
ItusestheNationalMarineElectronicsAssociation(NMEA)standard,whichcan beparsedtotellyouanynumberofthingssuchaslongitudeandlatitude,whether theGPShasafix,whattypeoffix,atimestamp,andthesignal-to-noiseratio.For moreinformationonGPSsystems,pleaseseeChapter5.
- GSM shield:ThisshieldwillallowyoutousethepoweroftheGlobalSystemfor
MobileCommunications(GSM)tosendtextmessagesbackandforthatgreat distances;thisshieldalsousesastandardprotocolcalledtheGSMprotocol.
- LCD shield:Wewillusethistoaddimagesandlifetoourrobots.TheLCDshield canalsobeusedtocreateyourownuserinterfaceforyourrobotoranyother projectthatyouwouldliketopersue.
- Sensors:Theseareveryimportantbecausetheygiveyourprojectslife.Some sensorexamplesarePIR(PassiveInfrared),sonar,andtemperature(seeFigure1- 5).
Figure 1-5. A PIR sensor (left) and a Sonar sensor (right)
- PIR sensor:Thisisanoutstandingsensorfordetectingchangesininfraredlight andcandetectchangesintemperature.Itisalsogreatatdetectingmotion,and that’swhatwewilluseitfor.
- Sonar sensor:Sonarsensorsaregoodatdetectingobjectsintheirsurroundings.
TheSonarsensorwewillbeusingisaParallaxsensorthatusesdigitalpingingto tellhowfarawayanobjectis.
- Temperature sensor:Thesesensorsareusedtoreadtemperature.Tousethem,you firstscalethevoltagetothetemperaturesyouwanttorecord;youcanfindmore informationaboutthissensorinChapter6.
- Servos and motors:Wewillbeusingmotorsandservostocontrolmanyaspectsof theprojects(seeFigure1-6).
Figure 1-6. Examples of a few motors:
- Miscellaneous:Thesearethemostcommoncomponents,suchasresistors, capacitors,LEDs,diodes,andtransistors(seeFigure1-7).
Figure 1-7. Miscellaneous pieces of hardware (terminal blocks, capacitors, resistors, LEDs, and switches)
Gathering Your Tools
Youwillalsouseavarietyoftools;thissectionwillbrieflydescribethem.Forafulllistoftoolsyouwill need,pleaseseeAppendixA.
- Soldering iron:Thistoolisusedtoconnectcircuitstoeachother;wewilluseit mostlytoconnectwiretocircuits(seeFigure1-8).
Figure 1-8. A Soldering iron and its stand
- Solder:Youwillusethisinconjunctionwiththesolderingiron;itisthemetalthat connectsthecircuitstogether.Solderhasaverylowmeltingpoint.
- Needle-nose pliers:Thesepliersareveryimportant;theyareusedtoholdwireand circuitsinplace,wrapwirearoundcircuitry,andsoon(seeFigure1-9).
- Magnifying glass:Thistoolisusedtobetterseecircuitry.
- Dikes:Theseareusedtocutwires(seeFigure1-9).
- Wire stripper:Thistoolisusedtotakeoffwireinsulation(seeFigure1-9).
- Multimeter:Possiblythemostimportanttoolyoucanown,thistoolallowsyouto readvoltage(AC(alternatecurrent)andDC(directcurrent)),amps(ampere),and ohms(seeFigure1-9).
- Scientific calculator:Thisallowsyoutodovariouscalculations(Ohm’sLaw, voltagedivider,etc.).
Figure 1-9. Additional Tools from left to right: multimeter, needle-nose pliers, wire clippers (top), wire stripper (bottom).
Understanding the Engineering Process
Theengineeringprocessisveryusefulinmakingyourdesignsmoreefficient,streamlined,and comprehensible.Theprocessconsistsofgatheringrequirements,creatingtherequirementsdocument, gatheringthecorrecthardware,configuringthehardware,writingthesoftware,debuggingthesoftware, troubleshootingthehardware,andthesigningoffonthefinishedprototype.
RequirementsGathering
OneDay,whenyou’reanengineer,youmaybeaskedtogotoacompanyandassessitsneedsfora particularproject.Thispartoftheengineeringprocessiscrucial;everythingwilldependonthe requirementsyougatheratthisinitialmeeting.Forexample,assumeyoulearnthatyourclientneedsto
blink an LED at a certain speed[insert an example case here to flush out the idea]. Andforthattask,you
andtheclientdeterminethattheArduinomicroprocessoristhebestchoice.TousetheArduinotoblink theLED[insert the example task here],acustomerneedsanLEDtoblinkat100msintervals.
CreatingtheRequirementsDocument
Basedontheclient’sneedsandyourproposedsolution,thefollowingisaverysimplerequirements document:
- Hardware
- Arduino
- LED
- 9Vbattery
- 9Vbatteryconnector
- 22ohmresis
- Software
- AprogramthatblinksanLEDat100msintervals Mindyou,thisisaverysimpleexample,butwewillbeusingthisformatfortherestofthisbook.
Oneofthereasonsyoucreatearequirementsdocumentistostopfeature creep.Thishappenswhena customerkeepsaddingfeaturestothesoftwareand/orhardware.Thisis,ofcourse,aproblembecause youwillbeworkingmorehourswithoutmorepayonaprojectthatmayneverend.Youshouldcreatea requirementsdocument,soyouandtheclientknowwhatyouaredoingandthefeaturesyouwillbe creatingforyourproject.Afteryouhavecreatedtherequirementsdocument,youcancreateaflowchart thatwillhelpyoudebugthesoftwarelaterinthedesignprocess(seeFigure1-10).
Figure 1-10. Blinking LEDs processes GatheringtheHardware
Thenextveryimportantpartoftheengineeringprocessismakingsureyouhavetherighthardware. Yourhardwareneedsshouldbedecidedasyou’regatheringrequirements,butitisimportanttomake sureallyourhardwareiscompatible.Ifitisnotcompatible,hardwarechangesmaybenecessary,but youshouldconsultthecompanyyouareworkingwithtomakesureitissatisfiedwithanyhardware changes.
ConfiguringtheHardware
Onceyouhavethecorrecthardware,itistimetoconfigureit.Dependingonthehardwarerequiredfor theproject,theconfigurationcanchange.Forexample,let’stakealookatthehardwareconfiguration fortheblinkingLEDproject.
- Arduino
- LED
- 9Vbattery
- 9Vconnector Tosetupthehardware,weneedtoconnecttheLEDtodigitalpin13andgroundontheArduino(see
Figure1-11),asillustratedintheschematicshowninFigure1-12.
Figure 1-11. The hardware setup for the Blinking LED project
Figure 1-12. A schematic of Blinking LED project
First,weneedtoinstalltheArduinoIDE.Todothis,goto ArduinoIDEwillworkwithWindowsVistaor7,MacOSX,andLinuxsystems.AftertheArduinoIDEis downloadedtoyourdesktop,itwillbeinazippedformat,sounziptheArduino-0022filetoyourdesktop. TheArduinoIDEisnowinstalled.
NowthatyouhavetheArduinoIDEinstalledonyourcomputer,youneedtomakesureitis configuredcorrectly.Todothis,opentheArduinoIDE,andgotoTools Serialport;selecttheserialport yourArduinoisconnectedto.Next,selectTools Boards,andselecttheArduinoboardyouareusing (thisbookusestheArduinoDuemilanoveAtmega328).Onceyourhardwareisconfigured,itistimeto writethesoftware.
WritingtheSoftware
Now,let’sconsiderthesoftwareweneedtowrite.Thispartoftheengineeringprocessiscrucial.Let’s takealookattheblinkingLEDsoftwarerequirementsdocumenttodecidewhatthesoftwarewillneed todo:theLEDneedstoblinkin100msnintervals.Thesoftwaremightlooksomethinglikethis:
// This code blinks an LED at 100ms const int LEDdelay = 100; // delay time void setup() {
pinMode(13, OUTPUT); // makes pin 13 an output } void loop() { digitalWrite(13, HIGH); // this writes a high bit to pin 13 delay(LEDdelay); // delay 100ms digitalWrite(13, LOW); delay(LEDdelay) // this will throw a syntax error due to a missing semicolon }
Note When you try to compile this program to your Arduino, it gives you an error. This is because of a syntax error that we will debug in the next section.
DebuggingtheArduinoSoftware
Thelastprogramfailedtocompilebecauseofasyntax error.Thistypeoferrorisbecauseofincorrectly formattedcode,suchasamissingsemicolon(whichiswhythelastprogramdidn’tcompile).Hereisthe revisedcode:
// This code blinks an LED at 100ms const int LEDdelay = 100; // delay time void setup() { pinMode(13, OUTPUT); // makes pin 13 an output } void loop() { digitalWrite(13, HIGH); // this writes a high bit to pin 13 delay(LEDdelay); // delay 100ms digitalWrite(13, LOW); delay(LEDdelay); // the semicolon is now present and the code will compile }
Syntaxerrorsarenottheworsterrorsoutthere.Theworsterrorsyoucanreceivearelogical errors; theseerrorsallowthecodetocompile,buttheendresultisunexpected.Forexample,usingagreater- thansymbolinsteadofless-thanisalogicalerror,andifitisinaprojectwiththousandsoflines,itcan bealmostimpossibletofix.
Note A logical error in the blinking LED project would be if you put digitalWrite(13, HIGH); forboth
digitalwritefunctions.WecandebuglogicalerrorsinanArduinoprogrambyusingaflowcharttofigureoutwherethe valuesarenotliningup.
TroubleshootingtheHardware
Thenumberonetoolusedtotroubleshoothardwareisthemultimeter.Thistoolcansaveyourhardware frombeingdamaged.Forinstance,ifyourmultimeterdetectsthatyourpowersupplyismorethanis required,thehardwaresetupfortheblinkingLEDprojectcouldusea22ohmresistortokeeptheLED fromburningout.
FinishedPrototype
Onceyouhavefinisheddebuggingthesoftwareandtroubleshootingthehardware,youshouldhavea completedprototypethatwillworkundermostcircumstances.Inthischapter,weusedaverysimple project,butinfuturechapters,theprojectswillgetmorecomplicated,andtheengineeringprocesswill becomeevenmorenecessarytomakesureourcodeisefficient,streamlined,andcomprehensible.
Summary
Inthischapter,youlearnedthedifferentpiecesofhardwareandvarioustoolssuchas:TheArduino, ArduinoShields,Multimeter,andneedle-nosepliers;justtonameafewthatwillbeusedthroughout thisbook.Wethenwentovertheengineeringprocess,whichisasequenceyoucanusetosolve problemsthatprovidestheformatforthisbook.Thestepsintheprocessarerequirementsgathering, creatingtherequirementsdocument,gatheringthehardware,configuringthehardware,writingthe software,debuggingtheArduinosoftware,troubleshootingthehardware,andfinishedprototype.Ialso definedafewnewtermsthatwillhelpyouunderstandtheengineeringprocess,andyoulearnedthe differencesbetweenlogicalandsyntaxerrors.
C H A P T E R 2 Understanding the Arduino Software
Inthischapter,wewilldiscussthevariousprogrammingcomponentsthatwillbeusedthroughoutthis book.IfyouhaveprogrammedinC,youwillfindthatprogrammingfortheArduinoisverysimilar.If not,thischapterwillteachyouthebasicconcepts.Whyisitimportantforyoutolearnthebasicsof programmingtheArduino?Inthelongrun,thiswillhelpkeepyourcodecleanandreadable.Also, learningthebasicloopsandstructuresinitiallywillallowustofocusmoreonthelibrarieslater.Libraries canbesetsofclasses,types,orfunctionsandcanbecalledbyusingkeywordsinyourprogram.The purposeofalibraryistoreadilyaddmorefunctionalitytoyourprogrambyusingcodethathasbeen createdpreviously;thispromotescodereuse.Thelibrarieswewillgooverbrieflyinthischapterare NewSoftwareSerial,LCDLibrary,TinyGPS,andafewothers.
Getting Started with setup() and loop()
AllArduinoprogramsmusthavetwomaincomponentstoworkproperly—setup()andloop()—and theyareimplementedlikethis:
// Basic Arduino Program void setup() { // Set up I/Os here } void loop() { // Do something } setup()isusedtosetupyourI/OportssuchasLEDs,sensors,motors,andserialports.Careful
setupisimportantbecauseinordertousethepinsontheArduino,weneedtotellArduinothattheyare goingtobeused. loop()holdsallofthecodethatcontrolsyourI/Oports.Forinstance,hereyou’dtellyourmotorto goacertainspeed.IwillexplainhowtosetupandcontrolyourI/O’sinthenextsections. Arduinoprogramsalsohavesubroutines—veryusefulextrafunctionsyoucancallwithinloop()or itssubroutines.Touseasubroutine,youmustfirstinitializeitatthebeginningofyourprogram;this initialmentioniscalledafunction prototype.Hereisanexample:
// Function Prototype void delayLED(); void setup() { } void loop() { } // Subroutine Example void delayLED() { // This will go after the loop() structure. } InitializingVariables
Variables arethemostbasicprogrammingbuildingblocks;theyareusedtopassdataaroundyour
programandareusedineveryprogramwewillwriteinthisbook.Wecanwriteseveraltypesofvariables totheArduinolanguage;Table2-1illustratesthem.
Table 2-1. Types of variables Type Name Type Value Type Range char 'a' –128to127 byte 1011 0to255 Int -1
- –32,768to32,767
unsigned int 5 0to65,535 long 512 –2,147,483,648to2,147,483,647 unsigned long 3,000,000 0to4,294,967,295 float 2.513
- –3.4028235E+38to 3.4028235E+38
double 2.513
- –3.4028235E+38to 3.4028235E+38
Nowthatyouknowwhattypesofvariablesareoutthere,youneedtoknowhowtodeclarethose variables.Inordertodeclarethem,youneedtoknowinwhatscopethosevariablescanbeusedandthen specify(ordeclare)thescopethatmeetsyourneeds.Inthisbook,wewilldeclaretwoscopesfor variables:localvariablesandglobalvariables.Alocal variableonlyworksinitsgivenscope.Forinstance, aforloopkeepsitsdeclaredvariablesonlywithinitsparentheses,sothosevariablesarelocaltothefor loop.Aglobal variablecanbecalledatanypointinyourprogram.Todefineaglobalvariable,initializeit atthebeginningofyourprogram.Thefollowingprogramillustrateshowtoinitializelocalandglobal variables:
// Initialize Variable int x; // This variable is declared globally and is avaiable for access throughout this // program. void setup() { } void loop() { x = 1 + 2; // Assigns the value 3 to x for(int i; i <= 100; i++) { // i is a local variable and can only be called in this for loop. } }
Therestofthedeclarationsaresetupthesamewayuntilyoustartusingarrays.Arraysallowyouto passmultiplevaluesofthesametype,forexample,ifyouwanttopassmultipledigitalpinswithout havingtodeclareeachoneindividually:
int pins[] = {13,9,8};
Itisagoodideatodeclarethesizeofthearray,asinthefollowingexample:
const int NumOfPins = 3; int pins[NumOfPins] = {13,9,8};
Thiswillallowyoutoaccessyourarray’sinformation,andthen,youcanpassthatinformationtoa digitalpinorwhateverelseyouwant.Nowthatyouhavedeclaredvariables,howdoyouusethem?This willbediscussedinthenextfewsectionsofthischapter. Note Whitespacing means that you’ve added blank lines and spaces in your code to make it more readable.
■
WritingConditionalStatements Conditional statements canbeusedtocontroltheflowofyourprogram.Forinstance,sayyouwantto
turnamotorononlywhenabuttonispressed;youcandosousingaconditionalstatement.Wewillbe discussingthefollowingconditionalstatements:if,if-elseif,if-else,andswitchstatements. Anifstatementsisaveryimportantconditionalstatement;itcanbeusedinanyBooleancapacity foravarietyofreasons,suchaslimitingtesting.Hereisanexampleofanifstatement:
int i; if (i < 10) { i++; }
Youcanalsoaddelseifstatementstotheendofyourifstatementtoaddotherconditionstoyour programandcreateanif-elseifstatement,forexample:
int i; if (i < 10) { i++; } else if (i > 10) { i--; }
Apracticaluseofaconditionalstatementwouldbetoreadingavaluefromapotentiometer,asin thefollowingexample:
potValue = analogRead(potPin); if (potValue <= 500) { digitalWrite(motorpin, 1); } else { digitalWrite(motorpin, 0); } Note You must remember set up your Arduino’s pins before you call them in a loop.
■
Aswitchstatementisusedifyouhavemultipleconditionsbecauseitcleansupyourcode.Hereis anexampleofaswitchstatement:
switch (potValue){ case 500; digitalWrite(motorPin,1); case 501;
digitalWrite(ledPin,1); break; default: digitalWrite(motorPin,0); digitalWrite(ledPin,0);
Inthisexample,ifpotValueisequalto500,themotorwillturnon,andifpotValueisequalto501,an LEDwillturnon.ThedefaultcaseistruewhenthepotValueequalsneither500nor501,andinthatcase, themotorandLEDarebothturnedoff.
Working with Loops
Loopshavemanyusesincludinggettingridofredundantcodeanditeratingthrougharrays.Theloops wewillusearefor,while,anddo. . .while.Theseloopswillallowustorunthroughcodewhilea conditionistrue(orfalse,insomecircumstances).
forloop:Thisloopisusedtorepeatablockofcodeafixednumberoftimes.The
- forloop’sbasicsetupis for(int i = 0; i <= 10; i++) { // Place statements here }
ApracticalapplicationforaforloopistouseittoupdatemultiplepinMode
- settings:
int pins[] = {13,9,8}; void setup() { for(int i = 0; i<=2;i++) // Sets up each pin { pinMode(pin[i], OUTPUT); } } void loop() { // Put code here }
Note pinMode is used to set up your I/O pins on the Arduino.
■ whileloop:Thisloopwillrununtilaconditionhasbeenmet;ifitsfirstconditionis
- false,itwillnotrunatall.Forexample,you’duseawhileloopifyouwantedtorun codeuntilacertainvaluecamefromasensor.Thefollowingexampleillustrates thisprinciple:
int potPin = A1;
int motorPin = 9; int potVal; void setup() { pinMode(motorPin,OUTPUT); pinMode(potPin,INPUT); } void loop() { potVal = analogRead(potPin); while(potVal <= 100) // Runs until potVal is greater than 100 { digitalWrite(motorPin,1); } }
Thefirstthingthiscodedoesisinitializethepotentiometerandmotorpins;then,
- itdeclarespotVal,ourvariablethatholdsthepotentiometervalue.Next,weset themotorPintoanoutput,andthepotPintoaninput.Finally,weuseawhileLoop withaconditionpotVal <= 100,andwhilethatconditionistrue,themotorwillbe on.
do . . . whileloop:Thisisthesameasthewhileloopexceptthattheconditional
- statementischeckedattheendoftheloop,sothisloopwillrunatleastonetime. Here’sanexample:
do { i++; // Increment i }while(i <= 100); Communicating Digitally
Throughoutthisbook,wewillbecommunicatingdifferenttypesofI/Othroughthedigitalpins,soitis importanttounderstandhowthatcommunicationworks.Specifically,weusethe
digitalWrite(pin,HIGH/LOW)anddigitalRead(pin)commandstocommunicatewiththedigitalpins.An
exampleofthisisshowninListing2-1.
Listing 2-1. Digital Commands int button = 12; int led = 13; int buttonState; void setup() { pinMode(button,INPUT); pinMode(led,OUTPUT);
} void loop() { buttonState = digitalRead(button); // Assigns button to buttonState if(buttonState == 1) { digitalWrite(led,HIGH); // Writes a 1 to pin 13 } Else { digitalWrite(led,LOW); // Writes 0 to pin 13 } }
ThisprogramusesdigitalWrite()anddigitalRead()togetthevalueofthebuttonpinandwritesa newvaluetoit(inthiscase,highorlow).
Note Use the PWM digital pins to control motor speed and LED brightness.
■ Communicating with Analog Components
Youcanalsouseanalogcommunicationwithsensorsandmotors,meaningyoucanconnect potentiometerstocontrolmotorspeedthroughapulsewidthmodulation(PWM)pinontheArduino. ThefunctionsforanalogcommunicationareanalogRead(value)andanalogWrite(pin,value).Theonly thingyouneedtorememberisthatapotentiometerwillgiveavalueof0to1024,soyouwillhaveto scaleanalogWritefrom0to255,forexample:
analogWrite(LED,ledValue/4); // 1024/4 = 255 Serial Communication
Wewillbeusingserialcommunicationthroughoutthisbook.Serialcommunicationallowsusto communicatewithacomputer,LCD,andmanyotherdevices,asyouwillseeinthenextseveral chapters.SomeserialcommandsareSerial.begin(baud),Serial.Println("anything you want to
write to the serial pin"),Serial.read(),Serial.write(Binary data),Serial.available(),and Serial.end().Thesecommandsallowustoreadandwritetoanyserialperipheralwewant.Hereisa
briefdescriptionofeachoftheseserialcommands:
Serial.begin(baud):Youwillputthiscommandinsideyoursetup()structureand
- puttheappropriatebaudrateforthedevicewithwhichtheserialwillbe communicating,forexample:
void setup() { Serial.begin(9600); // 9600 baud rate to communicate with a computer }
Serial.println():Usethiscommandtowritevaluestotheserialport,for
- example:
void loop() { Serial.println("Hello, World"); // Writes Hello, World to the serial port } Or… void loop() { Serial.println(potVal); // Writes potVal to the serial port } Serial.read():Thisreadsinavaluefromtheserialport.Forexample,youcould
- usethistoreadsomethingfromyourcomputerthatyou'dthenwanttowritetoan LCDontheArduino.
void loop() { char var = Serial.read(); // Read incoming byte from serial port }
Serial.write():Usethistowritebinarydatatoaserialport,forexample:
-
void loop() { while(Serial.available() > 0) { char var = Serial.read(); // Reads incoming byte from serial Serial.write(var); // Writes binary data to serial } }
Note In this book, most of the time you will use Serial.println() because we will be writing int or string ■ values to the serial monitor. The Serial.write() function is used to send binary data to the serial monitor or any other serial port program..
Serial.available():Thisfunctioncheckstoseeifthereareanyincomingbytesat •
theserialport,forexample:
void loop() { while(Serial.available() > 0) // This makes sure there is at least one byte at the // serial port. { // Put code here } }
Serial.end():Thisdisablesserialcommunication.
- Nowthatyouhaveseenthecommandsetforserialcommunication,wecanusetheminour programs.Listing2-2illustratesmostofthefunctionswehavebeendiscussing.
Listing 2-2. Serial Communication int incomingByte; const int ledPin = 13; void setup() { Serial.begin(9600); // Opens serial port, sets data rate to 9600 bps pinMode(ledPin, OUTPUT); } void loop() { while(Serial.available() > 0) { incomingByte = Serial.read(); // Reads incoming byte Serial.println(incomingByte, BYTE); // Prints incoming byte to serial port digitalWrite(ledPin, incomingByte); // Write to LED pin } }
Thisprogramisthefoundationofserialcommunication:itinitializesincomingByteandledPin.Next inthesetupstructure,thebaudrateissetto9,600.Whenwegetinsidetheloopstructure,thewhileloop ischeckingtoseeifanythingisattheserialport.Ifthereis,itassignstheinformationontheserialport toincomingByte.Finally,theprogramprintsthedatatotheserialportandwritesdatatoledPin(inthis case1or0).
Using Arduino Libraries
NowthatyouknowthebasicsofArduinoprogramming,wearegoingtogooverthelibrariesthatwillbe usedinthechapterstocome.Theprimarylibrarieswe'llusearetheNewSoftwareSerial,TinyGPS,and LCDlibraries,andafewotherswillbeexplainedinlaterchapters.Tousetheselibraries,youwillneedto downloadthemandunzipthemintotheLibrariesfolderintheArduino-022directory.Afteryoudothat, youshouldbeabletouseanylibrarythatiscompatiblewiththeArduino.
NewSoftwareSerial
TheNewSoftwareSeriallibraryallowsustowritetomultiplesoftwareserials(weneedtothankMikal Hart).Theonlycaveatisthatyoucannotreadandwriteatthesametime;theseactionsmustbe preformedsequencially.Tousethislibrary,thefirstthingyouhavetodoisobtainthe NewSoftwareSeriallibraryfromtheInternetandaddittotheLibrariesfolderintheArduinoIDEfolder. YoucandownloadNewSoftwareSerial
OnceyouhavedownloadedandaddedtheNewSoftwareSerialtotheArduinoIDEdirectoryallyou havetodoiscallNewSoftwareSerialintheprogramwhereyouwanttouseitin,likethis:
#include <NewSoftwareSerial.h>
NewSoftwareSerial gps(2,3); // This creates a new instance of NewSoftwareSerial under the // name gps. // the format in the brackets is (rx,tx)
Thiswillincludeagpsserialtopins2and3.Inthesetupstructure,youhavetosetthenewserial's baudrate,likeso:
void setup() { gps.begin(4800); }
Afterthat,insteadofusingtheSeriallibrary,youwillbecallingfunctionsfromthe NewSoftwareSeriallibrary,andyoucanjustcallthosefunctionsfromthegpsobjectwecreatedearlier, forexample:
Serial.read(); Becomes… gps.read(); TinyGPS
ThislibraryparsesNMEAdata,suchaslongitude,latitude,elevation,andspeed,intoauser-friendly style.WewillgointofurtherdetailontheTinyGPSlibraryinChapter5.Allyouneedtodonowis downloadtheTinyGPSlibraryfromeneedtothankMikal Hart).
ColorLCDShieldLibrary
TheLCDlibrarywillbeusedtoreadandwritetoanLCDscreen(weneedtothankPeterDavenport, ColemanSellers,andSparkfun).WewillgoovertheLCDlibraryinChapter4.Fornow,justdownload theLCDlibraryfrom
Putting Together the Arduino Language Basics
YoushouldnowknowhowtocreatethemostbasicArduinoprogram,solet’stakeamomenttorecap someofthekeyprogrammingpointsjustdiscussed.Youcanusethisrecaptohelpyouprogram throughoutthisbook,andthroughcreatingyourownprojects.Hereisanexampleofthatprogram:
void setup() { // Setup I/Os here } void loop() { // Put code here }
Wealsowentoverdeclaringvariablesandusingthemglobally,asinthefollowingexample:
char ch = 'A'; int pin = 13;
Thesevalueshavetypesofcharacterandinteger. Youalsolearnedaboutifandif-elsestatementsandhowtousethem:
if (condition) { // Put code here } else // Put code here
Alsoyoucannowaddelseifstatementstocreateif-elseifstatementstoaddmoreconditions,if youneedthem.
else if(condition) { // Put code here }
Wethenwentovertheswitchstatement,anothertypeofconditionalstatementthatisused sometimestocleanuplargerifstatements;ithasthisformat:
switch(value) { case value: // Put code here break; case: value: // Put code here break; default: // Put code here break; }
Aftertheconditionalstatementswereexplained,wewentoverthevariousloopstructuresyoucan usetoparseoriteratethroughcode.Thefirstloopwediscussedwastheforloop:
for(initialization;condition;Variable Manipulation { // Put code here }
Wethenwentoverthewhileloopanditsfunctions:
while(condition) { // Put code here }
Afterthat,youlearnedaboutacloserelativeofthewhileloopcalledthedo. . .whileloop;ithas thefollowingformat:
do { // Put code here }while(condition);