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

Lets beginning with arduino by m mokadem

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


arduino
Index

Introduction4
/whatisinteractiondesign?5
/whatisphysicalcomputing?5

thearduinoway7
/tinkering8
/patching9
/circuitbending10
/keyboardhacks11
/welovejunk12
/hackingtoys13
/collaboration14
/thearduinohardware15
/thesoftware
(IDE)16

reallygettingstarted…19
/theinteracticedevice19
/sensorsandactuators19
/basicintroductiontoprogramming20
/blinkingan
/whatiselectricity?25
/thebreadboard28
/readingapushbutton30
/tryingoutdifferenton~offsensors32
/usethelightsensorinsteadofthepushbutton33
/analogueinputs34


/trydufferentresistivesensors36
/serialcommunication37
/analogueinputs
/drivingbiggerloads(motors,lams,etc…)40
/complexsensors42
/talkingtosoftware43
LED23

(PWM)39

Introduction
Arduinoisanopen-sourcephysicalcomputingplatformbasedonasimplei/oboardanda
developmentenvironmentthatimplementstheProcessinglanguage.Arduinocanbeused


todevelopstand-aloneinteractiveobjectsorcanbeconnectedtosoftwareonyour
computer(e.g.Flash,Processing,Max/MSP).Theboardscanbeassembledbyhandor
purchasedpreassembled;theopen-sourceIDEcanbedownloadedforfree.
Arduinoisdifferentfromotherplatformsthatcanbefoundonthemarketbecauseofthese
features:
TheArduinoProjectwasdevelopedoutofaneducationalenvironmentandistherefore
greatfornewcomerstogetthingsworkingquickly.
ItisaMultiPlatformenvironment;itcanrunonWindows,MacintoshandLinux.Itis
BasedontheProcessingprogrammingIDE
ItisprogrammedviaaUSBcablenotaserialport.Thisisusefulbecausemanymodern
computersdon’thaveserialportsanymore.
ItisOpenSourcehardwareandsoftware-Ifyouwishyoucandownloadthecircuit
diagram,buyallthecomponents,andmakeyourown,withoutpayinganythingtothe
makersofArduino.
Thehardwareischeap.TheUSBboardcostaboutEUR20andreplacingaburntoutchip

ontheboardiseasyandcostsnomorethanEUR5.Soyoucanaffordtomakemistakes.
Thereisanactivecommunityofuserssothereisplentyofpeoplewhocanhelpyou.
Whatdoesthisallmean?We’regoingtodiscoveritthisthroughthisbookletthatis
designedtohelpdesignersandartististounderstandwhatbenefitstheycangetfrom
learninghowtousetheArduinoplatformandadoptingitsphilosophy.
/whatisinteractiondesign?
TherearemanydefinitionsofInteractionDesignbuttheonethatIlikethemostissimply
“InteractionDesignisaboutthedesignofanyinteractiveexperience”.Intoday’sworld
thisgenerallyisaboutthecreationofmeaningfulbetweenus(humans)andartefacts.We
alsoliketoexplorethecreationofbeautifulandmaybeevencontroversialbetween
technologyandus.
Specificallywebelieveindesigningthroughaniterativeprocessbasedonprototypesof
everincreasingfidelity.Thisapproach,alsopartofsometypesof“conventional”design,
canbeextendedtoincludeprototypingwithtechnologyandinparticularwithelectronics.
ThisparticularbrandofInteractionDesigniscalledPhysicalComputing(orPhysical
InteractionDesign).ThisbookletisinnowayasubstituteforabookonPhysical
Computing,werecommendyoubuyTomIgoe’sexcellent“PhysicalComputing”book.
/whatisphysicalcomputing?
PhysicalComputingisaboutprototypingwithelectronics,turningsensors,actuatorsand
microcontrollersintomaterialsfordesignersandartists.
Itinvolvesthedesignofinteractiveobjectsthatcancommunicatewithhumansusing
sensorsandactuatorscontrolledbyabehaviourimplementedassoftwarerunninginsidea
microcontroller.
Inthepastusingelectronicsmeanthavingtodealwithengineersallthetimeandthiskept
thedesignerfromplayingdirectlywiththemedium.Mostofthetoolsweremeantfor
engineersandrequiredextensiveknowledge.
Inrecentyearsmicrocontrollers(smallcomputersonasinglechip)havebecomecheap
andeasiertouseallowingthecreationsofbettertools.



TheworkthatwehavedonewithArduinoistotrytobringthesetoolsonestepcloserto
thebeginnerallowingpeopletostartbuildingstuffafteronly3or4daysofworkshop.
WithArduinothedesignerorartistcangettoknowthebasicsofelectronicsandsensors
veryquicklyandstartbuildingprototypeswithaninvestmentofaslittleas70EUR.

Fromthepunk-zine“sniffin’glue”England,circa1977

TheArduinoWay
TheArduinophilosophyisbasedonmakingdesignratherthentalkingaboutit.Itisa
constantsearchforfasterandmoreaccuratewaystobuildbetterprototypes.Wehave
exploredmanyprototypingtechniquesanddevelopedwaysofthinkingwithourhands.
TheclassicengineeringreliesonastrictprocessforgettingfromAtoBwhiletheArduino
wayisbasedonmaybegettinglostinthewayandfindingCinstead.Thisistheprocessof
tinkeringthatwearesofondabout;playingwiththemediuminanopen-endedway,
findingtheunexpected.Inthissearchwealsoselectedanumberofsoftwarepackagesthat
enablethatprocess,thisconstantmanipulationofthesoftwareandhardwaremedium.
Anotherconceptwedevelopedisthe“opportunisticprototyping”:whyspendtimeand
energybuildingfromscratch,aprocessthatrequirestimeandprofoundtechnical
knowledge,whilewecantakealreadymadedevicesandhacktheminordertoexploitthe
hardworkdonebylargecompaniesandgoodengineers?


ThisbecomeevidentinIvreawheretheheritageofOlivettiisrepresentedbyafew
junkyardswherecomputerparts,electroniccomponentsanddevicesofanysorthavebeen
dumpedafterthedemiseoftheItaliancompany.Wecouldbuythosedevicesforafew
eurosandhackthemintoourprototypesdramaticallyshorteningtheloop.
Thelastelementisthecommunity.Engagingpeopleandpushthemtosharebybeingthe
firsttoshare.We’restandingontheshouldersofthegiantsofopensourcehere.
Inthenextfewparagraphsyoucanseesomeofourreferencesthathaveinspiredthe
“ArduinoWay”.

/tinkering

Webelieveitisessentialtoplaywiththemedium,exploringdifferentpossibilitiesdirectly
onthehardwareandsoftware,sometimeswithoutaverydefinedgoal.Wecallthisprocess
Tinkering.AnexhibitionthattookplaceattheExploratoriumin2004hadthebest
definitionofit:
Tinkeringiswhathappenswhenyoutrysomethingyoudon’tquiteknowhowtodo,guided
bywhim,imagination,andcuriosity.
Whenyoutinker,therearenoinstructions-buttherearealsonofailures,norightor
wrongwaysofdoingthings.It’saboutfiguringouthowthingsworkandreworkingthem.
Contraptions,machines,wildlymismatchedobjectsworkinginharmony-Thisisthestuff
oftinkering.
Re-usingexistingtechnologyisoneofthebestwaysoftinkering.Gettingcheaptoysor
olddiscardedequipmentandhackingthemtomakethemdosomethingnewisoneofthe
bestwaystogettogreatresults.


/patching

RobertMoogbuilthisanaloguesynthesizersinamodularfashionandthemusiciancould
tryendlesscombinationby“Patching”togetherdifferentmoduleswithcables.Thismade
thesynthesizerlooklikeanoldtelephoneswitchbut,combinedwiththenumerousknobs,
wastheperfectplatformfortinkeringwithsoundandinnovatingmusic.Thistechnique
hasbeentranslatedintotheworldofsoftwarebyprogramslikeMaxorPureData.
/circuitbending


Circuitbendingisoneofthemostinterestingformsoftinkering.
It’sthecreativeshort-circuitingoflowvoltage,battery-poweredelectronicaudiodevices
suchasguitareffects,children’stoysandsmallsynthesizerstocreatenewmusical

instrumentsandsoundgenerators.Theheartofthisprocessis“theartofchance”.Itbegan
in1966whenReedGhazalabychance,shorted-outatoyamplifieragainstametalobject
inhisdeskdrawer,resultinginastreamofunusualsounds.
/keyboardhacks


Takingapartakeyboardrevealsaverysimple(andcheap)device.TheHeartofitisthis
smallboard.Byreplacingthekeyboardmatrixwithsensorswecanimplementnewways
tointeractwithsoftware.Thisisakeyhardwarecomponenttolearnaboutwhenstarting
inPhysicalComputing.
/welovejunk


Oneofthebestwaystoquicklygettoresultsistofindagreatsourceoftechnologyjunk
anduseittoquickly(andcheaply)gettoprototypeanexperience.Accumulatejunkand
gothroughitbeforestartingtobuildsomethingfromscratch.
/hackingtoys


Toysareafantasticsourceofcheaptechnologytohackandreuse.Thebestinterpretation
ofthiswayofworkingcomesfromHusmanHaqueandAdamSomlai-Fisherthat,with
their“Lowtechsensorsandactuators”project,haveperfectlydescribedthistechnique.
/collaboration
CollaborationbetweenusersisoneoftheykeypointsintheArduinoworld,throughthe
forumpeoplefromdifferentpartsoftheworldheleachotherwhilelearningaboutthe
platform.TheArduinoteamencouragespeopletocollaboratealsoatalocallevelby
helpigthemtoseutpusersgroupsineverycitytheyvisit.
/thearduinohardware



ThisisapictureoftheArduinoboard.Atthebeginningyoumightbeabitconfusedwith
allthoseconnectors.Hereisanexplanationofwhateveryelementoftheboarddoes:
14DigitalIO(pins0-13,)canbeinputsoroutputsassetinsoftware.
6AnalogueIn(pins0-5)arededicatedanalogueinputpins.Thesetakeanaloguevalues
(i.e.voltagereadings)andconvertthemintoanumberbetween0and1023.
3AnalogueOut(pins9,10,11)theseareactually3ofthedigitalpinsthatcanbe
reassignedtodoanalogueoutput.
TheboardcanbepoweredfromyourUSBportorfromthepowersocket.Thissettingcan
bechangedwiththejumpermarkedSV1inthediagram.Ifthejumperisclosesttothe
USBplugthentheboardispoweredfromthere.Ifthejumperisonthe2pinsclosestto
theDCconnectorthenitispoweredfromthere.
/thesoftware(IDE)
ThelastcomponentofArduinoisthesoftware.Thisisaspecialprogramrunningonyour
computerthatallowsyoutowriteprogramsfortheArduinoboardinasimplelanguage
modelledaftertheProcessinglanguage.Themagichappenswhenyoupressthebutton
thatuploadstheprogramtotheboard:thecodeyouhavewrittenistranslatedintoC
language,thatisnormallyquitehardtouseforabeginner,andpassedontotheavr-gcc
compiler,animportantpieceofopen-sourcesoftwarethatmakestheultimatetranslation
intothelanguageunderstoodbythemicrocontroller.Thislaststepisquiteimportant
becauseit’swhereArduinoismakingyourlifesimpleandhidingawayasmuchas
possibleofthecomplexitiesofprogrammingmicrocontrollers.


Downloadingandinstallingthesoftware
InordertoprogramtheArduinoboardyouneedtodownloadthedevelopment
environment(IDE)fromhere:
/>Choosetherightversionforyouroperatingsystem.
Downloadthefileanduncompressit.
Thefirstthingtodoistoinstallthedriversthatallowyourcomputertotalktoyourboard
throughtheUSBport.

Macintosh:
Lookforthe“Drivers”folderinsidethe“arduino-0004”folderanddouble-clickonthefile
calledFTDIUSBSerialDriver_v2_0_1.dmg.Whenthishasopened,installthesoftware
containedintheFTDIUSBSerialDriver.pkg.Attheendofthisprocessyou’llhaveto
restartyourmachinetomakesurethedriversapreproperlyloaded.Aftertheinstallationis
successfulyouwillalsoneedtorunthecommandcalled“macosx_setup.command”
Followtheinstructionsprovidedbytheprogramandtypethepasswordthatyouuseto
loginintoyourcomputerwhenasked.
Afterthisprogramhasrunsuccessfullyyouneedtoturnoffyourcomputer.Don’tjust
rebootorlogout,reallyturnitoffandbackonagain.
Whenthisphaseisoveryoucanplugtheboardintothecomputer.
Windows:
Unzipthefilecalled[FIXME]containedintheDriversdirectoryintoadirectoryyoucan
easilyfindlateron.
Plugtheboardintothecomputerand,whenthe[FIXME]NewDeviceFound[/FIXME]
windowcomesup,specifythelocationfortheinstallwizardtolookforthedrivers.
Thiswillhappentwicebecausethefirsttimethecomputerinstallsthelowleveldriver
thenapieceofcodethatmakestheboardlooklikeaserialport.
Oncethedriversareinstalledwecanlaunchthedevelopmentenvironmentandstartusing
Arduino.
Usingthedevelopmentenvironment
Aftertheapplicationhascomeupyouwillseeawindowlikethisone


Firstly,
youneedtofindoutwhichportyourdeviceisconnectedto
Macintosh:
Fromthe“Tools”menuselect“SerialPort”andselecttheportthatbeginswith“/dev/
cu.usbserial-“.Thelast3charactersidentifywhichoneistheUSBporttheboardis
pluggedtoandchangeifyouplugarduinointoadifferentport.

[PICscreenshotoftheTools/SerialPortmenushowingthelistofports]
Windows:
OnWindowstheprocessisabitcomplicatedatthebeginning.Openingthe“device
manger”from:
Startmenu->ControlPanel->System..->Hardware->DeviceManager
Lookforthedeviceinthelistunder“Ports(COM&LPT)”.
Arduinowillcomeupasan“USBSerialPort”andwillhaveanamelikeCOM4.[PIC
screenshotofthedevicemanagershowingarduino]
Note:ForsomereasonsonsomewindowsmachinetheCOMporthasanumbergreater
than9andthiscreatessomeproblemswhenArduinoistryingtocommunicatewithit.


CheckintheArduinotroubleshootingsectionofthewebsitehowtofixthat.
ThenintheIDE,selecttheappropriateportfromtheTools/SerialPortmenu.
NowtheArduinodevelopmentenvironmentcantalktotheArduinoboardandprogramit.

ReallyGettingStartedwithArduino
NowthatwehaveintroducedtheArduinophilosophyanditscomponentswearereadyto
makesomethinghappenwithyourboard.
Inthefollowingpageswewillgothroughafewexamplesofthebasicthingsyoucando
withArduino.Attheendoftheseexercisesyouarereadytoexperimentonyourown.
/theinteractivedevice
MostoftheobjectswewillbuildusingtheArduinoboardfollowaverysimplepattern
thatwecallthe“InteractiveDevice”
It’sanelectroniccircuitthatisabletosensetheenvironmentusingcomponentscalled
“sensors”andprocessingtheinformationthrough”behaviour”implementedassoftware.
Thedevicewillthenbeabletointeractbackwiththeworldusing“actuators”.
/sensorsandactuators
SensorsandActuatorsareelectroniccomponentsthatallowapieceofelectronicsto
interactwiththeworld.

Sincethemicrocontrollerisaverysimplecomputeritcanonlyprocesselectricsignals(a
bitliketheelectricpulsesthataresentbetweenneuronsinourbrains)inordertoenableit
tosenselight,temperatureorotherphysicalquantitiesitneedssomethingthatcanconvert
themintoelectricity.Inourbodytheeye,forexample,convertslightintosignalsthatget
senttothebrainusingnerveswhileintheelectronicwecoulduseasimpledevicecalled
LDRthatcanmeasuretheamountoflightthathitsitandreportitbackasasignalthatcan
beunderstoodbytheprocessor.[PICLDR.tiff]Oncethesensorshavebeenreadthe
devicehastheinformationneededto“decide”howtoreact.Thisisdonethrough
Actuators.Theseareelectroniccomponentsthatcanconvertanelectricsignalintoa
physicalaction.Forexamplein0urbodies,musclesreceiveelectricsignalsfromthebrain
andconvertthemintoamovementwhileintheelectronicworldthisfunctionscouldbe
performedbyanelectricmotor.[PICmotor_fan.tiff]
Inthenextchapterswewillseehowtoreadsensorsofdifferenttypesandcontroldifferent
kindsofactuators.
/basicintroductiontoprogramming
Someofyoumayneverhaveprogrammedbefore,ifyouhaveyoumayskipthispart.
Programmingisabouttranslatingthebehaviourwehaveinmindforourdeviceinto
instructionsthatcanbeunderstoodbytheprocessor.
Inrealitytheprocessorusesaverydetailedandverylow-levellanguagesothroughtime
“highlevel”languageshavebeendeveloped.Theseareabitmoreclosetohuman
languagesthaninstructionslike
lda0x0f

Let’sseehowwewouldgoabouttranslatingasimplebehaviourintoapieceofprogram.


Asimpleprogrammecanalwaysbemockedupassentence,forexample:Whenitisvery
darkIwantthelighttogoonandthemotortostartturningslowly
Wecouldthenrewritethisinto“pseudocode”(somethingthatlooksmorelikeaprogram
butit’sstillhumanlanguage):

Iflightlevelislessthan50thenTurnLighton
Turnmotoronslow
Loopagain

Wequicklyrealisethatweneedtwotypesofprogrammingstructures:loopsand
conditionalstatements.
Aloopisnecessarytoallowtheprocessortocontinuallyreadthestatesofitsinputsas
wellastoupdatethestatesofitsoutputs.Conditionalstatementswillbeusedtocheckfor
certainconditionsandchangethecourseoftheprogramdependingonthem.Sothebasic
Arduinoprogramlookslikethis:
//Thisisacomment
//variabledeclarationintx;
voidinit(){//putcodehere}
voidloop(){//putcodehere}

Atthebeginningoftheprogramwedeclarevariables,areasofmemoryusedtostoredata.
Thenthevoidinit()functionisusedtosetuptheprogram(definewhichpinsonthe
processorareinputsandwhichoneareoutputsetc)
Thelastfunction,voidloop(),willthenbeexecutedindefinitelyuntilyouturnthe
Arduinoboardoff.Sothisiswherewewantallourconditionallogictobestored.Itisthe
realprogramandwherewecancontroltheflowoftheprogram.
Thetextbeginningwith//isacomment,it’sveryusefulforyoutoremindyourselfwhat
yourcodedoeswhenyoure-openitafterawhileorforotherpeople
Variables
Onespecialthingaboutprogrammingisthateverytimeyouwanttostoresomevalueyou
needtouseavariablethatyouhavetodeclare.Thatis,tellthecomputerwhatkindof
valuetoexpect.Thereareafewbasicdatatypesthatacomputercanexpectthatwewill
gothroughhere:
intanintegerisawholenumberi.e.1,2,3,5etc.
byteanintegernumberbetween0and255,thisisusefulifyouneedtosavememory

becauseitusesonly1byteofmemory.(Rememberthatthearduinoboardhas
only1024bytesofRAM)
Formostoftheprogrammingyouwillbedoing,thesedatatypeswillbeallyouneed,to
gointomoredetail,see:[URLofarduinoreference]
Flowcontrol
If[condition]Then
InArduino,anifstatementlookslikethis:
if(expression){
statement;statement;
}

Wheretheexpressioncouldbeoneofthefollowing:


a==baequalsb
a!=baisnotequaltob
a>baisgreaterthanb
aa=<baislessthanorequalstoba>=baisgreaterthanorequalstob(N.B.donot
confuse==withtheassignmentoperator=thatactuallychangesthevalueofthevariable
totheleftofit,thiscanbeverydangerous!)
Statementscanbeanythingyoulike(includingmoreconditionalstatements).
Forloops
for(i=1;i<=8;i++){
statement;}

Aforloopisawaytoexecuteacertainpieceofcodeforaveryspecificamountoftimes.
Intheexampleshown“statement”isexecuted8timeswith“i”goingfrom1to8.
NoteInArduinoyoudon’tneedtoinitialisethelocalvariablei.Howeverinjava-based
languageslikeProcessingyouaddintinfrontofthefirstinstanceofi.

Delays
delay(100)//

Thedelay()functionisusefulforembeddedprogrammingtoslowdowntherateatwhich
theprocessorupdates.Thisisusedtomakethinghappensatacertainrate,forexampleif
wewanttoblinkandledeverysecond,afterweturnitonwecanplaceadelay(1000)
whichwillmaketheprocessorsitthereanddonothingforasecond(1000milliseconds)
Delayisalsousefulindebuggingandgeneralflowcontrol.
/blinkinganLED
ThisprogramisthefirstcodetoruntotestthatyourArduinoboardisworkingand
configuredcorrectly.TypethefollowingtextintoyourArduinoeditor.Nowthatthecode
isinyourIDEweneedtoverifyitanduploadittotheboard.Pressthe“Verify”button
andifeverythingiscorrectyou’llseethemessage“Donecompiling”appearatthebottom
oftheprogramtext.
Atthispointwecanuploaditintotheboard:presstheresetbuttonontheArduinoboard,
thisforcestheboardtostopwhatit’sdoingandlistenforinstructionscomingfromthe
USBport.Nowwehaveabout6or7secondstopressthe“UploadtoI/OBoard”button.
thissendsthecurrentprogramtotheboardthatwillstoreitinitsmemoryandeventually
runit.Youwillseeafewmessagesappearintheblackareaatthebottomofthewindow,
thesearemessagesthatmakeiteasiertounderstandiftheprocesshascompletedcorrectly.
Thereare2LEDsmarkedRXandTXontheboard,theyflasheverytimeabyteissentor
receivedbytheboard.Duringthedownloadprocesstheykeepflickering,ifthisdoesn’t
happenitmeansthereissomecommunicationproblemoryouhaven’tselectedtheright
portinthe“Tools/SerialPort”menu.
/*BlinkingLED
*–––—
*
*turnsonandoffanLEDconnectedtopin13*
*/
intledPin=13;//LEDconnectedto

voidsetup(){


pinMode(ledPin,OUTPUT);//setsthedigital
}
voidloop(){
digitalWrite(ledPin,HIGH);//turnstheLEDondelay(1000);//waitsforaseconddigitalWrite(ledPin,LOW);//turns
theLEDoffdelay(1000);//waitsforasecond
}

AssumingthatprogramhasbeenuploadedcorrectlyconnectanLEDtothepins13and
GNDontheboardlikeyouseeintheillustration.

/what
iselectricity
Ifyouhaveeverdoneanyplumbingathome,electronicswon’tbeaproblemforyouto
understand.Jokesaside,inordertounderstandhowelectricityandelectriccircuitswork
thebestwayistobuildamentalmodelcalledthe“wateranalogy”.Let’stakeasimple
devicelikeaportablefan,


ifyoutakeitapartyouwillseethatitcontainsasmallbatteryacoupleofwiresgoingto
anelectricmotorandoneofthewiresisinterruptedbyaswitch.Nowmakessureyou
haveanewbatteryfittedinthedeviceandactivatetheswitch;themotorwillstarttospin
providingthenecessaryrefreshment.Howdoesthiswork?Wellimaginethatthebatteryis
awaterpumpandtheswitchisatapwhilethemotorisoneofthosewheelsyouseein
watermills,whenyouopenthetapwaterwillflowfromthepumpandpushthewheelinto
motion.
Nowinthissimplehydraulicsystemtwoparametersareimportant:thepressureofthe
water(thisisgivenfromhowpowerfulisthepump)andtheamountofwaterthatwill

flowinthepipes(thisdependsfromthesizeofthepipesandtheresistancethatthewheel
willopposetothestreamofwaterhittingit).
Youquicklyunderstandthatifyouwantthewheeltospinfasteryouneedtoincreasethe
sizeofthepipes(butthisworksonlyuptoapoint)andincreasethepressurethatthe
pumpcanachieve.Increasingthesizeofthepipesallowsmoreflowofwatertogo
throughthem,effectivelybymakingthembiggerwehavereducedtheresistancethey
opposetotheflowofwater.Thisworksuntilacertainpointwherethewheelwon’tspin
anyfasterbecausethepressureofthewaterisnotstrongenoughandthisiswhenweneed
thepumptobestronger.


Thiscangoonuntilthepointwhenthewheelfallsapartbecausethewaterflowistoo
stronganddestroysit.Anotherthingyouwillnoticeisthatasthewheelspinstheaxlewill
heatupalittlebit,thisisbecausenomatterhowgoodisthewaywehavemountedthe
wheeltheattritionbetweentheaxleandtheholesitismountedinwillgenerateheat.This
isimportanttounderstandthatinasystemlikethisnotalltheenergyyoupumpintothe
systemwillbeconvertedintomovement,somewillbelostinanumberofinefficiencies
andwillgenerallyshowupasheatemanatingfromsomepartsofthesystem.
Sowhataretheimportantpartsofthesystemaswedescribeditbefore?Thepressure
producedbythepumpisone,theresistancethatthepipesandwheelopposetotheflowof
waterandtheactualflowofwater(let’ssaythatthisisrepresentedbythenumberoflitres
ofwaterthatflowinonesecond)aretheothers.
Withoutgoingintomuchdetailselectricityworksabitlikewater,youhaveakindof
pump(anysourceofelectricitylikeabatteryorawallplug)pusheselectriccharges
(imaginethemlike“drops”ofelectricity)downpipesrepresentedbythewireswhere
somedevicesareabletousethemtoproduceheat(yourgrandma’sthermalblanket)light
(yourbedroom’slamp)sound(yourstereo)movement(yourfan)andmuchmore.
Sowhenyoureadonabattery9VyoucanimaginetheVoltageofthebatterylikethe
waterpressurethatcanbepotentiallyproducedbythislittle“pump”.Thisismeasuredin
VoltsfromAlessandroVolta,theinventorofthefirstbattery.

Theflowofwaterhasgotandelectricequivalentcalled“current”thatismeasuredin
AmperesfromAndreMarieAmpere.Finallytheresistanceopposedtotheflowofcurrent
byanymeansittravelsthroughiscalled,yesyouguessedright,resistanceandit’s
measuredinOhmsfromtheGermanphysicistOhm.
Mrohmisalsoresponsibleforcomingupwiththemostimportantlawinelectricityand
theonlyformulayouwillreallyneedtoremember.
HewasabletodemonstratethatinacircuittheVoltage,theCurrentandtheResistanceare
allrelatedtoeachotherandinparticularthattheresistanceopposedbythecircuits


determinestheamountofcurrentthatwillflowthroughitgiveacertainsupplyvoltage.
It’sveryintuitiveifyouthinkaboutit:Takea9Vbatteryandplugitintoasimplecircuit
whilemeasuringcurrent,youwillfindthatthemoreresistorsyouaddtothecircuitthe
lesscurrentwilltravelthroughit.Goingbacktothewaterflowinginpipes,givenacertain
pumpifIplaceatap(whichwecanassimilatetoavariableresistorinelectricity)themore
Iclosethetap,increasingresistancetowaterflow,lesswaterwillflowthroughthepipes.
MrOhmsummarisedhislawintothisformulas:
R(resistance)=V(voltage)/I(current)
V=R*I
I=V/R
Thisistheonlyrulethatyoureallyhavetomemoriseandlearntouse,becauseinmostof
yourworkthiswillbetheonlyoneyouwillreallyneed.
/thebreadboard
Theprocessofgettingacircuittoworkislargelybasedonmakinglotsofchangestoit
untilitbehavesproperly;it’saveryfastiterativeprocessthatcouldbeseenasthe
electronicequivalenttosketching.Thedesignevolvesinyourhandsasyoutrydifferent
combinations.Inordertoachievethebestresultsyouwanttouseasystemthatwillallow
youtochangetheconnectionsbetweencomponentsinthefastest,mostpracticalandnondestructiveway.
Thisrequirementclearlyrulesoutsoldering,it’satimeconsumingprocedurethatputs
everycomponentunderstresseverytimeyouheatthemupandcoolthemdown.

Theanswertoourproblemscomesfromaverypracticaldevicecalled“Solder-less
Breadboard”.


Asyoucanseefromthepictureit’sasmallplasticboardfullofholes,eachoneofthem
containsaspring-loadedcontact.Youcanpushacomponent’slegintooneoftheholeand
itwillestablishanelectricalconnectionwithalltheotherholesinthesamevertical
columnofholes.Eachholeisatadistanceof2.54mmdistancefromtheothers,since
mostofthecomponentshavetheirlegs,knowntotechiesaspins,arespacedatthat
standarddistancethereforechipswithmultiplelegswillfitnicely.Notallthecontactson
abreadboardarecreatedequal,therearesomedifferences:thetopmostandbottomrow
(colouredinredandblueandaptlymarkedwith+and-)areconnectedhorizontallyand
areusedtocarrythepoweracrosstheboardsothatwhenweneedpowerorgroundwe
canprovideitveryquicklywithashortjumper(thisisnotasweaterorafunnyinsectbut
ashortpieceofwireusedtoconnecttwopointsinthecircuits)Thelastthisyouneedto
knowaboutbreadboardsistheinthemiddlethereisalargegapthatisaswideasthesize
ofasmallchip.Thisshowsthattheeachverticallineofholesisinterruptedinthemiddle
sothatwhenyouplugachipyouwon’tshortcircuitpinsthatareonthetwosidesofthe
chip,clevereh?
/readingapushbutton
Nowwe’regoingtoseehowArduinoisabletoreceiveinputfromtheexternalworld.
ThisisdonewiththedigitalRead()functionwhich,giventhenumberofapin,willtellyou
ifthereisavoltageappliedtoit.Ifthevoltageis2.5ormorevolts,digitalRead()will
returnHIGHwhileifthereisnovoltageitwillreturnLOW.
ThiscodechecksthestateofthedigitalpinandturnontheLEDifthebuttonispressed.
Verysimpleandwillgetyoustartedveryquickly,justbuildthecircuityouseeinthenext
page.
/*BlinkLEDwhenthebuttonispressed*––––––––
*/
intledPin=13;//choosethepinfortheLEDintinPin=7;//choosetheinputpin

//(forapushbutton)
intval=0;//variableforreadingthepinstatus
voidsetup(){
pinMode(ledPin,OUTPUT);//declareLEDasoutputpinMode(inPin,INPUT);//declarepushbuttonasinput
}
voidloop(){
val=digitalRead(inPin);//readinputvalue
//checkiftheinputisHIGH(buttonreleased)
if(val==HIGH){
digitalWrite(ledPin,LOW);//turnLEDOFF
}else{
//blinktheLEDandgoOFF
digitalWrite(ledPin,HIGH);
delay(200);
digitalWrite(ledPin,LOW);
delay(1000);
}


/tryingout
differenton/offsensors
Nowthatyou’veusedthepush-buttonyoucanreplaceitwithalotofdifferentsensorsthat
havethesametypeofoutput:acontactthatclosesandopens.
Onegoodexampleisthetiltsensor,thisisasimpleelectroniccomponentthatcontains
twocontactsandalittlemetalball.[PICoftiltsensors]Whenthesensorisinitsupright
positiontheballbridgesthetwocontactsandthisislikewhenyoupressthepush-button.
Whenyoutiltthissensortheballmovesandthecontactisopenedlikewhenyourelease
thepush-button.
Usingthissimplecomponentyoucanimplement,forexample,gesturalinterfacesthat
reactwhenanobjectismovedorshaken.

Anothersensoryoumightwanttotryistheinfra-redsensorfromburglaralarms(also
knownasPIRsensor).[PICofPIRsensors]Thissmalldevicetriggerswhenahuman
beingismovinginitsproximity.It’sasimplewaytodetectthepresenceofpeople.


Youshouldnowexperimentbylookingatallthepossibledevicesthathavetwocontacts
thatclose,likethethermostatthatisusedinapartmentstosettheroomtemperatureorjust
placingtwowiresnexttoeachothersanddroppingwaterontothem.
/usethelightsensorinsteadofthepushbutton
Nowwe’regoingtotryaninterestingexperiment:takealightsensorliketheonepictured
here.

ThisisanLDRorlightdependentresistor,thismeansthatindarknessitsresistanceis
quitehighwhilewhenyoushinesomelightatittheresistancequicklydropsandit
becomesareasonablygoodconductorofelectricity.NowplugtheLDRinplaceofthe
push-button,youwillnoticethatifyoucoveroruncoveritwithyourhandstheLEDturns
onandoff.You’vejustbuiltyourfirstsensordrivenLED.
/analogueinputs
AswehaveseenintheprevioussectionArduinoisabletodetectifthereisavoltage
appliedtooneofitspinsandreportittroughthedigitalReadfunction.Thisisfineinalot
ofapplicationsbutthelightsensorthatwehaveusedbeforeit’salsoabletotellusnotjust
ifthereislightornot,it’salsoabletotellushowmuchlightthereis.Thisisthedifference
betweenanon/offsensor(simplytellingusifsomethingisthereornot)andananalogue
sensorwhosevaluecontinuouslychanges.Inordertoreadthistypeofsensorsweneeda
differenttypeofpin.Inthelower-rightpartofArduinoyou’llsee6pinsmarked“Analog
In”,thesearespecialpinsthatnotonlycantellusifthereisavoltageappliedtothemor
notbutalsoitvalue.ByusingtheanalogReadfunctionwecanreadthevoltageappliedto
oneofthepins.Thisfunctionreturnsanumberbetween0and1023representingvoltages
between0and5volts.Forexampleifthereisavoltageof2.5voltsappliedtopin0



writinganalogRead(0)willreturn512etcetc.
Ifyounowbuildthecircuitthatyouseeintheillustrationbyusinga10kor4.7kresistor
andyourunthepieceofcodeyoufindhereyou’llseetheledblinkingataratethat’s
dependentontheamountoflightthathitsthesensor.

/*AnalogReadtoLED
*––––––
*copyleft2005DavidCuartielles*
*/
intsensorPin=0;//selecttheinputpinforthe//potentiometer
intledPin=13;//selectthepinfortheLED
intval=0;//variabletostorethevaluecoming//fromthesensor
voidsetup(){
pinMode(ledPin,OUTPUT);//ledPinisasanOUTPUT
}
voidloop(){
val=analogRead(sensorPin);//readthevaluefrom
digitalWrite(ledPin,HIGH);//turntheLEDondelay(val);//stoptheprogramfor
digitalWrite(ledPin,LOW);//turntheLEDoffdelay(val);//stoptheprogramfor
}

/trydifferentresistivesensors
Usingthesamecircuitthatyouhaveseenintheprevioussectionyoucanconnectalotof


otherresistivesensorsthaworkmoreorlessinthesameway.
Forexampleyoucouldconnectathermistor.

Thisisasimpledevicewhoseresistancechangeswithtemperature.Inthecircuitwehave

shownyouchangesinresistancebecomechangesinvoltagethatcanbemeasuredby
Arduino.
Beawarethatthereisn’tadirectconnectionbetweenthevalueyoureadtheactual
temperaturemeasured.Ifyouneedanexactreadingyoushouldreadthenumbersthat
comeoutoftheanaloguepinwhilemeasuringwitharealthermometer.Youcouldput
thesenumberssidebysideinatableandworkoutawaytofigureoutwhatisthe
relationshipbetweenthevalues.
UpuntilnowwehavejustusedanLEDasanoutputdevicebuthowdowereadtheactual
valuesthatArduinoisreadingfromthesensor?Certainlywecan’tmaketheboardblink
thevaluesinmorsecode.ForthistypeofissueswecanuseSerialCommunicationthatis
describedinthenextchapter.
/serialcommunication
WehaveseenatthebeginningofthebookletthatArduinohasanUSBconnectionthatis
usedbytheIDEtouploadcodeintotheprocessor.


×