Вы находитесь на странице: 1из 44

Getting

Started
with
Arduino
Massimo Banzi
|rst d|t|on
Getting Started with Arduino
by Massimo Banzi
Copyright ?009 Massino Banzi. All rights reserved.
Frinted in U.8.A.
Fublished by Make:Books, an inprint ol Maker Media,
a division ol O'Reilly Media, nc.
l005 Oravenstein Highway North, 8ebastopol, CA 954/?
O'Reilly books nay be purchased lor educational, business,
or sales pronotional use. For nore inlornation, contact our
corporate/institutional sales departnent: 8009989938
or corporateoreilly.con.
Print History: October ?008: First Edition
PubIisher: Dale Dougherty
Associate PubIisher: Dan Woods
Executive Editor: Brian Jepson
Creative Director: Daniel Carter
Designer: Brian 8cott
Production Manager: Terry Bronson
Copy Editor: Nancy Kotary
lndexer: Fatti 8chiendelnan
lIIustrations: Elisa Canducci
The O'Reilly logo is a registered tradenark ol O'Reilly Media, nc.
The Make: Fro|ects series designations and related trade dress
are tradenarks ol O'Reilly Media, nc. The tradenarks ol third
parties used in this work are the property ol their respective
owners.
Important Message to Our Readers: Your salety is your own
responsibility, including proper use ol equipnent and salety gear,
and deternining whether you have adequate skill and experi
ence. Electricity and other resources used lor these pro|ects are
dangerous unless used properly and with adequate precautions,
including salety gear. 8one illustrative photos do not depict
salety precautions or equipnent, in order to show the pro|ect
steps nore clearly. These pro|ects are not intended lor use by
children.
Use ol the instructions and suggestions in Cett|ng 5tarted w|th
Ardu|no is at your own risk. O'Reilly Media, nc. and the author
disclain all responsibility lor any resulting danage, in|ury, or
expense. t is your responsibility to nake sure that your activities
conply with applicable laws, including copyright.
8BN: 9/80596l555l3
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Ilntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .I
ntended Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z
What s Fhysical Conputing? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
ZThe Arduino Way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Frototyping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Tinkering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Fatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Circuit Bending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ID
Keyboard Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IZ
We Love Junkl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I4
Hacking Toys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I5
Collaboration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I6
3The Arduino PIatform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I9
The Arduino Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I9
The 8oltware (DE) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ZZ
nstalling Arduino on Your Conputer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ZZ
nstalling Drivers: Macintosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z3
nstalling Drivers: Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z3
Fort dentilcation: Macintosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z5
Fort dentilcation: Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z6
4ReaIIy Getting Started with Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Z9
8ensors and Actuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3D
Blinking an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3D
Fass Me the Farnesan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Arduino s Not lor Quitters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Real Tinkerers Write Connents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
The Code, 8tep by 8tep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
What We Will Be Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
What s Electricity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Using a Fushbutton to Control the LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Z
How Does This Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
One Circuit, A Thousand Behaviours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5Advanced lnput and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Trying Out Other On/Oll 8ensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Controlling Light with FWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Use a Light 8ensor nstead ol a Fushbutton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Z
Analogue nput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Try Other Analogue 8ensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
8erial Connunication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Driving Bigger Loads (Motors, Lanps, and the Like) . . . . . . . . . . . . . . . . . . . . . . . 7D
Conplex 8ensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7D
6TaIking to the CIoud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Flanning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Coding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Assenbling the Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Here's How to Assenble t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7TroubIeshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . S7
Testing the Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Testing Your Breadboarded Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
solating Froblens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9D
Froblens with the DE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9D
How to Oet Help Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9I
Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Appendix A/The Breadboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Appendix B/Reading Reistors and Capacitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Appendix C/The Quick Relerence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Appendix D/Reading 8chenatic Diagrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IID
Preface
A ew years ao was |ven a very |nterest|n
cha||ene. teach des|ners the bare n|n|nun
|n e|ectron|cs so that they cou|d bu||d |nter
act|ve rototyes o the obects they were
des|n|n.
started lollowing a subconscious instinct to teach electronics the sane
way was taught in school. Later on realised that it sinply wasn't working
as well as would like, and started to renenber sitting in a class, bored
like hell, listening to all that theory being thrown at ne without any practical
application lor it.
n reality, when was in school already knew electronics in a very enpirical
way: very little theory, but a lot ol handson experience.
started thinking about the process by which really learned electronics:
x took apart any electronic device could put ny hands on.
x slowly learned what all those conponents were.
x began to tinker with then, changing sone ol the connections inside
ol then and seeing what happened to the device: usually sonething
between an explosion and a pull ol snoke.
x started building sone kits sold by electronics nagazines.
x conbined devices had hacked, and repurposed kits and other circuits
that lound in nagazines to nake then do new things.
As a little kid, was always lascinated by discovering how things work,
therelore, used to take then apart. This passion grew as targeted any
unused ob|ect in the house and then took it apart into snall bits. Even
tually, people brought all sorts ol devices lor ne to dissect. My biggest
Preface v vi Getting Started with Arduino
pro|ects at the tine were a dishwasher and an early conputer that cane
lron an insurance ollce, which had a huge printer, electronics cards,
nagnetic card readers, and nany other parts that proved very interesting
and challenging to conpletely take apart.
Alter quite a lot ol this dissecting, knew what electronic conponents
were and roughly what they did. On top ol that, ny house was lull ol old
electronics nagazines that ny lather nust have bought at the beginning
ol the l9/0s. spent hours reading the articles and looking at the circuit
diagrans without understanding very nuch.
This process ol reading the articles over and over, with the benelt ol
knowledge acquired while taking apart circuits, created a slow virtuous
circle.
A great breakthrough cane one Christnas, when ny dad gave ne a kit
that allowed teenagers to learn about electronics. Every conponent was
housed in a plastic cube that would nagnetically snap together with other
cubes, establishing a connection, the electronic synbol was written on
top. Little did know that the toy was also a landnark ol Oernan design,
because Dieter Rans designed it back in the l960s.
With this new tool, could quickly put together circuits and try then out to
see what happened. The prototyping cycle was getting shorter and shorter.
Alter that, built radios, anplilers, circuits that would produce horrible
noises and nice sounds, rain sensors, and tiny robots.
've spent a long tine looking lor an English word that would sun up that
way ol working without a specilc plan, starting with one idea and ending
up with a conpletely unexpected result. Finally, tinkering cane along.
recognised how this word has been used in nany other lelds to describe
a way ol operating and to portray people who set out on a path ol explora
tion. For exanple, the generation ol French directors who gave birth to the
Nouvelle Vague were called the tinkerers. The best delnition ol tinkering
that 've ever lound cones lron an exhibition held at the Exploratoriun
in 8an Francisco:
T|nker|ng |s what happens when you try soneth|ng you dont qu|te know
how to do, gu|ded oy wh|n, |nag|nat|on, and cur|os|ty. \hen you t|nker,
there are no |nstruct|ons-out there are a|so no fa||ures, no r|ght or wrong
ways of do|ng th|ngs. lts aoout fgur|ng out how th|ngs work and rework|ng
then.
Contrapt|ons, nach|nes, w||d|y n|snatched oojects work|ng |n harnony-
th|s |s the stu of t|nker|ng.
T|nker|ng |s, at |ts nost oas|c, a process that narr|es p|ay and |nqu|ry.
-www.exploralorium.edu/linkering
Fron ny early experinents knew how nuch experience you would need
in order to be able to create a circuit that would do what you wanted start
ing lron the basic conponents.
Another breakthrough cane in the sunner ol l98?, when went to London
with ny parents and spent nany hours visiting the 8cience Museun.
They had |ust opened a new wing dedicated to conputers, and by lollow
ing a series ol guided experinents, learned the basics ol binary nath
and progranning.
There realised that in nany applications, engineers were no longer build
ing circuits lron basic conponents, but were instead inplenenting a lot
ol the intelligence in their products using nicroprocessors. 8oltware was
replacing nany hours ol electronic design, and would allow a shorter
tinkering cycle.
When cane back started to save noney, because wanted to buy a
conputer and learn how to progran.
My lrst and nost inportant pro|ect alter that was using ny brandnew
ZX8l conputer to control a welding nachine. know it doesn't sound like
a very exciting pro|ect, but there was a need lor it and it was a great chal
lenge lor ne, because had |ust learned how to progran. At this point, it
becane clear that writing lines ol code would take less tine than nodily
ing conplex circuits.
Twentyodd years later, 'd like to think that this experience allows ne to
teach people who don't even renenber taking any nath class and to inluse
then with the sane enthusiasn and ability to tinker that had in ny youth
and have kept ever since.
-Massino
Preface vii
viii Getting Started with Arduino
AcknowIedgments
This book is dedicaled lo Luisa and Alexandra.
Firsl o all I wanl lo lhank my parlners in lhe Arduino Team:
David Cuarlielles, David Mellis, Cianluca Marlino, and Tom Igoe.
Il is an amazing experience working wilh you guys.
Barbara Chella, she doesn'l know bul, wilhoul her precious
advice, Arduino and lhis book mighl have never happened.
Bill Verplank or having laughl me more lhan Physical Compuling.
Cillian CramplonSmilh or giving me a chance and or all I have
learned rom her.
Hernando Barragan or lhe work he has done on Wiring.
Brian Jepson or being a greal edilor and enlhusiaslic supporler
all along.
Nancy Kolary, Brian Scoll, Terry Bronson, and Palli Schiendelman
or lurning whal I wrole inlo a nished book.
I wanl lo lhank a lol more people bul Brian lells me I'm running
oul o space so I'll |usl lisl a small number o people I have lo
lhank or many reasons:
Adam SomlaiFisher, Ailadi Corlellelli, Alberlo Pezzolli,
Alessandro Cerminasi, Alessandro Masserdolli, Andrea Piccolo,
Anna Capellini, Casey Reas, Chris Anderson, Claudio Moderini,
Clemenlina Coppini, Concella Capecchi, Csaba Waldhauser,
Dario Buzzini, Dario Molinari, Dario Parravicini, Donala Piccolo,
Edoardo Brambilla, Elisa Canducci, Fabio Violanle, Fabio Zanola,
Fabrizio Pignoloni, Flavio Mauri, Francesca Mocellin, Francesco
Monico, Ciorgio Olivero, Ciovanna Cardi, Ciovanni Ballislini,
Healher Marlin, Jennier Bove, Laura Dellamolla, Lorenzo
Parravicini, Luca Rocco, Marco Baioni, Marco Eynard, Maria
Teresa Longoni, Massimiliano Bolondi, Malleo Rivolla, Mallhias
Richler, Maurizio Pirola, Michael Thorpe, Nalalia Jordan,
Ombrella Banzi, Oresle Banzi, Oscar Zoggia, Pielro Dore,
Pro Salvioni, Raaella Ferrara, Renzo Ciusli, Sandi Alhanas,
Sara Carpenlieri, Sigrid Wiederhecker, Sleano Mirli, Ubi De Feo,
Veronika Bucko.
How to Contact Us
We have veried lhe inormalion in lhis book lo lhe besl o our
abilily, bul you may nd lhings lhal have changed (or even lhal
we made mislakes!). As a reader o lhis book, you can help
us lo improve ulure edilions by sending us your eedback.
Please lel us know aboul any errors, inaccuracies, misleading
or conusing slalemenls, and lypos lhal you nd anywhere
in lhis book.
Please also lel us know whal we can do lo make lhis book more
useul lo you. We lake your commenls seriously and will lry
lo incorporale reasonable suggeslions inlo ulure edilions.
You can wrile lo us al:
Maker Media
l005 Cravenslein Highway Norlh
Sebaslopol, CA 95472
(800) 9989938 (in lhe U.S. or Canada)
(707) 82905l5 (inlernalional/local)
(707) 8290l04 (ax)
Maker Media is a division o O'Reilly Media devoled enlirely lo
lhe growing communily o resourceul people who believe lhal
i you can imagine il, you can make il. Consisling o MAKE
magazine, CRAFT magazine, Maker Faire, as well as lhe Hacks,
Make:Pro|ecls, and DIY Science book series, Maker Media
encourages lhe DoIlYoursel menlalily by providing crealive
inspiralion and inslruclion.
For more information about Maker Media, visit us onIine:
MAKE www.makezine.com
CRAFT: www.cralzine.com
Maker Faire: www.makeraire.com
Hacks: www.hackszine.com
To commenl on lhe book, send email lo
bookqueslionsoreilly.com.
The O'Reilly web sile or Cett|ng 5tarted w|th Ardu|no lisls
examples, errala, and plans or ulure edilions. You can nd
lhis page al www.makezine.com/gelslarledarduino.
For more inormalion aboul lhis book and olhers, see lhe
O'Reilly web sile: www.oreilly.com.
For more inormalion aboul Arduino, including discussion
orums and urlher documenlalion, see www.arduino.cc.
Preface ix
Ilntroduction

Ardu|no |s an oen source hys|ca| conut|n
|atorn based on a s|n|e |nutoutut
(O) board and a deve|onent env|ronnent
that |n|enents the Frocess|n |anuae
(www.processing.org). Ardu|no can be used
to deve|o standa|one |nteract|ve obects
or can be connected to sotware on your
conuter (such as |ash, Frocess|n, VVVV,
or MaxMcF). The boards can be assenb|ed
by hand or urchased reassenb|ed, the
oen source D (nterated Deve|onent
nv|ronnent) can be down|oaded or ree
ron www.arduino.cc.
Arduino is dillerent lron other platlorns on the narket because ol these
leatures:
x t is a nultiplatlorn environnent, it can run on Windows, Macintosh,
and Linux.
x t is based on the Frocessing progranning DE, an easytouse
developnent environnent used by artists and designers.
x You progran it via a U8B cable, not a serial port. This leature is uselul,
because nany nodern conputers don't have serial ports.
x t is open source hardware and soltware-il you wish, you can
download the circuit diagran, buy all the conponents, and nake your
own, without paying anything to the nakers ol Arduino.
Introduction 1 2 Getting Started with Arduino
x The hardware is cheap. The U8B board costs about ?0 (currently,
about U8S35) and replacing a burntout chip on the board is easy and
costs no nore than 5 or U8S4. 8o you can allord to nake nistakes.
x There is an active connunity ol users, so there are plenty ol people
who can help you.
x The Arduino Fro|ect was developed in an educational environnent and
is therelore great lor newconers to get things working quickly.
This book is designed to help beginners understand what benelts they
can get lron learning how to use the Arduino platlorn and adopting its
philosophy.
lntended Audience
This book was written lor the original Arduino users: designers and
artists. Therelore, it tries to explain things in a way that night drive sone
engineers crazy. Actually, one ol then called the introductory chapters
ol ny lrst dralt lull. That's precisely the point. Let's lace it: nost
engineers aren't able to explain what they do to another engineer, let
alone a regular hunan being. Let's now delve deep into the lull.
NOTE: Arduino buiIds upon the thesis work Hernando Barragan did on
the Wiring pIatform whiIe studying under Casey Reas and me at IDII
Ivrea.
Alter Arduino started to becone popular, realised how experinenters,
hobbyists, and hackers ol all sorts were starting to use it to create beauti
lul and crazy ob|ects. realised that you're all artists and designers in
your own right, so this book is lor you as well.
Arduino was born to teach nteraction Design, a design discipline that
puts prototyping at the centre ol its nethodology. There are nany delni
tions ol nteraction Design, but the one that preler is:

Interaction Design is the design of any interactive experience.
n today's world, nteraction Design is concerned with the creation
ol neaninglul experiences between us (hunans) and ob|ects. t is a
good way to explore the creation ol beautilul-and naybe even contro
versial-experiences between us and technology. nteraction Design
encourages design through an iterative process based on prototypes
ol everincreasing ldelity. This approach-also part ol sone types
ol conventional design-can be extended to include prototyping with
technology, in particular, prototyping with electronics.
The specilc leld ol nteraction Design involved with Arduino is Fhysical
Conputing (or Fhysical nteraction Design).
What ls PhysicaI Computing?
Fhysical Conputing uses electronics to prototype new naterials lor
designers and artists.
t involves the design ol interactive ob|ects that can connunicate with
hunans using sensors and actuators controlled by a behaviour inple
nented as soltware running inside a nicrocontroller (a snall conputer
on a single chip).
n the past, using electronics neant having to deal with engineers all the
tine, and building circuits one snall conponent at the tine, these issues
kept creative people lron playing around with the nediun directly. Most
ol the tools were neant lor engineers and required extensive knowledge.
n recent years, nicrocontrollers have becone cheaper and easier to use,
allowing the creation ol better tools.
The progress that we have nade with Arduino is to bring these tools one
step closer to the novice, allowing people to start building stull alter only
two or three days ol a workshop.
With Arduino, a designer or artist can get to know the basics ol electronics
and sensors very quickly and can start building prototypes with very little
investnent.
Introduction 3
ZThe Arduino Way

The Ardu|no h||osohy |s based on na||n
des|ns rather than ta|||n about then. t |s
a constant search or aster and nore ower
u| ways to bu||d better rototyes. \e have
ex|ored nany rototy|n techn|ques and
deve|oed ways o th|n||n w|th our hands.
Classic engineering relies on a strict process lor getting lron A to B,
the Arduino Way delights in the possibility ol getting lost on the way and
lnding C instead.
This is the tinkering process that we are so lond ol-playing with the
nediun in an openended way and lnding the unexpected. n this search
lor ways to build better prototypes, we also selected a nunber ol solt
ware packages that enable the process ol constant nanipulation ol the
soltware and hardware nediun.
The next lew sections present sone philosophies, events, and pioneers
that have inspired the Arduino Way.
The Arduino Way 5 6 Getting Started with Arduino
Frototyping is at the heart ol the Arduino Way: we nake things and build
ob|ects that interact with other ob|ects, people, and networks. We strive
to lnd a sinpler and laster way to prototype in the cheapest possible way.
A lot ol beginners approaching electronics lor the lrst tine think that they
have to learn how to build everything lron scratch. This is a waste ol
energy: what you want is to be able to conlrn that sonething's working
very quickly so that you can notivate yoursell to take the next step or
naybe even notivate sonebody else to give you a lot ol cash to do it.
This is why we developed opportunistic prototyping: why spend tine
and energy building lron scratch, a process that requires tine and in
depth technical knowledge, when we can take readynade devices and
hack then in order to exploit the hard work done by large conpanies
and good engineers?
Our hero is Janes Dyson, who nade 5l?/ prototypes ol his vacuun
cleaner belore he was satisled that he'd gotten it right (www.inlernalional.
dyson.com/|d/l947.asp).
Frototyping Tinkering
We believe that it is essential to play with technology, exploring dillerent
possibilities directly on hardware and soltware-sonetines without a
very delned goal.
Reusing existing technology is one ol the best ways ol tinkering. Oetting
cheap toys or old discarded equipnent and hacking then to nake then
do sonething new is one ol the best ways to get to great results.
The Arduino Way 7
8 Getting Started with Arduino
Fatching
have always been lascinated by nodularity and the ability to build conplex
systens by connecting together sinple devices. This process is very well
represented by Robert Moog and his analogue synthesizers. Musicians
constructed sounds, trying endless conbinations by patching together
dillerent nodules with cables. This approach nade the synthesizer look
like an old telephone switch, but conbined with the nunerous knobs, that
was the perlect platlorn lor tinkering with sound and innovating nusic.
Moog described it as a process between witnessing and discovering.
'n sure nost nusicians at lrst didn't know what all those hundreds ol
knobs did, but they tried and tried, relning their own style with no inter
ruptions in the low.
Reducing the nunber ol interruptions to the low is very inportant lor
creativity-the nore seanless the process, the nore tinkering happens.
This technique has been translated into the world ol soltware by visual
progranning environnents like Max, Fure Data, or VVVV. These tools
can be visualised as boxes lor the dillerent lunctionalities that they pro
vide, letting the user build patches by connecting these boxes together.
These environnents let the user experinent with progranning without
the constant interruption typical ol the usual cycle: type progran,
conpile, dann-there is an error, lx error, conpile, run. l you are nore
visually ninded, reconnend that you try then out.
The Arduino Way 9 10 Getting Started with Arduino
Circuit Bending
Circuit bending is one ol the nost interesting lorns ol tinkering. t's the
creative shortcircuiting ol lowvoltage, batterypowered electronic audio
devices such as guitar ellect pedals, children's toys, and snall synthesiz
ers to create new nusical instrunents and sound generators. The heart
ol this process is the art ol chance. t began in l966 when Reed Ohazala,
by chance, shortedout a toy anpliler against a netal ob|ect in his desk
drawer, resulting in a strean ol unusual sounds. What like about circuit
benders is their ability to create the wildest devices by tinkering away with
technology without necessarily understanding what they are doing on the
theoretical side.
t's a bit like the 5n|n C|ue lanzine shown here: during the punk era,
knowing three chords on a guitar was enough to start a band. Don't let the
experts in one leld tell you that you'll never be one ol then. gnore then
and surprise then.
The Arduino Way 11 12 Getting Started with Arduino
Keyboard Hacks
Conputer keyboards are still the nain way to interact with a conputer
alter nore than 60 years. Alex Fentland, acadenic head ol the MT Media
Laboratory, once renarked: Excuse the expression, but nen's urinals
are snarter than conputers. Conputers are isolated lron what's around
then.
l

As tinkerers, we can inplenent new ways to interact with soltware by
replacing the keys with devices that are able to sense the environnent.
Taking apart a conputer keyboard reveals a very sinple (and cheap) de
vice. The heart ol it is a snall board. t's nornally a snelly green or brown
circuit with two sets ol contacts going to two plastic layers that hold the
connections between the dillerent keys. l you renove the circuit and use
a wire to bridge two contacts, you'll see a letter appear on the conputer
screen. l you go out and buy a notionsensing detector and connect
this to your keyboard, you'll see a key being pressed every tine sone
body walks in lront ol the conputer. Map this to your lavourite soltware,
and you have nade your conputer as snart as a urinal. Learning about
keyboard hacking is a key building block ol prototyping and Fhysical
Conputing.
The Arduino Way 13
l
Quoted in 8ara Reese Hedberg, MT Media Lab's quest lor perceptive conputers, ntelligent 8ystens and
Their Applications, EEE, Jul/Aug l998.
14 Getting Started with Arduino
We Love Junkl
Feople throw away a lot ol technology these days: old printers, conput
ers, weird ollce nachines, technical equipnent, and even a lot ol nilitary
stull. There has always been a big narket lor this surplus technology,
especially anong young and/or poorer hackers and those who are |ust
starting out. This narket becone evident in vrea, where we developed
Arduino. The city used to be the headquarters ol the Olivetti conpany.
They had been naking conputers since the l960s, in the nid l990s, they
threw everything away in |unkyards in the area. These are lull ol con
puter parts, electronic conponents, and weird devices ol all kinds. We
spent countless hours there, buying all sorts ol contraptions lor very little
noney and hacking into our prototypes. When you can buy a thousand
loudspeakers lor very little noney, you're bound to cone up with sone
idea in the end. Accunulate |unk and go through it belore starting to build
sonething lron scratch.
Hacking Toys
Toys are a lantastic source ol cheap technology to hack and reuse, as
evidenced by the practise ol circuit bending nentioned earlier. With the
current inlux ol thousands ol very cheap hightech toys lron China, you
can build quick ideas with a lew noisy cats and a couple ol light swords.
have been doing this lor a lew years to get ny students to understand
that technology is not scary or dillcult to approach. One ol ny lavourite
resources is the booklet Low Tech 8ensors and Actuators by Usnan
Haque and Adan 8onlaiFischer (lowlech.proposilions.org.uk). think
that they have perlectly described this technique in that handbook, and
have been using it every since.
The Arduino Way 15 16 Getting Started with Arduino
Collaboration
Collaboration between users is one ol they key principles in the Arduino
world-through the lorun at www.arduino.cc, people lron dillerent parts
ol the world help each other learn about the platlorn. The Arduino tean
encourages people to collaborate at a local level as well by helping then
set up users' groups in every city they visit. We also set up a Wiki called
Flayground (www.arduino.cc/playground) where users docunent their
lndings. t's so anazing to see how nuch knowledge these people pour
out on the Web lor everybody to use. This culture ol sharing and helping
each other is one ol the things that 'n nost proud ol in regard to Arduino.
3The Arduino PIatform
Ardu|no |s conosed o two naor arts. the
Ardu|no board, wh|ch |s the |ece o hardware
you wor| on when you bu||d your obects, and
the Ardu|no D, the |ece o sotware you run
on your conuter. +ou use the D to create
a s|etch (a ||tt|e conuter roran) that you
u|oad to the Ardu|no board. The s|etch te||s
the board what to do.
Not too long ago, working on hardware neant building circuits lron
scratch, using hundreds ol dillerent conponents with strange nanes like
resistor, capacitor, inductor, transistor, and so on.
Every circuit was wired to do one specilc application, and naking
changes required you to cut wires, solder connections, and nore.
With the appearance ol digital technologies and nicroprocessors, these
lunctions, which were once inplenented with wires, were replaced by
soltware prograns.
8oltware is easier to nodily than hardware. With a lew keypresses, you can
radically change the logic ol a device and try two or three versions in the
sane anount ol tine that it would take you to solder a couple ol resistors.
The Arduino Hardware
The Arduino board is a snall nicrocontroller board, which is a snall circuit
(the board) that contains a whole conputer on a snall chip (the nicro
controller). This conputer is at least a thousand tines less powerlul than
the MacBook 'n using to write this, but it's a lot cheaper and very uselul
to build interesting devices. Look at the Arduino board: you'll see a black
chip with ?8 legs-that chip is the ATnegal68, the heart ol your board.
The Arduino Platform 19 20 Getting Started with Arduino
We (the Arduino tean) have placed on this board all the conponents
that are required lor this nicrocontroller to work properly and to con
nunicate with your conputer. There are nany versions ol this board, the
one we'll use throughout this book is the Arduino Duenilanove, which is
the sinplest one to use and the best one lor learning on. However, these
instructions apply to earlier versions ol the board, including the nore
recent Arduino Diecinila and the older Arduino NO. Figure 3l shows the
Arduino Duenilanove, Figure 3? shows the Arduino NO.
n those illustrations, you see the Arduino board. At lrst, all those con
nectors night be a little conlusing. Here is an explanation ol what every
elenent ol the board does:
I4 DigitaI IO pins (pins D-I3)
These can be inputs or outputs, which is speciled by the sketch you
create in the DE.
6 AnaIogue In pins (pins D-5)
These dedicated analogue input pins take analogue values (i.e., voltage
readings lron a sensor) and convert then into a nunber between 0 and
l0?3.
6 AnaIogue Out pins (pins 3, 5, 6, 9, ID, and II)
These are actually six ol the digital pins that can be reprogranned lor
analogue output using the sketch you create in the DE.
The board can be powered lron your conputer's U8B port, nost U8B
chargers, or an AC adapter (9 volts reconnended, ?.lnn barrel tip,
center positive). l there is no power supply plugged into the power
socket, the power will cone lron the U8B board, but as soon as you plug
a power supply, the board will autonatically use it.
NOTE: If you are using the oIder ArduinoNG or Arduino DiecimiIa,
you wiII need to set the power seIection jumper (IabeIIed PWR_SEL on
the board) to specify EXT (externaI) or USB power. This jumper can be
found between the pIug for the AC adapter and the USB port.
Figure 3-1. The Arduino Duemilanove
Figure 3-2. The Arduino NG
The Arduino Platform 21
22 Getting Started with Arduino
The Software {lDE)
The DE (ntegrated Developnent Environnent) is a special progran
running on your conputer that allows you to write sketches lor the
Arduino board in a sinple language nodeled alter the Frocessing
(www.processing.org) language. The nagic happens when you press
the button that uploads the sketch to the board: the code that you have
written is translated into the C language (which is generally quite hard lor
a beginner to use), and is passed to the avrgcc conpiler, an inportant
piece ol open source soltware that nakes the lnal translation into the
language understood by the nicrocontroller. This last step is quite inpor
tant, because it's where Arduino nakes your lile sinple by hiding away as
nuch as possible ol the conplexities ol progranning nicrocontrollers.
The progranning cycle on Arduino is basically as lollows:
x Flug your board into a U8B port on your conputer.
x Write a sketch that will bring the board to lile.
x Upload this sketch to the board through the U8B connection and wait
a couple ol seconds lor the board to restart.

x The board executes the sketch that you wrote.
NOTE: InstaIIing Arduino on Linux is somewhat compIicated at the time
of this writing. See www.arduino.cc/playground/Learning/Linux for
compIete instructions.
lnstaIIing Arduino on Your Computer
To progran the Arduino board, you nust lrst download the developnent
environnent (the DE) lron here: www.arduino.cc/en/Main/Solware.
Choose the right version lor your operating systen.
Download the lle and doubleclick on it to unconpress it, this will create
a lolder naned ardu|nojvers|on], such as ardu|no00I2. Drag that lolder
to wherever you would like it to be: your desktop, your App||cat|ons lolder
(on a Mac), or your C.\Progran l||es lolder (on Windows). Now whenever
you want to run the Arduino DE, you'll open up the ardu|no lolder, and
doubleclick the Arduino icon. Don't do this |ust yet, though, there is one
nore step to perlorn.
NOTE: If you have any troubIe running the Arduino IDE, see Chapter 7,
TroubIeshooting.

Now you nust install the drivers that allow your conputer to talk to your
board through the U8B port.
lnstaIIing Drivers: Macintosh
Look lor the Dr|vers lolder inside the ardu|no00I2 lolder and doubleclick
the lle called lTDlU5B5er|a|Dr|ver_x_x_x.dng (x_x_x will be replaced
with the version nunber ol the driver, lor exanple lTDlU5B5er|a|Dr|ver_
v2_2_9_lnte|.dng). Doubleclick the .dng lle to nount it.
NOTE: If you are using an InteIbased Mac, such as a MacBook, Mac
Book Pro, MacBook Air, Mac Pro, or InteIbased Mac Mini or iMac, be
sure to instaII the driver with InteI" in its name, as in =K;@LJ9J\i`Xc$
;i`m\iVm)V)V0V@ek\c%[d^. If you aren't using an InteIbased Mac, instaII
the one without InteI" in its name.
Next, install the soltware lron the FTDU8B8erialDriver package by
doubleclicking on it. Follow the instructions provided by the installer and
type the password ol an adninistrative user il asked. At the end ol this
process, restart your nachine to nake sure that the drivers are properly
loaded. Now plug the board into your conputer. The FWR light on the
board should cone on and the yellow LED labelled L should start blink
ing. l not, see Chapter /, Troubleshooting.
lnstaIIing Drivers: Windows
Flug the Arduino board into the conputer, when the Found New Hard
ware Wizard window cones up, Windows will lrst try to lnd the driver on
the Windows Update site.
Windows XF will ask you whether to check Windows Update, il you don't
want to use Windows Update, select the No, not at this tine option and
click Next.
On the next screen, choose nstall lron a list or specilc location and
click Next.
The Arduino Platform 23 24 Getting Started with Arduino
Check the box labeled nclude this location in the search, click Browse,
select the lolder where you installed Arduino, and select the Dr|vers\lTDl
U5B Dr|vers lolder as the location. Click OK, and Next.
Windows Vista will lrst attenpt to lnd the driver on Windows Update, il
that lails, you can instruct it to look in the Dr|vers\lTDl U5B Dr|vers lolder.
You'll go through this procedure twice, because the conputer lrst installs
the lowlevel driver, then installs a piece ol code that nakes the board
look like a serial port to the conputer.
Once the drivers are installed, you can launch the Arduino DE and start
using Arduino.
Next, you nust lgure out which serial port is assigned to your Arduino
board-you'll need that inlornation to progran it later. The instructions
lor getting this inlornation are in the lollowing sections.
Port ldentication: Macintosh
Fron the Tools nenu in the Arduino DE, select 8erial Fort and select
the port that begins with devcu.usoser|a|, this is the nane that your
conputer uses to reler to the Arduino board. Figure 33 shows the list
ol ports.
Figure 3-3.
The Arduino IDEs list of serial ports
The Arduino Platform 25 26 Getting Started with Arduino
Port ldentication: Windows
On Windows, the process is a bit nore conplicated-at least at the begin
ning. Open the Device Manager by clicking the 8tart nenu, rightclicking
on Conputer (Vista) or My Conputer (XF), and choosing Froperties. On
Windows XF, click Hardware and choose Device Manager. On Vista, click
Device Manager (it appears in the list ol tasks on the lelt ol the window).
Look lor the Arduino device in the list under Forts (COM & LFT). The
Arduino will appear as a U8B 8erial Fort and will have a nane like COM3,
as shown in Figure 34.
Figure 3-4.
The Windows Device Manager showing all available serial ports
NOTE: On some Windows machines, the COM port has a number
greater than 9; this numbering creates some probIems when Arduino is
trying to communicate with it. See Chapter 7, TroubIeshooting for heIp
on this probIem.
Once you've lgured out the COM port assignnent, you can select that
port lron the Tools ~ 8erial Fort nenu in the Arduino DE.
Now the Arduino developnent environnent can talk to the Arduino board
and progran it.
The Arduino Platform 27
4ReaIIy Getting Started
with Arduino
Now you|| |earn how to bu||d and roran an
|nteract|ve dev|ce.
Anatomy of an lnteractive Device
All ol the ob|ects we will build using Arduino lollow a very sinple pattern
that we call the nteractive Device. The nteractive Device is an electronic
circuit that is able to sense the environnent using sensors (electronic
conponents that convert realworld neasurenents into electrical signals).
The device processes the inlornation it gets lron the sensors with
behaviour that's inplenented as soltware. The device will then be able to
interact with the world using actuators, electronic conponents that can
convert an electric signal into a physical action.
Really Getting Started with Arduino 29
Figure 4-1.
The interactive device
Sensors
Actuators
Behavior
(software)
Sense/Perceive
Act/React
30 Getting Started with Arduino
Sensors and Actuators
8ensors and actuators are electronic conponents that allow a piece ol
electronics to interact with the world.
As the nicrocontroller is a very sinple conputer, it can process only
electric signals (a bit like the electric pulses that are sent between neurons
in our brains). For it to sense light, tenperature, or other physical quantities,
it needs sonething that can convert then into electricity. n our body, lor
exanple, the eye converts light into signals that get sent to the brain using
nerves. n electronics, we can use a sinple device called a lightdependent
resistor (an LDR or photoresistor) that can neasure the anount ol light
that hits it and report it as a signal that can be understood by the nicro
controller.
Once the sensors have been read, the device has the inlornation needed
to decide how to react. The decisionnaking process is handled by the
nicrocontroller, and the reaction is perlorned by actuators. n our bodies,
lor exanple, nuscles receive electric signals lron the brain and convert
then into a novenent. n the electronic world, these lunctions could be
perlorned by a light or an electric notor.
n the lollowing sections, you will learn how to read sensors ol dillerent
types and control dillerent kinds ol actuators.
BIinking an LED
The LED blinking sketch is the lrst progran that you should run to test
whether your Arduino board is working and is conlgured correctly. t is also
usually the very lrst progranning exercise soneone does when learning
to progran a nicrocontroller. A lightenitting diode (LED) is a snall elec
tronic conponent that's a bit like a light bulb, but is nore ellcient and
requires lower voltages to operate.
Your Arduino board cones with an LED preinstalled. t's narked L. You
can also add your own LED-connect it as shown in Figure 4?.
K indicates the cathode (negative), or shorter lead, A indicates the anode
(positive), or longer lead.
Once the LED is connected, you need to tell Arduino what to do. This is
done through code, that is, a list ol instructions that we give the nicro
controller to nake it do what we want.
Really Getting Started with Arduino 31
Figure 4-2.
Connecting an LED to Arduino
32 Getting Started with Arduino
On your conputer, go open the lolder where you copied the Arduino DE.
Doubleclick the Arduino icon to start it. 8elect File ~ New and you'll be
asked to choose a sketch lolder nane: this is where your Arduino sketch
will be stored. Nane it B||nk|ng_lD and click OK. Then, type the lollowing
text (Exanple 0l) into the Arduino sketch editor (the nain window ol
the Arduino DE). You can also download it lron www.makezine.com/
gelslarledarduino. t should appear as shown in Figure 43.
// Example 01 : Blinking LED
#dene LED 13 // LED connected to
// digital pin 13
void setup()
{
pinMode(LED, OUTPUT); // sets the digital
// pin as output
}
void loop()
{
digitalWrite(LED, HIGH); // turns the LED on
delay(1000); // waits for a second
digitalWrite(LED, LOW); // turns the LED off
delay(1000); // waits for a second
}
Figure 4-3.
The Arduino IDE with your rst sketch loaded
Now that the code is in your DE, you need to verily that it is correct. Fress
the Verily button (Figure 43 shows its location), il everything is correct,
you'll see the nessage Done conpiling appear at the botton ol the
Arduino DE. This nessage neans that the Arduino DE has translated
your sketch into an executable progran that can be run by the board, a
bit like an .exe lle in Windows or an .app lle on a Mac.
At this point, you can upload it into the board: press the Upload to /O
Board button (see Figure 43). This will reset the board, lorcing it to stop
what it's doing and listen lor instructions coning lron the U8B port. The
Arduino DE sends the current sketch to the board, which will store it in
its nenory and eventually run it.
Verify Upload to I/O board
Your sketch goes here
Really Getting Started with Arduino 33 34 Getting Started with Arduino
You will see a lew nessages appear in the black area at the botton ol the
window, and |ust above that area, you'll see the nessage Done upload
ing appear to let you know the process has conpleted correctly. There
are two LEDs, narked RX and TX, on the board, these lash every tine
a byte is sent or received by the board. During the upload process, they
keep lickering.
l you don't see the LEDs licker, or il you get an error nessage instead ol
Done uploading, then there is a connunication problen between your
conputer and Arduino. Make sure you've selected the right serial port (see
Chapter 3) in the Tools ~ 8erial Fort nenu. Also, check the Tools ~ Board
nenu to conlrn that the correct nodel ol Arduino is selected there.
l you are still having problens, check Chapter /, Troubleshooting.
Once the code is in your Arduino board, it will stay there until you put
another sketch on it. The sketch will survive il the board is reset or turned
oll, a bit like the data on your conputer's hard drive.
Assuning that the sketch has been uploaded correctly, you will see the
LED L turn on lor a second and then turn oll lor a second. l you installed
a separate LED as shown back in Figure 4?, that LED will blink, too.
What you have |ust written and ran is a conputer progran, or sketch,
as Arduino prograns are called. Arduino, as 've nentioned belore, is a
snall conputer, and it can be progranned to do what you want. This is
done using a progranning language to type a series ol instructions in
the Arduino DE, which turns it into an executable lor your Arduino board.
'll next show you how to understand the sketch. First ol all, the Arduino
executes the code lron top to botton, so the lrst line at the top is the
lrst one read, then it noves down, a bit like how the playhead ol a video
player like QuickTine Flayer or Windows Media Flayer noves lron lelt
to right showing where in the novie you are.
Pass Me the Parmesan
Notice the presence ol curly brackets, which are used to group together
lines ol code. These are particularly uselul when you want to give a nane
to a group ol instructions. l you're at dinner and you ask sonebody,
Flease pass ne the Farnesan cheese, this kicks oll a series ol actions
that are sunnarised by the snall phrase that you |ust said. As we're
hunans, it all cones naturally, but all the individual tiny actions required
to do this nust be spelled out to the Arduino, because it's not as powerlul
as our brain. 8o to group together a nunber ol instructions, you stick a (
belore your code and an ] alter.
You can see that there are two blocks ol code that are delned in this way
here. Belore each one ol then there is a strange connand:
void setup()
This line gives a nane to a block ol code. l you were to write a list ol
instructions that teach Arduino how to pass the Farnesan, you would
write vo|d passTheParnesan() at the beginning ol a block, and this block
would becone an instruction that you can call lron anywhere in the
Arduino code. These blocks are called functions. l alter this, you write
passTheParnesan() anywhere in your code, Arduino will execute those
instructions and continue where it lelt oll.
Arduino ls Not for Quitters
Arduino expects two lunctions to exists-one called setup() and one
called |oop().
setup() is where you put all the code that you want to execute once at the
beginning ol your progran and |oop() contains the core ol your progran,
which is executed over and over again. This is done because Arduino is
not like your regular conputer-it cannot run nultiple prograns at the
sane tine and prograns can't quit. When you power up the board, the
code runs, when you want to stop, you |ust turn it oll.
ReaI Tinkerers Write Comments
Any text beginning with is ignored by Arduino. These lines are connents,
which are notes that you leave in the progran lor yoursell, so that you can
renenber what you did when you wrote it, or lor sonebody else, so that
they can understand your code.
t is very connon ( know this because do it all the tine) to write a piece
ol code, upload it onto the board, and say Okay-'n never going to have
to touch this sucker againl only to realise six nonths later that you need
to update the code or lx a bug. At this point, you open up the progran,
and il you haven't included any connents in the original progran, you'll
think, Wow-what a nessl Where do start? As we nove along, you'll
see sone tricks lor how to nake your prograns nore readable and easier
to naintain.
Really Getting Started with Arduino 35 36 Getting Started with Arduino
The Code, Step by Step
At lrst, you night consider this kind ol explanation to unnecessary, a
bit like when was in school and had to study Dante's D|v|na Conned|a
(every talian student has to go through that, as well as another book
called l proness| spos|, or The Betrothed-oh, the nightnares). For each
line ol the poens, there were a hundred lines ol connentaryl However,
the explanation will be nuch nore uselul here as you nove on to writing
your own prograns.
// Example 01 : Blinking LED
A connent is a uselul way lor us to write little notes. The preceding title
connent |ust reninds us that this progran, Exanple 0l, blinks an LED.
#dene LED 13 // LED connected to
// digital pin 13
#defne is like an autonatic search and replace lor your code, in this
case, it's telling Arduino to write the nunber l3 every tine the word lD
appears. The replacenent is the lrst thing done when you click Verily or
Upload to /O Board (you never see the results ol the replacenent as it's
done behind the scenes). We are using this connand to specily that the
LED we're blinking is connected to the Arduino pin l3.
void setup()
This line tells Arduino that the next block ol code will be called setup().
{
With this opening curly bracket, a block ol code begins.
pinMode(LED, OUTPUT); // sets the digital
// pin as output
Finally, a really interesting instruction. p|nMode tells Arduino how to con
lgure a certain pin. Digital pins can be used either as NFUT or OUTFUT.
n this case, we need an output pin to control our LED, so we place the
nunber ol the pin and its node inside the parentheses. p|nMode is a lunc
tion, and the words (or nunbers) speciled inside the parentheses are
arguments. NFUT and OUTFUT are constants in the Arduino language.
(Like variables, constants are assigned values, except that constant val
ues are predelned and never change.)
}
This closing curly bracket signiles the end ol the setup() lunction.
void loop()
{
|oop() is where you specily the nain behaviour ol your interactive device.
t will be repeated over and over again until you switch the board oll.
digitalWrite(LED, HIGH); // turns the LED on
As the connent says, d|g|ta|\r|te() is able to turn on (or oll) any pin that
has been conlgured as an OUTFUT. The lrst argunent (in this case, lD)
speciles which pin should be turned on or oll (renenber that lD is a
constant value that relers to pin l3, so this is the pin that's switched). The
second argunent can turn the pin on (HOH) or oll (LOW).
nagine that every output pin is a tiny power socket, like the ones you
have on the walls ol your apartnent. European ones are ?30 V, Anerican
ones are ll0 V, and Arduino works at a nore nodest 5 V. The nagic here
is when soltware becones hardware. When you write d|g|ta|\r|te(lD,
HlCH), it turns the output pin to 5 V, and il you connect an LED, it will light
up. 8o at this point in your code, an instruction in soltware nakes sone
thing happen in the physical world by controlling the low ol electricity to
the pin. Turning on and oll the pin at will now let us translate these into
sonething nore visible lor a hunan being, the LED is our actuator.
delay(1000); // waits for a second
Arduino has a very basic structure. Therelore, il you want things to happen
with a certain regularity, you tell it to sit quietly and do nothing until it is
tine to go to the next step. de|ay() basically nakes the processor sit
there and do nothing lor the anount ol nilliseconds that you pass as
an argunent. Milliseconds are thousands ol seconds, therelore, l000
nilliseconds equals l second. 8o the LED stays on lor one second here.
digitalWrite(LED, LOW); // turns the LED off
This instruction now turns oll the LED that we previously turned on. Why
do we use HOH and LOW? Well, it's an old convention in digital electronics.
HOH neans that the pin is on, and in the case ol Arduino, it will be set at
5 V. LOW neans 0 V. You can also replace these argunents nentally with
ON and OFF.
delay(1000); // waits for a second
Here, we delay lor another second. The LED will be oll lor one second.
}
This closing curly bracket narks end ol the loop lunction.
Really Getting Started with Arduino 37
38 Getting Started with Arduino
To sun up, this progran does this:
x Turns pin l3 into an output (|ust once at the beginning)

x Enters a loop
x 8witches on the LED connected to pin l3
x Waits lor a second

x 8witches oll the LED connected to pin l3
x Waits lor a second

x Ooes back to beginning ol the loop

hope that wasn't too painlul. You'll learn nore about how to progran as
you go through the later exanples.
Belore we nove on to the next section, want you to play with the code.
For exanple, reduce the anount ol delay, using dillerent nunbers lor
the on and oll pulses so that you can see dillerent blinking patterns. n
particular, you should see what happens when you nake the delays very
snall, but use dillerent delays lor on and oll . . . there is a nonent when
sonething strange happens, this sonething will be very uselul when
you learn about pulsewidth nodulation later in this book.
What We WiII Be BuiIding
have always been lascinated by light and the ability to control dillerent
light sources through technology. have been lucky enough to work on
sone interesting pro|ects that involve controlling light and naking it
interact with people. Arduino is really good at this. Throughout this book,
we will be working on how to design interactive lanps, using Arduino
as a way to learn the basics ol how interactive devices are built.
n the next section, 'll try to explain the basics ol electricity in a way that
would bore an engineer, but won't scare a new Arduino progranner.
What ls EIectricity?
l you have done any plunbing at hone, electronics won't be a problen
lor you to understand. To understand how electricity and electric circuits
work, the best way is to use sonething called the water analogy. Let's
take a sinple device, like the batterypowered portable lan shown in
Figure 44.
Figure 4-4.
A portable fan
l you take a lan apart, you will see that it contains a snall battery, a
couple ol wires, and an electric notor, and that one ol the wires going to
the notor is interrupted by a switch. l you have a lresh battery in it and
turn the switch on, the notor will start to spin, providing the necessary
Really Getting Started with Arduino 39 40 Getting Started with Arduino
chill. How does this work? Well, inagine that the battery is both a water
reservoir and a punp, the switch is a tap, and the notor is one ol those
wheels that you see in waternills. When you open the tap, water lows
lron the punp and pushes the wheel into notion.
n this sinple hydraulic systen, shown in Figure 45, two lactors are
inportant: the pressure ol the water (this is deternined by the power ol
punp) and the anount ol water that will low in the pipes (this depends on
the size ol the pipes and the resistance that the wheel will provide to the
strean ol water hitting it).
Figure 4-5.
A hydraulic system
You'll quickly realise that il you want the wheel to spin laster, you need to
increase the size ol the pipes (but this works only up to a point) and in
crease the pressure that the punp can achieve. ncreasing the size ol the
pipes allows a greater low ol water to go through then, by naking then
bigger, we have ellectively reduced the pipes' resistance to the low ol
water. This approach works up to a certain point, at which the wheel won't
spin any laster, because the pressure ol the water is not strong enough.
When we reach this point, we need the punp to be stronger. This nethod
ol speeding up the waternill can go on until the point when the wheel lalls
apart because the water low is too strong lor it and it is destroyed.
Another thing you will notice is that as the wheel spins, the axle will heat
up a little bit, because no natter how well we have nounted the wheel,
the lriction between the axle and the holes in which it is nounted in will
generate heat. t is inportant to understand that in a systen like this, not
all the energy you punp into the systen will be converted into novenent,
sone will be lost in a nunber ol inellciencies and will generally show up
as heat enanating lron sone parts ol the systen.
8o what are the inportant parts ol the systen? The pressure produced by
the punp is one, the resistance that the pipes and wheel oller to the low
ol water, and the actual low ol water (let's say that this is represented
by the nunber ol litres ol water that low in one second) are the others.
Electricity works a bit like water. You have a kind ol punp (any source
ol electricity, like a battery or a wall plug) that pushes electric charges
(inagine then as drops ol electricity) down pipes, which are repre
sented by the wires-sone devices are able to use these to produce heat
(your grandna's thernal blanket), light (your bedroon lanp), sound
(your stereo), novenent (your lan), and nuch nore.
8o when you read that a battery's voltage is 9 V, think ol this voltage like
the water pressure that can potentially be produced by this little punp.
Voltage is neasured in volts, naned alter Alessandro Volta, the inventor
ol the lrst battery.
Just as water pressure has an electric equivalent, the low rate ol water
does, too. This is called current, and is neasured in anperes (alter
AndreMarie Anpere, electronagnetisn pioneer). The relationship
between voltage and current can be illustrated by returning to the water
wheel: a higher voltage (pressure) lets you spin a wheel laster, a higher
low rate (current) lets you spin a larger wheel.
Finally, the resistance opposing the low ol current over any path that it
travels is called-you guessed it-resistance, and is neasured in ohns
(alter the Oernan physicist Oeorg Ohn). Herr Ohn was also responsible
lor lornulating the nost inportant law in electricity-and the only lornula
that you really need to renenber. He was able to denonstrate that in a
circuit the voltage, the current, and the resistance are all related to each
other, and in particular that the resistance ol a circuit deternines the
anount ol current that will low through it, given a certain voltage supply.
t's very intuitive, il you think about it. Take a 9 V battery and plug it into
a sinple circuit. While neasuring current, you will lnd that the nore resis
tors you add to the circuit, the less current will travel through it. Ooing back
to the analogy ol water lowing in pipes, given a certain punp, il install
a valve (which we can relate to a variabIe resistor in electricity), the nore
Really Getting Started with Arduino 41 42 Getting Started with Arduino
close the valve-increasing resistance to water low-the less water will
low through the pipes. Ohn sunnarised his law in these lornulae:
R (resistance) = V (voltage) / I (current)
V = R * I
I = V / R
This is the only rule that you really have to nenorise and learn to use,
because in nost ol your work, this is the only one that you will really need.
Using a Pushbutton to ControI the LED
Blinking an LED was easy, but don't think you would stay sane il your
desk lanp were to continuously blink while you were trying to read a
book. Therelore, you need to learn how to control it. n our previous
exanple, the LED was our actuator, and our Arduino was controlling it.
What is nissing to conplete the picture is a sensor.
n this case, we're going to use the sinplest lorn ol sensor available:
a pushbutton.
l you were to take apart a pushbutton, you would see that it is a very
sinple device: two bits ol netal kept apart by a spring, and a plastic cap
that when pressed brings the two bits ol netal into contact. When the bits
ol netal are apart, there is no circulation ol current in the pushbutton (a bit
like when a water valve is closed), when we press it, we nake a connection.
To nonitor the state ol a switch, there's a new Arduino instruction that
you're going to learn: the d|g|ta|Read() lunction.
d|g|ta|Read() checks to see whether there is any voltage applied to the
pin that you specily between parentheses, and returns a value ol HOH or
LOW, depending on its lndings. The other instructions that we've used so
lar haven't returned any inlornation-they |ust executed what we asked
then to do. But that kind ol lunction is a bit linited, because it will lorce
us to stick with very predictable sequences ol instructions, with no input
lron the outside world. With d|g|ta|Read(), we can ask a question ol
Arduino and receive an answer that can be stored in nenory sonewhere
and used to nake decisions innediately or later.
Build the circuit shown in Figure 46. To build this, you'll need to obtain sone
parts (these will cone in handy as you work on other pro|ects as well):
Figure 4-6.
Hooking up a pushbutton
x 8olderless breadboard: Radio8hack (www.radioshack.com) part
nunber ?/600?, Maker 8hed (www.makershed.com) part nunber
MKKN3. Appendix A is an introduction to the solderless breadboard.

x Frecut |unper wire kit: Radio8hack ?/6l/3, Maker 8hed MKKN4
x One l0K Ohn resistor: Radio8hack ?/ll335 (5pack), 8parkFun
(www.sparkun.com) COM083/4
x Monentary tactile pushbutton switch: 8parkFun COM0009/
Really Getting Started with Arduino 43
44 Getting Started with Arduino
NOTE: instead of buying precut jumper wire, you can aIso buy ZZ AWG
soIidcore hookup wire in smaII spooIs and cut and strip it using wire
cutters and wire strippers.
Let's have a look at the code that we'll be using to control the LED with our
pushbutton:
// Example 02: Turn on LED while the button is pressed
#dene LED 13 // the pin for the LED
#dene BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == HIGH) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
n Arduino, select File ~ New (il you have another sketch open, you nay
want to save it lrst). When Arduino asks you to nane your new sketch
lolder, type FushButtonControl. Type the Exanple 0? code into Arduino
(or download it lron www.makezine.com/gelslarledarduino and paste
it into the Arduino DE). l everything is correct, the LED will light up when
you press the button.
How Does This Work?
have introduced two new concepts with this exanple progran: lunctions
that return the result ol their work and the |f statenent.
The |f statenent is possibly the nost inportant instruction in a progran
ning language, because it allows the conputer (and renenber, the
Arduino is a snall conputer) to nake decisions. Alter the |f keyword,
you have to write a question inside parentheses, and il the answer,
or result, is true, the lrst block ol code will be executed, otherwise, the
block ol code alter else will be executed. Notice that have used the ==
synbol instead ol =. The lorner is used when two entities are conpared,
and returns TRUE or FAL8E, the latter assigns a value to a variable. Make
sure that you use the correct one, because it is very easy to nake that
nistake and use |ust =, in which case your progran will never work. know,
because alter ?5 years ol progranning, still nake that nistake.
Holding your lnger on the button lor as long as you need light is not
practical. Although it would nake you think about how nuch energy
you're wasting when you walk away lron a lanp that you lelt on, we need
to lgure out how to nake the on button stick.
One Circuit, A Thousand Behaviours
The great advantage ol digital, progrannable electronics over classic
electronics now becones evident: will show you how to inplenent nany
dillerent behaviours using the sane electronic circuit as in the previous
section, |ust by changing the soltware.
As 've nentioned belore, it's not very practical to have to hold your lnger
on the button to have the light on. We therelore nust inplenent sone
lorn ol nenory, in the lorn ol a soltware nechanisn that will renen
ber when we have pressed the button and will keep the light on even alter
we have released it.
To do this, we're going to use what is called a variabIe. (We have used
one already, but haven't explained it.) A variable is a place in the Arduino
nenory where you can store data. Think ol it like one ol those sticky
notes you use to renind yoursell about sonething, such as a phone
nunber: you take one, you write Luisa 0? 555 l?l? on it, and you stick
it to your conputer nonitor or your lridge. n the Arduino language,
it's equally sinple: you |ust decide what type ol data you want to store
(a nunber or sone text, lor exanple), give it a nane, and when you want
to, you can store the data or retrieve it. For exanple:
int val = 0;
|nt neans that your variable will store an integer nunber, va| is the nane
ol the variable, and = 0 assigns it an initial value ol zero.
Really Getting Started with Arduino 45 46 Getting Started with Arduino
A variable, as the nane intinates, can be nodiled anywhere in your
code, so that later on in your progran, you could write:
val = 112;
which reassigns a new value, ll?, to your variable.

NOTE: Have you noticed that in Arduino, every instruction, with one
exception (#defne), ends with a semicoIon? This is done so that the
compiIer (the part of Arduino that turns your sketch into a program
that the microcontroIIer can run) knows that your statement is hnished
and a new one is beginning. Remember to use it aII the time, excIuding
any Iine that begins with #defne. The #defnes are repIaced by the
compiIer before the code is transIated into an Arduino executabIe.
n the lollowing progran, va| is used to store the result ol d|g|ta|Read(),
whatever Arduino gets lron the input ends up in the variable and will
stay there until another line ol code changes it. Notice that variables use
a type ol nenory called RAM. t is quite last, but when you turn oll your
board, all data stored in RAM is lost (which neans that each variable is re
set to its initial value when the board is powered up again). Your prograns
thenselves are stored in lash nenory-this is the sane type used by
your nobile phone to store phone nunbers-which retains its content
even when the board is oll.

Let's now use another variable to renenber whether the LED has to stay
on or oll alter we release the button. Exanple 03A is a lrst attenpt at
achieving that:
// Example 03A: Turn on LED when the button is pressed
// and keep it on after it is released
#dene LED 13 // the pin for the LED
#dene BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int state = 0; // 0 = LED off while 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop() {
val = digitalRead(BUTTON); // read input value and store it
// check if the input is HIGH (button pressed)
// and change the state
if (val == HIGH) {
state = 1 - state;
}
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
Now go test this code. You will notice that it works . . . sonewhat. You'll
lnd that the light changes so rapidly that you can't reliably set it on or oll
with a button press.

Let's look at the interesting parts ol the code: state is a variable that
stores either 0 or l to renenber whether the LED is on or oll. Alter the
button is released, we initialise it to 0 (LED oll).
Really Getting Started with Arduino 47 48 Getting Started with Arduino
Later, we read the current state ol the button, and il it's pressed (va| ==
HlCH), we change state lron 0 to l, or vice versa. We do this using a snall
trick, as state can be only either l or 0. The trick use involves a snall
nathenatical expression based on the idea that l - 0 is l and l - l is 0:
state = 1 state;
The line nay not nake nuch sense in nathenatics, but it does in pro
granning. The synbol = neans assign the result ol what's alter ne to
the variable nane belore ne-in this case, the new value ol state is as
signed the value ol l ninus the old value ol state.

Later in the progran, you can see that we use state to lgure out whether
the LED has to be on or oll. As nentioned, this leads to sonewhat laky
results.

The results are laky because ol the way we read the button. Arduino is
really last, it executes its own internal instructions at a rate ol l6 nillion
per second-it could well be executing a lew nillion lines ol code per sec
ond. 8o this neans that while your lnger is pressing the button, Arduino
night be reading the button's position a lew thousand tines and chang
ing state accordingly. 8o the results end up being unpredictable, it night
be oll when you wanted it on, or vice versa. As even a broken clock is right
twice a day, the progran night show the correct behaviour every once
in a while, but nuch ol the tine it will be wrong.

How do we lx this? Well, we need to detect the exact nonent when the
button is pressed-that is the only nonent that we have to change state.
The way like to do it is to store the value ol va| belore read a new one,
this allows ne to conpare the current position ol the button with the
previous one and change state only when the button becones HOH alter
being LOW.

Exanple 03B contains the code to do so:
// Example 03B: Turn on LED when the button is pressed
// and keep it on after it is released
// Now with a new and improved formula!
#dene LED 13 // the pin for the LED
#dene BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
Test it: we're alnost therel
You nay have noticed that this approach is not entirely perlect, due to
another issue with nechanical switches. Fushbuttons are very sinple
devices: two bits ol netal kept apart by a spring. When you press the
Really Getting Started with Arduino 49
50 Getting Started with Arduino
button, the two contacts cone together and electricity can low. This
sounds lne and sinple, but in real lile the connection is not that perlect,
especially when the button is not conpletely pressed, and it generates
sone spurious signals called bouncing.
When the pushbutton is bouncing, the Arduino sees a very rapid sequence
ol on and oll signals. There are nany techniques developed to do
debouncing, but in this sinple piece ol code 've noticed that it's usually
enough to add a l0 to 50nillisecond delay when the code detects a
transition.
Exanple 03C is the lnal code:
Really Getting Started with Arduino 51
// Example 03C: Turn on LED when the button is pressed
// and keep it on after it is released
// including simple de-bouncing
// Now with another new and improved formula!!
#dene LED 13 // the pin for the LED
#dene BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
5Advanced lnput
and Output
\hat you have ust |earned |n Chater 4 are
the nost e|enentary oerat|ons we can do |n
Ardu|no. contro|||n d||ta| outut and read|n
d||ta| |nut. Ardu|no were sone sort o
hunan |anuae, those wou|d be two |etters
o |ts a|habet. Cons|der|n that there are ust
ve |etters |n th|s a|habet, you can see how
nuch nore wor| we have to do beore we can
wr|te Ardu|no oetry.
Trying Out Other OnZOff Sensors
Now that you've learned how to use a pushbutton, you should know that
there are nany other very basic sensors that work according to the sane
principle:
Switches
Just like a pushbutton, but doesn't autonatically change state when
released
Thermostats
A switch that opens when the tenperature reaches a set value
Magnetic switches (also known as reed relays")
Has two contacts that cone together when they are near a nagnet, used
by burglar alarns to detect when a window is opened
Carpet switches
8nall nats that you can place under a carpet or a doornat to detect the
presence ol a hunan being (or heavy cat)
Advanced Input and Output 53 54 Getting Started with Arduino
TiIt switches
A sinple electronic conponent that contains two contacts and a little
netal ball (or a drop ol nercury, but don't reconnend using those)
An exanple ol a tilt switch is called a tilt sensor. Figure 5l shows the
inside ol a typical nodel. When the sensor is in its upright position, the
ball bridges the two contacts, and this works |ust as il you had pressed
a pushbutton. When you tilt this sensor, the ball noves, and the contact
is opened, which is |ust as il you had released a pushbutton. Using this
sinple conponent, you can inplenent, lor exanple, gestural interlaces
that react when an ob|ect is noved or shaken.
Figure 5-1.
The inside of a tilt sensor
Another sensor that you night want to try is the inlrared sensor as lound
in burglar alarns (also known as a passive inlrared or FR sensor, see
Figure 5?). This snall device triggers when a hunan being (or other living
being) noves within its proxinity. t's a sinple way to detect notion.
Figure 52.
Typical PIR sensor
Advanced Input and Output 55
56 Getting Started with Arduino
You should now experinent by looking at all the possible devices that
have two contacts that close, like the thernostat that sets a roon's ten
perature (use an old one that's no longer connected), or |ust placing two
contacts next to each other and dropping water onto then.
For exanple, by using the lnal exanple lron Chapter 4 and a FR sensor,
you could nake your lanp respond to the presence ol hunan beings, or
you could use a tilt switch to build one that turns oll when it's tilted on
one side.
ControIIing Light with PWM
With the knowledge that you have so lar gained, you could build an
interactive lanp that can be controlled-and not |ust with a boring on/oll
switch, but naybe in a way that's a bit nore elegant. One ol the linita
tions ol the blinking LED exanples that we have used so lar is that you
can turn the light only on and oll. A lancy interactive lanp needs to be
dinnable. To solve this problen, we can use a little trick that nakes a lot
ol things such as TV or cinena possible: persistence ol vision.
As hinted alter the lrst exanple in Chapter 4, il you change the nun
bers in the delay lunction until you don't see the LED blinking any nore,
you will notice that the LED seens to be dinned at 50 ol its nornal
brightness. Now change the nunbers so that the LED is on is one quarter
ol the tine that it's oll. Run the sketch and you'll see that the brightness
is roughly ?5. This technique is called puIse width moduIation (PWM),
a lancy way ol saying that il you blink the LED last enough, you don't see
it blink any nore, but you can change its brightness by changing the ratio
between the on tine and the oll tine. Figure 53 shows how this works.
This technique also works with devices other than an LED. For exanple,
you can change the speed ol a notor in the sane way.
While experinenting, you will see that blinking the LED by putting delays
in your code is a bit inconvenient, because as soon as you want to read a
sensor or send data on the serial port, the LED will licker while it's waiting
lor you to lnish reading the sensor. Luckily, the processor used by the
Arduino board has a piece ol hardware that can very ellciently blink three
LEDs while your sketch does sonething else. This hardware is inple
nented in pins 9, l0, and ll, which can be controlled by the ana|og\r|te()
instruction.
Figure 5-3.
PWM in action
Advanced Input and Output 57 58 Getting Started with Arduino
For exanple, writing ana|og\r|te(9,I28) will set the brightness ol an LED con
nected to pin 9 to 50. Why l?8? ana|og\r|te() expects a nunber between 0
and ?55 as an argunent, where ?55 neans lull brightness and 0 neans oll.
NOTE: Having three channeIs is very good, because if you buy red,
green, and bIue LEDs, you can mix their Iights and make Iight of any
coIour that you Iike!
Let's try it out. Build the circuit that you see in Figure 54. Note that LEDs
are polarized: the long pin (positive) should go to the right, and the short
pin (negative) to the lelt. Also, nost LEDs have a lattened negative side,
as shown in the lgure.
Figure 5-4.
LED connected to PWM pin
Then, create a new sketch in Arduino and use Exanple 04 (you can also
download code exanples lron www.makezine.com/gelslarledarduino):
// Example 04: Fade an LED in and out like on
// a sleeping Apple computer
#dene LED 9 // the pin for the LED
int i = 0; // Well use this to count up and down
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
}
void loop(){
for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms because analogWrite
// is instantaneous and we would
// not see any change
}
for (i = 255; i > 0; i--) { // loop from 255 to 1 (fade out)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms
}
}
Now you have a replicated a lancy leature ol a laptop conputer (naybe
it's a bit ol a waste to use Arduino lor sonething so sinple). Let's the use
this knowledge to inprove our lanp.
Add the circuit we used to read a button (back in Chapter 4) to this bread
board. 8ee il you can do this without looking at the next page, because
want you to start thinking about the lact that each elenentary circuit
show here is a building block to nake bigger and bigger pro|ects. l
you need to peek ahead, don't worry, the nost inportant thing is that you
spend sone tine thinking about how it night look.
Advanced Input and Output 59 60 Getting Started with Arduino
To create this circuit, you will need to conbine the circuit you |ust built
(shown in Figure 54) with the pushbutton circuit shown in Figure 46.
l you'd like, you can sinply build both circuits on dillerent parts ol the
breadboard, you have plenty ol roon. However, one ol the advantages
ol the breadboard (see Appendix A) is that there is a pair ol rails running
horizontally across the botton and top. One is narked red (lor positive)
and the other blue or black (lor ground).
These rails are used to distribute power and ground to where it's needed.
n the case ol the circuit you need to build lor this exanple, you have
two conponents (both ol then resistors) that need to be connected
to the OND (ground) pin on the Arduino. Because the Arduino has two
OND pins, you could sinply connect these two circuits exactly as shown
in each ol the two lgures, |ust hook then both up to the Arduino at the
sane tine. Or, you could connect one wire lron the breadboard's ground
rail to one ol the OND pins on the Arduino, and then take the wires that
are connected to OND in the lgures and connect then instead to the
breadboard ground rail.
l you're not ready to try this, don't worry: sinply wire up both circuits to
your Arduino as shown in Figures 46 and 54. You'll see an exanple that
uses the ground and positive breadboard rails in Chapter 6.

Oetting back to this next exanple, il we have |ust one pushbutton, how
do we control the brightness ol a lanp? We're going to learn yet another
interaction design technique: detecting how long a button has been
pressed. To do this, need to upgrade exanple 03C lron Chapter 4 to
add dinning. The idea is to build an interlace in which a press and
release action switches the light on and oll, and a press and hold action
changes brightness.
Let's have a look at the sketch:
// Example 05: Turn on LED when the button is pressed
// and keep it on after it is released
// including simple de-bouncing.
// If the button is held, brightness changes.
#dene LED 9 // the pin for the LED
#dene BUTTON 7 // input pin of the pushbutton
int val = 0; // stores the state of the input pin
int old_val = 0; // stores the previous value of "val"
int state = 0; // 0 = LED off while 1 = LED on
int brightness = 128; // Stores the brightness value
unsigned long startTime = 0; // when did we begin pressing?
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop() {

val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)) {

state = 1 - state; // change the state from off to on
// or vice-versa
startTime = millis(); // millis() is the Arduino clock
// it returns how many milliseconds
// have passed since the board has
// been reset.
// (this line remembers when the button
// was last pressed)
delay(10);
}
Advanced Input and Output 61
62 Getting Started with Arduino

// check whether the button is being held down
if ((val == HIGH) && (old_val == HIGH)) {
// If the button is held for more than 500ms.
if (state == 1 && (millis() - startTime) > 500) {
brightness++; // increment brightness by 1
delay(10); // delay to avoid brightness going
// up too fast
if (brightness > 255) { // 255 is the max brightness
brightness = 0; // if we go over 255
// lets go back to 0
}
}
}
old_val = val; // val is now old, lets store it
if (state == 1) {
analogWrite(LED, brightness); // turn LED ON at the
// current brightness level
} else {
analogWrite(LED, 0); // turn LED OFF
}
}
Now try it out. As you can see, our interaction nodel is taking shape. l
you press the button and release it innediately, you switch the lanp on
or oll. l you hold the button down, the brightness changes, |ust let go
when you have reached the desired brightness.
Now let's learn how to use sone nore interesting sensors.
Use a Light Sensor lnstead of the Pushbutton
Now we're going to try an interesting experinent. Take a light sensor,
like the one pictured in Figure 55. You can get a lvepack ol these lron
Radio8hack (part nunber ?/6-l65/).
Figure 5-5.
Light-dependent resistor (LDR)
n darkness, the resistance ol a lightdependent resistor (LDR) is quite
high. When you shine sone light at it, the resistance quickly drops and it
becones a reasonably good conductor ol electricity. t is thus a kind ol
lightactivated switch.
Build the circuit that cane with Exanple 0? (see Using a Fushbutton to
Control the LED in Chapter 4), then upload the code lron Exanple 0? to
your Arduino.
Now plug the LDR onto the breadboard instead ol the pushbutton. You
will notice that il you cover the LDR with your hands, the LED turns oll.
Uncover the LDR, and the light goes on. You've |ust built your lrst real
sensordriven LED. This is inportant because lor the lrst tine in this
book, we are using an electronic conponent that is not a sinple nechani
cal device: it's a real rich sensor.
Advanced Input and Output 63 64 Getting Started with Arduino
AnaIogue lnput
As you learned in the previous section, Arduino is able to detect whether
there is a voltage applied to one ol its pins and report it through the
d|g|ta|Read() lunction. This kind ol either/or response is lne in a lot ol
applications, but the light sensor that we |ust used is able to tell us not
|ust whether there is light, but also how nuch light there is. This is the
dillerence between an on/oll sensor (which tells us whether sonething
is there) and an analogue sensor, whose value continuously changes.
n order to read this type ol sensor, we need a dillerent type ol pin.
n the lowerright part ol the Arduino board, you'll see six pins narked
Analog n, these are special pins that can tell us not only whether
there is a voltage applied to then, but il so, also its value. By using the
ana|ogRead() lunction, we can read the voltage applied to one ol the pins.
This lunction returns a nunber between 0 and l0?3, which represents
voltages between 0 and 5 volts. For exanple, il there is a voltage ol ?.5 V
applied to pin nunber 0, ana|ogRead(0) returns 5l?.
l you now build the circuit that you see in Figure 56, using a l0k resistor,
and run the code listed in Exanple 06A, you'll see the onboard LED
(you could also insert your own LED into pins l3 and OND as shown in
Blinking an LED in Chapter 4) blinking at a rate that's dependent upon
the anount ol light that hits the sensor.
Figure 5-6.
An analogue sensor circuit
Advanced Input and Output 65 66 Getting Started with Arduino
// Example 06A: Blink LED at a rate specied by the
// value of the analogue input
#dene LED 13 // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup() {
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop() {
val = analogRead(0); // read the value from
// the sensor
digitalWrite(13, HIGH); // turn the LED on
delay(val); // stop the program for
// some time
digitalWrite(13, LOW); // turn the LED off
delay(val); // stop the program for
// some time
}
Now, try Exanple 06B: but belore you do, you'll need to nodily your
circuit. Take a look at Figure 54 again and hook the LED up to pin 9 as
shown. Because you've already got sone stull on the breadboard, you'll
need to lnd a spot on the breadboard where the LED, wires, and resistor
won't overlap with the LDR circuit.
// Example 06B: Set the brightness of LED to
// a brightness specied by the
// value of the analogue input
#dene LED 9 // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup() {
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop() {
val = analogRead(0); // read the value from
// the sensor
analogWrite(LED, val/4); // turn the LED on at
// the brightness set
// by the sensor

delay(10); // stop the program for
// some time
}
NOTE: we specify the brightness by dividing mXc by 4, because
XeXcf^I\X[ returns a number up to IDZ3, and XeXcf^Ni`k\
accepts a maximum of Z55.
Advanced Input and Output 67
68 Getting Started with Arduino
Try Other AnaIogue Sensors
Using the sane circuit that you have seen in the previous section, you
can connect a lot ol other resistive sensors that work in nore or less the
sane way. For exanple, you could connect a thernistor, which is a sinple
device whose resistance changes with tenperature. n the circuit, have
shown you how changes in resistance becone changes in voltage that
can be neasured by Arduino.
l you do work with a thernistor, be aware that there isn't a direct connec
tion between the value you read and the actual tenperature neasured. l
you need an exact reading, you should read the nunbers that cone out ol
the analogue pin while neasuring with a real thernoneter. You could put
these nunbers side by side in a table and work out a way to calibrate the
analogue results to realworld tenperatures.
Until now, we have |ust used an LED as an output device, but how do we
read the actual values that Arduino is reading lron the sensor? We can't
nake the board blink the values in Morse code (well, we could, but there
is an easier way lor hunans to read the values). For this, we can have
Arduino talk to a conputer over a serial port, which is described in the
next section.
SeriaI Communication
You learned at the beginning ol this book that Arduino has a U8B connec
tion that is used by the DE to upload code into the processor. The good
news is that this connection can also be used by the sketches that we
write in Arduino to send data back to the conputer or to receive connands
lron it. For this purpose, we are going to use a serial ob|ect (an object is
a collection ol capabilities that are bundled together lor the convenience
ol people writing sketches).
This ob|ect contains all the code that we need to send and receive data.
We're now going to use the last circuit we built with the photoresistor and
send the values that are read back to the conputer. Type this code into
a new sketch (you can also download the code lron www.makezine.com/
gelslarledarduino):
// Example 07: Send to the computer the values read from
// analogue input 0
// Make sure you click on "Serial Monitor"
// after you upload
#dene SENSOR 0 // select the input pin for the
// sensor resistor
int val = 0; // variable to store the value coming
// from the sensor
void setup() {
Serial.begin(9600); // open the serial port to send
// data back to the computer at
// 9600 bits per second
}
void loop() {
val = analogRead(SENSOR); // read the value from
// the sensor
Serial.println(val); // print the value to
// the serial port
delay(100); // wait 100ms between
// each send
}
Alter you've uploaded the code to your Arduino, press the 8erial
Monitor button on the Arduino DE (the rightnost button in the tool
bar), you'll see the nunbers rolling past in the botton part ol the
window. Now, any soltware that can read lron the serial port can talk
to Arduino. There are nany progranning languages that let you write
prograns on your conputer that can talk to the serial port. Frocessing
(www.processing.org) is a great conplenent to Arduino, because the
languages and DEs are so sinilar.
Advanced Input and Output 69 70 Getting Started with Arduino
Driving Bigger Loads (Motors, ans, and the ||e)
Each one ol the pins on an Arduino board can be used to power devices
that use up to ?0 nillianps: this is a very snall anount ol current, |ust
enough to drive an LED. l you try to drive sonething like a notor, the pin
will innediately stop working, and could potentially burn out the whole
processor. To drive bigger loads like notors or incandescent lanps, we
need to use an external conponent that can switch such things on and oll
and that is driven by an Arduino pin. One such device is called a MO8FET
transistor-ignore the lunny nane-it's an electronic switch that can be
driven by applying a voltage to one ol its three pins, each ol which is called
a gate. t is sonething like the light switch that we use at hone, where the
action ol a lnger turning the light on and oll is replaced by a pin on the
Arduino board sending voltage to the gate ol the MO8FET.
NOTE: MOSFET means metaI-oxide-semiconductor heIdeffect
transistor." It's a speciaI type of transistor that operates based on the
heIdeffect principIe. This means that eIectricity wiII how though a
piece of semiconductor materiaI (between the Drain and Source pins)
when a voItage is appIied to the Gate pin. As the Gate is insuIated from
the rest through a Iayer of metaI oxide, there is no current howing
from Arduino into the MOSFET, making it very simpIe to interface.
They are ideaI for switching on and off Iarge Ioads at high frequencies.
n Figure 5/, you can see how you would use a MO8FET like the RF5?0
to turn on and oll a snall notor attached to a lan. You will also notice that
the notor takes its power supply lron the 9 V connector on the Arduino
board. This is another benelt ol the MO8FET: it allows us to drive devices
whose power supply dillers lron the one used by Arduino. As the MO8FET
is connected to pin 9, we can also use ana|og\r|te() to control the speed
ol the notor through FWM.
CompIex Sensors
We delne compIex sensors as those that produce a type ol inlornation
that requires a bit nore than a d|g|ta|Read() or an ana|ogRead() lunction
to be used. These usually are snall circuits with a snall nicrocontroller
inside that preprocesses the inlornation.
8one ol the conplex sensors available include ultrasonic rangers,
inlrared rangers, and acceleroneter. You can lnd exanples on how to
use then on our website in the Tutorials section (www.arduino.cc/en/
Tulorial/HomePage).
Ton goe's Mak|ng Th|ngs Ta|k (O'Reilly) has extensive coverage ol these
sensors and nany other conplex sensors.
Figure 5-7.
A motor circuit for Arduino
Advanced Input and Output 71
n the reced|n chaters, you |earned the
bas|cs o Ardu|no and the undanenta| bu||d
|n b|oc|s ava||ab|e to you. et ne ren|nd you
what na|es u the Ardu|no A|habet.
DigitaI Output
We used it to control an LED but, with the proper circuit, it can be used to
control notors, nake sounds, and a lot nore.
AnaIog Output
This gives us the ability to control the brightness ol the LED, not |ust turn
it on or oll. We can even control the speed ol a notor with it.
DigitaI Input
This allows us to read the state ol sinple sensors, like pushbuttons or tilt
switches.
AnaIog Input
We can read signals lron sensors that send a continuous signal that's not
|ust on or oll, such as a potentioneter or a light sensor.
SeriaI Communication
This allows us to connunicate with a conputer and exchange data or
sinply nonitor what's going on with the sketch that's running on the Arduino.
n this chapter, we're going to see how to put together a working application
using what you have learned in the previous chapters. This chapter should
show you how every single exanple can be used as a building block lor a
conplex pro|ect.
Here is where the wannabe designer in ne cones out. We're going to
nake the twentylrstcentury version ol a classic lanp by ny lavourite
talian designer, Joe Colonbo. The ob|ect we're going to build is inspired
by a lanp called Aton lron l964.
6TaIking to the CIoud
Talking to the Cloud 73 74 Getting Started with Arduino
The lanp, as you can see in Figure 6l, is a sinple sphere sitting on a base
with a large hole to keep the sphere lron rolling oll your desk. This design
allows you to orient the lanp in dillerent directions.
n terns ol lunctionality, we want to build a device that would connect
to the nternet, letch the current list ol articles on the Make blog (bIog.
makezine.com) and count how nany tines the words peace, love,
and Arduino are nentioned. With these values, we're going to generate
a colour and display it on the lanp. The lanp itsell has a button we can
use to turn it on and oll, and a light sensor lor autonatic activation.
Figure 6-1.
The nished lamp
PIanning
Let's look at what we want to achieve and what bits and pieces we need.
First ol all, we need Arduino to be able to connect to the nternet. As the
Arduino board has only a U8B port, we can't plug it directly into an nternet
connection, so we need to lgure out how to bridge the two. Usually what
people do is run an application on a conputer that will connect to the
nternet, process the data, and send Arduino sone sinple bit ol distilled
inlornation.
Arduino is a sinple conputer with a snall nenory, it can't process large
lles easily, and when we connect to an R88 leed we'll get a very verbose
XML lle that would require a lot nore RAM. We'll inplenent a proxy to
sinplily the XML using the Frocessing language.
Processing
Frocessing is where Arduino cane lron. We love this language and
use it to teach progranning to beginners as well as to build beautilul
code. Frocessing and Arduino are the perlect conbination. Another
advantage is that Frocessing is open source and runs on all the na|or
platlorns (Mac, Linux, and Windows). t can also generate stand
alone applications that run on those platlorns. What's nore, the Fro
cessing connunity is lively and helplul, and you can lnd thousands
ol prenade exanple prograns.
The proxy does the lollowing work lor us: it downloads the R88 leed lron
makezine.com and extracts all the words lron the resulting XML lle.
Then, going through all ol then, it counts the nunber ol tines peace,
love, and Arduino appear in the text. With these three nunbers, we'll
calculate a colour value and send it to Arduino. The board will send back
the anount ol light neasured by the sensor and show it on the conputer
screen.
On the hardware side, we'll conbine the pushbutton exanple, the light
sensor exanple, the FWM LED control (nultiplied by 3l) and serial con
nunication.
As Arduino is a sinple device, we'll need to codily the colour in a sinple
way. We'll use the standard way that colours are represented in HTML: #
lollowed by six hexadecinal digits.
Hexadecinal nunbers are handy, because each 8bit nunber is stored in
exactly two characters, with decinal nunbers this varies lron one to three
Talking to the Cloud 75
76 Getting Started with Arduino
characters. Fredictability also nakes the code sinpler: we wait until we see an
#, then we read the six characters that lollow into a ouer (a variable used as
a tenporary holding area lor data). Finally, we turn each group ol two charac
ters into a byte that represents the brightness ol one ol the three LEDs.
Coding
There are two sketches that you'll be running: one Frocessing sketch, and
one Arduino sketch. Here is the code lor the Frocessing sketch. You can
download it lron www.makezine.com/gelslarledarduino.
// Example 08A: Arduino networked lamp
// parts of the code are inspired
// by a blog post by Tod E. Kurt (todbot.com)
import processing.serial.*;
String feed = "http://blog.makezine.com/index.xml";
int interval = 10; // retrieve feed every 60 seconds;
int lastTime; // the last time we fetched the content
int love = 0;
int peace = 0;
int arduino = 0;
int light = 0; // light level measured by the lamp
Serial port;
color c;
String cs;
String buffer = ""; // Accumulates characters coming from Arduino
PFont font;
void setup() {
size(640,480);
frameRate(10); // we don't need fast updates
font = loadFont("HelveticaNeue-Bold-32.vlw");
ll(255);
textFont(font, 32);
// IMPORTANT NOTE:
// The rst serial port retrieved by Serial.list()
// should be your Arduino. If not, uncomment the next
// line by deleting the // before it, and re-run the
// sketch to see a list of serial ports. Then, change
// the 0 in between [ and ] to the number of the port
// that your Arduino is connected to.
//println(Serial.list());
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600); // connect to Arduino
lastTime = 0;
fetchData();
}
void draw() {
background( c );
int n = (interval - ((millis()-lastTime)/1000));
// Build a colour based on the 3 values
c = color(peace, love, arduino);
cs = "#" + hex(c,6); // Prepare a string to be sent to Arduino
text("Arduino Networked Lamp", 10,40);
text("Reading feed:", 10, 100);
text(feed, 10, 140);
text("Next update in "+ n + " seconds",10,450);
text("peace" ,10,200);
text(" " + peace, 130, 200);
rect(200,172, peace, 28);
text("love ",10,240);
text(" " + love, 130, 240);
rect(200,212, love, 28);
text("arduino ",10,280);
text(" " + arduino, 130, 280);
rect(200,252, arduino, 28);
// write the colour string to the screen
text("sending", 10, 340);
text(cs, 200,340);
Talking to the Cloud 77 78 Getting Started with Arduino
text("light level", 10, 380);
rect(200, 352,light/10.23,28); // this turns 1023 into 100
if (n <= 0) {
fetchData();
lastTime = millis();
}
port.write(cs); // send data to Arduino
if (port.available() > 0) { // check if there is data waiting
int inByte = port.read(); // read one byte
if (inByte != 10) { // if byte is not newline
buffer = buffer + char(inByte); // just add it to the buffer
}
else {
// newline reached, let's process the data
if (buffer.length() > 1) { // make sure there is enough data
// chop off the last character, it's a carriage return
// (a carriage return is the character at the end of a
// line of text)
buffer = buffer.substring(0,buffer.length() -1);

// turn the buffer from string into an integer number
light = int(buffer);
// clean the buffer for the next read cycle
buffer = "";
// We're likely falling behind in taking readings
// from Arduino. So let's clear the backlog of
// incoming sensor readings so the next reading is
// up-to-date.
port.clear();
}
}
}
}
void fetchData() {
// we use these strings to parse the feed
String data;
String chunk;
// zero the counters
love = 0;
peace = 0;
arduino = 0;
try {
URL url = new URL(feed); // An object to represent the URL
// prepare a connection
URLConnection conn = url.openConnection();
conn.connect(); // now connect to the Website
// this is a bit of virtual plumbing as we connect
// the data coming from the connection to a buffered
// reader that reads the data one line at a time.
BufferedReader in = new
BufferedReader(new InputStreamReader(conn.getInputStream()));
// read each line from the feed
while ((data = in.readLine()) != null) {
StringTokenizer st =
new StringTokenizer(data,"\"<>,.()[] ");// break it down
while (st.hasMoreTokens()) {
// each chunk of data is made lowercase
chunk= st.nextToken().toLowerCase() ;
if (chunk.indexOf("love") >= 0 ) // found "love"?
love++; // increment love by 1
if (chunk.indexOf("peace") >= 0) // found "peace"?
peace++; // increment peace by 1
if (chunk.indexOf("arduino") >= 0) // found "arduino"?
arduino++; // increment arduino by 1
}
}
// Set 64 to be the maximum number of references we care about.
if (peace > 64) peace = 64;
if (love > 64) love = 64;
if (arduino > 64) arduino = 64;
Talking to the Cloud 79 80 Getting Started with Arduino
peace = peace * 4; // multiply by 4 so that the max is 255,
love = love * 4; // which comes in handy when building a
arduino = arduino * 4; // colour that is made of 4 bytes (ARGB)
}
catch (Exception ex) { // If there was an error, stop the sketch
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
}
There are two things you need to do belore the Frocessing sketch will run
correctly. First, you need to tell Frocessing to generate the lont that we
are using lor the sketch. To do this, create and save this sketch. Then, with
the sketch still opened, click Frocessing's Tools nenu, then select Create
Font. 8elect the lont naned HelveticaNeueBold, choose 3? lor the lont
size, and then click OK.
8econd, you will need to conlrn that the sketch is using the correct serial
port lor talking to Arduino. You'll need to wait until you've assenbled the
Arduino circuit and uploaded the Arduino sketch belore you can conlrn
this. On nost systens, this Frocessing sketch will run lne. However, il
you don't see anything happening on the Arduino and you don't see any
inlornation lron the light sensor appearing onscreen, lnd the connent
labeled MFORTANT NOTE in the Frocessing sketch and lollow the
instructions there.
Here is the Arduino sketch (also available at nnn%dXb\q`e\%Zfd&
^\kjkXik\[Xi[l`ef):
// Example 08B: Arduino Networked Lamp
#dene SENSOR 0
#dene R_LED 9
#dene G_LED 10
#dene B_LED 11
#dene BUTTON 12
int val = 0; // variable to store the value coming from the sensor
int btn = LOW;
int old_btn = LOW;
int state = 0;
char buffer[7] ;
int pointer = 0;
byte inByte = 0;
byte r = 0;
byte g = 0;
byte b = 0;
void setup() {
Serial.begin(9600); // open the serial port
pinMode(BUTTON, INPUT);
}
void loop() {
val = analogRead(SENSOR); // read the value from the sensor
Serial.println(val); // print the value to
// the serial port
if (Serial.available() >0) {
// read the incoming byte:
inByte = Serial.read();
// If the marker's found, next 6 characters are the colour
if (inByte == '#') {
while (pointer < 6) { // accumulate 6 chars
buffer[pointer] = Serial.read(); // store in the buffer
pointer++; // move the pointer forward by 1
}
Talking to the Cloud 81
82 Getting Started with Arduino
// now we have the 3 numbers stored as hex numbers
// we need to decode them into 3 bytes r, g and b
r = hex2dec(buffer[1]) + hex2dec(buffer[0]) * 16;
g = hex2dec(buffer[3]) + hex2dec(buffer[2]) * 16;
b = hex2dec(buffer[5]) + hex2dec(buffer[4]) * 16;

pointer = 0; // reset the pointer so we can reuse the buffer

}
}
btn = digitalRead(BUTTON); // read input value and store it
// Check if there was a transition
if ((btn == HIGH) && (old_btn == LOW)){
state = 1 - state;
}
old_btn = btn; // val is now old, let's store it
if (state == 1) { // if the lamp is on

analogWrite(R_LED, r); // turn the leds on
analogWrite(G_LED, g); // at the colour
analogWrite(B_LED, b); // sent by the computer
} else {
analogWrite(R_LED, 0); // otherwise turn off
analogWrite(G_LED, 0);
analogWrite(B_LED, 0);
}

delay(100); // wait 100ms between each send
}
int hex2dec(byte c) { // converts one HEX character into a number
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
}
8jj\dYc`e^k_\:`iZl`k
Figure 6? shows how to assenble the circuit. You need to use l0K resis
tors lor all ol the resistors shown in the diagran, although you could get
away with lower values lor the resistors connected to the LEDs.
Renenber lron the FWM exanple in Chapter 5 that LEDs are polarized:
in this circuit, the long pin (positive) should go to the right, and the short
pin (negative) to the lelt. (Most LEDs have a lattened negative side, as
shown in the lgure.)
Figure 6-2.
The Arduino Networked Lamp circuit
Talking to the Cloud 83 84 Getting Started with Arduino
Build the circuit as shown, using one red, one green, and one blue LED.
Next, load the sketches into Arduino and Frocessing, then run the sketches
and try it out. l you run into any problens, check Chapter /, Trouble
shooting.
Now let's conplete the construction by placing the breadboard into a
glass sphere. The sinplest and cheapest way to do this is to buy an KEA
FADO table lanp. t's now selling lor about U8Sl4.99/tl4.99/8.99
(ahh, the luxury ol being European).
nstead ol using three separate LEDs, you can use a single ROB LED,
which has lour leads coning oll it. You'll hook it up in nuch the sane
way as the LEDs shown in Figure 6?, with one change: instead ol three
separate connections to the ground pin on Arduino, you'll have a single
lead (called the connon cathode) going to ground.
8parkFun sells a 4lead ROB LED lor a lew dollars (nnn%jgXib]le%Zfd,
part nunber COM00l05). Also, unlike discrete singlecolor LEDs, the
longest lead on this ROB LED is the one that goes to ground. The three
shorter leads will need to connect to Arduino pins 9, l0, and ll (with
a resistor between the leads and the pins, |ust as with the separate red,
green, and blue LEDs).
?\i\j?fnkf8jj\dYc\@k1
Unpack the lanp and renove the cable that goes into the lanp lron the
botton. You will no longer be plugging this into the wall.
8trap the Arduino on a breadboard and hotglue the breadboard onto the
back ol the lanp.
8older longer wires to the ROB LED and glue it where the lightbulb used to
be. Connect the wires coning lron the LED to the breadboard (where it
was connected belore you renoved it). Renenber that you will only need
one connection to ground il you are using a 4lead ROB LED.
Either lnd a nice piece ol wood with a hole that can be used as a stand
lor the sphere or |ust cut the top ol the cardboard box that cane with the
lanp at approxinately 5cn (or ?") and nake a hole with a dianeter that
cradles the lanp. Reinlorce the inside ol the cardboard box by using hot
glue all along the inside edges, which will nake the base nore stable.
Flace the sphere on the stand and bring the U8B cable out ol the top and
connect it to the conputer.
Fire oll your Frocessing code, press the on/oll button, and watch the
lanp cone to lile.

As an exercise, try to add code that will turn on the lanp when the roon
gets dark. Other possible enhancenents are:
x Add tilt sensors to turn the lanp on or oll by rotating it in dillerent
directions.
x Add a snall FR sensor to detect when sonebody is around and turn it
oll when nobody is there to watch.

x Create dillerent nodes so that you can get nanual control ol the
colour or nake it lade through nany colours.

Think ol dillerent things, experinent, and have lunl
Talking to the Cloud 85
There w||| cone a nonent |n your exer|nen
tat|on when noth|n w||| be wor||n and you
w||| have to ure out how to x |t. Troub|eshoot
|n and debu|n are anc|ent arts |n wh|ch
there are a ew s|n|e ru|es, but nost o the
resu|ts are obta|ned throuh a |ot o wor|.
The nore you work with electronics and Arduino, the nore you will learn
and gain experience, which will ultinately nake the process less painlul.
Don't be discouraged by the problens that you will lnd-it's all easier
than it seens at the beginning.
As every Arduinobased pro|ect is nade both ol hardware and soltware,
there will be nore than one place to look il sonething goes wrong. While
looking lor a bug, you should operate along three lines:
Understanding
Try to understand as nuch as possible how the parts that you're using
work and how they're supposed to contribute to the lnished pro|ect.
This approach will allow you to devise sone way to test each conponent
separately.
SimpIihcation and segmentation
The Ancient Ronans used to say d|v|de et |npera: divide and rule. Try
to break down (nentally) the pro|ect into its conponents by using the
understanding you have and lgure out where the responsibility ol each
conponent begins and ends.
ExcIusion and certainty
While investigating, test each conponent separately so that you can be
absolutely certain that each one works by itsell. You will gradually build
up conldence about which parts ol pro|ect are doing their |ob and which
ones are dubious.
7TroubIeshooting
Troubleshooting 87
88 Getting Started with Arduino
Deougg|ng is the tern used to describe this process as applied to soltware.
The legend says it was used lor the lrst tine by Orace Hopper back in the
l940s, when conputers where nostly electronechanical, and one ol then
stopped working because actual insects got caught in the nechanisns.
Many ol today's bugs are not physical anynore: they're virtual and invis
ible, at least in part. Therelore they require a sonetines lengthy and
boring process to be identiled.
Testing the Board
What il the very lrst exanple, blink an LED, didn't work? Wouldn't that
be a bit depressing? Let's lgure out what to do.
Belore you start blaning your pro|ect, you should nake sure that a lew
things are in order, as airline pilots do when they go through a checklist
to nake sure that the airplane will be lying properly belore takeoll:
Flug your Arduino into a U8B plug on your conputer.
Make sure the conputer is on (yes, it sounds silly, but it has
happened). l the green light narked FWR turns on, this neans that
the conputer is powering the board. l the LED seens very laint,
sonething is wrong with the power: try a dillerent U8B cable and
inspect the conputer's U8B port and the Arduino's U8B plug to see
whether there is any danage. l all else lails, try a dillerent U8B port
on your conputer or a dillerent conputer entirely.
l the Arduino is brand new, the yellow LED narked L will start blink
ing in a bit ol a nervous pattern, this is the test progran that was
loaded at the lactory to test the board.
l you have been using an external power supply and are using an old
Arduino (Extrene, NO, or Diecinila), nake sure that the power sup
ply is plugged in and that the |unper narked 8Vl is connecting the
two pins that are nearest to the external power supply connector.
NOTE: When you are having troubIe with other sketches and need to
conhrm that the board is functioning, open the hrst bIink an LED"
exampIe in the Arduino IDE and upIoad it to the board. The onboard
LED shouId bIink in a reguIar pattern.
x
x
x
Troubleshooting 89
l you have gone through all these steps successlully, then you can be
conldent that your Arduino is working correctly.
Testing Your Breadboarded Circuit
Now connect the board to your breadboard by running a |unper lron the
5 V and OND connections to the positive and negative rails ol the bread
board. l the green FWR LED turns oll, renove the wires innediately. This
neans there is a big nistake in your circuit and you have a short circuit
sonewhere. When this happens, your board draws too nuch current and
the power gets cut oll to protect the conputer.
NOTE: If you're a concerned that you may damage your computer,
remember that on many computers, the current protection is usuaIIy
quite good and responds quickIy. AIso, the Arduino board is htted with
a PoIyFuse," a currentprotection device that resets itseIf when the
fauIt is removed.
If you're reaIIy paranoid, you can aIways connect the Arduino board
through a seIfpowered USB hub. In this case, if it aII goes horribIy
wrong, the USB hub is the one that wiII be pushing up daisies, not your
computer.
l you're getting a short circuit, you have to start the sinplilcation and
segnentation process. What you nust do is go through every sensor in
the pro|ect and connect |ust one at a tine.
The lrst thing to start lron is always the power supply (the connections
lron 5 V and OND). Look around and nake sure that each part ol the
circuit is powered properly.
Working step by step and naking one single nodilcation at a tine is the
nunber one rule lor lxing stull. This rule was hannered into ny young
head by ny school prolessor and lrst enployer, Maurizio Firola. Every
tine 'n debugging sonething and things don't look good (and believe
ne, it happens a lot), his lace pops in ny head saying one nodilcation
at a tine . . . one nodilcation at a tine and that's usually when lx
everything. This is very inportant, because you will know what lxed
the problen (it's all too easy to lose track ol which nodilcation actually
solved the problen, which is why it's so inportant to nake one at a tine).
90 Getting Started with Arduino
Each debugging experience will build up in your head a knowledge base
ol delects and possible lxes. And belore you know it, you'll becone
an expert. This will nake you look very cool, because as soon as a newbie
says This doesn't workl you'll give it a quick look and have the answer
in a split second.
lsoIating ProbIems
Another inportant rule is to lnd a reliable way to reproduce a problen.
l your circuit behaves in a lunny way at randon tines, try really hard to
lgure out the exact nonent the problen occurs and what is causing it.
This process will allow you to think about a possible cause. t is also very
uselul when you need to explain to sonebody else what's going on.
Describing the problen as precisely as possible is also a good way to lnd
a solution. Try to lnd sonebody to explain the problen to-in nany cases,
a solution will pop into your head as you articulate the problen. Brian W.
Kernighan and Rob Fike, in The Pract|ce of Progrann|ng (AddisonWesley,
l999), tell the story ol one university that kept a teddy bear near the help
desk. 8tudents with nysterious bugs were required to explain then to the
bear belore they could speak to a hunan counselor.
ProbIems with the lDE
n sone cases, you nay have a problen using the Arduino DE, particularly
on Windows.
l you get an error when you doubleclick on the Arduino icon, or il nothing
happens, try doubleclicking the run.oat lle as an alternative nethod to
launch Arduino.
Windows users nay also run into a problen il the operating systen assigns
a COM port nunber ol COMl0 or greater to Arduino. l this happens, you
can usually convince Windows to assign a lower port nunber to Arduino.
First, open up the Device Manager by clicking the 8tart nenu, right
clicking on Conputer (Vista) or My Conputer (XF), and choosing Froper
ties. On Windows XF, click Hardware and choose Device Manager. On
Vista, click on Device Manager (it appears in the list ol tasks on the lelt
ol the window).
Look lor the serial devices in the list under Forts (COM & LFT). Find a serial
device that you're not using that is nunbered COM9 or lower. Rightclick it
and choose Froperties lron the nenu. Then, choose the Fort 8ettings tab
Troubleshooting 91
and click Advanced. 8et the COM port nunber to COMl0 or higher, click OK
and click OK again to disniss the Froperties dialog.
Now, do the sane with the U8B 8erial Fort device that represents Arduino,
with one change: assign it the COM port nunber (COM9 or lower) that
you |ust lreed up.
l these suggestions don't help, or il you're having a problen not described
here, check out the Arduino troubleshooting page at www.arduino.cc/en/
Cuide/Troubleshooling.
How to Get HeIp OnIine
l you are stuck, don't spend days running around alone-ask lor help.
One ol the best things about Arduino is its connunity. You can always
lnd help il you can describe your problen well.
Oet the habit ol cutting and pasting things into a search engine and see
whether sonebody is talking about it. For exanple, when the Arduino DE
spits out a nasty error nessage, copy and paste it into a Ooogle search
and see what cones out. Do the sane with bits ol code you're working on
or |ust a specilc lunction nane. Look around you: everything has been
invented already and it's stored sonewhere on a web page.
For lurther investigation, start lron the www.arduino.cc nain website
and look at the FAQ (www.arduino.cc/en/Main/FA), then nove on to
the playground (www.arduino.cc/playground), a lreely editable wiki that
any user can nodily to contribute docunentation. t's one ol the best
parts ol the whole open source philosophy. Feople contribute docunen
tation and exanples ol anything you can do with Arduino. Belore you
start a pro|ect, search the playground and you'll lnd a bit ol code or a
circuit diagran to get you started.
l you still can't lnd an answer that way, search the lorun (www.arduino.cc/
cgibin/yabb2/YaBB.pl). l that doesn't help, post a question there. Fick
the correct board lor your problen: there are dillerent areas lor soltware
or hardware issues and even loruns in lve dillerent languages. Flease
post as nuch inlornation as you can:
What Arduino board are you using?
What operating systen are you using to run the Arduino DE?
x
x
92 Getting Started with Arduino
Oive a general description ol what you're trying to do. Fost links to
datasheets ol strange parts you're using.

The nunber ol answers you get depends on how well you lornulate your
question.
Your chances increase il you avoid these things at aII cost (these rules
are good lor any online loruns, not |ust Arduino's):
Typing your nessage all in CAFTAL8. t annoys people a lot and is
like walking around with newbie tattooed on your lorehead (in on
line connunities, typing in all capitals is considered shouting).

Fosting the sane nessage in several dillerent parts ol the lorun.

Bunping your nessage by posting lollowup connents asking
Hey, how cone no one replied? or even worse, sinply posting the
text bunp. l you didn't get a reply, take a look at your posting. Was
the sub|ect clear? Did you provide a wellworded description ol the
problen you are having? Were you nice? Always be nice.
Writing nessages like want to build a space shuttle using arduino
how do do that. This neans that you want people to do your work
lor you, and this approach is sinply not lun lor a real tinkerer. t's
better to explain what you want to build and then ask a specilc
question about one part ol the pro|ect and take it lron there.

A variation ol the previous point is when the question is clearly
sonething the poster ol the nessage is getting paid to do. l you ask
specilc questions people are happy to help, but il you ask then to do
all your work (and you don't share the noney), the response is likely
to be less nice.
Fosting nessages that look suspiciously like school assignnents and
asking the lorun to do your honework. Frolessors like ne roan the
loruns and slap such students with a large trout.
x
x
x
x
x
x
x
Appendix A
The Breadboard
The process ol getting a circuit to work involves naking lots ol changes
to it until it behaves properly, it's a very last, iterative process that's
sonething like an electronic equivalent to sketching. The design evolves
in your hands as you try dillerent conbinations. For the best results,
use a systen that allows you to change the connections between
conponents in the lastest, nost practical, and least destructive way.
These requirenents clearly rule out soldering, which is a tineconsuning
procedure that puts conponents under stress every tine you heat then
up and cool then down.
The answer to this problen is a very practical device called the solderless
breadboard. As you can see lron Figure Al, it's a snall plastic board lull
ol holes, each ol which contains a springloaded contact. You can push
a conponent's leg into one ol the holes, and it will establish an electrical
connection with all ol the other holes in the sane vertical colunn ol holes.
Each hole is a distance ol ?.54 nn lron the others.
Because nost ol the conponents have their legs (known to techies as
pins) spaced at that standard distance, chips with nultiple legs lt
nicely. Not all ol the contacts on a breadboard are created equal-there
are sone dillerences. The top and botton rows (coloured in red and
blue and narked with + and -) are connected horizontally and are used
to carry the power across the board so that when you need power or
ground, you can provide it very quickly with a junper (a short piece ol
wire used to connect two points in the circuits). The last thing you need to
know about breadboards is that in the niddle, there is a large gap that is
as wide as the size ol a snall chip. Each vertical line ol holes is interrupted
in the niddle, so that when you plug in a chip, you don't shortcircuit the
pins that are on the two sides ol the chip. Clever, eh?
Appendix A 93 94 Getting Started with Arduino
Figure A-1.
The solderless breadboard
n order to use electronic parts, you need to be able to identily then,
which can be a dillcult task lor a beginner. Most ol the resistors that you
lnd in a shop have a cylindrical body with two legs sticking out and have
strange coloured narkings all around then. When the lrst connercial
resistors were nade, there was no way to print nunbers snall enough
to lt on their body, so clever engineers decided that they could |ust
represent the values with strips ol coloured paint.
Today's beginners have to lgure out a way to interpret these signs. The
key is quite sinple: generally, there are lour stripes, and each colour
represents a nunber. One ol rings is usually goldcoloured, this one
represents the precision ol that resistor. To read the stripes in order, hold
the resistor so the gold (or silver in sone cases) stripe is to the right.
Then, read the colours and nap then to the corresponding nunbers. n
the lollowing table, you'll lnd a translation between the colours and their
nuneric values.
For exanple, brown, black, orange, and gold narkings nean l 0 3 p5.
Easy, right? Not quite, because there is a twist: the third ring actually
represents the nunber ol zeros in the value. Therelore l 0 3 is actually l
0 lollowed by 3 zeros, so the end result is l0,000 ohns p5. Electronics
geeks tend to shorten values by expressing then in kilo ohn (lor thousands
Appendix BReading
Resistors and Capacitors
CoIour VaIue
Black 0
Brown l
Red 2
Orange 3
Yellow 4
Creen 5
Blue 6
Purple 7
Crey 8
While 9
Silver l0
Cold 5
Appendix B 95 96 Getting Started with Arduino
ol ohns) and nega ohns (lor nillions ol ohns), so a l0,000 ohn resistor
is usually shortened to l0k, while l0,000,000 becones l0M. Flease note
that because engineers are lond ol optinising everything, on sone sche
natic diagrans you night lnd values expressed as 4k/, which neans 4./
kilo ohns, or 4/00.
Capacitors are a bit easier: the barrelshaped capacitors (electrolytic ca
pacitors) generally have their values printed on then. A capacitor's value
is neasured in larads (F), but nost capacitors that you encounter will be
neasured in nicro larads (F). 8o il you see a capacitor labelled l00 F,
it's a l00 nicro larad capacitor.
Many ol the discshaped capacitors (ceranic capacitors) do not have
their units listed, and use a threedigit nuneric code indicating the
nunber ol pico larads (pF). There are l,000,000 pF in one F. 8inilar to
the resistor codes, you use the third nunber to deternine the nunber
ol zeros to put alter the lrst two, with one dillerence: il you see 0-5,
that indicates the nunber ol zeros. 6 and / are not used, and 8 and 9 are
handled dillerently. l you see 8, nultiply the nunber that the lrst two
digits lorn by 0.0l, and il you see 9, nultiply it by 0.l.
8o, a capacitor labelled l04 would be l00,000 pF or 0.l F. A capacitor
labeled ??9 would be ?.? pF.
Here is a quick explanation ol all the standard instructions supported
by the Arduino language.
For a nore detailed relerence, see: arduino.cc/en/Reerence/HomePage
STRUCTURE
An Arduino sketch runs in two parts:

void setup()
This is where you place the initialisation code-the instructions that set
up the board belore the nain loop ol the sketch starts.
void loop()
This contains the nain code ol your sketch. t contains a set ol instruc
tions that get repeated over and over until the board is switched oll.
SPEClAL SYMBOLS
Arduino includes a nunber ol synbols to delineate lines ol code, con
nents, and blocks ol code.
; (semicoIon)
Every instruction (line ol code) is terninated by a senicolon. This syntax
lets you lornat the code lreely. You could even put two instructions on
the sane line, as long as you separate then with a senicolon. (However,
this would nake the code harder to read.)
Exanple:
delay(100);
{] (curIy braces)
This is used to nark blocks ol code. For exanple, when you write code lor
the |oop() lunction, you have to use curly braces belore and alter the code.
Exanple:
void loop() {
Serial.println("ciao");
}
Appendix C 97
Appendix CArduino
Quick Reference
98 Getting Started with Arduino
comments
These are portions ol text ignored by the Arduino processor, but are ex
trenely uselul to renind yoursell (or others) ol what a piece ol code does.
There are two styles ol connents in Arduino:
// single-line: this text is ignored until the end of the line
/* multiple-line:
you can write
a whole poem in here
*/
CONSTANTS
Arduino includes a set ol predelned keywords with special values.
HIGH and LOW are used, lor exanple, when you want to turn on or oll
an Arduino pin. INPUT and OUTPUT are used to set a specilc pin to be
either and input or an output
true and faIse indicate exactly what their nanes suggest: the truth or
lalsehood ol a condition or expression.
VARlABLES
Variables are naned areas ol the Arduino's nenory where you can
store data that you can use and nanipulate in your sketch. As the nane
suggests, they can be changed as nany tines as you like.
Because Arduino is a very sinple processor, when you declare a variable
you have to specily its type. This neans telling the processor the size ol
the value you want to store.
Here are the datatypes that are available:
booIean
Can have one ol two values: true or lalse.
char
Holds a single character, such as A. Like any conputer, Arduino stores
it as a nunber, even though you see text. When chars are used to store
nunbers, they can hold values lron -l?8 to l?/.
NOTE: There are two major sets of characters avaiIabIe on computer
systems: ASCII and UNICODE. ASCII is a set of IZ7 characters that
was used for, among other things, transmitting text between seriaI
terminaIs and timeshared computer systems such as mainframes
and minicomputers. UNICODE is a much Iarger set of vaIues used by
modern computer operating systems to represent characters in a
wide range of Ianguages. ASCII is stiII usefuI for exchanging short bits
of information in Ianguages such as ItaIian or EngIish that use Latin
characters, Arabic numeraIs, and common typewriter symboIs for
punctuation and the Iike.
byte
Holds a nunber between 0 and ?55. As with chars, bytes use only one
byte ol nenory.
int
Uses ? bytes ol nenory to represent a nunber between -3?,/68 and
3?,/6/, it's the nost connon data type used in Arduino.
unsigned int
Like int, uses ? bytes but the unsigned prelx neans that it can't store
negative nunbers, so its range goes lron 0 to 65,535.
Iong
This is twice the size ol an int and holds nunbers lron -?,l4/,483,648 to
?,l4/,483,64/.
unsigned Iong
Unsigned version ol Iong, it goes lron 0 to 4,?94,96/,?95.
hoat
This quite big and can hold loatingpoint values, a lancy way ol saying
that you can use it to store nunbers with a decinal point in it. t will eat up
4 bytes ol your precious RAM and the lunctions that can handle then use
up a lot ol code nenory as well. 8o use hoats sparingly.
doubIe
Doubleprecision loatingpoint nunber, with a naxinun value ol
l./9/693l3486?3l5/ x l0
308
. Wow, that's hugel
string
A set ol A8C characters that are used to store textual inlornation (you
night use a string to send a nessage via a serial port, or to display on
Appendix C 99
100 Getting Started with Arduino
an LCD display). For storage, they use one byte lor each character in the
string, plus a null character to tell Arduino that it's the end ol the string.
The lollowing are equivalent:
char string1[] = "Arduino"; // 7 chars + 1 null char
char string2[8] = "Arduino"; // Same as above
array
A list ol variables that can be accessed via an index. They are used to
build tables ol values that can easily be accessed. For exanple, il you
want to store dillerent levels ol brightness to be used when lading an LED,
you could create six variables called light0l, light0?, and so on. Better yet,
you could use a sinple array like:
int light[6] = {0, 20, 50, 75, 100};
The word array is not actually used in the variable declaration: the
synbols || and {} do the |ob.
CONTROL STRUCTURES
Arduino includes keywords lor controlling the logical low ol your sketch.
if . . . eIse
This structure nakes decisions in your progran. |f nust be lollowed by
a question speciled as an expression contained in parentheses. l the
expression is true, whatever lollows will be executed. l it's lalse, the block
ol code lollowing else will be executed. t's possible to use |ust |f without
providing an e|se clause.
Exanple:
if (val == 1) {
digitalWrite(LED,HIGH);
}
for
Lets you repeat a block ol code a speciled nunber ol tines.
Exanple:
for (int i = 0; i < 10; i++) {
Serial.print("ciao");
}
switch case
The |f statenent is like a lork in the road lor your progran. sw|tch case is
like a nassive roundabout. t lets your progran take a variety ol directions
depending on the value ol a variable. t's quite uselul to keep your code
tidy as it replaces long lists ol |f statenents.
Exanple:
switch (sensorValue) {
case 23:
digitalWrite(13,HIGH);
break;
case 46:
digitalWrite(12,HIGH);
break;
default: // if nothing matches this is executed
digitalWrite(12,LOW);
digitalWrite(13,LOW);
}
whiIe
8inilar to |f, this executes a block ol code while a certain condition is true.
Exanple:
// blink LED while sensor is below 512
sensorValue = analogRead(1);
while (sensorValue < 512) {
digitalWrite(13,HIGH);
delay(100);
digitalWrite(13,HIGH);
delay(100);
sensorValue = analogRead(1);
}
do . . . whiIe
Just like wh||e, except that the code is run |ust belore the the condition
is evaluated. This structure is used when you want the code inside your
block to run at least once belore you check the condition.
Exanple:
do {
digitalWrite(13,HIGH);
delay(100);
digitalWrite(13,HIGH);
delay(100);
sensorValue = analogRead(1);
} while (sensorValue < 512);
Appendix C 101 102 Getting Started with Arduino
break
This tern lets you leave a loop and continue the execution ol the code
that appears alter the loop. t's also used to separate the dillerent sections
ol a sw|tch case statenent.
Exanple:
// blink LED while sensor is below 512
do {
// Leaves the loop if a button is pressed
if (digitalRead(7) == HIGH)
break;
digitalWrite(13,HIGH);
delay(100);
digitalWrite(13,HIGH);
delay(100);
sensorValue = analogRead(1);
} while (sensorValue < 512);
continue
When used inside a loop, cont|nue lets you skip the rest ol the code inside
it and lorce the condition to be tested again.
Exanple:
for (light = 0; light < 255; light++)
{
// skip intensities between 140 and 200
if ((x > 140) && (x < 200))
continue;
analogWrite(PWMpin, light);
delay(10);
}
return
8tops running a lunction and returns lron it. You can also use this to
return a value lron inside a lunction.
For exanple, il you have a lunction called conputeTenperature() and you
want to return the result to the part ol your code that invoked the lunction
you would write sonething like:
int computeTemperature() {
int temperature = 0;
temperature = (analogRead(0) + 45) / 100;
return temperature;
}
ARlTHMETlC AND FORMULAS
You can use Arduino to nake conplex calculations using a special syntax.
+ and - work like you've learned in school, and nultiplication is represent
ed with an and division with a /.
There is an additional operator called nodulo (), which returns
the renainder ol an integer division. You can use as nany levels ol
parentheses as necessary to group expressions. Contrary to what you
night have learned in school, square brackets and curly brackets are
reserved lor other purposes (array indexes and blocks, respectively).
Exanples:
a = 2 + 2;
light = ((12 * sensorValue) - 5 ) / 2;
remainder = 3 % 2; // returns 2 because 3 / 2 has remainder 1
COMPARlSON OPERATORS
When you specily conditions or tests lor |f, wh||e, and for statenents,
these are the operators you can use:
== equal to
l= not equal to
less than
~ greater than
= less than or equal to
~= greater than or equal to
BOOLEAN OPERATORS
These are used when you want to conbine nultiple conditions. For exanple,
il you want to check whether the value coning lron a sensor is between 5
and l0, you would write:
if ((sensor => 5) && (sensor <=10))
There are three operators: and, represented with &&, or, represented with
]], and lnally not, represented with !.
COMPOUND OPERATORS
These are special operators used to nake code nore concise lor sone
very connon operations like increnenting a value.
Appendix C 103 104 Getting Started with Arduino
For exanple, to increnent va|ue by l you would write:
value = value +1;
but using a conpound operator, this becones:
value++;
increment and decrement (-- and ++)
These increnent or decrenent a value by l. Be carelul, though. l you
write |++ this increnents | by l and evaluates to the equivalent ol |+I,
++| evaluates to the value ol | then increnents |. The sane applies to --.
+ , -, * and 7
These nake it shorter to write certain expressions. The lollowing two
expressions are equivalent:
a = a + 5;
a += 5;
lNPUT AND OUTPUT FUNCTlONS
Arduino includes lunctions lor handling input and output. You've already
seen sone ol these in the exanple prograns throughout the book.
pinMode(pin, mode)
Reconlgures a digital pin to behave either as an input or an output.
Exanple:
pinMode(7,INPUT); // turns pin 7 into an input
digitaIWrite(pin, vaIue)
Turns a digital pin either on or oll. Fins nust be explicitly nade into an
output using p|nMode belore d|g|ta|\r|te will have any ellect.
Exanple:
digitalWrite(8,HIGH); // turns on digital pin 8
int digitaIRead(pin)
Reads the state ol an input pin, returns HOH il the pin senses sone
voltage or LOW il there is no voltage applied.
Exanple:
val = digitalRead(7); // reads pin 7 into val
int anaIogRead(pin)
Reads the voltage applied to an analog input pin and returns a nunber
between 0 and l0?3 that represents the voltages between 0 and 5 V.
Exanple:
val = analogRead(0); // reads analog input 0 into val
anaIogWrite(pin, vaIue)
Changes the FWM rate on one ol the pins narked FWM. p|n nay be ll,l0,
9, 6, 5, 3. va|ue nay be a nunber between 0 and ?55 that represents the
scale between 0 and 5 V output voltage.
Exanple:
analogWrite(9,128); // Dim an LED on pin 9 to 50%
shiftOut(dataPin, cIockPin, bitOrder, vaIue)
8ends data to a sh|ft reg|ster, devices that are used to expand the nunber
ol digital outputs. This protocol uses one pin lor data and one lor clock.
o|tOrder indicates the ordering ol bytes (least signilcant or nost
signilcant) and va|ue is the actual byte to be sent out.
Exanple:
shiftOut(dataPin, clockPin, LSBFIRST, 255);
unsigned Iong puIseIn(pin, vaIue)
Measures the duration ol a pulse coning in on one ol the digital inputs.
This is uselul, lor exanple, to read sone inlrared sensors or acceleron
eters that output their value as pulses ol changing duration.
Exanple:
time = pulsein(7,HIGH); // measures the time the next
// pulse stays high
TlME FUNCTlONS
Arduino includes lunctions lor neasuring elapsed tine and also lor pausing
the sketch.
unsigned Iong miIIis()
Returns the nunber ol nilliseconds that have passed since the sketch
started.
Exanple:
duration = millis()-lastTime; // computes time elapsed since "lastTime"
Appendix C 105
106 Getting Started with Arduino
deIay(ms)
Fauses the progran lor the anount ol nilliseconds speciled.
Exanple:
delay(500); // stops the program for half a second
deIayMicroseconds(us)
Fauses the progran lor the given anount ol nicroseconds.
Exanple:
delayMicroseconds(1000); // waits for 1 millisecond
MATH FUNCTlONS
Arduino includes nany connon nathenatical and trigononetric
lunctions:
min(x, y)
Returns the snaller ol x and y.
Exanple:
val = min(10,20); // val is now 10
max(x, y)
Returns the larger ol x and y.
Exanple:
val = max(10,20); // val is now 20
abs(x)
Returns the absolute value ol x, which turns negative nunbers into
positive. l x is 5 it will return 5, but il x is -5, it will still return 5.
Exanple:
val = abs(-5); // val is now 5
constrain(x, a, b)
Returns the value ol x, constrained between a and b. l x is less than a, it
will |ust return a and il x is greater than o, it will |ust return o.
Exanple:
val = constrain(analogRead(0), 0, 255); // reject values bigger than 255
map(vaIue, fromLow, fromHigh, toLow, toHigh)
Maps a value in the range fronlow and naxlow to the range tolow and
toH|gh. Very uselul to process values lron analogue sensors.
Exanple:
val = map(analogRead(0),0,1023,100, 200); // maps the value of
// analog 0 to a value
// between 100 and 200
doubIe pow(base, exponent)
Returns the result ol raising a nunber (oase) to a value (exponent).
Exanple:
double x = pow(y, 32); // sets x to y raised to the 32nd power
doubIe sqrt(x)
Returns the square root ol a nunber.
Exanple:
double a = sqrt(1138); // approximately 33.73425674438
doubIe sin(rad)
Returns the sine ol an angle speciled in radians.
Exanple:
double sine = sin(2); // approximately 0.90929737091
doubIe cos(rad)
Returns the cosine ol an angle speciled in radians.
Exanple:
double cosine = cos(2); // approximately -0.41614685058
doubIe tan(rad)
Returns the tangent ol an angle speciled in radians.
Exanple:
double tangent = tan(2); // approximately -2.18503975868
Appendix C 107 108 Getting Started with Arduino
RANDOM NUMBER FUNCTlONS
l you need to generate randon nunbers, you can use Arduino's pseudo
randon nunber generator.
randomSeed(seed)
Resets Arduino's pseudorandon nunber generator. Although the distribu
tion ol the nunbers returned by randon() is essentially randon, the se
quence is predictable. 8o, you should reset the generator to sone randon
value. l you have an unconnected analog pin, it will pick up randon noise
lron the surrounding environnent (radio waves, cosnic rays, electronag
netic interlerence lron cell phones and luorescent lights, and so on).
Exanple:
randomSeed(analogRead(5)); // randomize using noise from pin 5
Iong random(max)
Iong random(min, max)
Returns a pseudorandon |ong integer value between n|n and nax - I.
l nin is not speciled, the lower bound is 0.
Exanple:
long randnum = random(0, 100); // a number between 0 and 99
long randnum = random(11); // a number between 0 and 10
SERlAL COMMUNlCATlON
As you saw in Chapter 5, you can connunicate with devices over the U8B
port using a serial connunication protocol. Here are the serial lunctions.
SeriaI.begin(speed)
Frepares Arduino to begin sending and receiving serial data. You'll
generally use 9600 bits per second (bps) with the Arduino DE serial noni
tor, but other speeds are available, usually no nore than ll5,?00 bps.
Exanple:
Serial.begin(9600);
SeriaI.print(data)
SeriaI.print(data, encoding)
8ends sone data to the serial port. The encoding is optional, il not
supplied, the data is treated as nuch like plain text as possible.
Exanples:
Serial.print(75); // Prints "75"
Serial.print(75, DEC); // The same as above.
Serial.print(75, HEX); // "4B" (75 in hexadecimal)
Serial.print(75, OCT); // "113" (75 in octal)
Serial.print(75, BIN); // "1001011" (75 in binary)
Serial.print(75, BYTE); // "K" (the raw byte happens to
// be 75 in the ASCII set)
SeriaI.printIn(data)
SeriaI.printIn(data, encoding)
8ane as 5er|a|.pr|nt(), except that it adds a carriage return and lineleed
(\r\n) as il you had typed the data and then pressed Return or Enter.
Exanples:
Serial.println(75); // Prints "75\r\n"
Serial.println(75, DEC); // The same as above.
Serial.println(75, HEX); // "4B\r\n"
Serial.println(75, OCT); // "113\r\n"
Serial.println(75, BIN); // "1001011\r\n"
Serial.println(75, BYTE); // "K\r\n"
int SeriaI.avaiIabIe()
Returns how nany unread bytes are available on the 8erial port lor
reading via the read() lunction. Alter you have read() everything available,
5er|a|.ava||ao|e() returns 0 until new data arrives on the serial port.
Exanple:
int count = Serial.available();
int SeriaI.read()
Fetches one byte ol inconing serial data.
Exanple:
int data = Serial.read();
SeriaI.hush()
Because data nay arrive through the serial port laster than your progran
can process it, Arduino keeps all the inconing data in a buller. l you need
to clear the buller and let it lll up with lresh data, use the fush() lunction.
Exanple:
Serial.ush();
Appendix C 109
110 Getting Started with Arduino
8o lar, we have used very detailed illustrations to describe how to assenble
our circuits, but as you can inagine, it's not exactly a quick task to draw
one ol those lor any experinent you want to docunent.
8inilar issues arise, sooner or later, in every discipline. n nusic, alter you
write a nice song, you need to write it down using nusical notation.
Engineers, being practical people, have developed a quick way to capture
the essence ol a circuit in order to be able to docunent it and later rebuild
it or pass it to sonebody else.
n electronics, schenat|c d|agrans allow you to describe your circuit in
a way that is understood by the rest ol the connunity. ndividual conpo
nents are represented by synbols that are a sort ol abstraction ol either
the shape ol the conponent or the essence ol then. For exanple, the
capacitor is nade ol two netal plates separated by either air or plastic,
therelore, its synbol is:
Appendix DReading
Schematic Diagrams
Another clear exanple is the inductor, which is built by
winding copper wire around a cylindrical shape, conse
quently the synbol is:
The connections between conponents are usually nade
using either wires or tracks on the printed circuit board
and are represented on the diagran as sinple lines.
When two wires are connected, the connection is repre
sented by a big dot placed where the two lines cross:
Appendix D 111
This is all you need to understand basic schenatics. Here is a nore
conprehensive list ol synbols and their neanings:
You nay encounter variations in these synbols (lor exanple, both
variants ol resistor synbols are shown here). 8ee en.wikipedia.org/wiki/
Eleclronic_symbol lor a larger list ol electronics synbols. By convention,
diagrans are drawn lron lelt to right. For exanple, a radio would be
drawn starting with the antenna on the lelt, lollowing the path ol the radio
signal as it nakes its way to the speaker (which is drawn on the right).
The lollowing schenatic describes the pushbutton circuit shown earlier
in this book:
DIODE LED PUSHBUTTON POTENTIOMETER
RESISTOR CAPACITOR THERMISTOR LDR LIGHT SENSOR
ARDUINO
PIN 7
GND GND
+5 V
112 Getting Started with Arduino
lndex
, (senicolon), 46, 9/
// (connent deliniter), 34-35, 36-3/, 98
(decrenent operator), l04
/ (connent deliniter), 98
&& (and operator), l03
{} (curly brackets), 34-35, 9/
== (equal to), 44-45, l03
= (equality operator), 44-45
~ (greater than), l03
~= (greater than or equal to), l03
++ (increnent operator), l04
(less than), l03
= (less than or equal to), l03
(nodulo), l03
l= (not equal to), l03
l (not operator), l03
|| (or operator), l03
() (parentheses), 36
4lead ROB LED, 84
A
aos lunction, l06
AC adapters, ?0
acceleroneters, /0-/l
actuators
LED, 3/
overview, 30
Anpere, AndreMarie, 4l
anperes, 4l
ana|ogRead lunction, 64-6/, l05
analogue
ana|ogRead lunction, 64-6/, l05
ana|og\r|te lunction, 56-58, 65-6/, l05
input, 64-6/, /3
output, 56-6?, /3
pins, Arduino board, ?0-?l, 64-6/
sensors, 64-68
synthesizers, 8
ana|og\r|te lunction, 56-58, 65-6/, l05
and operator, l03
Arduino
analogue O pins, ?0-?l, 64-6/
delned, l
Diecinila board, ?0, 88
digital O pins, ?0-?l
Duenilanove board, ?0-?l
Extrene board, 88
lorun, 9l-9?
OND pins, 60
hardware, l9-?l
DE, downloading, ??
DE, overview, ??
DE, troubleshooting, 90-9l
DE, website, l
installing, ??-?/
Linux, ??
NO board, ?0-?l, 88
overview, l-3
philosophy, 5-l6
pins, MO8FET transistors, /0
FolyFuse, 89
port identilcation, ?5-?/
power selection |unper, ?0
power supplies, ?0
soltware, ??
troubleshooting board, 88-89
website, l, 9l
website, troubleshooting, 9l
argunents, 36
arithnetic, l03
array variable, l00
A8C, 99
assenbling sphere lanp, 84-85
ATnegal68, l9-?l
Aton lanp, /3
B
Barragan, Hernando, ?
bending circuits, l0-ll
The Betrothed, 36
bitOrder, l05
blinking LED, 30-38, 64-6/
Boolean
operators, l03
variable, 98
bouncing, 49-5l
brackets, curly, 34-35
breadboard, 43, 60, 89-90, 93-94
break control structure, l0?
buller, /6
byte variable, 99
C
C language, ??
calculations, l03
capacitors
reading, 95-96
synbol, ll0, lll
carpet switches, 53
char variable, 98
circuits
bending, l0-ll
blinking LED, 65
building, supplies, 4?-44
pulse width nodulation (FWM), 58-60
pushbuttoncontrolled LED, 4?-43
sphere lanp, 83-84
synbols, schenatics, ll0-lll
testing, 89-90
clockFin, l05
code. 5ee a|so progranning
blinking LED, 3?-38, 64-6/
blocks, nanes, 34-35
pushbuttoncontrolled LED, 44-5l
serial ob|ects, 68-69
sphere lanp, /5-8?
collaboration, l6
Colonbo, Joe, /3
colourcodes, resistors, 95-96
colours, HTML coding, /5-/6
COM ports, Windows, ?6-?/, 90-9l
connand, #defne, 36, 46
connents, 35, 36-3/, 98
connunication, serial, ?5-?/, 68-69, /3,
90-9l, l08-l09
conparison operators, l03
conpiling sketches, 33, 46
conplex sensors, /0-/l
conpound operators, l03-l04
connections, synbol, ll0
constants, 36
constra|n lunction, l06
contact inlornation, ix
continue control structure, l0?
control structures, l00-l0?
cos lunction, l0/
curly brackets, 34-35, 9/
current, 4l-4?
current protection, 89
D
Dante, 36
data connunication, serial ob|ects, 68-69, /3
dataFin, l05
datatypes, 98-l00
debugging
Arduino board, 88-89
breadboarded circuit, 89-90
delned, 88
DE (ntegrated Developnent
Environnent), 90-9l
online help, 9l-9?
reproducing problens, 90
Windows, 90-9l
decrenent operator, l04
#defne, 36, 46
defne connand, 36, 46
de|ay lunction, 3/, l06
de|ayM|croseconds lunction, l06
deliniters
code blocks, 34-35
connent, 35
diagrans, circuits, ll0-lll
Diecinila board, ?0
digital
input, 36-38, /3
O pins, Arduino board, ?0-?l
output, 36-38, /3
d|g|ta|Read lunction, 4?, 64, l04
d|g|ta|\r|te lunction, 3/, l04
diode, synbol, lll
d|v|de et |npera, 8/
D|v|na Conned|a, 36
docunentation, online, 9l-9?
double cos lunction, l0/
double pow lunction, l0/
double s|n lunction, l0/
double tan lunction, l0/
double variable, 99
do...while control structure, l0l
Drain pin, MO8FET transistors, /0
drivers, installing, ?3-?4
driving large loads, /0
Duenilanove board, ?0-?l
Dyson, Janes, 6
E
electricity, 39-4?
equality operator, 44-45
errata, ix
executing sketches, 34
external power, ?0
Extrene board, 88
F
FAL8E, 45
lalse, 98
loat variable, 99
lolder, sketch storage, 3?
lont, generating, 80
lor control structure, l00
lor statenents, l03
lornulas, l03
lorun, Arduino, 9l-9?
lunctions
aos, l06
ana|ogRead, 64-6/, l05
ana|og\r|te, 56-58, 65-67, l05
constra|n, l06
cos, l0/
de|ay, l06
de|ay lunction, 3/
de|ayM|croseconds, l06
d|g|ta|Read, 4?
d|g|ta|\r|te, 3/, l04
|oop, 35, 3/
nap, l0/
nath, l06-l0/
nax, l06
n||||s, l05
n|n, l06
overview, 34-35, 36-3/
p|nMode, 36, l04
pow, l0/
pu|se|n, l05
randon, l08
randon nunber, l08
randon5eed, l08
returning result, 44-45
serial, l08-l09
5er|a|.ava||ao|e, l09
5er|a|.oeg|n, l08
5er|a|.fush, l09
5er|a|.pr|nt, l08-l09
5er|a|.pr|nt|n, l09
5er|a|.read, l09
setup, 35, 36
sh|ftOut, l05
s|n, l0/
tan, l0/
lime, l05-l06
vo|d type, 36-3/
Index 113 114 Getting Started with Arduino
G
gates, MO8FET transistors, /0
Ohazala, Reed, l0
OND pins, 60
ground pins, 60
H
hacking
circuit bending, l0-ll
|unk, l4
keyboards, l?-l3
toys, l5
Haque, Usnan, l5
hardware, Arduino, l9-?l
hexadecinal, /5-/6
HOH, 3/, 98
Hopper, Orace, 88
HTML colour coding, /5-/6
l
l preness| spos|, 36
DE (ntegrated Developnent Environnent)
downloading, ??
overview, ??
troubleshooting, 90-9l
website, l
il control structure. 5ee il statenents
il statenents, 44-45, l00, l03
il...else control structure, l00
goe, Ton, /l
KEA lanp, 84
iMac drivers, ?3
incandescent lanps, driving, /0
increnent operator, l04
inductor, synbol, ll0
inlrared rangers, /0-/l
inlrared sensors, 55, 56
NFUT, 36, 98
input
analogue, 64-6/, /3
digital, 36-38, /3
lunctions, l04-l08
installing
Arduino, ??-?/
Macintosh drivers, ?3
Windows drivers, ?3-?4
int ana|ogRead lunction, l05
int d|g|ta|Read lunction, l04
int 5er|a|.ava||ao|e lunction, l09
int 5er|a|.read lunction, l09
int variable, 99
ntegrated Developnent Environnent (DE).
5ee DE (ntegrated Developnent
Environnent)
ntel drivers, ?3
nteraction Design, ?-3
nteractive Device, ?9
interactive lanps, 38
O pins, Arduino board, ?0-?l, 64-6/
isolating problens, 90
J
|unper, power selection, ?0
|unper wire, 43-44
|unk, l4
K
Kernighan, Brian W., 90
keyboards, hacking, l?-l3
L
lanps
Aton, /3
driving, /0
interactive, 38
sphere, /4-85
LDRs (lightdependent resistors), 30, 63, lll
LEDs
4lead ROB, 84
blinking, 30-38
light sensors, 6?-63
pulse width nodulation (FWM), 56-6?
pushbuttoncontrolled, 4?-5l
sphere lanp, /4-85
synbols, lll
light. 5ee a|so lanps, LEDs
inlrared rangers, /0-/l
lightdependent resistors (LDRs), 30, 63
playing with, 38
pulse width nodulation (FWM), 56-6?
yellow lashing, 88
Linux, ??
loads, driving, /0
long randon lunction, l08
long variable, 99
loop lunction, 35, 3/
LOW, 3/, 98
Low Tech 8ensors and Actuators, l5
M
Macintosh
drivers, installing, ?3
port identilcation, ?5
nagnetic switches, 53
Mak|ng Th|ngs Ta|k, /l
nap lunction, l0/
nath lunctions, l06-l0/
Max, 8
nax lunction, l06
netaloxideseniconductor leldellect
transistor, /0
n||||s lunction, l05
n|n lunction, l06
nodulo, l03
nonentary tactile pushbutton switch, 43
Moog, Robert, 8
MO8FET transistors, /0
notion detection
acceleroneters, /0-/l
carpet switches, 53
nagnetic switches, 53
passive inlrared sensors, 55, 56
reed relays, 53
tilt switches, 54, 56
notors, driving, /0
nultipleline connents, 98
N
nanes, code blocks, 34-35
NO board, ?0-?l, 88
not operator, l03
nunbers
arithnetic and lornulas, l03
nath lunctions, l06-l0/
randon, lunctions, l08
trigononetric lunctions, l06-l0/
variables, 98-l00
O
ob|ects, serial, 68-69, /3
Ohn, Oeorg, 4l
ohns, 4l
Ohn's Law, 4l-4?
Olivetti, l4
on/oll sensors, 53-56
online help, 9l-9?
operators
boolean, l03
conparison, l03
conpound, l03-l04
opportunistic prototyping, 6
or operator, l03
OUTFUT, 36-3/, 98
output
analogue, 56-6?, /3
digital, 36-38, /3
lunctions, l04-l08
P
parentheses, 36
passive inlrared sensors (FR
sensors), 55, 56, 85
patching, 8-9
Fentland, Alex, l3
persistence ol vision, 56-6?
philosophy, Arduino, 5-l6
photoresistors, 30. 5ee a|so LDRs
(lightdependent resistors)
Fhysical Conputing, delned, 3
Fhysical nteraction Design, 3
Fike, Rob, 90
p|nMode unclion, 36, l04
pins, Arduino board
analogue O, ?0-?l
digital O, ?0-?l
ground, 60
MO8FET transistors, /0
FR sensors (passive inlrared
sensors), 55, 56, 85
Firola, Maurizio, 89
Flayground Wiki, l6, 9l
FolyFuse, 89
port identilcation, ?5-?/, 80, 90-9l
potentioneter, synbol, lll
pow lunction, l0/
power supplies, ?0, /0, 88, 89
The Pract|ce of Progrann|ng, 90
Frocessing, l, ??, 69, /5-8?
progranning
aos lunction, l06
ana|ogRead lunction, 64-6/, l05
ana|og\r|te lunction, 56-58, 65-6/, l05
argunents, 36
blinking LED, 30-38, 64-6/
blinking LED code explanation, 36-38
boolean operators, l03
bouncing, 49-5l
calculations, l03
connents, 35, 36-3/
conparison operators, l03
conpound operators, l03-l04
constants, 36, 98
constra|n lunction, l06
control structures, l00-l0?
cos lunction, l0/
curly brackets, 34-35, 9/
cycle, ??
datatypes, 98-l00
#defne, 36, 46
de|ay lunction, 3/, l06
de|ayM|croseconds lunction, l06
d|g|ta|Read lunction, 4?, 64, l04
d|g|ta|\r|te lunction, 3/, l04
lunctions, 34-35, l04-l08
|f statenent, 44-45
|oop lunction, 35, 3/
nap lunction, l0/
nath lunctions, l06-l0/
nax lunction, l06
n||||s lunction, l05
n|n lunction, l06
p|nMode lunction, 36, l04
pow lunction, l0/
pulse width nodulation (FWM), 56-6?
pu|se|n lunction, l05
pushbuttoncontrolled LED, 4?-5l
RAM, 46
randon lunction, l08
randon nunber lunctions, l08
randon5eed lunction, l08
serial lunctions, l08-l09
serial ob|ects, 68-69, /3
5er|a|.ava||ao|e lunction, l09
5er|a|.oeg|n lunction, l08
5er|a|.fush lunction, l09
5er|a|.pr|nt lunction, l08-l09
5er|a|.pr|nt|n lunction, l09
5er|a|.read lunction, l09
setup lunction, 35, 36
sh|ftOut lunction, l05
s|n lunction, l0/
special characters, 9/-98
sphere lanp, /5-8?
state, 4/-48
structure, 9/
tan lunction, l0/
tine lunctions, l05-l06
va|, 46-48
variables, 45-46, 98-l00
visual, 8
vo|d lunction type, 36-3/
prototyping, 6
proxy, /5
pseudorandon nunber generator, l08
pulse width nodulation (FWM), 56-6?
pu|se|n lunction, l05
Fure Data, 8
pushbuttoncontrolled LEDs, 4?-5l, lll
FWM (pulse width nodulation), 56-6?
FWR_8EL, ?0
Index 115 116 Getting Started with Arduino
R
rails, breadboard, 60
RAM, 46
randon lunction, l08
randon nunber lunctions, l08
randon5eed lunction, l08
reading resistors and capacitors, 95-96
Reas, Casey, ?
receiving data, serial ob|ects, 68-69, /3
reed relays, 53
register, shilt, l05
relays, reed, 53
reproducing problens, 90
resistance, 4l-4?, 68
resistors
circuit building supplies, 43
lightdependent (LDR), 30, 63
reading, 95-96
synbol, lll
variable, 4l
return control structure, l0?
ROB LED, 4lead, 84
R88 leed, lanp control, /5
S
schenatics, synbols, ll0-lll
selecting ports, ?5-?/
senicolon, 46, 9/
sending data, serial ob|ects, 68-69, /3
sensors
acceleroneters, /0-/l
analogue, 64-68
blinking LED, 64-6/
carpet switches, 53
circuit diagran synbols, lll
conplex, /0-/l
inlrared, 55, 56, 85
inlrared rangers, /0-/l
keyboard hacking, l3
light, 6?-63
nagnetic switches, 53
on/oll, 53-56
overview, 30
pushbutton, 4?
reed relays, 53
thernistors, 68
thernostats, 53, 56
tilt switches, 54, 56, 85
ultrasonic rangers, /0-/l
serial
connunication, ?5-?/, 68-69, /3,
90-9l, l08-l09
ob|ects, 68-69, /3
ports, ?5-?/, 90-9l
5er|a|.ava||ao|e lunction, l09
5er|a|.oeg|n lunction, l08
5er|a|.fush lunction, l09
5er|a|.pr|nt lunction, l08-l09
5er|a|.pr|nt|n lunction, l09
5er|a|.read lunction, l09
setup lunction, 35, 36
shilt register, l05
sh|ftOut lunction, l05
short circuits, 89
s|n lunction, l0/
singleline connents, 98
sketches
aos lunction, l06
ana|ogRead lunction, 64-6/, l05
ana|og\r|te funct|on, 56-58, 65-6/, l05
argunents, 36
blinking LED, 30-38, 64-6/
blinking LED code explanation, 36-38
boolean operators, l03
bouncing, 49-5l
calculations, l03
connents, 35, 36-3/
conparison operators, l03
conpiling, 33, 46
conpound operators, l03-l04
constants, 36, 98
constra|n lunction, l06
control structures, l00-l0?
cos lunction, l0/
curly brackets, 34-35, 9/
datatypes, 98-l00
#defne, 36, 46
de|ay lunction, 3/, l06
de|ayM|croseconds lunction, l06
d|g|ta|Read lunction, 4?, 64, l04
d|g|ta|\r|te lunction, 3/, l04
downloading, 3?
executing, 34
lunctions, 34-35, l04-l08
il statenent, 44-45
|oop lunction, 35, 3/
nap lunction, l0/
nath lunctions, l06-l0/
nax lunction, l06
n||||s lunction, l05
n|n lunction, l06
passive inlrared sensors, 56-6?
p|nMode lunction, 36, l04
pow lunction, l0/
pulse width nodulation (FWM), 56-6?
pu|se|n lunction, l05
pushbuttoncontrolled LED, 4?-5l
RAM, 46
randon lunction, l08
randon nunber lunctions, l08
randon5eed lunction, l08
serial lunctions, l08-l09
serial ob|ects, 68-69, /3
5er|a|.ava||ao|e lunction, l09
5er|a|.oeg|n lunction, l08
5er|a|.fush lunction, l09
5er|a|.pr|nt lunction, l08-l09
5er|a|.pr|nt|n lunction, l09
5er|a|.read lunction, l09
setup lunction, 35, 36
sh|ftOut lunction, l05
s|n lunction, l0/
special characters, 9/-98
sphere lanp, /5-8?
state, 4/-48
structure, 9/
tan lunction, l0/
tine lunctions, l05-l06
uploading, 33
va|, 46-48
variables, 45-46, 98-l00
vo|d lunction type, 36-3/
5n|n C|ue, ll
solderless breadboard, 43, 93-94
8onlaiFischer, Adan, l5
sound, ultrasonic rangers, /0-/l
8ource pin, MO8FET transistors, /0
special characters
, (senicolon), 46, 9/
// (connent deliniter), 34-35, 36-3/, 98
(decrenent operator), l04
/ (connent deliniter), 98
&& (and operator), l03
{} (curly brackets), 34-35, 9/
== (equal to), 44-45, l03
~ (greater than), l03
~= (greater than or equal to), l03
= (il statenent), 44-45
++ (increnent operator), l04
(less than), l03
(nodulo), l03
l= (not equal to), l03
l (not operator), l03
|| (or operator), l03
() (parentheses), 36
arithnetic synbols, l03
A8C, 99
UNCODE, 99
sphere lanp, /4-85
state, 4/-48
string variable, 99-l00
structure, sketch, 9/, l00-l0?
supplies, circuit building, 4?-44
surplus, l4
8Vl |unper, 88
switch case control structure, l00-l0l
switches
bouncing, 49-5l
carpet, 53
nagnetic, 53
MO8FET transistors, /0
on/oll, 53
pushbutton, 43
reed relays, 53
tilt, 54, 56, 85
synbols
progranning (5ee special characters)
schenatics, ll0-lll
synthesizers, analogue, 8
T
tactile pushbutton switch, 43
tan lunction, l0/
test progran, Arduino, 88
thernistors, 68, lll
thernostats, 53, 56
tilt switches, 54, 56, 85
tine lunctions, l05-l06
tinkering, /
toys, hacking, l5
transistors, MO8FET, /0
trigononetric lunctions, l06-l0/
troubleshooting
Arduino board, 88-89
breadboarded circuit, 89-90
DE (ntegrated Developnent
Environnent), 90-9l
online help, 9l-9?
overview, 8/-88
reproducing problens, 90
Windows, 90-9l
trout, large, 9?
TRUE, 45
true, 98
U
ultrasonic rangers, /0-/l
UNCODE, 99
unsigned int variable, 99
unsigned long n||||s lunction, l05
uploading sketch, 33
U8B
ports, Windows, ?6-?/, 90-9l
power supplies, ?0
serial ob|ects, 68-69
testing, 88
V
vacuun cleaner, 6
val, 46-48
variable resistors, 4l
variables, 44-46, 98-l00
Verily button, 33
Vista, Windows
drivers, ?4
port identilcation, ?6-?/, 90-9l
troubleshooting, 90-9l
visual progranning, 8
vo|d lunction type, 36-3/
Volta, Alessandro, 4l
voltage, 4l-4?
volts, 4l
VVVV, 8
W
water analogy, electricity, 39-4?
while control structure, l0l
wh||e statenents, l03
Wiki, Flayground, l6, 9l
Windows
drivers, installing, ?3-?4
port identilcation, ?5, ?6-?/
troubleshooting, 90-9l
wire, |unper, 43-44
X
XML, proxy, /5
XF, Windows
drivers, ?3-?4
port identilcation, ?6-?/, 90-9l
troubleshooting, 90-9l
Y
yellow lashing light, 88
Index 117

Вам также может понравиться