67

Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

  • Upload
    others

  • View
    9

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters
Page 2: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Arduino

MasterTheArduinoBasics

Writtenby

DanRiley

Page 3: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

©Copyright2017byDanRiley-Allrightsreserved.

Thefollowingbookisreproducedbelowwiththegoalofprovidinginformationthatisasaccurateandreliableaspossible.Regardless,purchasingthisbookcanbeseenasconsenttothefactthatboththepublisherandtheauthorofthisbookare in no way experts on the topics discussed within and that anyrecommendations or suggestions that are made herein are for entertainmentpurposesonly.Professionalsshouldbeconsultedasneededpriortoundertakinganyoftheactionendorsedherein.

ThisdeclarationisdeemedfairandvalidbyboththeAmericanBarAssociationandtheCommitteeofPublishersAssociationandis legallybindingthroughouttheUnitedStates.

Furthermore, the transmission, duplication or reproduction of any of thefollowingwork includingspecific informationwillbeconsideredan illegalactirrespectiveof if it isdoneelectronicallyor inprint.Thisextendstocreatingasecondaryor tertiarycopyof theworkora recordedcopyand isonlyallowedwithexpresswrittenconsentofthePublisher.Alladditionalrightreserved.

Theinformationinthefollowingpagesisbroadlyconsideredtobeatruthfulandaccurate account of facts and as such any inattention, use or misuse of theinformation in question by the reader will render any resulting actions solelyundertheirpurview.Therearenoscenariosinwhichthepublisherortheoriginalauthor of this work can be in any fashion deemed liable for any hardship ordamagesthatmaybefallthemafterundertakinginformationdescribedherein.

Additionally, the information in the following pages is intended only forinformationalpurposesandshouldthusbethoughtofasuniversal.Asbefittingits nature, it is presentedwithout assurance regarding its prolongedvalidityorinterimquality.Trademarksthatarementionedaredonewithoutwrittenconsent

Page 4: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

andcaninnowaybeconsideredanendorsementfromthetrademarkholder.

Page 5: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

TableofContents

Introduction

Chapter1:GettingStartedwithArduino

WhyShouldIChooseArduino?

SettingUpthePlatform

Chapter2:TheFunctionsofArduino

VariablesandDataTypes

Chapter3:LearningtheArduinoCode

InstalltheDrivers

WorkingonYourFirstSketch

Chapter4:HowtoReadtheAnalogSensors

Chapter5:HowtoStoreDataonArduino

Chapter6:USBandSerialCommunicationonArduino

InformationtogetStarted

Chapter7:CanArduinoWorkWirelessly?

Chapter8:OtherCodesforYourArduinoBoard

Conclusion

Page 6: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Introduction

Congratulationsonchoosing“Arduino:MasterTheArduinoBasics”,andthankyoufordoingso.

The following chapters will discuss everything that you need to know to getstarted with the Arduino software. While there may be quite a few optionsavailableforyouwhentryingtoworkonyourveryownroboticsorengineeringproject,noneofthemareasversatileandaseasytouseastheArduinosystem.Simplypickouttheboardthatyouwanttouse,learnafewbasiclinesofcode,andmakesuretheIDEissetupproperly,andyouarereadytogowithall thegreatprojectsavailable.

ThisguidebookisgoingtospendsometimehelpingyoutounderstandhowtheArduino system works. We will start out with some basic information onArduinosuchasthetoolsthatyouneedtostartbeforemovingontoinformationabout how the codingworks on these boards, how to read the analog signals,howtostorethingsontheboard,andevenhowtosendinformationwirelesslytosavetimeandenergy.

Even if you are a beginner in theworld of technology andprogramming, youwill find that the Arduino system is easy to use and won’t give you a bigheadache to get it all done. This guidebook will provide you with all of theinformation thatyouneed toensure thatyoucanget thoseprojectsdone innotime.

There are plenty of books on this subject on the market, thanks again forchoosingthisone!Everyeffortwasmadetoensureit isfullofasmuchusefulinformationaspossible,pleaseenjoy!

Page 7: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter1:

Page 8: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

GettingStartedwithArduino

BeforewegettoofarintosomeofthetechnicalstuffthatcomeswithArduino,itis important thatwe takesome time togetagoodfeel forwhatArduino isallabout.Ifyouaresomeonewholikestoworkonroboticsprojects,youwillfindthatworkingwithanArduinoboardcanmakethingseasier,whetheryouareabeginnerorsomeonewhohasbeenworkingonthesetypesofprojectsforalongtime.When you first get started on a newproject, there are a lot of things toconsider,buttheArduinoplatformisoneofthebesttohelpyougetstarted.

WhenyouhearaboutArduino,youhearaboutaspecialmicrocontrollerthatcanbeprogrammedandsoftwarethatwillhelpyoutocontrolsomeoftheroboticsprojects thatyouwant toworkwith. Inmanycases, this isagreatprototypingplatformthathelpsyoutoworkonthoseprojectsandgivethingsatrywithsomebasiccode.EventhoughthereisalotofsimplicitythatcomeswiththeArduinoplatform,youwillfindthatithasaprettylargefanbasewhenitcomestousingthissoftwaretohelpbuildupsomeelectronicprojects.

There are a wide variety of projects that you can use with Arduino and theATMega chip that comeswith it. Some choose to useArduino because it canworkasatemporaryadditionthatiseasytoaddintotheprojectwhiletheyarefinishingitup.Oryoucanchoosetomakeitamorepermanentpartandembedit into theprojectwheneverything isdone.Thismakes iteasier toworkwith,anditcanfitanyofyourneeds.

Whenyouarestartingoutwiththeboard,youwillbeabletoprogramitwiththeArduino software; this software is easy to work with even if you have neverworkedonprogrammingoraroboticsprojectbefore. IfyouhaveworkedwithJavaorC++inthepast,youwillnoticethatthecodinglanguageforArduinoissimilar,sothiscanmakethingseasier.Thesoftwareissimple,butyouwillenjoyallofthepowerthatcanbefoundonthisboard,soeventhosewithabitmore

Page 9: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

experiencewillgetsomeofthepowerthattheywantoutoftheirprojects.

AnotherthingtonoticeaboutArduinoisthatitsplatformisopensourced,whichmeans that anyonewho is interested,will be able touse thisplatform for freeandthosewhoarewillingcanmakesomeadjustmentstothecodewithoutanyhassle. This is a good thing if you are just starting outwithArduino orwithcodingbecauseyoucanaccesscodesandprojectsfromotherpeoplewhohaveusedthissoftwareinthepast.

Notonlywillyoubeabletolookaroundandfindthatthecodesyouwanttousehavealreadybeendevelopedbysomeoneelse(whichcansaveyoualotoftimeandhassletryingtofigureoutthecodingonyourown),beginnerswilllikethefact that the Arduino community is vast and can offer them quite a fewopportunities. Thismakes it easier for you to find forums and other locationswhere you canmeet upwith others, ask your questions, learn something new,anddootherthingsthatmakeyourprojecteasiertohandle.

DespiteallofthepowerthatyoucanfindontheArduinoplatform,youwillfindthatitisprettybasictouse.Thereareonlygoingtobetwomainpartsthatcomewiththisplatform,whichcanmakethingssimplerinthelongrun.Thetwopartsof theArduinoplatform include:TheHardware: The first component of thisplatform is the hardware. This is basically the microcontroller, which is thecircuitboard.Youcantakethemicrocontrollerandphysicallyprogramittodowhat your project needs. You will also find that there are a few of thesemicrocontrollersorboardsthatyouareabletopickfromandeachofthemofferssomethingnewforyoutoenjoy.

TheSoftware:Thesecondcomponentof thisplatformis thesoftware.This islike theenvironment thatyouwilluseonyourboard,andyoucanrun thatonyourpersonalcomputer.Theenvironment,whichisalsoknownastheIDE,willbeuseful inhelpingyoutouploadaswellas towrite thecodes thatshouldbesentasinstructionstotheboards.Whentheprogramsarewrittenonyourboard,

Page 10: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

itshouldreactbasedonthematterthatyouask.

Thesetwocomponentsaregoingtoworktogethertohelpyourprojectcometolife.TheonlyhardwarethatyoureallyneedtomakethisworkisagoodArduinoboardandeachprojectwillneedadifferentkindtohelpyouout.Thesoftwareisprettycoolbecauseyouwillbeabletowriteoutthecodesthatyouwanttouseandgetsomegoodresults.

Before you start writing out the codes that you want to send to the Arduinoboard,youhavetomakesurethatyouhavetheArduinoIDEinplace.ThisIDEisfree,thankstothefactthattheArduinosoftwareisopensource,whichmeansthatyoucanjustgoonlineanddownloaditonyourcomputeratnoextracost.Once ithasbeendownloadedonyourcomputer,youwillbeable towriteoutyourowncodesforeachprojectorusethecodesthatareprovidedifyougettheprojects from another source, with the help of the Arduino programminglanguage.TheIDEforArduinowillworkonmostoperatingsystemsfromyourpersonalcomputer,sothisshouldnotbeanissue.

There isonethingthatyoushouldkeepinmindifyouare tryingtodownloadthisArduinoIDEonacomputerthatusestheWindows7operatingsystemoranearlierversionofWindows.Therewillbeafewadditionalstepsthatareneededcomparedtosomeoftheotheroperatingsystems.Thistakesjustafewsecondslonger, but it can be frustrating when you try to get things done, and it isn’tworking.YouwillbeabletousetheIDEontheseoldercomputerssodon'tfeellikeyouneedtoupdateyourwholesystemtomakethiswork.

Page 11: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

WhyShouldIChooseArduino?

One question that you may be asking about this software is why you shouldchoosetogowiththeArduinoboardinsteadofoneoftheotheroptionsthatareavailable.Therearequiteafewprogramminglanguagesandboardsthatyoucanuseforyourproject,sopickingtheonethatwillmakeyourprojectdoamazingthingscanseemimpossible.ButArduinoisabitdifferentthantheotherboardsonthemarket,andthiscanhelpmakeittheperfectchoice.

When you get yourArduino board, youwill notice that there are quite a fewprojectsthatyoucandoonthisplatform.First,itisreallyeasytoworkwiththecoding.IfyouhaveworkedwiththeC++languageinthepast,youwillbeabletopickuponthecodingthatiswithArduinoinnotimeatall.Thenwhenyouaredonewritingthecode,itwilltravelfromyourIDEwhichisonthecomputer,andthenendupontheArduinoboardthatyoupurchasedfor thatproject.Theboardcansometimesdotheprojectallonitsown,suchasturningitintoakindofgame,oryoucanaddittooneofyourownpersonalelectronicprojectsandreallyhavesomefun.

TherearequiteafewthingsthatyouwillbeabletodowithyourArduinoboard,whetheryouwanttotrysomethingnewandhaveheardabouttheseboardsbeingable to help or you are just starting out, you will be able to work on someamazingprojectswiththisboard.TheArduinoplatformisreallyeasytolearnsothereisn’talotoftechnicalknowledgethatyouaregoingtogetstuckwithasabeginner.Itworkswellinalotofelectronicprojectsbecauseitcanmakesounds,itcancontrolascreenthatisattachedtoit,itcandothingswithblinkinglights,andsomuchmore.Wewilldiscusssomeoftheprojectslateron,andyouwillbeamazedatallofthecoolthingsthatyouareabletodowiththisboard.

YouwillalsoenjoybeingabletousetheArduinoboardforsomeofyourownpersonal needs.Many peoplewho like towork on robotics and programming

Page 12: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

choose thiskindofboardbecause itoffersavarietyofways tomakesomeoftheir own projects. But this is not just something for experts; beginners oftenpickthisboardbecauseitwillhelpthemtomakesomeprojectswithouthavingto learn a ton of coding. Sometimes, a beginner will have a great project hewantstoworkonoratleastanideaofaprojectbutmaybeworriedthathewon'tbeabletostartitduetolackoftherightprogrammingknowledge.ButArduinoiseasyandsimpleenoughforabeginner.

SomeoftheotherbenefitsofArduinoandwhyyoushouldchoosethisplatformcomparedtoanyoftheothersinclude:

It canworkonavarietyofplatforms:youwill be able todownload theIDEusedforArduinoonprettymuchanyoperatingsystemthatyouwantto use. This makes it great whether you are working on a Windowscomputer,aMac,ortheLinuxoperatingsystem.

Simpleenvironment:unlikesomeoftheotherenvironmentsthatyoumayhaveworkedoninthepast,theenvironmentforArduinoisprettysimpletolearn.ItissimilartotheC++environment,butsomepeoplefindthatitiseveneasiertoworkwith,makingitperfectforthebeginner.

Opensource: thisisprobablyoneofthebiggestbenefitsofchoosingtheArduino system. The board plans that you can use with this board aregoingtobepublishedonlineandareopensource.Thisisgreatbecauseitencouragesadvancedprogrammers tomakemoreplans forothers touseand they can improve and enhance some of the plans that are alreadyavailable. Beginners are going to enjoy this because it gives them theoptiontofindsomeplansfortheirprojectswithoutallthehassle.

Free:youmayhavetospendjustabit topurchaseanewArduinoboardforyourproject,buttheIDEandthesoftwarethatyouneedtomaketheprojectworkwill allbe free.Thecodeand the IDEwillbe free, so thissavesalotoftime,hassle,andmoneywhenyoufirstgetstarted.Thegood

Page 13: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

newsisthattheboardsdon’tcostalotofmoney,soyouwillbeabletoputyourprojecttogetherwithoutspendingaton.

Largecommunity:onethingthatbeginnerswilllikeisthattherearemanyotherpeopleusingtheArduinosystemfortheirownprojects.Thismeansthat therearequitea fewforumsandotherplaceswhereyoucan talk topeopleworkingonprojectssimilartoyours.Youcaneasilyfindplanstofollow,people to askquestions, and even tutorials tohelpyouout.Thislarge community is there to help you get going on the right track in notime.

As a beginner, youwill discover that there are somany things youwill loveaboutusingArduino.It issosimple, it iseasytofindtheplans thatyouwant,andyouwillbeabletogettheprojectsdonewithoutspendingalotoftimeandmoneyintheprocess.

While we have spent some time on all the great benefits that come with theArduino board, it is important to realize that there are a few limitations thatcomewiththisboard.Forexample,youwon’tbeabletofindalotofprocessingpowerso ifyourproject isconsideredpretty intensive,youwillneed to findadifferentkindofplatform toworkwith.Thismeans thatyouwon’tbeable towork on projects that include recording, video, or audio, but you can attach asimplescreentotheprojectforsomeofyourneeds.

Some beginners get the Arduino board confused with a computer board, butthere are few differences. You won’t be able to hook up some things to theboard, such as a keyboard or awebcam, so youwill find that there are a fewlimitationsthatcomewithyourproject.Sometimestheconfusioncomesbecausethere are some similarities between the Arduino board and the Raspberry Pi,which is a product that looks the same but can take on some of these othercapabilities.TheArduinoboardcanenhanceandhelpoutwithsomeofourownelectronicsandroboticsprojects,butyoucannotuseitaspartofyourcomputer

Page 14: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

orturnitintoyourownpersonalcomputer.

Page 15: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

SettingUpthePlatform

Now thatwehave an idea ofwhatArduino is all about and someof the coolthings that you are able to do with this software, it is time to get started onsettinguptheplatform.Thisplatformisprettypopulartouse,whichmeansthatforbeginners,therewillbesomethingnewtolearninordertoworkwithit.Thissectionisgoingtospendsometimefocusingonhowtogettheplatformsetupinordertoexecutesomeoftheprojectsyoulike.

Before you get started, ensure that you have access to a few things that willmakeiteasierforyoutowork.Forexample,youwillnotabletostartwiththeplatformifyoudon’thaveoneoftheArduinoboardstoworkwith.So,let’stakealookatsomeoftheitemsandstepsthatyouneedtogetthisallsetup.

TheArduinoBoard

ThefirstthingweneedinordertogetthisprojectstartedistheArduinoboard.Thispart isprettynecessary ifyouwant toworkonanyprojectsince it is thepartthatwillholdontothecodeandtelltheprojecthowtobehave.Thereareafewdifferentoptionsthatyoucanpickfrombasedonthetypeofprojectthatyouwould like to complete. Many projects will help you out and tell you whichboardisrecommended,butovertime,youwillbeabletofigureoutthebestoneallonyourown.

EventhoughthereareavarietyofArduinoboardsouttherethatyoucanchoosefromforyourproject,therearesomebasicsthatarefoundoneachoftheboard.Someofthecomponentsthatshouldbefoundonalltheboardsyouworkwithwhichwillhelpthemfunctionproperlyinclude:

USBandaBarrelJack:Nomatterwhatkindofboardyoupurchaseandworkwith,therehavetobesomemeans,eitherwiththehelpofaUSBor

Page 16: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

aBarrel Jack, that youwill be able to connect them to a power source.Somewillhaveoptionsthatconnectrightintothecomputerandotherscanconnecttothewall,buttheyneedtobeabletoconnectsomehowforthemto work. Most of the boards you see will have some sort of USBconnection so that you can hook them up to the computer and easilytransferthecodeswhenyouaredone.

Pins:Thenextcomponentthatyoushouldlookforarethepins.Thesearethepointswhereyouareable tocreate thecircuits thatyouwantbeforeconnectingthemupwithwires.Therewillbeafewtypesofpinsthatyoucanworkwith,andeachofthemhasaspecificjobtodo.

Reset Button: Somewhere on the Arduino board that you pick, thereshouldbeaplacewhereyouareabletoresettheboard.Thisbuttonistheone that will allow your pin to rest on the ground before restarting thecode thatyou loadedonto theboardby thispoint. It isagoodbutton toworkwithbecauseitisgreatfortestingoutthecodetomakesurethatitworks. It is important to rememberwhenyoupush the resetbutton, thisdoesn’tmean that itwill reset everythingon theboard, soyouwon’tbeabletousethisasawaytofixyourboardifsomethingiswrong.

PowerIndicator:Anotherthingthatshouldbeonyourboardisthepowerindicator. This is simply a small light that you can find near the ONbutton.Itisapowersourceofsomekindandwheneveryoupluginyourboard,thislightshouldshowupforyou.

VoltageRegulator:ThispartofyourArduinoboardisgoingtobethepartthatwillcontrolthevoltagethatcomesontheboardatanygiventime.Ifyouhaveavoltagethatisabovethislimit,theboardwillsimplyturnitallaway. Remember that most of these board won’t be able to take on avoltagethat ishigherthan20volts,sokeepthepowersourcebelowthisnumber.Ifyouletitgettoohigh,therewillbesomeissueswithdestroyingtheboard.

Page 17: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Eachof thesepartswillbe important to theproject thatyouwant toworkon.Youshouldpickoutaboardthathasalloftherightparts,plussomeextrasifthatiswhatyourprojectwillcallfor.Thegoodnewsisthatmostoftheprojectsthatyouchoosetoworkonasabeginnerwilltellyouthetypeofboardyouneedtoworkon,so thiscanhelpyougainsomefamiliaritywith thedifferent typesofboardsbeforeyougooutandtrytodoitallonyourown.

Hookingthesoftwareup

AfteryouhavehadsometimetolookattheboardsthatareavailablewiththisArduinoplatform,itistimetoworkonyourfirstproject.Butbeforeyouareabletogetoutthereandstartwritingtheamazingcodesthatwillstartyourproject,youhavetoinstalltheIDE,orthesoftware,sothattheArduinoboardwillworkproperly.Basically,thisIDEisgoingtobetheenvironmentthatyouwillworkon.Youwillopenthisuptowriteoutanyandallcodesthatyourprojectneeds.When you are done, this IDE will help you to send that code over to yourArduinoboardsothateverythingisconnectedandwillworktheproperway.Ifyoudon’tdownloadtheIDEforyourproject,youwillneverbeabletowriteoutyour code orwork on your project, and themicrocontrollerwill just sit therewithoutanylifetoit.

Thegoodnews is that it isprettyeasy todownload the IDE for someofyourprojects.Yousimplyneed tovisit thewebsitewww.arduino.ccwhereyouwillfindalinktodownloadthecorrectIDE.Rememberthatyouaredownloadingawholeenvironment,soitdoestakesometimeforittoallfinishandbeonyourcomputer.

Once the IDE has been downloaded, you should notice a zip folder on yourcomputer.Nowyouneedtoopenupthezipfileandsaveittowhateverlocationis easiest for you to remember later on your computer. The location doesn’t

Page 18: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

matterasmuchaslongasyouareabletofinditwhenyouwanttopullitup.

From here, it is time to go into the zip file and look for a file that saysArduino.EXE.Thisisthefilethatyouneedtoopenandruninordertostarttheinstallation.Alongtheway,youwill run intoafewcommandpromptsfor thisprocess.Youcanreadthroughthemtoseewhattheysayandthenclicknextoragree to continue one. After the IDE has been installed and all the rightcomponentsareinplace,youareset.Youcanstartonsomeofyourownprojectsorlookupafewthatyouthinkaregood.TheIDEisallreadyforyoutoworkwith andyou can easilywrite out your codes and send them right over to theArduinoboardwhenyouaredone.

Andthat isall that there is to thewholeprocess.Whileyouwillbeable todosomeamazingprojectswiththehelpoftheArduinoboardandsoftware,gettingitallsetupsothatyoucanstartisnotacomplicatedprocedure.Bythetimeyoufinishthestepsabove,youwillbereadytolearnabitofcodingandgetstartedonyourveryfirstproject.

Page 19: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter2:

Page 20: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

TheFunctionsofArduino

NowthatwehavetakenalookatsomeofthebasicsthatcomewiththeArduinoboardandmadesurethatwewereabletogettheIDEsetup,itistimetoworkwithabitoftheprogramming.Withouttherightprogramminginplace,itishardtosendoverthecommandsthatyouwantsothattheboardworksproperlyforyour project. This chapterwill talk about a few of the different parts that arecommon,eveninthemostbasiccodesthatyouwanttoworkwithandthenwewillmoveontowritingyourfirstcodeontheseboardssoyoucangetthehangofit.

Page 21: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

VariablesandDataTypes

So,thefirstpartofourcodethatwewilltakealookatarethevariablesandthedatatypes.Whentalkingaboutaprogramminglanguage,thevariablesarelikealabelforyourArduinoboardbecausetheyarethepartsinchargeofassociatingthe right values with their names. Before using your variable inside of aprogram,orasketchastheyarecalledinArduino,youhavetostopforabitandthen declare that variable.When youmake that declaration, then that iswhenyoustartworkingwiththedatatype.

Now,inprogramming,thedatatypeisgoingtobethepart that is inchargeoftellingtheprogramwhatdatatypesaregoingtobefoundinsideofeachvariabletype. Without a name or a specific data type present, the variables can't bedeclaredinthesesketches.

Therearequiteafewtypesofdatathatwecanworkwithinthesesketches.Butwearegoingtokeepthisprettysimpletohelpmakeiteasier.Someofthemostcommondatatypesthatyouwillfindinsideofthesesketchesinclude:

Integer: theseare theintegernumbers,andonthis typeofprogramming,theywillbesomewherebetween32768and32767.

Long:theseareliketheintegers,buttheyaregoingtoincludemuchlargernumbers.

Characters:thesecanbeeithernumbersorlettersthatwillfallinthecode.They can be any letter that is in the alphabet, but the numberswill fallbetween-128and127.

Boolean:withthesedatatypes,weareworkingwithdatathatiseithertrueor false or data that is either 0 or 1. These data types will look at theexpressionsthattheyarepresentedwithandthentrytofigureoutwhetherthe answer is going to be false or true based on the information in the

Page 22: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

code.

Declaring your variables is not a process that is too difficult when you areworkingwiththeArduinoboard.Let'stakealookatanexampleofthis.Forthisone,wewilllookatavariablethatwewillcallledpinandwewilldeclareit.Tostart,weneedtopickoutadatatypeforthisvariableandgiveitavalueoffive.Inordertodeclarethisone,wewouldjustusethefollowingcode:intledPin=5;

And that is really all that you need to do in order to declare a variable in theArduino board. Of course, there will be some times when it gets a bit morecomplicated,butitwillstillfollowthesamekindofideanomatterwhatyouareworkingon.OnethingthatyoushouldkeepinmindthoughisthatasemicolonneedstobeaddedtotheendofitsothatithelpstheIDEreadthroughthewholethingproperly.Otherthanthat,youaregoodtogo.

Operators

Thenextpartofyourcodethatyouneedtounderstandis theoperators.Theseoperatorsareagreatwaytoaddsomemorepowertothecodebecausetheyareoften used to help manipulate the variable. In some of the programminglanguagesthatyouchoose,therewillbequiteafewoperatorstopickfrom,butArduinowillfocusonjustthefourmainonestokeepitprettysimple.Someofthe operators that you are able to work with in the Arduino coding languageinclude:BooleanOperators:This issimilar towhatwediscussedbeforewiththedata types.Theseoperatorswillneed to focusondata types thatareeithertrueorfalseor0or1.Thesymbolsthatyouwouldusefortheseoperatorswouldinclude(!)foror,the(&&)forand,andthe(||)fornot.

LogicalOperators: If you are trying to work on a project that needs to docomparisons, you have to work with the logical operators. There are a fewoptionstousesuchasthe(==)symbolwhichmeansequalto,the(<=)forless

Page 23: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

thanorequalto,andsoon.

MathematicalOperators:Thesearethesymbolsyouarefamiliarwithanytimeyouheadtoamathclass.Theyareusedinyoursketchanytimeyouneedtodoamathequationofanysortinthecode.Youwillbeabletousethesignssuchas(+),(-),(*),(/,and(%).

AssignmentOperators:Thisonewillusually justhaveonesymbol, theequal(=) symbolbecause it isused tocalculatewhatwillbe the finalvalueofyourdata type. This final value is going to show up on the right-hand side of thisequalsign.Itcanalsoshowthattheinformationthatisontheright-handsideisequaltotheinformationontheleftside.

You can also work with some operators that are in charge of increments anddecrements. For example, if you use the symbol (++) after you name thevariable, itmeans that you justwant to add one towhatever the value of thevariableis.Thesamecanbetrueifyougotheotherway.Ifyouusethe(--),youaregoingtosubtractonefromthevariable.

Expressions

Nexton the list is expressions.Whenwebringup expressions in theArduinocode,we are able to combine a few of the different data types thatwe listedabovetomakeourexpressions.Whenthesedifferentdatatypescometogether,youwillbeabletoaddalotofcontroltothecodethatyouareworkingon.

Oneexampleoftheseexpressionswouldbetocreateamathematicalexpression.Thiscouldlookassimpleassomethinglikea=4*2-6.Thecompiler,whichisthepartofyourIDEthatreadsthroughthecodeandtranslatesit,willseetheequalsignandwilltakealookattheleft-handsidetoseewhatthevariableisbeforegoingthroughandcomputingtheanswerofthenumbersontherightside.

While we are here, we need to remember that when doing the mathematical

Page 24: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

equations,thecompilerwillusetheMDASruletofigureoutwhattheanswersare. This means that it will multiply everything first, do the division, theaddition, and then finish with the subtraction. This is the standard in mostmathematicalequationssoitshouldn'tbeanythingnewinthispart.Thismeansthattheanswerwewouldgetfromthisequationwouldbea=2.

You are able to write out expressions that aren't mathematical as well. Forexample,youcanworkwithlogicalexpressions,whichwillbetheonesthatusethe Boolean and the logical operators. You will actually see these quite a bitwhenyou start towriteoutyourArduino sketches.There are a fewways thatyouareabletodothis,butlet'slookataquickexample.

Let’ssaythatwehavetwopinsthatweareworkingwith.Pin1isgoingtobeHIGHandpin2isgoingtobeHIGH.Fromhereyouwillbeabletocreatewhatisknownasaconditionalstatementtomaketheboardbehaveinthemannerthatyouwould like, but youwould need the logical operator to help you get thisfinished.

Towriteoutyourconditionalexpressionwith the information that isprovided,youcanusethefollowing:(pin1==HIGH||pin2==HIGH).Insideofthiscode,youcanseethe(||)symbolswhicharelogicaloperators.Thisonemeansthatifthefirstorthesecondconditionistrue(itdoesn'tmatterwhichoneorifbotharetrue),thenthewholeexpressionwillbetrue.Ifyouwouldliketohavebothofyourpinsbeat theHIGHsettingbeforeanythinghappens,youwouldneed tochange up the conditional statement that you are using. It would now looksomethinglikethis:(pin1==HIGH&&pin2==HIGH).

ThesethreetopicsarejustthebeginningofwhatyouareabletodowiththecodewearewritingfortheArduinoboard,buttheywillhelpyoutowritealotofthedifferentcodesthatyouwouldlikeforyourprojects.Youcanusethedifferentdatatypesthatareavailabletocreateexpressions,manipulatethedataanddosomuchmore.Beforewegetintosomeofthecodesandprojectsthatwewilltalk

Page 25: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

about in this guidebook, open up your IDE and experimentwith some of thetopicsinthischaptersoyoucanbecomefamiliarwithhowthecodingworks.

Page 26: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter3:

Page 27: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

LearningtheArduinoCode

Nowitistimetoworkonlearninghowtowritesomeofthecodethatisneededforyourboardand to test tomakesure that theboard isworkingproperly.BythistimetheIDEshouldbesetup,andyouhavehadabitoftimetogothroughandtryoutafewofthedifferentsketchesthatwetalkedaboutinthelastchapter.Butnowthatwehaveallofthatdown,itistimetoworkwithusingourboardandmakingsurethatitworksproperly.

Ifyouarestillnewtoprogramming,youmaybelookingattheArduinoboardandfeelabitworriedabouthowyouwillproceed.Therearealotofpartsthatcancomewiththeboard,anditmaybeabitconfusingtogetstarted.ButifyouhavetheIDEsetup,youwillbejustfine,andyourprojectswillcometolifeinnotime.

Startingoutonyourfirstprojectisnotgoingtobethatdifficult.Thereareafewthingsthatneedtobesetupbeforeyougetgoing.First,youneedtomakesurethatyouhaveyourIDEsetupandworking.Also,ensurethatyourcomputerisabletorecognizetheArduinoboardthatyouchoosetouseandthenyouhavetowriteoutthecorrectcode.Onceyouhavethesecomponentsinplace,itistimetostartonaproject.

WeneedtotakeamomenttolookatthecodingabitmorebecausethisisoftenthemostcomplicatedpartthatcomeswithusingtheArduinosystem.ForthosewhohavebeenabletoworkwithC++inthepast,youwillfindthattherulesforArduinoaregoingtobeprettysimplesothiscanhelpout.Don’tfrettoomuchifyouhaven’tbeenabletolearnC++inthepast.Thislanguageisprettybasic,andmostoftheprojectsyouworkonwilluseasimilarapproach,soyouwillcatchupfast.

Beforewestartworkingonthisfirstproject,makesurethattheIDEisreadytogo.Youneedituploadedandturnonthecomputersothatitwillworkproperly

Page 28: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

and will recognize the codes that you want. This seems simple, but it isimpossibletoworkonanyoftheprojectsthatyouwantiftheIDEisn’tevenonyourcomputer.

Atthispoint,youshouldhavethehardwareinplace,andyourArduinoIDEsetup.Wearegoing to takeamoment to testoutourprogramtoensure that it isworkingproperly.Thiswillbe thefirstproject thatweworkwithandwill testthattheboardisworkingandwillgiveyouabitmoreexperiencewithworkinginthiscodinglanguage.

Remember that thereareanumberofdifferentboards thatyoucanworkwithwhencreatingaprojectwithArduino,butforthisparticulartestproject,wearegoingtoworkwiththeArduinoUNOortheR3board.Thisisoneofthemostpopularboards, soyouwill find that a lotofdifferentprojectswillworkwiththistypeofboard.Itispossibletouseanotherboardifyouwouldliketomakethis testprojectwork,butyoumayneedtomakeafewquickmodifications toseeitwork.InadditiontogettingtheUNOboard,youwillneedthefollowingitems

AnLED:YouwillneedtomakesurethatyouhaveanLEDlightorthatyourboardcomeswithone.Thisneedstoworkwiththeparticularboardthatyoupickoutsothatyoucanseeiftheboardisactuallyworking.

AUSBCable:NextonthelistisaUSBcable.YouwillneedtopicktheAtoBoptionbecause thismakes iteasier foryou tohookup theboard toyourcomputer.Ifyouarenotabletofindthiskindofcord,itisalsofinetojustpickoutanytypethatwillhooktheboardandthecomputertogether.

Computer:Ofcourse,youwillneedtohaveacomputertoworkwithforthisproject.Thecomputerdoesn'thavetobeabrandnewmodel,butonethatis20ormoreyearsoldandhasn'tbeenupdatedinyears,willprobablynotworkoptimally.YoucanpickfromaWindowsXPorhigheroperatingsystem.LinuxandMacworkwelltoo.

Page 29: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Oncealloftheseitemsaregatheredtogether,andyouarereadytoworkonthisproject,itistimetostarttestingouttheboard.Thisisasimpleproject,butitwillhelpyoutotestoutanyoftheboardsthatyouwanttoworkwithandwillensurethatyougetthecodingandthesystemdownforwhenitistimetoworkonyourownprojects.

PluggingintheBoard

Thefirstthingthatweneedtodoisgettheboardpluggedinandrecognizedbythecomputer.YoucaneasilyusetheUSBcordthatwasrecommendedearliertohelpyouplugthisboardintothecomputer,oranotherpowersupplywillworkinsomecases.Somepeoplewillstartbyhookingittoawalltogiveitsomepower,but thiswillnotallowyoutohooktheboardwithyourIDEwhichmeansanycode you write will not transfer over, so hooking up with the USB cable isusually the best option.Once the coding ismovedover to the board, you canchoosewhethertohookituptothewallortothecomputer.

So, youwill need to hook theUSB cable up to the right port on theArduinoboardandthenalsohooktheotherendtothecomputer.Nowthatthecomputerand theboardareconnected, takea lookatyourboardand seewhere theONlight is located. If the board is working properly, this lightwill start blinkingquickly.ThisisknownasthedefaultprogramfortheONlight,anditisalreadyplacedonachipinsidetheboard.

Withthisproject,wearegoingtooverridethedefaultprogramsothatinsteadofgettinganLEDlightthatblinksrapidly,itisgoingtoblinkonandoffwithtwosecondsoccurringbetweenyourblinks. It isn’tmuch,but it isagreatway foryoutogetstarted.

IfyoulookatyourboardandnoticethattheONlightisnotblinkingatallrightnow,itistimetodosometroubleshooting.Thefirstthingtolookforiswhether

Page 30: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

theUSBcablehasbeenpluggedinproperlytothemachine.Sometimesitisanissuewithusing thewrongcord.Check to see if these areboth right. Inmostcases,fixingoneofthesetwoissueswillturntheONlighton,anditwillbegintoblinkforyou.

Page 31: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

InstalltheDrivers

Now that you have yourArduino board hooked up to the computer, youwillneedtotakeafewminutestoinstallyourdriverssothattheprogramyouwriteactuallyworks.ForthoseusingaWindows7computeroraWindowsoperatingsystemthatisolder,thereareafewextrastepsthatneedstobetakentoensurethat the system recognizes the Arduino board. These steps will need to becompleted any time that you use a brand new boardwith your computer. Forthose using aWindows 8 or higher operating system,Linux, orMacOS, youwillbeabletoskipoverthefollowingsteps.YoursystemwillalreadyhavethetechnologypresenttorecognizetheArduinoboardwithoutthesesteps.

For thoseusing theearlierversionsofWindowsoperatingsystems, thesestepswill help you get your drivers onto a computer so thatwhen youwrite out acode, theywillgoover to theboard the rightway.The steps thatyouneed totakeinclude:

MakesurethattheArduinoboardispluggedintothecomputercorrectly.You will notice that your operating systemwill start going through theprocess of driver installation, but it won’t be able to finish the process.Youshouldgetamessagethattheinstallationfailed.

Afterthisinstallationprocesshasfailed,youshouldgotoyourStartMenubeforeclickingontheControlPanel.

Look through yourControl Panel until you find the tab for System andSecurity.ClickontheSystemTab.

Afterthiswindowhassometimetoloadup,youcansearchfortheDeviceManager.Makesuretoclickonthis.

Fromhere, thereshouldbea tabforPorts.Look tosee if there isaportthatisopenandwhichiscalledArduinoUNO(COMxx).Sometimes,the

Page 32: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Ports tab is not going to show up for the particular device that you areworkingon.Ifthishappenstoyou,doasearchforOtherDevicesandthensearchforUnknownDevices.

Onceyoufindyourdevice,youcanrightclickonit.Therewillbeafewoptions that come up for you to choose from. You should pick UpdateDriverSoftware.

Finally,itistimetoselectafilethatisnamedArduino.inf.ThisoneshouldbeunderyourDriversfolderforyourArduinoSoftwaredownload.IfyouareworkingwithoneoftheolderversionsofyourIDE,youwillneedtolookforafilethatisnamedArduinoUNO.inf.

Afterclickingonthesethings,youroperatingsystemcangothroughandfinishtherestoftheinstallationprocesswithoutneedinganythingelse.

Keep in mind that you will only need to go through these steps if you areworkingwithanoperatingsystemfromWindowsthatisolderthanWindowsXP.For any of the newer versions of Windows or the Mac and Linux operatingsystems,youcanskipoverthesestepsbecauseyourcomputerwillautomaticallynoticetheboard.YoujustneedtohookintheUSBcabletotherightspotandthecomputerwillrecognizethedevice,makingiteasierforyoutostartyourworkrightaway.

Page 33: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

WorkingonYourFirstSketch

At this point, regardless of the kind of operating system you are using, youshouldhavetheArduinoboardhookedupandrecognizedbyyourcomputer.Itisnowtimetodoatestdriveofyourboardandtryoutasimpleprogramforthefirsttime.Thisprogramwon'tmakemuchofachangeontheboard,wearejustchangingablinkinglight,butitwillhelpyoutogainsomefamiliaritywithyourboardandthecodinglanguagethatwewillusewhenitistimetoworkonafewoftheotherprojects.

Whenwritingoneofyourownsketches,youneed tomakesure that therearetwo void functions inside of the code. These void functions should not beallowedtoreturnavaluetoyou,andtheycanincludetheloop()andthesetup()functions.With thesetup() function,wearegoing touse it to tell theprogramthatwewant to just run throughoursketchone time, rightafter theboardhasbeenpoweredupandisreadytostart.

Ontheotherhand,wealsoneedtheloop()function.Thisistheonethatwilltelltheboardthatyouwant thesketchtocontinueina loopuntilyouunplugyourboardfromacomputer.Sinceweareworkingonablinkinglight,thesetwoaregoing to tell the board to start blinking the light right when you turn on theArduinoboardandthatyouwanttokeeptheblinkinggoinguntilyouunplugtheboardlateron.

Duringoursetup()part,weneedtomakesurethatwetakecareofanyandallinitializationstepssothatwhentheloop()partcomesintoplay,thecodewillrunproperly and keep on going over and over again on the board. There is somebasiccodingthatweareabletousetomakethisallhappenanditincludesthefollowing:

voidsetup(){

Page 34: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

}

voidloop(){

}Thisis thebasicsyntaxthatyouwilluseinmostcodes,andasyoucansee, ithasbothofthevoidfunctionsthatyouneedtomakethecodeworkproperly.ButifyouwentthroughandtypedthisinformationintoyourIDE,itwouldn’tknowwhatyouwanted tohappenbecause there isn’t anycode insideof it.Youwillneedtoputinabitmoretothecodetomakesurethatitwilltelltheboardtherightstufftodo.Despitethis,itisstillagoodsyntaxthatyoucanstartwith.

Nowthatwehavethebasicsyntaxthatweneedtowriteoutacode,itistimetowriteoutourcode.Someof theothersteps thatyouneed toworkon tomakethiscodeworkis:

MakesurethattheArduinoboardyouareusingisstillhookeduptothecomputerandthatyourapplicationforArduinoislaunched.

NowyoucanopenupthesketchthatisfortheBlinkexamples.Ifyouaresearchingforthis,youjustneedtoclickonFilefirst,thenExamples,andthen1_Basics,andBlink.

Fromhere,youareabletopickoutthetypeofboardthatyouwillbeusingon this particular project. To pick out the board you are using, you canclick on Tools and then Board, before clicking on the board of yourchoice.

NowitistimetochoosewhetheryouareusingtheserialportortheCOMport.YoucanlooktoseewhichonetheArduinoboardisattachedto.YoucanclickonTools,Port,andfinishwithCOMxx.

Sometimesitishardtofigureoutwhichtypeofserialdeviceyouareusingontheboard,especiallyifyouareabeginner.Youcanjustgetintothelastpartand

Page 35: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

take a look to see which ports are available and which one matches up withyours. Sometimes you may need to unplug your board for a second and seewhichoftheportsdisappearstohelpfindwhichoneisrightforyou.

GettingtheLighttoWork

Nowwearemovingtothefinalstep.Ifyouhadtogothroughandunplugyourboardintheotherstep,makesurethatitisproperlypluggedbackinsothatthisworks.Make sure that the Blink sketch is still open to use. From here, thereshouldbeanUploadbuttonthatyouareabletopress.Atthispoint,youneedtowaitjustabitbeforelookingtoseewhethertheLEDlightsneartheRandtheTXareflashingwhileyourprogramuploadstotheboard.

If thisuploadhasbeensuccessful, it is time tocheck thecomputer.Thestatusbar that is foundwith theBlinkSketchwill let you know that the program isDoneUploadingifthewholethingwassuccessful.

Aftertheuploadingisalldone,youcanlookatyourArduinoboardandcheckhow the LED light for yourON button is working. It should have an orangecoloranditshouldstartblinkinginaslowandsteadymannerratherthanattherapidpacethat itdidwhenwefirststarted.Ifyourlight isblinkingwithabouttwosecondsinbetweeneachone,thenyouweresuccessful,andtheprogramisdone.

Asyoucansee,workingwiththeArduinoboardisnotsomethingthathastobeovercomplicated.Aslongasyouhavetherightstepsinplaceandyouget thedeviceall setup in theproperway,youare set togo.Andnow thatyouhavefinishedthischapter,youhavecompletedyourveryfirstproject!

Page 36: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter4:

Page 37: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

HowtoReadtheAnalogSensors

TheArduinoboard isa littlebitdifferent fromsomeof theotherprojects thatyouhaveworkedon. Insteadofbeingable to lookatacomputerscreen togettheinformationthatyouwantlikewithalotoftraditionalprogramming,youaresendingthingsovertoaboardandgettingittobehave.Thisishowthingshavetoworkifyouwanttogettheprogrammingovertoatwooranotherelectronicproject.Butsinceweareworkingwith theboard, therewillbeafewdifferentthingsthatwehavetolearnhowtodotomakeithappen.

In thischapter,wearegoingto takea lookatsomeof theanalogfeatures thatcome with the Arduino board. We will look at how to read the input of theanalogwhenitisonpin0,howtoconvertthevaluesfromyouranalogread()andchangeitovertovoltage,andthengettheserialmonitortoprintoffinourIDE.

First,youhavetomakesurethatyouhavetherighthardwareinplacetomakethisprojectwork.Thisonewillbeprettysimple.YouneedtomakesurethatyouhaveanArduinoboardsetupandreadytogo.Youwillalsoneedtohavea10kohmpotentiometeraswell.

Thesecondthingthatweneedtoworkonisgettingallthewireshookeduptotherightplace.Weneedtotakethethreewiresthatcomefromourpotentiometerandgetthemhookeduptotheboard.Thefirstofthewireswillgototheground,butitshouldstartwithoneoftheouterpinsonyourpotentiometer.Thenyoucantakethesecondwireandconnectittothe5voltsontheArduinoboardandthentotheotherouterpinonyourpotentiometer.Thenthethirdonewillstartonthemiddlepinofyourpotentiometer,anditwillbeplacedintheanaloginput2.

Now that all of the wires are in place, it is time to turn the shaft of thepotentiometer.Whenyoudothis,youwillchangetheamountofresistancethatis coming throughon either side of thewiper, or the part that is connected toyourcenterpin.Thiswillbasicallychangehowmuchvoltage ison thecenter

Page 38: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

pin.Whenyouchangethevoltagesothattheresistancebetweenthesidethatisconnected to the 5 volts and the center gets closer to zero, the voltage at thecenterisgoingtogetclosetofivevolts.Whentheresistancesarereversed,thevoltageforyourcenterpinwillchangeto0,ortotheground.Thisinputthatyouarereadingisknownastheanalogvoltage.

When you work on the Arduino board, you will notice that there is a circuitfound inside of the microcontroller that is known as the analog-to-digitalconverter.We are going to call it the ADC. This is going to be in charge ofreading the changing voltage and then will convert it to a number that issomewherebetween0and1023.Ifyouturnyourshafttoonesidealltheway,therewillbe0voltsthatwillreachthepin,sotheinputvaluethatgoesthereisgoingtobe0.But thenifyouturntheshaft to theotherdirections, thismeansthatthepinisgoingtostartreceiving5volts,soyourinputvalueisgoingtobe1023. Of course, there will be times when the voltage will be somewhere inbetween0and5, so theanalogRead() isgoing togiveyouanumber that fallsbetweenthe0and1023basedonhowmuchvoltagehasbeenappliedtothepin.

Itisnowtimetolookatthecodethatwewillusetomakeallofthishappen.Intheprogramthatwewillwritebelow,thefirstthingthatwedowillbetousethesetup function to begin our serial communication.Wewillmake sure thatwehaveitsetuptobe9600bitsofdataeachsecondandthiswilloccurbetweenthecomputerandtheboard.

Oncethatisdone,itistimetoworkonthemainloopforthiscode.Insidethatmain loop, we need to work on establishing a variable that will store theresistancevalue (remember that this is inbetween0and1023), that iscomingfromthepotentiometer.Youcanalsogothroughandchangethevaluesfrom0to1023 toa range thatwillcorrespondwith thevoltageyourpinsare reading. Ifyoudothis,youmustmakesuretocreateanothervariable,whichisknownasafloat,andthenaddinabitofmath.Toscalethesenumbersbetween0and5,you

Page 39: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

needtodivide5by1023andthenmultiplythatbyoursensorValue.

Andfinally,weneedtomakesurethatwetellthesystemthatwewanttoprintouttheinformationsothatitshowsupinourserialwindowintheend.Thisisprettysimpletodo.JustaddtheSerial.println()tothelastlineofthecode,andyouareallsettogo.

Oncethecodehasallbecompleted,youshouldbeabletoopenuptheIDEandthen open your Serial Monitor. If you are having trouble finding the SerialMonitor,justclickontheiconthatistotherightofyourtopgreenbar.YoucanalsoclickonControl,Shift,andMtomakethishappen.OncetheSerialMonitoris all open, you should see a nice steady stream of numbers that rangesomewherebetween0and5.Asyouturnyourlittleswitchfromonedirectiontoanother, thevalues aregoing to change, andyouwill see that thevoltage thatcorrespondstothatchangewillcomeuponpinA0.

So,whenyouarereadytowriteoutthecodethatyouwouldliketouseforthisserialreading,youwillusethefollowing:

//thesetuproutinerunsoncewhenyoupressreset:

voidsetup(){

//initializeserialcommunicationat9600bitspersecond:

Serial.begin(9600);

}

//thelooproutinerunsoverandoveragainforever:

voidloop(){

//readtheinputonanalogpin0:

intsensorValue=analogRead(A0);

//Converttheanalogreading(whichgoesfrom0-1023)toavoltage(0-5V):

floatvoltage=sensorValue*(5.0/1023.0);

Page 40: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

//printoutthevalueyouread:

Serial.println(voltage);

And that isall thatyouneed todo inorder tosetupyouranalogpinsandgetthemtoworkforyou.Thereareotherthingsthatyoucandowiththeseanalogpins,butthesebasicswillhelpyoutolearnhowtheyworkandhowtogetitsetupsothattheIDEisabletoreadthemproperly.

Page 41: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter5:

Page 42: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

HowtoStoreDataonArduino

TheremaybesometimeswhenyouwouldliketogettheArduinotosaveandstoreyourdata.Theprojectyouhavemayrequiretheabilitytorecognizevoicepatternslateronorsomenamesandpasswordsdependingonthetypeofprojectthatyouwanttoworkwith.Whilethereareafewoptionsavailabletohelpyoustore the data, the sketches that seem to be the most useful will be theVemierThermistorStore or the VemierAnalogStore. Both of these are going toworkprettymuch the same, and theywill take your readings from the analogsensor before storing this information inside the EEPROM memory of yourArduinoboard.

OneofthenicethingsaboutusingtheEEPROMmemoryisthatitisconsiderednon-volatile. Thismeans that evenwhen you take the power away from yourArduinoboard,thedatawillcontinuetobesavedonit.Thelimitofpointsthatyoucanusewiththisoptionthoughwillbe511.

Now,youhavetochoosewhichoptionyouwouldliketoworkwith.Unlessyouwant to keep track of the temperatures with your board, theVemierThermistorStorewillprobablynotbetheoptionthatyouwanttogowith.ThismeansthatwewillfocusourenergyonusingtheVemierAnalogStore.Thisoptionwillbeabletohandletheanalogsensorthathasalinearcalibration.Asitiswritten, itwillbeable tocollectdata from thedual-range force sensoreachsecond.Youwillfindthatwithsomeexperience,itcanbeeasiertomodifythissketch for a different sensor if youwould like or even for a different rate ofcollection.

There are going to be a few things that youwill need in order tomake thesesketcheswork.Thesethingsinclude:

Tostartcollectingthedatatostore,whichwillalsowipeoutthedatathatyouhavecollectedandstoredinthepast,youwilljustneedtopressand

Page 43: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

hold thepushbutton for about two seconds.YourLED light is going toblink for every time that your data point is taken. If your Arduino isconnectedtoyourcomputer,youcanwatchtheSerialMonitortoseewhatdatahasbeencollected.Ifyougetstartedwiththiscollectionofdataanddecidethatyouwouldliketostopsometimebeforeallthedatapointsarecollected,youwouldjustpressthesamebuttonagain.YouaresuccessfulwhentheLEDflashesthreemoretimesquickly.

Thegoodnews is thatyouwillbeable to take thedataaway fromyourcomputer and thenbring it back to see againwith thehelpof theSerialMonitor,as longasyoumakesure theArduinohaspower.Youcanalsochoosewheretoplacethisdata,suchasinsidetheLoggerProfilesothatyoucanlookatthemlater.

Once your data collection is done, it is time to send your collected andstored data that is inside of the EEPROMmemory over to your SerialMonitor.Theprocessfordoingthisisprettysimpleandwilljustneedthefollowingsteps:

MakesurethatyourArduinoisconnectedtoyourcomputerwiththehelpofaUSBcable.

IfyourIDEisnotalreadyupandrunning,itistimetoturnitonandgetitready.

NowopenuptheSerialMonitorforArduino.

PressthebuttonthatisonyourArduinobutmakesurethatyoudonotholditdownformorethantwoseconds.Ifyouholditforlongerthan this time, youwill basicallybe starting the collectionof dataagain,anditwillwipeoutalltheinformation.

All thedata thatyoucollectedearlier should start toappear in theSerialMonitorafteryouaredonewiththisstep.

Page 44: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Ifyouwouldliketobeabletochangetherate that thedata isbeingcollected,you will just need to change the variable that you are using underTimeBetweenReadings.Notethatyouareonlyabletostoreupto511pointsinyour EEPROMmemorywhile using this sketch. Thismeans that itmay be agoodideatoincreasetheamountoftimethathappensinbetweenyourreadings.Thismakesiteasiertocollectthedataoveralongerperiodoftimeratherthandoingitasmuchaspossible.

Nowthatwehavetakenalookatsomeofthestepsthatyouneedtotakeinordertostartstoringandcollectingthedataonyourboard,itistimetobringoutthecodethatwillhelpyoutogetthisdone.Thecodeisabitlengthy,butitisgoingtotelltheboardexactlywhatyouwanttobedone.YoujustneedtotypeitintoyourIDE,andtheboardwillrespond.Thecodethatyouneedtouseincludes:

intbuttonPin=12;//analoginputpintouseasadigitalinput

intledPin1=13;//digitaloutputpinforLED1indicator

intdebounce=20;//msdebounceperiodtopreventflickeringwhenpressingorreleasingthebutton

intholdTime=2000;//msholdperiod:howlongtowaitforpress+holdevent

#include<EEPROM.h>

intbase=0;//thebaseaddressinEEPROMfordatastorage

//notefirsttwobytesstorethenumberofpointscollected

//Buttonvariables

intbuttonVal=0;//valuereadfrombutton

intbuttonLast=1;//bufferedvalueofthebutton'spreviousstate

longbtnDnTime;//timethebuttonwaspresseddown

longbtnUpTime;//timethebuttonwasreleased

longReadingTime;//timeatwhichareadingwastaken

longElapsedTime;//timesincelastreading

Page 45: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

booleanignoreUp=false;//whethertoignorethebuttonreleasebecausetheclick+holdwastriggered

booleanledVal1=false;//stateofLED1

intAnalogDataPin=A0;//thismaybechangeddependingoncircuitwiring

intCount;

floatVoltage;

floatSensorReading;

unsignedlongTime;

longunsignedintTimeBetweenReadings=1000;//inms

intNumberOfPoints=511;StringSensorName="Dual-RangeForceSensor,10N";

StringMeasurement="Force";

StringShortMeasurement="F";//thisisashortenedversionofthelabel

StringUnits="Newtons";

floatIntercept=12.25;

floatSlope=-4.9;voidsetup()

{

//Setbuttoninputpin

pinMode(buttonPin,INPUT);

digitalWrite(buttonPin,HIGH);

pinMode(AnalogDataPin,INPUT);

pinMode(ledPin1,OUTPUT);//SetLEDoutputpin

Serial.begin(9600);

Serial.println("VernierAnalogStoresketch");

Page 46: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Serial.println("Pressandholdtocollectnewdata");

Serial.println("PressbuttonbrieflytoreaddatastoredinEEPROM");

Serial.println("andsendittotheSerialMonitor");

Serial.println("");

}voidloop()

{

digitalWrite(ledPin1,false);

//Readthestateofthebutton

buttonVal=digitalRead(buttonPin);//buttondownislow

//Testforbuttonpressedandstorethedowntime

if(buttonVal==LOW&&buttonLast==HIGH&&(millis()-btnUpTime)>long(debounce))

{

//buttonpressed

btnDnTime=millis();//notetimeofpress

}

//Testforbuttonreleaseandstoretheuptime

if(buttonVal==HIGH&&buttonLast==LOW&&(millis()-btnDnTime)>long(debounce))

{

if(ignoreUp==false)ReadEEPROMData();//readdatafromEEPROMandsendtoSerialMonitor

elseignoreUp=false;

btnUpTime=millis();//notetimeofbuttonrelease

}

Page 47: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

//Testforbuttonhelddownforlongerthantheholdtime

if(buttonVal==LOW&&(millis()-btnDnTime)>long(holdTime))

{

CollectData();//collectnewdata

ignoreUp=true;

btnDnTime=millis();//getnewbuttondowntime

}

buttonLast=buttonVal;

}

Page 48: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter6:

Page 49: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

USBandSerialCommunicationonArduino

Throughoutthisguidebook,wehavespentsometimetalkingaboutafewoftheprojects that you can executewith the help of yourArduino board.A few ofthesehaverequiredyoutouseaUSBcordtohelphookuptoacomputersothatyoucandownloadwhatevercodeyouwanttouse.Nowwearegoingtotakethisa bit further and work on serial communication and how we can use this tofigureoutwhichsensorsareworking,whetherourprojectswillmaketherightdecisions,tochangeourvariablevalues,andtocontrolothermovements.

Page 50: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

InformationtogetStarted

Beforeweareable togetstartedwith thiskindofcommunication,weneed tohave a good idea of what serial communication is all about. This type ofcommunicationisgoingtoworkonaseriesof1sand0sorabinarysystem.TheArduino board will be able to send these bits (which are the 1s and the 0s)serially,onebyone.Tokeep thingssimple, the1saregoing tobe theHIGHs,andthe0saregoingtobeLOWS,andthenthesebitswillcometogethertoformsomebytes.

Whenyouseeabyte,itmeansthatyouhaveasequenceof8bits.Eachbitthatyouworkwithwillrepresentanumberthatyouneedtoadd.Thefirstbit,ortheone that ison thefar right,will representoneplace,kindof likewhatyouareused toworkingwith in the decimal system. 1 is going to equal 1 and 0willequal0.Thenwhenyoumovetothevalueofthenetbit,youwouldmultiplyitbytwo,so10isgoingtoequal2,11willequal3and01willequal1andsoon.Thesebitscangoallthewayupto255.

Serialoutputcode

Nowitistimetoworkonthecodethatyouwanttouseinordertohelpwiththeserial output.This code is pretty simple, andyouwill just need to type in thefollowingtomakethishappen:

voidsetup(){

Serial.begin(9600)

}

voidloop(){

Serial.print(“Theanalogvalueis:“);

Serial.println(analogRead(A0));

Page 51: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

delay(100);

}Asyoucanseewiththisone,thereisthesetup()andtheloop()functionjustlikewedidwiththeearlierexamplesthatweshowed.Inaddition,theserialprintisgoingtobeafunctionthatisinchargeofprintingwhatevermessageyouspecifyinyourserialmonitor.Forthisspecificcode,wehavedecidedtoprinttheanalogvalueforthepointthatisinsideofAnalogPin0.

Then we moved on to the void setup. This is where we will tell the serialmonitorwhenitissupposedtostart.Forthisproject,itshouldstartupwhenwereachthebaudrateof9600.Duringthevoidloop, thereis thefunctionfor theSerialprintlnaswell.INhere,wearegoingtoprintoutthevaluethatwefindintheA0partoftheAnalogRead.

HowtoUseit

Sofar,wehavetakenthetimetolookatacodefortheserialcommunicationandtoexplorewhatthistypeofcommunicationisallabout,butwhatisitallabout?Whywouldwewanttousethistypeofcommunicationandhowcanbeitusedon theArduinoboard?Over theyears, serial communicationhasbeenused inmanywaystohelpfinishouttheprojectsthatyouwouldliketoworkon.

Inthisproject,wearegoingtoturnonandoffanLEDlight.Thiswillbesimilartowhatwedidbefore,butwewillusetheserialnumbersratherthantheothermethod thatweusedbefore.First,youwillneed to take theLEDandplace itwith thepin-13andtheground.Thenyoucanconnect theUSBcable thatyouwanttouse.

We can then move on to create a new integer that we will use to store theincomingbytesthataresentover.Youcanpickthenamethatyouwanttocallthisinteger,butwearegoingtocallit“inByte”forthisexample.Nowwewill

Page 52: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

gobacktothevoidsetup,andmakesurethatwesetthepin13astheoutput.WewillkeeptheSerial.beginthesamesincewewanttogetittoworkwith9600bitspersecond.

Now it is time tomove to thevoid loop. In this,we firstneed toknowwhichbyteisaroundthatitcanread.SowewillusetheSerial(available).Thisfunctionwillletyouknowhowmanybytesarethereforyoutoreadthrough.So,wecanchoose to write out something like “if(Serial.avialable() > 0)”, we know thattherewillbeoneormorebytethatwillshowupthatcanberead.Insideofthisifstatement,wehavetoreadthebyteandthenmakesurethatitisstoredlaterforuse.WecandothisbywritingoutSerial.read(),whichwill tell theprogramtoreadyourbyteandthensaveitovertotheinByte.Tofinalizethisline,itisgoingtosayinByte–Serial.read();Whileyouarestill insideyourmainifstatement,wecanadd insomeother if statements ifwe like. Ifyouwant theprogram towriteorreadalettertoyourvariable,youwillplacethatparticularletterinsomesinglequotationmarks.Forthisexample,wewanttolettheLEDlightturnonwhenwesendoveran‘a’toourboards.Thismeansthatthestatementwewillwritetomakethishappenwouldinclude“if(inByte==‘a’).

Next,wewillmove on to the Serial.printlin(). This is important because it isgoingtotellArduinothatitshouldnotifyusinsideoftheSerialmonitorthatthe‘a' has shownup and that ourLED light has started.The if statement thatwewanttoworkwithwillbelikethefollowing:

if(inByte==‘a’){//byteis‘a’

digitalWrite(13,HIGH);

Serial.println(“LED–ON”);

}Inthisproject,weneedtoensurethattheLEDwillturnoffifweputinanyoftheotherlettersoutsideofthe‘a’thatwespecifiedbefore,soitisimportantthat

Page 53: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

weaddinanelsestatement.Whenthishappens,theLEDlightisgoingtoturnitselfoff.

PuttingitallTogether

Uptothispoint,wehavespentsometimetalkingaboutthecodethatisneededto turn the light on and off based on the Serial communication, or the binarycode.Now let’sput it all together.Thiswill tell theprogram thatyouwant toturnthelightonwhenthe‘a’isputin,andthenwhenanyotherletterisaddedtothemix, theLEDwill be turned off. The code you need tomake this happenincludes:

intinByte;//Storesincomingcommand

voidsetup(){

Serial.begin(9600)

pinMode(13,OUTPUT);//Ledpin

Serial.println(“Ready”);//Readytoreceivecommands

}

voidloop(){

if(Serial.available()>0){//Abyteisreadytoreceive

inByte=Serial.read();

if(inByte==‘a’){//byeis‘a’

digitalWrite(13,HIGH);

Serial.println(“LED–On”)

}

Page 54: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Else{//byteisn’t‘a’

digitalWrite(13,LOW);

Serial.printlin(“LED–off”);

}

}

}And that is all that youneed to do in order to get theArduinoboard toworkproperlyanduseanLEDlightwiththehelpoftheSerialcommunication.

Page 55: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter7:

Page 56: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

CanArduinoWorkWirelessly?

Sofarinthisguidebook,wehavespentsometimelookingattheArduinoboardandhowyoucansendovervariouscodes,buttheboardhastobeconnectedtothe computer tomake thiswork.AUSBcable is usually enough tomake thishappen, but there may be times when you wish you were able to send overinformation wirelessly between your IDE on the computer and the Arduinoboardthatyouareusing.

Thegoodnewsisthatsendingcodewirelesslyissomethingthatyoucando.YoucanusewhatisknownastheArduinoWirelessProgrammerinordertouploadsomeprogramsfromyourcomputerovertotheArduinoboardwiththehelpofBluetooth.

Beforewecanworkwith thewirelesscapabilities,weneedto takethe timetoupdate the program inside of our boards.There are some timeswhenwewillneedtoopenuptheboxorthecasetodothisandtimeswhenweareabletojustupdatetheprogram.Anytimeyouwanttodothiskindofwirelessprogrammingwithout having to use a USB cable, you will find that the ArduinoWirelessProgrammerisgoingtobeoneofthebestchoicestouse.

When picking out this program, you should be a bit careful. There are someprojectsthatwillnotbecompatiblewiththisprogram,andyouwillstillneedtoplugtheboardintothecomputer.Forexample,ifyouareworkingonaprojectthatwillneedtouseD1orD0orthehardwareRX,TXorUART,youwon'tbeabletousethesewirelesscapabilities.Thisisbecausethisprogrammerneedstobeable tooccupytwoofyourpinspermanently towork,and thiscanruin theprojectinsomecases.

There are also only a fewboards that you canusewith this programmer.TheArduinoDeumilanoveandtheArduinoUNOwillworkwiththisprogram.Thereare some different configurations that will sometimes work with the other

Page 57: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

models,buttheywillonlysupportthemainboardthatyouareusing.

So now it is time to work on uploading this wireless program to your boardwithout having to bring on the USB cable. This step can be a bit hard for abeginner,butonceyouaredone,itwillmakeitsomucheasierforyoutoworkonsomeofyourprojectswithouthavingtohookituptothecomputerforeachproject.

Sotostart,weneedtomakesure thatwehaveourArduinoIDEsetup.MakesurethatwhenpickingoutanIDEtouse,youshouldnotusetheArduino00xxversion.Whilethisisdownloading,youalsoneedtodownloadtherxlxserial.dllfile,andthiscanbeusedasareplacementfortheonethatcomeswithyourIDEfolder.

Whileyouareonyourcomputer,itistimetoopenuptheBluetoothcapabilities,wherever those are located on your computer. You can add a device. AfterfindingtheBluetoothdevicethatyouwouldliketoworkon,clickon"Enterthedevice'spairingcode."Youcanusethedefaultcode"1234"becauseitiseasytoworkwith.NowyoucanopenuptheBluetoothdevicethatyouareworkingonandchoose it.Click the rightbuttononyourmouseso thatyoucanselect theoptionforproperties.

Nowthatwehaveaddedtheboardweareusingforthisproject,thenextstepisto actually upload the program that we want to place on the Arduino board.Remember that for these steps,we are going to upload our code to the boardwithoutusingaUSBcordofanytype.

Togetstartedwiththis,weneedtomakesurethatourIDEisopen.WecanthenselectonToolsandthenBoard.Thenthereareafewoptionswecanpickfrom.We will either pick the Arduino UNO or the Arduino Duemilanovew/Atmega328dependingontheoptionthatweareusingforthisproject.

Afterwehaveselectedtheboardthatweareworkingwith,itistimetoclickon

Page 58: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

ToolsagainandSerialPortbeforeclickingonCOMX.ThislastpartisgoingtobethespecificserialportthatwillbeusedfortheBluetoothsoclickingonthisoneisimportant.

Forthistowork,theprogramyouintendtouploadneedstobeontheArduinoIDE already. If you haven’t done it, you should go through andwrite out thecodeyouintendusingsothattheboardhastherightcommandsthatitneedstogettheworkdone.Oncetheprogramisdoneandsaved,ensurethatitisopen,oropen it ifyoudid thecodingearlier.Press theUploadbutton so that it canbesentwirelesslyovertotheboardyouareusing.

And that is all there is to thisproject.Therewillbe timeswhenyourprojectswillnotlikeworkingwiththewirelesscapabilitiessincethiscantakeupsomevaluablespaceonyourdeviceandifyouneedtouseallofthepinstomakethishappen your project will not work. But there are many cases when workingwirelesslycansavesomehassle,especiallyifyouhavelostyourUSBcableanditishardtoalwaysbestuckonacomputer!

Page 59: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Chapter8:

Page 60: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

OtherCodesforYourArduinoBoard

WehavespentsometimetalkingaboutthetechnicalthingsthatyoucandowiththehelpoftheArduinoboard.Bythistime,youshouldbefamiliarwithsomeofthecodingthatcomeswiththisboardandhowtodoafewlittleprojectstostoreinformation that youwant and even to change how theLED lightswork.Butmost people do not pick to work with an Arduino board because of all thetechnicalstuff.Theychoosetoworkonitbecausetheywanttolearnhowtodosomeneatprojects.Nowthatyouhavethebasicsandthetechnicalstuffdown,itis time to learn a few projects that can add some fun to working with thistechnology.

HeatingBlanket

Thefirstprojectwearegoingtotakea lookat isaheatingblanket.Thesecanfeelniceandwarmwhenyouaredealingwithacoldwinters’day,buttheyareexpensivetopurchaseonyourown.Thegoodnewsisthatifyoupurchaseafewpartsfor theArduinoboardand thematerial thatyouwant touse,youcangetthisblanketupandrunninginnotime.Thisonewillalsoneedacodetohelpitget startedsomakesure thatyouhaveagoodUSBcord tohelpyouget italldone. Some of the materials that you need to make your very own heatingblanketinclude:

Redhookupwire

LilyPadArduinoboard

Awalladapterforpowersupply(5VDC1A)

N-ChannelMOSFET60V30A

25X15Heatingpads

Switch

Page 61: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Conductivethread

LIlyPadLEDlight

BlackhookupwaterOnceyouhavehadachancetocollectallthematerialsthatyouneed,itistimetogetstarted.Sothefirststep is tosewupthehandwarmerblankets thatyoupicked out. You can design this to look any way that you would like so getcreativeandhavesomefun.Once thatcreativity isdone,youwillneed touseyour conducting thread to sew onto your board before connecting this to thepositiveside,whichwillbewheretheblueLEDlightswillbelocated.Youwillalsoneedtotakesometimetosewtogetherthenegativepartsifyouwantthistowork.

Nowyoucangrabyourhookupwire,whichwillbetheredwirethatyouhave,andmakesuretoconnectittothepositivecontactoftheboard,makingsurethatit is on the side that has the positive side of your switch. It is good to use aparallelconnectionso that itwillhookup to thepositivepartofyourpadandalsosaveyousomehassle.

Whenyouaredonegettingthepositivesideallhookedup,thenextstepistogetthenegativepartready.Youcanbringouttheblackhookupwiretohelpconnectupthesenegativepartsoftheboard,sotheyarehookeduptothepowersourceaswell.Continueonsothatthesepartsareallconnectedtothenegativepartoftheswitch.

Fromhere,youcanworkonaparallelconnectionthatwillgoallthewaytotheSlegofyourMOSFET.Whenthatisdone,createanotheronethatwillgotothe10k resistor, goingparallel aswell.Nowyouneed to takeyour11thpin fromyour Arduino board and hook it up, so it connects with the G leg of yourMOSFET. There should be a branch when you are done that ends up goingparalleltotheotherendoftheresistor.Andfinally,youwillconnecttheDlegof

Page 62: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

theMOSFETtothenegativepartsthatareontheheatingblanket.

Atthispoint,youwillneedtoturntoyourcomputerandworkforabitinsideofthe IDE.Thiswill allowyou tocreate thecode that isneeded for thisproject.Thecode thatwillmake theboardworkandcreateagreatheatingblanket foryouwillinclude:

language:C

/*

HardwareConnections:

-led1=D9;

-led2=D10;

-led3=D11;

-button=D2;

-Mofset=D3;

*/

intbtnPin=2;

booleanbtnPressed=false;

intfetPin=3;

intled1=9;

intled2=10;

intled3=11;

intmode;

voidsetup(){

//initializethedigitalpinasanoutput.

pinMode(btnPin,INPUT);

pinMode(fetPin,OUTPUT);

pnMode(led1,OUTPUT);

Page 63: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

pinMode(led2,OUTPUT);

pinMode(led3,OUTPUT);

}

//thelooproutinerunsoverandoveragainforever:

voidloop(){

//incrementmodeondepress,unlessmode=3,thenresetto0

if(btnPressed&&digitalRead(btnPin)==LOW)

mode=mode==3?0:mode+1:

//Assignbuttonstate

btnPressed=digitalRead(btnPin):

switch(mode)

{

case0:

analogWrite(fetPin,0);//off

digitalWrite(led1,LOW)

digitalWrite(led2,LOW)

digitalWrite(led3,LOW)

break;

case1:

analogWrite(fetPin,85);//33%dutycycle

digitalWrite(led1,HIGH);

digitalWrite(led2,LOW);

digitalWrite(led3,LOW);

break;

case2:

analogWrite(fetPin,170);//66%dutycycle

Page 64: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

digitalWrite(led1,HIGH);

digitalWrite(led2,HIGH);

digitalWrite(led3,LOW);

break:

case3:

analogWrite(fetPin,255);//100%dutycycle

digitalWrite(led1,HIGH);

digitalWrite(led2,HIGH):

digitalWrite(led3,HIGH);

break;

}

}Yes,thiscodemaylookalittlelongwhengettingstarted,butitdoesgiveallofthedirections thatareneeded toget thatheatingblanketupandstarted. Itwilltellyourblankethowhotitcanget,withafewdifferentsettingsplacedin.Thecodewillalsoinstructtheblanketonhowitshouldturnonandoff,soyouareabletogetittoworkforyou.Thisprovidesyouwithalotofdifferentoptionsfor the blanket when you are done, and you are sure to stay nice and comfyduringwinter.

LEDLightupStrip

Thenextproject thatwearegoingtoworkoniscreatingourownlightupthestrip.Thiswill require thehelpof somethingknownasane-textilewhichcanactuallymakeitabiteasiertoworkontheproject.Togetthisonedone,wearegoingtocreateanLEDlightupwiththehelpofLilyPad.Thesuppliesthatyoucanusetogetthisprojectdoneinclude:

Page 65: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Fabric

Embroideryhoop

Needlethreader

Coincellbattery

Conductionthreadbobbin

ALilyPadcoincellbatteryholder

Scissors

RainbowLEDstrip

NeedlesOnceyouhavehadachance tocollect these supplies, it is time toget started.Taketheneedleandgetitallsetupwiththeconductivethreadthatweareusing.Youmay find thatplacing the fabric in theembroideryhoopcanhelpbecausethiskeepsitallinplacewhileyouaredoingthework.

At thispoint,weneed toworkonmakingapositive trace.What thismeans isthatwe have tomake amark that goes fromour source of power over to thepositivepartofourLEDstrip.Youcanstartonthisrightbesidethebatterypack.Youwillbecreatingaplace for thebatterypack (butdon'tput it in thereyet)nearwheretheLEDlightsshouldbeandmakesurebothoftheseareneareachother.Thesewillbehelpfulbecauseyouwillbeabletousethemasthenegativeandthepositivepinsinyourbatterypack.

Now, we need to ensure that we place the battery pack in the correct spacebeforestartingwiththesewingprocess.Youcanfirststartwithtrappingtheedgeofyourboard into the fabric.Youcando thisbywrapping itup in the thread,aboutfourtimeswillbefineoneachofyourpositivepins(therewillbethefirstone thatwe talked about aswell as a secondone near the top of theArduinoboard).Whenthesepinsarebeingsewnintoplace,youneedtomakesurethat

Page 66: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

you keep the stitches pretty small rather than just doing one long stitch. Thishelps to ensure that the pack is going to stay in its place and youwon't havethingsmovingaroundandshortingoutthecircuits.

Take some time to finish the stitchingall theway through thepositive sideofyourLEDstrip.Youwillhavetocheckafewtimestomakesurethatyouareonthe right pole. If you end up sewing on thewrong pole at any time, youwillexperiencesomeissuesbecausenotalltheLEDlightswillshowup.

After you are done getting the positive side all sewn up, it is time to startworkingontheotherside.Todothis,youneedtoreturnfromthecurrentsideoftheLEDtothenegativepartofyourpack.Youwillbasicallybedoingthesamesteps that we talked about before, but theywill be done on the negative sideinsteadtohelpgetthewholepackagereadytoworkwiththeLEDlights.

Onceyou reach the endof this, you should take a few seconds to look at theprojecttoseeifthereisanythreaddanglinganywhereontheproject.Ifthereis,youneed tosnip itoff toavoidproblems.Youcanalsodoublecheck tosee ifyournegativeandpositive tracesare touchinganyotherparts. If theyare,youneedtoredosomeofthestitchesbecauseitcouldleadtoseveralissueswhenitistimetogetthelightworkingagain.

Ifyouhavecheckedoverthewholeprojectandyounoticethatitalllooksgoodandyour sidesareplaced togetherproperly, it is time to takeyourcellbatteryand place it in the pack. Once the battery is inside the pack, the LED lightsshouldstart showingup rightaway.Andat thispoint,youaredonewithyourproject!

Page 67: Arduino: Master The Arduino Basics · 2019-04-03 · Introduction Congratulations on choosing “Arduino: Master The Arduino Basics”, and thank you for doing so. The following chapters

Conclusion

Thanks for making it through to the end of this book, let’s hope it wasinformative and able to provide youwith all of the tools you need to achieveyourgoalswhatevertheymaybe.

ThenextstepistogetoutthereandstartfindingtheArduinoboardthatyouwilllike toworkwith. For themost part,we focused on theArduinoUNOboardbecause this is the one that ismost commonly used, but there aremany greatoptionsthatyoucanchoosefrom,andtheonethatyoupickwilloftendependonthetypeofprojectthatyouareworkingwith.

ThisguidebookhastakensometimetolookoverthevariouscomponentsoftheArduinosoftwareandhowyouareabletouseit.Arduinoismostlyusedtohelpwith someengineeringand roboticsprojectsbut theboard is so simple touse,and the codematches C++, so even beginners are able to get thingsworkingeasilyforthem.

Insidethisguidebook,weexploredsomeofthedifferenttopicsthatweneedtoknowinordertousetheArduinosoftwareonanyproject.FromlearningwhatArduinoisallabouttolookingatthepartsofthecodeandhowtoworkonyourownproject and even looking at how toworkon someof your codes to sendthemoverwirelessly,youwillbeabletogofrombeginnertoexpertwithallofyourprojectsinnotime.

Ifyouhavesomegreat ideas tohelpyouwithagoodengineeringproject,butyoujustaren'tsurehowtogetitstarted,itistimetobringouttheArduinoboardtohelpyouout.Thisguidebookwillprovideyouwithall the information thatyouneedtogetstarted.