Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Massimo Banzi-Getting Started with Arduino -Make (2011)
Description: Massimo Banzi-Getting Started with Arduino -Make (2011)

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Getting
Started
with
Arduino
Massimo Banzi
Second Edition

Getting Started with Arduino
by Massimo Banzi

Copyright © 2011 Massimo Banzi
...

Printed in the U
...
A
...

1005 Gravenstein Highway North, Sebastopol, CA 95472
O’Reilly books may be purchased for educational, business,
or sales promotional use
...
com
...

The Make: Projects series designations and related trade dress
are trademarks of O’Reilly Media, Inc
...

Important Message to Our Readers: Your safety is your own
responsibility, including proper use of equipment and safety gear,
and determining whether you have adequate skill and experience
...
Some illustrations do not depict safety
precautions or equipment, in order to show the project steps
more clearly
...

Use of the instructions and suggestions in Getting Started with
Arduino is at your own risk
...
, and the author
disclaim all responsibility for any resulting damage, injury, or
expense
...


ISBN: 978-1-449-309879

[LSI]

Contents
Preface
...
1
Intended Audience
...
3
2/The Arduino Way
...

Prototyping
...
7
Patching
...
10
Keyboard Hacks
...
14
Hacking Toys
...
16
3/The Arduino Platform
...
17
The Software (IDE)
...
20
Installing Drivers: Macintosh
...
21
Port Identification: Macintosh
...
24
4/Really Getting Started with Arduino
...
27
Sensors and Actuators
...
28
Pass Me the Parmesan
...
33
Real Tinkerers Write Comments
...
34
What We Will Be Building
...
37
Using a Pushbutton to Control the LED
...
42
One Circuit, A Thousand Behaviours
...
51
Trying Out Other On/Off Sensors
...
54

Use a Light Sensor Instead of the Pushbutton
...
62
Try Other Analogue Sensors
...
66
Driving Bigger Loads (Motors, Lamps, and the Like)
...
68
6/Talking to the Cloud
...
73
Coding
...
81
Here’s How to Assemble It
...
85
Testing the Board
...
87
Isolating Problems
...
88
How to Get Help Online
...
91
Appendix A/The Breadboard
...
93
Appendix C/Arduino Quick Reference
...
108
Index
...

I started following a subconscious instinct to teach electronics the same
way I was taught in school
...

In reality, when I was in school I already knew electronics in a very empirical
way: very little theory, but a lot of hands-on experience
...

» I slowly learned what all those components were
...


» I started building some kits sold by electronics magazines
...


As a little kid, I was always fascinated by discovering how things work;
therefore, I used to take them apart
...
Eventually, people brought all sorts of devices for me to dissect
...

After quite a lot of this dissecting, I knew what electronic components
were and roughly what they did
...
I spent hours reading the articles and looking at the circuit
diagrams without understanding very much
...

A great breakthrough came one Christmas, when my dad gave me a kit
that allowed teenagers to learn about electronics
...
Little did I know that the toy was also a landmark of German design,
because Dieter Rams designed it back in the 1960s
...
The prototyping cycle was getting shorter and shorter
...

I’ve spent a long time looking for an English word that would sum up that
way of working without a specific plan, starting with one idea and ending
up with a completely unexpected result
...

I recognised how this word has been used in many other fields to describe
a way of operating and to portray people who set out on a path of exploration
...
The best definition of tinkering
that I’ve ever found comes from an exhibition held at the Exploratorium
in San Francisco:  
Tinkering is what happens when you try something you don’t quite know
how to do, guided by whim, imagination, and curiosity
...
It’s about figuring out how things work and reworking
them
...

Tinkering is, at its most basic, a process that marries play and inquiry
...
exploratorium
...

Another breakthrough came in the summer of 1982, when I went to London
with my parents and spent many hours visiting the Science Museum
...

There I realised that in many applications, engineers were no longer building circuits from basic components, but were instead implementing a lot
of the intelligence in their products using microprocessors
...

When I came back I started to save money, because I wanted to buy a
computer and learn how to program
...
I know it doesn’t sound like
a very exciting project, but there was a need for it and it was a great challenge for me, because I had just learned how to program
...

Twenty-odd years later, I’d like to think that this experience allows me to
teach people who don’t even remember taking any math class and to infuse
them with the same enthusiasm and ability to tinker that I had in my youth
and have kept ever since
...

First of all I want to thank my partners in the Arduino Team:
David Cuartielles, David Mellis, Gianluca Martino, and Tom Igoe
...

Barbara Ghella, she doesn’t know, but, without her precious
advice, Arduino and this book might have never happened
...

Gillian Crampton-Smith for giving me a chance and for all I have
learned from her
...

Brian Jepson for being a great editor and enthusiastic supporter
all along
...

I want to thank a lot more people but Brian tells me I’m running
out of space, so I’ll just list a small number of people I have to
thank for many reasons:
Adam Somlai-Fisher, Ailadi Cortelletti, Alberto Pezzotti,
Alessandro Germinasi, Alessandro Masserdotti, Andrea Piccolo,
Anna Capellini, Casey Reas, Chris Anderson, Claudio Moderini,
Clementina Coppini, Concetta Capecchi, Csaba Waldhauser,
Dario Buzzini, Dario Molinari, Dario Parravicini, Donata Piccolo,
Edoardo Brambilla, Elisa Canducci, Fabio Violante, Fabio Zanola,
Fabrizio Pignoloni, Flavio Mauri, Francesca Mocellin, Francesco
Monico, Giorgio Olivero, Giovanna Gardi, Giovanni Battistini,
Heather Martin, Jennifer Bove, Laura Dellamotta, Lorenzo
Parravicini, Luca Rocco, Marco Baioni, Marco Eynard, Maria
Teresa Longoni, Massimiliano Bolondi, Matteo Rivolta, Matthias
Richter, Maurizio Pirola, Michael Thorpe, Natalia Jordan,
Ombretta Banzi, Oreste Banzi, Oscar Zoggia, Pietro Dore,
Prof Salvioni, Raffaella Ferrara, Renzo Giusti, Sandi Athanas,
Sara Carpentieri, Sigrid Wiederhecker, Stefano Mirti, Ubi De Feo,
Veronika Bucko
...
As a reader of this book, you can help
us to improve future editions by sending us your feedback
...

Please also let us know what we can do to make this book more
useful to you
...

You can write to us at:
Maker Media
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the U
...
or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)
Maker Media is a division of O’Reilly Media devoted entirely to
the growing community of resourceful people who believe that
if you can imagine it, you can make it
...

For more information about Maker Media, visit us online:
MAKE
www
...
com
CRAFT:
www
...
com
Maker Faire: www
...
com
Hacks:
www
...
com
To comment on the book, send email to
bookquestions@oreilly
...

The O’Reilly web site for Getting Started with Arduino lists
examples, errata, and plans for future editions
...
makezine
...

For more information about this book and others, see the
O’Reilly website: www
...
com
...
arduino
...


Preface

ix

1/Introduction
Arduino is an open source physical computing
platform based on a simple input/output
(I/O) board and a development environment
that implements the Processing language
(www
...
org)
...
The boards can be assembled
by hand or purchased preassembled; the
open source IDE (Integrated Development
Environment) can be downloaded for free
from www
...
cc
...


» It is based on the Processing programming IDE, an easy-to-use


development environment used by artists and designers
...
This feature is useful,


because many modern computers don’t have serial ports
...


Introduction

1

» The hardware is cheap
...
So you can afford to make mistakes
...


» The Arduino Project was developed in an educational environment and


is therefore great for newcomers to get things working quickly
...


Intended Audience
This book was written for the “original” Arduino users: designers and
artists
...
Actually, one of them called the introductory chapters
of my first draft “fluff”
...
Let’s face it: most
engineers aren’t able to explain what they do to another engineer, let
alone a regular human being
...

NOTE: Arduino builds upon the thesis work Hernando Barragan did on
the Wiring platform while studying under Casey Reas and me at IDII
Ivrea
...
I realised that you’re all artists and designers in
your own right, so this book is for you as well
...
There are many definitions of Interaction Design, but the one that I prefer is:

Interaction Design is the design of any interactive experience
...
It is a
good way to explore the creation of beautiful—and maybe even controversial—experiences between us and technology
...
This approach—also part of some types
of “conventional” design—can be extended to include prototyping with
technology; in particular, prototyping with electronics
...


What Is Physical Computing?
Physical Computing uses electronics to prototype new materials for
designers and artists
...

In the past, using electronics meant having to deal with engineers all the
time, and building circuits one small component at the time; these issues
kept creative people from playing around with the medium directly
...

In recent years, microcontrollers have become cheaper and easier to use,
allowing the creation of better tools
...

With Arduino, a designer or artist can get to know the basics of electronics
and sensors very quickly and can start building prototypes with very little
investment
...
It is
a constant search for faster and more powerful ways to build better prototypes
...

Classic engineering relies on a strict process for getting from A to B;
the Arduino Way delights in the possibility of getting lost on the way and
finding C instead
...
In this search
for ways to build better prototypes, we also selected a number of software packages that enable the process of constant manipulation of the
software and hardware medium
...


The Arduino Way

5

Prototyping
Prototyping is at the heart of the Arduino Way: we make things and build
objects that interact with other objects, people, and networks
...

A lot of beginners approaching electronics for the first time think that they
have to learn how to build everything from scratch
...

This is why we developed “opportunistic prototyping”: why spend time
and energy building from scratch, a process that requires time and indepth technical knowledge, when we can take ready-made devices and
hack them in order to exploit the hard work done by large companies
and good engineers?
Our hero is James Dyson, who made 5127 prototypes of his vacuum
cleaner before he was satisfied that he’d gotten it right (www
...

dyson
...
asp)
...

Reusing existing technology is one of the best ways of tinkering
...


The Arduino Way

7

Patching
I have always been fascinated by modularity and the ability to build complex
systems by connecting together simple devices
...
Musicians
constructed sounds, trying endless combinations by “patching together”
different modules with cables
...

Moog described it as a process between “witnessing and discovering”
...

Reducing the number of interruptions to the flow is very important for
creativity—the more seamless the process, the more tinkering happens
...
These tools
can be visualised as “boxes” for the different functionalities that they provide, letting the user build “patches” by connecting these boxes together
...
If you are more
visually minded, I recommend that you try them out
...
It’s the
creative short-circuiting of low-voltage, battery-powered electronic audio
devices such as guitar effect pedals, children’s toys, and small synthesizers to create new musical instruments and sound generators
...
It began in 1966 when Reed Ghazala,
by chance, shorted-out a toy amplifier against a metal object in his desk
drawer, resulting in a stream of unusual sounds
...


10

Getting Started with Arduino

It’s a bit like the Sniffin’ Glue fanzine shown here: during the punk era,
knowing three chords on a guitar was enough to start a band
...
Ignore them
and surprise them
...
Alex Pentland, academic head of the MIT Media
Laboratory, once remarked: “Excuse the expression, but men’s urinals
are smarter than computers
...
”1
As tinkerers, we can implement new ways to interact with software by
replacing the keys with devices that are able to sense the environment
...
The heart of it is a small board
...
If you remove the circuit and use
a wire to bridge two contacts, you’ll see a letter appear on the computer
screen
...
Map this to your favourite software,
and you have made your computer as smart as a urinal
...


1
Quoted in Sara Reese Hedberg, “MIT Media Lab’s quest for perceptive computers,” Intelligent Systems and
Their Applications, IEEE, Jul/Aug 1998
...
There has always been a big market for this surplus technology,
especially among young and/or poorer hackers and those who are just
starting out
...
The city used to be the headquarters of the Olivetti company
...
These are full of computer parts, electronic components, and weird devices of all kinds
...
When you can buy a thousand
loudspeakers for very little money, you’re bound to come up with some
idea in the end
...


14

Getting Started with Arduino

Hacking Toys
Toys are a fantastic source of cheap technology to hack and reuse, as
evidenced by the practise of circuit bending mentioned earlier
...

I have been doing this for a few years to get my students to understand
that technology is not scary or difficult to approach
...
propositions
...
uk)
...


The Arduino Way

15

Collaboration
Collaboration between users is one of they key principles in the Arduino
world—through the forum at www
...
cc, people from different parts
of the world help each other learn about the platform
...
We also set up a Wiki called
“Playground” (www
...
cc/playground) where users document their
findings
...
This culture of sharing and helping
each other is one of the things that I’m most proud of in regard to Arduino
...
You use the IDE to create
a sketch (a little computer program) that you
upload to the Arduino board
...

Not too long ago, working on hardware meant building circuits from
scratch, using hundreds of different components with strange names like
resistor, capacitor, inductor, transistor, and so on
...

With the appearance of digital technologies and microprocessors, these
functions, which were once implemented with wires, were replaced by
software programs
...
With a few keypresses, you can
radically change the logic of a device and try two or three versions in the
same amount of time that it would take you to solder a couple of resistors
...
This computer is at least a thousand times less powerful than
the MacBook I’m using to write this, but it’s a lot cheaper and very useful
to build interesting devices
...

The Arduino Platform

17

We (the Arduino team) have placed on this board all the components that
are required for this microcontroller to work properly and to communicate
with your computer
...
However, these instructions apply
to earlier versions of the board, including the Arduino Duemilanove from
2009
...

In those illustrations, you see the Arduino board
...
Here is an explanation of what every
element of the board does:
14 Digital IO pins (pins 0–13)
These can be inputs or outputs, which is specified by the sketch you
create in the IDE
...
e
...

6 Analogue Out pins (pins 3, 5, 6, 9, 10, and 11)
These are actually six of the digital pins that can be reprogrammed for
analogue output using the sketch you create in the IDE
...
1mm barrel tip,
center positive)
...


NOTE: If you are using the older Arduino-NG or Arduino Diecimila,
you will need to set the power selection jumper (labelled PWR_SEL on
the board) to specify EXT (external) or USB power
...


18

Getting Started with Arduino

Figure 3-1
...
The Arduino Duemilanove

The Arduino Platform

19

The Software (IDE)
The IDE (Integrated Development Environment) is a special program
running on your computer that allows you to write sketches for the
Arduino board in a simple language modeled after the Processing
(www
...
org) language
...
This last step is quite important, because it’s where Arduino makes your life simple by hiding away as
much as possible of the complexities of programming microcontrollers
...

» Write a sketch that will bring the board to life
...


» The board executes the sketch that you wrote
...
See
www
...
cc/playground/Learning/Linux for instructions
...
arduino
...

Choose the right version for your operating system
...
0
...
On the Mac, double-clicking it will open a disk
image with an Arduino application (drag it to your Applications folder)
...
Don’t do this yet, though; there is one more step
...


Now you must install the drivers that allow your computer to talk to your
board through the USB port
...
Plug the board into your computer
...

You might see a popup window telling you that a new network interface
has been detected
...
” and when it opens, click
,
“Apply”
...
Quit System Preferences
...
arduino
...

If the Arduino doesn’t work, see Chapter 7, Troubleshooting
...

Windows XP will ask you whether to check Windows Update; if you don’t
want to use Windows Update, select the “No, not at this time” option and
click Next
...


The Arduino Platform

21

Navigate to and select the Uno’s driver file, named ArduinoUNO
...
Windows will finish up the driver
installation from there
...
arduino
...

Once the drivers are installed, you can launch the Arduino IDE and start
using Arduino
...
The instructions
for getting this information are in the following sections
...
usbmodem; this is the name that your
computer uses to refer to the Arduino board
...


Figure 3-3
...
Open the Device Manager by clicking the Start menu, right-clicking
on Computer (Vista) or My Computer (XP), and choosing Properties
...
On Vista, click
Device Manager (it appears in the list of tasks on the left of the window)
...
The
Arduino will appear as “Arduino UNO” and will have a name like COM3,
as shown in Figure 3-4
...

The Windows Device Manager showing all available serial ports

24

Getting Started with Arduino

Note: On some Windows machines, the COM port has a number
greater than 9; this numbering creates some problems when Arduino is
trying to communicate with it
...


Once you’ve figured out the COM port assignment, you can select that
port from the Tools > Serial Port menu in the Arduino IDE
...


The Arduino Platform

25

4/Really Getting Started
with Arduino
Now you’ll learn how to build and program an
interactive device
...
The Interactive Device is an electronic
circuit that is able to sense the environment using sensors (electronic
components that convert real-world measurements into electrical signals)
...
The device will then be able to
interact with the world using actuators, electronic components that can
convert an electric signal into a physical action
...

The interactive device

Really Getting Started with Arduino

27

Sensors and Actuators
Sensors and actuators are electronic components that allow a piece of
electronics to interact with the world
...
For it to sense light, temperature, or other physical quantities,
it needs something that can convert them into electricity
...
In electronics, we can use a simple device called a light-dependent
resistor (an LDR or photoresistor) that can measure the amount of light
that hits it and report it as a signal that can be understood by the microcontroller
...
The decision-making process is handled by the
microcontroller, and the reaction is performed by actuators
...
In the electronic world, these functions could be
performed by a light or an electric motor
...


Blinking an LED
The LED blinking sketch is the first program that you should run to test
whether your Arduino board is working and is configured correctly
...
A light-emitting diode (LED) is a small
electronic component that’s a bit like a light bulb, but is more efficient and
requires lower voltages to operate
...
It’s marked “L”
...

If you intend to keep the LED lit for a long period of time, you should
use a resistor as described on page 56
...


28

Getting Started with Arduino

Figure 4-2
...
This is
done through code, that is, a list of instructions that we give the microcontroller to make it do what we want
...

Double-click the Arduino icon to start it
...
Name it Blinking_LED and click OK
...
You can also download it from www
...
com/
getstartedarduino
...


// Example 01 : Blinking LED
const int 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

}

30

Getting Started with Arduino

Verify
Upload to I/O board

Your sketch goes here
Figure 4-3
...
Press
the “Verify” button (Figure 4-3 shows its location); if everything is correct,
you’ll see the message “Done compiling” appear at the bottom of the
Arduino IDE
...
exe file in Windows or an
...

At this point, you can upload it into the board: press the Upload to I/O
Board button (see Figure 4-3)
...
The
Arduino IDE sends the current sketch to the board, which will store it in
its memory and eventually run it
...
There
are two LEDs, marked RX and TX, on the board; these flash every time
a byte is sent or received by the board
...

If you don’t see the LEDs flicker, or if you get an error message instead of
“Done uploading”, then there is a communication problem between your
computer and Arduino
...
Also, check the Tools > Board
menu to confirm that the correct model of Arduino is selected there
...

Once the code is in your Arduino board, it will stay there until you put
another sketch on it
...

Assuming that the sketch has been uploaded correctly, you will see the
LED “L” turn on for a second and then turn off for a second
...

What you have just written and run is a “computer program”, or sketch,
as Arduino programs are called
...
This is
done using a programming language to type a series of instructions in
the Arduino IDE, which turns it into an executable for your Arduino board
...
First of all, the Arduino
executes the code from top to bottom, so the first line at the top is the
first one read; then it moves down, a bit like how the playhead of a video
player like QuickTime Player or Windows Media Player moves from left
to right showing where in the movie you are
...
These are particularly useful when you want to give a name
to a group of instructions
...
As we’re
humans, it all comes naturally, but all the individual tiny actions required
to do this must be spelled out to the Arduino, because it’s not as powerful
32

Getting Started with Arduino

as our brain
...

You can see that there are two blocks of code that are defined in this way
here
...
If you were to write a list of
instructions that teach Arduino how to pass the Parmesan, you would
write void passTheParmesan() at the beginning of a block, and this block
would become an instruction that you can call from anywhere in the
Arduino code
...
If after this, you write
passTheParmesan() anywhere in your code, Arduino will execute those
instructions and continue where it left off
...

setup() is where you put all the code that you want to execute once at the
beginning of your program and loop() contains the core of your program,
which is executed over and over again
...
When you power up the board, the
code runs; when you want to stop, you just turn it off
...
These lines are comments,
which are notes that you leave in the program for yourself, so that you can
remember what you did when you wrote it, or for somebody else, so that
they can understand your code
...
At this point, you open up the program,
and if you haven’t included any comments in the original program, you’ll
think, “Wow—what a mess! Where do I start?” As we move along, you'll
see some tricks for how to make your programs more readable and easier
to maintain
...
For each
line of the poems, there were a hundred lines of commentary! However,
the explanation will be much more useful here as you move on to writing
your own programs
...
The preceding title
comment just reminds us that this program, Example 01, blinks an LED
...
e
...
It’s like an automatic search and replace for your code; in this case, it’s telling Arduino to write the number 13
every time the word LED appears
...

void setup()

This line tells Arduino that the next block of code will be called setup()
...

pinMode(LED, OUTPUT); // sets the digital
// pin as output

Finally, a really interesting instruction
...
Digital pins can be used either as INPUT or OUTPUT
...

pinMode is a function, and the words (or numbers) specified inside the
parentheses are arguments
...
(Like variables, constants are assigned values, except
that constant values are predefined and never change
...


34

Getting Started with Arduino

void loop()
{

loop() is where you specify the main behaviour of your interactive device
...

digitalWrite(LED, HIGH);

// turns the LED on

As the comment says, digitalWrite() is able to turn on (or off) any pin that
has been configured as an OUTPUT
...
The
second argument can turn the pin on (HIGH) or off (LOW)
...
European ones are 230 V, American
ones are 110 V, and Arduino works at a more modest 5 V
...
When you write digitalWrite(LED,
HIGH), it turns the output pin to 5 V, and if you connect an LED, it will light
up
...
Turning on and off the pin at will now let us translate these into
something more visible for a human being; the LED is our actuator
...
Therefore, if you want things to happen
with a certain regularity, you tell it to sit quietly and do nothing until it is
time to go to the next step
...
Milliseconds are thousandths of seconds; therefore, 1000
milliseconds equals 1 second
...

digitalWrite(LED, LOW);

// turns the LED off

This instruction now turns off the LED that we previously turned on
...

HIGH means that the pin is on, and in the case of Arduino, it will be set at
5 V
...
You can also replace these arguments mentally with
ON and OFF
...
The LED will be off for one second
...


Really Getting Started with Arduino

35

To sum up, this program does this:

» Turns pin 13 into an output (just once at the beginning)
» Enters a loop
» Switches on the LED connected to pin 13
» Waits for a second
» Switches off the LED connected to pin 13
» Waits for a second
» Goes back to beginning of the loop
I hope that wasn’t too painful
...

Before we move on to the next section, I want you to play with the code
...
In
particular, you should see what happens when you make the delays very
small, but use different delays for on and off … there is a moment when
something strange happens; this “something” will be very useful when
you learn about pulse-width modulation later in this book
...
I have been lucky enough to work on
some interesting projects that involve controlling light and making it
interact with people
...
Throughout this book,
we will be working on how to design “interactive lamps”, using Arduino
as a way to learn the basics of how interactive devices are built
...


36

Getting Started with Arduino

What Is Electricity?
If you have done any plumbing at home, electronics won’t be a problem
for you to understand
...
Let’s
take a simple device, like the battery-powered portable fan shown in
Figure 4-4
...

A portable fan

If you take a fan apart, you will see that it contains a small battery, a
couple of wires, and an electric motor, and that one of the wires going to
the motor is interrupted by a switch
...
How does this work? Well, imagine that the battery is both a water
reservoir and a pump, the switch is a tap, and the motor is one of those
wheels that you see in watermills
...

In this simple hydraulic system, shown in Figure 4-5, two factors are
important: the pressure of the water (this is determined by the power of
pump) and the amount of water that will flow in the pipes (this depends on
the size of the pipes and the resistance that the wheel will provide to the
stream of water hitting it)
...

A hydraulic system

You’ll quickly realise that if you want the wheel to spin faster, you need to
increase the size of the pipes (but this works only up to a point) and increase the pressure that the pump can achieve
...
This approach works up to a certain point, at which the wheel won’t
spin any faster, because the pressure of the water is not strong enough
...
This method
of speeding up the watermill can go on until the point when the wheel falls
apart because the water flow is too strong for it and it is destroyed
...
It is important to understand that in a system like this, not
all the energy you pump into the system will be converted into movement;
some will be lost in a number of inefficiencies and will generally show up
as heat emanating from some parts of the system
...

Electricity works a bit like water
...

So when you read that a battery’s voltage is 9 V, think of this voltage like
the water pressure that can potentially be produced by this little “pump”
...

Just as water pressure has an electric equivalent, the flow rate of water
does, too
...
The relationship
between voltage and current can be illustrated by returning to the water
wheel: a higher voltage (pressure) lets you spin a wheel faster; a higher
flow rate (current) lets you spin a larger wheel
...
Herr Ohm was also responsible
for formulating the most important law in electricity—and the only formula
that you really need to remember
...

It’s very intuitive, if you think about it
...
While measuring current, you will find that the more resistors you add to the circuit, the less current will travel through it
...
Ohm summarised his law in these formulae:
R (resistance) = V (voltage) / I (current)
V = R * I
I = V / R

This is the only rule that you really have to memorise and learn to use,
because in most of your work, this is the only one that you will really need
...

Therefore, you need to learn how to control it
...

What is missing to complete the picture is a sensor
...

If you were to take apart a pushbutton, you would see that it is a very
simple device: two bits of metal kept apart by a spring, and a plastic cap
that when pressed brings the two bits of metal into contact
...

To monitor the state of a switch, there’s a new Arduino instruction that
you’re going to learn: the digitalRead() function
...
The other instructions that we’ve used so
far haven’t returned any information—they just executed what we asked
them to do
...
With digitalRead(), we can “ask a question” of
Arduino and receive an answer that can be stored in memory somewhere
and used to make decisions immediately or later
...
To build this, you’ll need to obtain some
parts (these will come in handy as you work on other projects as well):

40

Getting Started with Arduino

» Solderless breadboard: Maker Shed (www
...
com) part number MKKN3, Arduino Store (bit
...
Appendix A
is an introduction to the solderless breadboard
...
ly/ArduinoStore10k, 10-pack)

» Momentary tactile pushbutton switch: Maker Shed JM119011, Arduino
Store (bit
...

Hooking up a pushbutton

Really Getting Started with Arduino

41

NOTE: instead of buying precut jumper wire, you can also buy 22 AWG
solid-core hookup wire in small spools and cut and strip it using wire
cutters and wire strippers
...
When Arduino asks you to name your new sketch
folder, type PushButtonControl
...
makezine
...
If everything is correct, the LED will light up when
you press the button
...

42

Getting Started with Arduino

The if statement is possibly the most important instruction in a programming language, because it allows the computer (and remember, the
Arduino is a small computer) to make decisions
...
Notice that I have used the ==
symbol instead of =
...
Make
sure that you use the correct one, because it is very easy to make that
mistake and use just =, in which case your program will never work
...

Holding your finger on the button for as long as you need light is not
practical
...


One Circuit, A Thousand Behaviours
The great advantage of digital, programmable electronics over classic
electronics now becomes evident: I will show you how to implement many
different “behaviours” using the same electronic circuit as in the previous
section, just by changing the software
...
We therefore must implement some
form of “memory”, in the form of a software mechanism that will remember when we have pressed the button and will keep the light on even after
we have released it
...
(We have used
one already, but I haven’t explained it
...
Think of it like one of those sticky
notes you use to remind yourself about something, such as a phone
number: you take one, you write “Luisa 02 555 1212” on it, and you stick
it to your computer monitor or your fridge
...
For example:
int val = 0;

int means that your variable will store an integer number, val is the name
of the variable, and = 0 assigns it an initial value of zero
...


Note: Have you noticed that in Arduino, every instruction ends with
a semicolon? This is done so that the compiler (the part of Arduino
that turns your sketch into a program that the microcontroller can
run) knows that your statement is finished and a new one is beginning
...


In the following program, val is used to store the result of digitalRead();
whatever Arduino gets from the input ends up in the variable and will stay
there until another line of code changes it
...
It is quite fast, but when you turn off your board,
all data stored in RAM is lost (which means that each variable is reset
to its initial value when the board is powered up again)
...

Let’s now use another variable to remember whether the LED has to stay
on or off after we release the button
...
You will notice that it works … somewhat
...

Let’s look at the interesting parts of the code: state is a variable that
stores either 0 or 1 to remember whether the LED is on or off
...

Really Getting Started with Arduino

45

Later, we read the current state of the button, and if it’s pressed (val ==
HIGH), we change state from 0 to 1, or vice versa
...
The trick I use involves a small
mathematical expression based on the idea that 1 – 0 is 1 and 1 – 1 is 0:
state = 1 – state;

The line may not make much sense in mathematics, but it does in programming
...

Later in the program, you can see that we use state to figure out whether
the LED has to be on or off
...

The results are flaky because of the way we read the button
...
So this means that while your finger is pressing the button, Arduino
might be reading the button’s position a few thousand times and changing state accordingly
...
As even a broken clock is right
twice a day, the program might show the correct behaviour every once
in a while, but much of the time it will be wrong
...

The way I like to do it is to store the value of val before I read a new one;
this allows me to compare the current position of the button with the
previous one and change state only when the button becomes HIGH after
being LOW
...
Pushbuttons are very simple
devices: two bits of metal kept apart by a spring
...
This
sounds fine and simple, but in real life the connection is not that perfect,
especially when the button is not completely pressed, and it generates
some spurious signals called bouncing
...
There are many techniques developed to do
de-bouncing, but in this simple piece of code I’ve noticed that it’s usually
enough to add a 10- to 50-millisecond delay when the code detects a
transition
...
If Arduino were some sort of
human language, those would be two letters
of its alphabet
...

Trying Out Other On/Off Sensors
Now that you’ve learned how to use a pushbutton, you should know that
there are many other very basic sensors that work according to the same
principle:
Switches
Just like a pushbutton, but doesn’t automatically change state when
released
Thermostats
A switch that opens when the temperature reaches a set value
Magnetic switches (also known as “reed relays”)
Has two contacts that come together when they are near a magnet; used
by burglar alarms to detect when a window is opened
Carpet switches
Small mats that you can place under a carpet or a doormat to detect the
presence of a human being (or heavy cat)

Advanced Input and Output

51

Tilt switches
A simple electronic component that contains two contacts and a little
metal ball (or a drop of mercury, but I don’t recommend using those)
An example of a tilt switch is called a tilt sensor
...
When the sensor is in its upright position, the
ball bridges the two contacts, and this works just as if you had pressed a
pushbutton
...
Using this simple
component, you can implement, for example, gestural interfaces that react
when an object is moved or shaken (bit
...


Figure 5-1
...
This small device triggers when a human being (or other living
being) moves within its proximity
...


Figure 5–2
...

For example, by using the final example from Chapter 4 and a PIR sensor,
you could make your lamp respond to the presence of human beings, or
you could use a tilt switch to build one that turns off when it’s tilted on
one side
...
One of the limitations of the blinking LED examples that we have used so far is that you
can turn the light only on and off
...
To solve this problem, we can use a little trick that makes a lot
of things such as TV or cinema possible: persistence of vision
...
Now change the numbers so that the LED is on is one quarter
of the time that it’s off
...
This technique is called pulse width modulation (PWM),
a fancy way of saying that if you blink the LED fast enough, you don’t see
it blink any more, but you can change its brightness by changing the ratio
between the on time and the off time
...

This technique also works with devices other than an LED
...

While experimenting, 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 flicker while it’s waiting
for you to finish reading the sensor
...
This hardware is implemented in pins 9, 10, and 11, which can be controlled by the analogWrite()
instruction
...

PWM in action

Advanced Input and Output

55

For example, writing analogWrite(9,128) will set the brightness of an LED connected to pin 9 to 50%
...


Note: Having three channels is very good, because if you buy red,
green, and blue LEDs, you can mix their lights and make light of any
colour that you like!

Let’s try it out
...
Note that LEDs
are polarized: the long pin (positive) should go to the right, and the short
pin (negative) to the left
...
Use a 270 ohm resistor (red violet brown)
...

LED connected to PWM pin

56

Getting Started with Arduino

Then, create a new sketch in Arduino and use Example 04 (you can also
download code examples from www
...
com/getstartedarduino):

// Example 04: Fade an LED in and out like on
// a sleeping Apple computer
const int LED = 9; // the pin for the LED
int i = 0;

// We’ll 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 fancy feature of a laptop computer (maybe
it’s a bit of a waste to use Arduino for something so simple)
...

Add the circuit we used to read a button (back in Chapter 4) to this breadboard
...
If
you need to peek ahead, don’t worry; the most important thing is that you
spend some time thinking about how it might look
...

If you’d like, you can simply build both circuits on different parts of the
breadboard; you have plenty of room
...
One is marked red (for positive)
and the other blue or black (for ground)
...

In the case of the circuit you need to build for this example, you have
two components (both of them resistors) that need to be connected to
the GND (ground) pin on the Arduino
...
Or, you could connect one wire from the breadboard’s ground
rail to one of the GND pins on the Arduino, and then take the wires that
are connected to GND in the figures and connect them instead to the
breadboard ground rail
...
You’ll see an example that
uses the ground and positive breadboard rails in Chapter 6
...
To do this, I need to upgrade example 03C from Chapter 4 to
add dimming
...

Let’s have a look at the sketch:

58

Getting Started with Arduino

//

Example 05: Turn on LED when the button is pressed

//

and keep it on after it is released

//

including simple de-bouncing
...


const int LED = 9;

// the pin for the LED

const int 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
...

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
// let’s go back to 0
}
}
}
old_val = val; // val is now old, let’s 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
...
If
you press the button and release it immediately, you switch the lamp on
or off
...

Now let’s learn how to use some more interesting sensors
...
Take a light sensor, like
the one pictured in Figure 5-5
...
ly/ArduinoStoreLDR
...

Light-dependent resistor (LDR)

In darkness, the resistance of a light-dependent resistor (LDR) is quite
high
...
It is thus a kind of
light-activated switch
...

Now plug the LDR onto the breadboard instead of the pushbutton
...

Uncover the LDR, and the light goes on
...
This is important because for the first time in this
book, we are using an electronic component that is not a simple mechanical device: it’s a real rich sensor
...
This kind of either/or response is fine in a lot of
applications, but the light sensor that we just used is able to tell us not
just whether there is light, but also how much light there is
...

In order to read this type of sensor, we need a different type of pin
...
By using the
analogRead() function, we can read the voltage applied to one of the pins
...
For example, if there is a voltage of 2
...

If you now build the circuit that you see in Figure 5-6, using a 10k resistor,
and run the code listed in Example 06A, you’ll see the onboard LED
(you could also insert your own LED into pins 13 and GND as shown in
“Blinking an LED” in Chapter 4) blinking at a rate that’s dependent upon
the amount of light that hits the sensor
...

An analogue sensor circuit

Advanced Input and Output

63

// Example 06A: Blink LED at a rate specified by the
// value of the analogue input
const int 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(LED, HIGH); // turn the LED on
delay(val); // stop the program for
// some time
digitalWrite(LED, LOW); // turn the LED off
delay(val); // stop the program for
// some time
}

Now, try Example 06B: but before you do, you’ll need to modify your
circuit
...
Because you’ve already got some stuff on the breadboard, you’ll
need to find a spot on the breadboard where the LED, wires, and resistor
won’t overlap with the LDR circuit
...


Advanced Input and Output

65

Try Other Analogue Sensors
Using the same circuit that you have seen in the previous section, you
can connect a lot of other resistive sensors that work in more or less the
same way
...
In the circuit, I have
shown you how changes in resistance become changes in voltage that
can be measured by Arduino
...
If
you need an exact reading, you should read the numbers that come out of
the analogue pin while measuring with a real thermometer
...

Until now, we have just used an LED as an output device, but how do we
read the actual values that Arduino is reading from the sensor? We can’t
make the board blink the values in Morse code (well, we could, but there
is an easier way for humans to read the values)
...


Serial Communication
You learned at the beginning of this book that Arduino has a USB connection that is used by the IDE to upload code into the processor
...
For this purpose, we are going to use a serial object (an object is
a collection of capabilities that are bundled together for the convenience
of people writing sketches)
...

We’re now going to use the last circuit we built with the photoresistor and
send the values that are read back to the computer
...
makezine
...
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
...

Now, any software that can read from the serial port can talk to Arduino
...
Processing
(www
...
org) is a great complement to Arduino, because the
languages and IDEs are so similar
...
If you try to drive something like a motor, the pin
will immediately stop working, and could potentially burn out the whole
processor
...
One such device is called a MOSFET
transistor—ignore the funny name—it’s an electronic switch that can be
driven by applying a voltage to one of its three pins, each of which is called
a gate
...


Note: MOSFET means “metal–oxide–semiconductor field-effect
transistor
...
This means that electricity will flow though a
piece of semiconductor material (between the Drain and Source pins)
when a voltage is applied to the Gate pin
...

They are ideal for switching on and off large loads at high frequencies
...
You will also notice
that the motor takes its power supply from the 9 V connector on the
Arduino board
...
As the
MOSFET is connected to pin 9, we can also use analogWrite() to control
the speed of the motor through PWM
...
ly/ArduinoStoreIRF520) and an 1N4007 diode
(bit
...
If the motor randomly turns on during
upload, place a 10K resistor between pin 9 and GND
...
These usually are small circuits with a small microcontroller
inside that preprocesses the information
...
You can find examples on how to use them on our website in the
“Tutorials” section (www
...
cc/en/Tutorial/HomePage)
...


Figure 5-7
...
Let me remind you
what makes up the “Arduino Alphabet”:
Digital Output
We used it to control an LED but, with the proper circuit, it can be used to
control motors, make sounds, and a lot more
...
We can even control the speed of a motor with it
...

Analog Input
We can read signals from sensors that send a continuous signal that’s not
just on or off, such as a potentiometer or a light sensor
...

In this chapter, we’re going to see how to put together a working application
using what you have learned in the previous chapters
...

Here is where the wannabe designer in me comes out
...
The object we’re going to build is inspired
by a lamp called “Aton” from 1964
...

The finished lamp

The lamp, as you can see in Figure 6-1, is a simple sphere sitting on a base
with a large hole to keep the sphere from rolling off your desk
...

In terms of functionality, we want to build a device that would connect
to the Internet, fetch the current list of articles on the Make blog (blog
...
com) and count how many times the words “peace”, “love”,
and “Arduino” are mentioned
...
The lamp itself has a button we can
use to turn it on and off, and a light sensor for automatic activation
...

First of all, we need Arduino to be able to connect to the Internet
...
Usually what
people do is run an application on a computer that will connect to the
Internet, process the data, and send Arduino some simple bit of distilled
information
...
We’ll implement a proxy to
simplify the XML using the Processing language
...
We love this language and
use it to teach programming to beginners as well as to build beautiful
code
...
Another
advantage is that Processing is open source and runs on all the major
platforms (Mac, Linux, and Windows)
...
What’s more, the Processing community is lively and helpful, and you can find thousands
of premade example programs
...
com and extracts all the words from the resulting XML file
...
With these three numbers, we’ll
calculate a colour value and send it to Arduino
...

On the hardware side, we’ll combine the pushbutton example, the light
sensor example, the PWM LED control (multiplied by 3!) and serial
communication
...
We’ll use the standard way that colours are represented in HTML: #
followed by six hexadecimal digits
...
Predictability also makes the code simpler: we wait until we see an
#, then we read the six characters that follow into a buffer (a variable used as
a temporary holding area for data)
...


Coding
There are two sketches that you’ll be running: one Processing sketch, and
one Arduino sketch
...
You can
download it from www
...
com/getstartedarduino
...
Kurt (todbot
...
serial
...
makezine
...
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
...
list()
// should be your Arduino
...
Then, change
// the 0 in between [ and ] to the number of the port
// that your Arduino is connected to
...
list());
String arduinoPort = Serial
...
23,28); // this turns 1023 into 100
if (n <= 0) {
fetchData();
lastTime = millis();
}
port
...
available() > 0) { // check if there is data waiting
int inByte = port
...
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
...
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
...

port
...
openConnection();
conn
...

BufferedReader in = new
BufferedReader(new InputStreamReader(conn
...
readLine()) != null) {
StringTokenizer st =
new StringTokenizer(data,"\"<>,
...
hasMoreTokens()) {
// each chunk of data is made lowercase
chunk= st
...
toLowerCase() ;
if (chunk
...
indexOf("peace") >= 0)
peace++;

// found "peace"?

// increment peace by 1

if (chunk
...

if (peace > 64)

peace = 64;

if (love > 64)

love = 64;

if (arduino > 64) arduino = 64;

Talking to the Cloud

77

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
...
out
...
getMessage());
}
}

There are two things you need to do before the Processing sketch will run
correctly
...
To do this, create and save this sketch
...
Select the font named HelveticaNeue-Bold, choose 32 for the font
size, and then click OK
...
You’ll need to wait until you’ve assembled the
Arduino circuit and uploaded the Arduino sketch before you can confirm
this
...
However, if
you don’t see anything happening on the Arduino and you don’t see any
information from the light sensor appearing onscreen, find the comment
labeled “IMPORTANT NOTE” in the Processing sketch and follow the
instructions there
...
makezine
...
begin(9600);

// open the serial port

pinMode(BUTTON, INPUT);
}
void loop() {
val = analogRead(SENSOR); // read the value from the sensor
Serial
...
available() >0) {
// read the incoming byte:
inByte = Serial
...
read(); // store in the buffer
pointer++; // move the pointer forward by 1
}

Talking to the Cloud

79

// 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;
}
}

80

Getting Started with Arduino

Assembling the Circuit
Figure 6-2 shows how to assemble the circuit
...

Remember from the PWM example 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 left
...
)

Figure 6-2
...

Next, load the sketches into Arduino and Processing, then run the
sketches and try it out
...

Now let’s complete the construction by placing the breadboard into a
glass sphere
...
It’s now selling for about US$19
...
99/£11
...

Instead of using three separate LEDs, you can use a single RGB LED,
which has four leads coming off it
...

The Arduino Store sells a 4-lead RGB LED for a few dollars
(bit
...
Also, unlike discrete single-color LEDs, the
longest lead on this RGB LED is the one that goes to ground
...


Here’s How to Assemble It
Unpack the lamp and remove the cable that goes into the lamp from the
bottom
...

Strap the Arduino on a breadboard and hot-glue the breadboard onto the
back of the lamp
...
Connect the wires coming from the LED to the breadboard (where it
was connected before you removed it)
...

Either find a nice piece of wood with a hole that can be used as a stand
for the sphere or just cut the top of the cardboard box that came with the
lamp at approximately 5cm (or 2") and make a hole with a diameter that
cradles the lamp
...


82

Getting Started with Arduino

Place the sphere on the stand and bring the USB cable out of the top and
connect it to the computer
...

As an exercise, try to add code that will turn on the lamp when the room
gets dark
...


» Add a small PIR sensor to detect when somebody is around and turn it


off when nobody is there to watch
...


Think of different things, experiment, and have fun!

Talking to the Cloud

83

7/Troubleshooting
There will come a moment in your experimentation when nothing will be working and you
will have to figure out how to fix it
...

The more you work with electronics and Arduino, the more you will learn
and gain experience, which will ultimately make the process less painful
...

As every Arduino-based project is made both of hardware and software,
there will be more than one place to look if something goes wrong
...

This approach will allow you to devise some way to test each component
separately
...
Try
to break down (mentally) the project into its components by using the
understanding you have and figure out where the responsibility of each
component begins and ends
...
You will gradually build
up confidence about which parts of project are doing their job and which
ones are dubious
...

The legend says it was used for the first time by Grace Hopper back in the
1940s, when computers where mostly electromechanical, and one of them
stopped working because actual insects got caught in the mechanisms
...
Therefore they require a sometimes lengthy and
boring process to be identified
...

Before you start blaming your project, you should make sure that a few
things are in order, as airline pilots do when they go through a checklist
to make sure that the airplane will be flying properly before takeoff:
Plug your Arduino into a USB plug on your computer
...
If the green light marked PWR turns on, this means that
the computer is powering the board
...
If all else fails, try a different USB port
on your computer or a different computer entirely
...


»»

If you have been using an external power supply and are using an old
Arduino (Extreme, NG, or Diecimila), make sure that the power supply is plugged in and that the jumper marked SV1 is connecting the
two pins that are nearest to the external power supply connector
...
The on-board
LED should blink in a regular pattern
...


Testing Your Breadboarded Circuit
Now connect the board to your breadboard by running a jumper from the
5 V and GND connections to the positive and negative rails of the breadboard
...
This
means there is a big mistake in your circuit and you have a “short circuit”
somewhere
...


NOTE: If you’re a concerned that you may damage your computer,
remember that on many computers, the current protection is usually
quite good and responds quickly
...

If you’re really paranoid, you can always connect the Arduino board
through a self-powered USB hub
...


If you’re getting a short circuit, you have to start the “simplification and
segmentation” process
...

The first thing to start from is always the power supply (the connections
from 5 V and GND)
...

Working step by step and making one single modification at a time is the
number one rule for fixing stuff
...
Every
time I’m debugging something and things don’t look good (and believe
me, it happens a lot), his face pops in my head saying “one modification
at a time … one modification at a time” and that’s usually when I fix
everything
...


Troubleshooting

87

Each debugging experience will build up in your head a “knowledge base”
of defects and possible fixes
...
This will make you look very cool, because as soon as a newbie
says “This doesn’t work!” you’ll give it a quick look and have the answer
in a split second
...

If your circuit behaves in a funny way at random times, try really hard to
figure out the exact moment the problem occurs and what is causing it
...
It is also very
useful when you need to explain to somebody else what’s going on
...
Try to find somebody to explain the problem to—in many cases,
a solution will pop into your head as you articulate the problem
...

Kernighan and Rob Pike, in The Practice of Programming (Addison-Wesley,
1999), tell the story of one university that “kept a teddy bear near the help
desk
...


Problems with the IDE
In some cases, you may have a problem using the Arduino IDE, particularly
on Windows
...
bat file as an alternative method to
launch Arduino
...
If this happens, you
can usually convince Windows to assign a lower port number to Arduino
...
On Windows XP, click Hardware and choose Device Manager
...

Look for the serial devices in the list under “Ports (COM & LPT)
...
Right-click it
and choose Properties from the menu
...
Set the COM port number to COM10 or higher, click OK
and click OK again to dismiss the Properties dialog
...

If these suggestions don’t help, or if you’re having a problem not described
here, check out the Arduino troubleshooting page at www
...
cc/en/
Guide/Troubleshooting
...

One of the best things about Arduino is its community
...

Get the habit of cutting and pasting things into a search engine and see
whether somebody is talking about it
...
Do the same with bits of code you’re working on
or just a specific function name
...

For further investigation, start from the www
...
cc main website
and look at the FAQ (www
...
cc/en/Main/FAQ), then move on to
the playground (www
...
cc/playground), a freely editable wiki that
any user can modify to contribute documentation
...
People contribute documentation and examples of anything you can do with Arduino
...

If you still can’t find an answer that way, search the forum (www
...
cc/
cgi-bin/yabb2/YaBB
...
If that doesn’t help, post a question there
...
Please
post as much information as you can:

»»

What Arduino board are you using?

»»

What operating system are you using to run the Arduino IDE?

Troubleshooting

89

»»

Give a general description of what you’re trying to do
...


The number of answers you get depends on how well you formulate your
question
...
It annoys people a lot and is
like walking around with “newbie” tattooed on your forehead (in online communities, typing in all capitals is considered “shouting”)
...


»»

“Bumping” your message by posting follow-up comments asking
“Hey, how come no one replied?” or even worse, simply posting the
text “bump
...
Was
the subject clear? Did you provide a well-worded description of the
problem you are having? Were you nice? Always be nice
...
This means that you want people to do your work
for you, and this approach is simply not fun for a real tinkerer
...


»»

A variation of the previous point is when the question is clearly
something the poster of the message is getting paid to do
...


»»

Posting messages that look suspiciously like school assignments and
asking the forum to do your homework
...


90

Getting Started with Arduino

Appendix A/
The Breadboard
The process of getting a circuit to work involves making lots of changes to it
until it behaves properly; it’s a very fast, iterative process that’s something
like an electronic equivalent to sketching
...
For the best results, use a system that
allows you to change the connections between components in the fastest,
most practical, and least destructive way
...

The answer to this problem is a very practical device called the solderless
breadboard
...
You can push
a component’s leg into one of the holes, and it will establish an electrical
connection with all of the other holes in the same vertical column of holes
...
54 mm from the others
...
Not all of the contacts on a breadboard are created equal—there
are some differences
...
The last thing you need to
know about breadboards is that in the middle, there is a large gap that is
as wide as the size of a small chip
...
Clever, eh?

Appendix A

91

Figure A-1
...
Most of the resistors that you
find in a shop have a cylindrical body with two legs sticking out and have
strange coloured markings all around them
...

Today’s beginners have to figure out a way to interpret these signs
...
One of rings is usually gold-coloured; this one
represents the precision of that resistor
...

Then, read the colours and map them to the corresponding numbers
...


Colour

Value

Black

0

Brown

1

Red

2

Orange

3

Yellow

4

Green

5

Blue

6

Violet

7

Grey

8

White

9

Silver

10%

Gold

5%

For example, brown, black, orange, and gold markings mean 1 0 3 ±5%
...
Therefore 1 0 3 is actually 1
0 followed by 3 zeros, so the end result is 10,000 ohms ±5%
...
Please note
that because engineers are fond of optimising everything, on some schematic diagrams you might find values expressed as 4k7, which means 4
...

Capacitors are a bit easier: the barrel-shaped capacitors (electrolytic capacitors) generally have their values printed on them
...
So if you see a capacitor labelled 100 µF,
it’s a 100 micro farad capacitor
...
There are 1,000,000 pF in one µF
...
6 and 7 are not used, and 8 and 9 are
handled differently
...
01, and if you see 9, multiply it by 0
...

So, a capacitor labelled 104 would be 100,000 pF or 0
...
A capacitor
labeled 229 would be 2
...


94

Getting Started with Arduino

Appendix C/Arduino
Quick Reference
Here is a quick explanation of all the standard instructions supported
by the Arduino language
...
cc/en/Reference/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 before the main loop of the sketch starts
...
It contains a set of instructions that get repeated over and over until the board is switched off
...

; (semicolon)
Every instruction (line of code) is terminated by a semicolon
...
You could even put two instructions on
the same line, as long as you separate them with a semicolon
...
)
Example:
delay(100);

{} (curly braces)
This is used to mark blocks of code
...

Example:
void loop() {
Serial
...

There are two styles of comments 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 of predefined keywords with special values
...
INPUT and OUTPUT are used to set a specific pin to be
either and input or an output
true and false indicate exactly what their names suggest: the truth or
falsehood of a condition or expression
...
As the name
suggests, they can be changed as many times as you like
...
This means telling the processor the size of
the value you want to store
...

char
Holds a single character, such as A
...
When chars are used to store
numbers, they can hold values from –128 to 127
...
ASCII is a set of 127 characters that
was used for, among other things, transmitting text between serial
terminals and time-shared computer systems such as mainframes
and minicomputers
...
ASCII is still useful for exchanging short bits
of information in languages such as Italian or English that use Latin
characters, Arabic numerals, and common typewriter symbols for
punctuation and the like
...
As with chars, bytes use only one
byte of memory
...

unsigned int
Like int, uses 2 bytes but the unsigned prefix means that it can’t store
negative numbers, so its range goes from 0 to 65,535
...

unsigned long
Unsigned version of long; it goes from 0 to 4,294,967,295
...
It will eat up
4 bytes of your precious RAM and the functions that can handle them use
up a lot of code memory as well
...

double
Double-precision floating-point number, with a maximum value of
1
...
Wow, that’s huge!
string
A set of ASCII characters that are used to store textual information (you
might use a string to send a message via a serial port, or to display on
Appendix C

97

an LCD display)
...

The following are equivalent:
char string1[]

= "Arduino"; // 7 chars + 1 null char

char string2[8] = "Arduino"; // Same as above

array
A list of variables that can be accessed via an index
...
For example, if you
want to store different levels of brightness to be used when fading an LED,
you could create six variables called light01, light02, and so on
...


Control Structures
Arduino includes keywords for controlling the logical flow of your sketch
...
else
This structure makes decisions in your program
...
If the
expression is true, whatever follows will be executed
...
It’s possible to use just if without
providing an else clause
...

Example:
for (int i = 0; i < 10; i++) {
Serial
...
switch case is
like a massive roundabout
...
It’s quite useful to keep your code
tidy as it replaces long lists of if statements
...

Example:
// 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
...
This structure is used when you want the code inside your
block to run at least once before you check the condition
...
It’s also used to separate the different sections
of a switch case statement
...

Example:
for (light = 0; light < 255; light++)
{
// skip intensities between 140 and 200
if ((x > 140) && (x < 200))
continue;
analogWrite(PWMpin, light);
delay(10);
}

return
Stops running a function and returns from it
...

For example, if you have a function called computeTemperature() and you
want to return the result to the part of your code that invoked the function
you would write something like:
int computeTemperature() {
int temperature = 0;
temperature = (analogRead(0) + 45) / 100;
return temperature;
}
100

Getting Started with Arduino

Arithmetic and formulas
You can use Arduino to make complex calculations using a special syntax
...

There is an additional operator called “modulo” (%), which returns
the remainder of an integer division
...
Contrary to what you
might have learned in school, square brackets and curly brackets are
reserved for other purposes (array indexes and blocks, respectively)
...
For example,
if you want to check whether the value coming from a sensor is between 5
and 10, you would write:
if ((sensor => 5) && (sensor <=10))

There are three operators: and, represented with &&; or, represented with
||; and finally not, represented with !
...

Appendix C

101

For example, to increment value by 1 you would write:
value = value +1;

but using a compound operator, this becomes:
value++;

increment and decrement (–– and ++)
These increment or decrement a value by 1
...
The same applies to ––
...
The following two
expressions are equivalent:
a = a + 5;
a += 5;

Input and output functions
Arduino includes functions for handling input and output
...

pinMode(pin, mode)
Reconfigures a digital pin to behave either as an input or an output
...
Pins must be explicitly made into an
output using pinMode before digitalWrite will have any effect
...

Example:
val = digitalRead(7); // reads pin 7 into val
102

Getting Started with Arduino

int analogRead(pin)
Reads the voltage applied to an analog input pin and returns a number
between 0 and 1023 that represents the voltages between 0 and 5 V
...
pin may be 11,10,
9, 6, 5, 3
...

Example:
analogWrite(9,128); // Dim an LED on pin 9 to 50%

shiftOut(dataPin, clockPin, bitOrder, value)
Sends data to a shift register, devices that are used to expand the number
of digital outputs
...

bitOrder indicates the ordering of bytes (least significant or most
significant) and value is the actual byte to be sent out
...

This is useful, for example, to read some infrared sensors or accelerometers that output their value as pulses of changing duration
...

unsigned long millis()
Returns the number of milliseconds that have passed since the sketch
started
...

Example:
delay(500); // stops the program for half a second

delayMicroseconds(us)
Pauses the program for the given amount of microseconds
...

Example:
val = min(10,20); // val is now 10

max(x, y)
Returns the larger of x and y
...
If x is 5 it will return 5, but if x is –5, it will still return 5
...
If x is less than a, it
will just return a and if x is greater than b, it will just return b
...
Very useful to process values from analogue sensors
...

Example:
double x = pow(y, 32); // sets x to y raised to the 32nd power

double sqrt(x)
Returns the square root of a number
...
73425674438

double sin(rad)
Returns the sine of an angle specified in radians
...
90929737091

double cos(rad)
Returns the cosine of an angle specified in radians
...
41614685058

double tan(rad)
Returns the tangent of an angle specified in radians
...
18503975868

Appendix C

105

Random number functions
If you need to generate random numbers, you can use Arduino’s pseudorandom number generator
...
Although the distribution of the numbers returned by random() is essentially random, the sequence is predictable
...
If you have an unconnected analog pin, it will pick up random noise
from the surrounding environment (radio waves, cosmic rays, electromagnetic interference from cell phones and fluorescent lights, and so on)
...

If min is not specified, the lower bound is 0
...
Here are the serial functions
...
begin(speed)
Prepares Arduino to begin sending and receiving serial data
...

Example:
Serial
...
print(data)
Serial
...
The encoding is optional; if not
supplied, the data is treated as much like plain text as possible
...
print(75);

// Prints "75"

Serial
...


Serial
...
print(75, OCT);

// "113" (75 in octal)

Serial
...
print(75, BYTE); // "K" (the raw byte happens to
// be 75 in the ASCII set)

Serial
...
println(data, encoding)
Same as Serial
...

Examples:
Serial
...
println(75, DEC);

// The same as above
...
println(75, HEX);

// "4B\r\n"

Serial
...
println(75, BIN);

// "1001011\r\n"

Serial
...
available()
Returns how many unread bytes are available on the Serial port for
reading via the read() function
...
available() returns 0 until new data arrives on the serial port
...
available();

int Serial
...

Example:
int data = Serial
...
flush()
Because data may arrive through the serial port faster than your program
can process it, Arduino keeps all the incoming data in a buffer
...

Example:
Serial
...

Similar issues arise, sooner or later, in every discipline
...

Engineers, being practical people, have developed a quick way to capture
the essence of a circuit in order to be able to document it and later rebuild
it or pass it to somebody else
...
Individual components are represented by symbols that are a sort of abstraction of either
the shape of the component or the essence of them
...


The connections between components are usually made
using either wires or tracks on the printed circuit board
and are represented on the diagram as simple lines
...

108

Getting Started with Arduino

This is all you need to understand basic schematics
...
See en
...
org/wiki/
Electronic_symbol for a larger list of electronics symbols
...
For example, a radio would be
drawn starting with the antenna on the left, following the path of the radio
signal as it makes its way to the speaker (which is drawn on the right)
...
See also Arduino language
basic building blocks, 71
collaboration between users, 16
connection to Internet, 73
Diecimila board, 18, 86
differences from other platforms, 1
Duemilanove board, 19
FAQs on main website, 89
hardware, 17–19
installing, 20
major parts, board and IDE, 17
motor circuit for, 69
NG board, 18, 86
philosophy, 5, 7, 10
solderless breadboard, 91

testing the board, 86
Uno board, 19, 21
Arduino language, 95–108
Boolean operators, 101
comparison operators, 101
compound operators, 101
control structures, 98–101
datatypes, 96–98
input and output functions, 102
mathematical and trigonometric functions, 104
random number functions, 106
serial communication, 106
special characters, 95
variables, 96
Arduino Store, 41
ArduinoUNO
...
See also troubleshooting
decimal numbers, 73
delay( ) function, 35, 104
changing the time, 54
delayMicroseconds( ) function, 104
delays
adjusting to eliminate pushbutton
bouncing, 48
changing amount for different blinking
patterns, 36
design, Interaction Design, 2
Device Manager (Windows), 24, 88
Diecimila board, 18, 86
digital
input, 71
INPUT or OUTPUT mode for pins, 34
output, 71
pins, 18, 34
programmable electronics, advantages of, 43
digitalRead( ) function, 40, 102
storing returned result in a variable, 44
digitalWrite( ) function, 35, 102
diodes
1N4007, 68
symbol for, 109
divide and rule, 85
double datatype, 97
do
...
else statement, 98
if statements, 43
IKEA “FADO” table lamp, 82
inductor, symbol for, 108
infrared rangers, 69
infrared sensors, 53
input
analogue, 62, 71
digital, 71
functions for, 102
INPUT, 34
input/output (I/O) board, 1
int datatype, 97
Interaction Design, 2

Interactive Device, 27
int variable, 43

J
jumper wire kit, 41
junk, using, 14

K
K (cathode), 28
Kernighan, Brian W
...
See LDRs
light emitting diodes
...
See MOSFET transistor
microcontrollers, 3
milliseconds, 35
millis( ) function, 103
min( ) function, 104
momentary tactile pushbutton switch,
41
Moog, Robert, 8
MOSFET transistor, 68
IRF520, 68
motion detection, passive infrared (PIR)
sensors, 53

N
NG board, 18, 86

O
object, defined, 66
ohms, 39, 41
Ohm’s law formula, 40
on/off sensors, 51–53
on/off values (state variable), 45
opportunistic prototyping, 6
output
analogue, 71
digital, 71
functions for, 102
OUTPUT, 34
114

Index

P
passive infrared or PIR sensors, 53
patching, 8
photoresistor, 28
Physical Computing, 3
Pike, Rob, 88
pinMode( ) function, 34, 102
pins, Arduino board, 18, 91
20 milliamps maximum capacity, 68
analog, 103
Analog In, 62
checking if voltage is applied, 40
configuring, 34
configuring digital pins, 102
controlling with analogWrite( ) function,
54
LED connected to PWM pin, 56
Playground wiki, 89
Playground (Wiki), 16
port identification, 23–25
Windows COM port number, 88
potentiometer, symbol for, 109
power selection jumper (PWR_SEL), 18
power supplies, 18
troubleshooting, 88
pow( ) function, 105
Practice of Programming, The, 88
pre-cut jumper wire kit, 41
Processing language, 1, 20, 67
advantages of using with Arduino, 73
sketch, Arduino networked lamp,
74–78
programming
...
bat file, using to launch Arduino, 88
RX and TX (LEDs), 32

S
schematic diagrams, reading, 108
sensors, 27
complex, 68
how they work, 28
light sensors, 60–66
on/off, 51–53
on/off vs
...
available( ) function, 107
Serial
...
flush( ) function, 107
Serial Monitor button, 67
serial ports, 32
identification on Macintosh, 23
identification on Windows, 24
Serial
...
println( ) function, 107
Serial
...
)
–– (decrement) operator, 102
/= (division and assignment) operator,
102
/ (division) operator, 101
= (equals sign), assignment operator,
43, 46
== (equal to) operator, 43, 46, 101
< (greater than) operator, 101
>= (greater than or equal to) operator, 101
++ (increment) operator, 102
< (less than) operator, 101
<= (less than or equal to) operator, 101
% (modulo) operator, 101
*= (multiplication and assignment)
operator, 102
* (multiplication) operator, 101
!= (not equal to) operator, 101
! (not) operator, 101
|| (or) operator, 101
( ) (parentheses), 34, 43, 101
# (pound sign), in HTML color codes,
73
; (semicolon), 44, 95
[ ] (square brackets), 98, 101
-= (subtraction and assignment)
operator, 102
– (subtraction) operator, 101
sqrt( ) function, 105
state variables, 45
strings, 97
SV1 jumper connections, 86
switch case statement, 98
switches, 51
momentary tactile pushbutton switch,
41
MOSFET transistors, 68
tilt, 52
synthesizers
circuit bending with, 10
Moog analog synthesizers, 8

T
tan( ) function, 105
thermistor, symbol for, 109
thermostats, 51
116

Index

tilt switches, 52
time, functions for, 103
tinkering, 5, 7
circuit bending, 10
reusing existing technology, 7
toys, hacking, 15
transistor, MOSFET, 68
trigonometric functions, 104
troubleshooting, 85–90
excluding each component separately
with testing, 85
IDE (Integrated Development Environment), 88
isolating problems, 88
simplifying and segmenting the
project, 85
testing the board, 86
understanding how parts work and
interact, 85
using online help sources for Arduino,
89
TRUE, 43
true and false, 96
TX and RX (LEDs), 32

U
ultrasonic rangers, 69
UNICODE, 97
Uno board, 18
unsigned int datatype, 97
Upload to I/O Board button, 31
USB
Arduino connection, 66
port identification on Windows, 89
power supplies, 18
programming Arduino over, 1
troubleshooting Arduino connection,
86
users’ groups, 16

V
variables, 43, 96
datatypes, 96–98
state, 45
Vista (Windows)
port identification, 24

troubleshooting port identification, 88
“visual programming” environments, 8
voltage, 35
applied to pin, checking with analog
Read( ), 62
applied to pin, checking with digitalRead( ) function, 40
defined, 39
readings, 18
relationship to current, 39

W
while statement, 99
Wiki, “Playground”, 16
Windows
COM port number for Arduino, 88
installing Arduino, 20
installing drivers, 21
port identification, 24

X
XML file from RSS feed, 73
XP (Windows)
installing drivers, 21
port identification, 24
troubleshooting port identification, 88

Index

117

save 15% with coupon code ARDINTRO
offer expires at midnight on 12/31/2011

Ultimate Microcontroller Pack

ARDUINO UNO

The Ultimate Microcontroller Pack includes everything you need to dive
right into the world of microcontrollers
...
Everyone from beginners to advanced users will appreciate all that
the Ultimate Microcontroller Pack has to offer
...
Create
your circuits the way you want,
and easily make changes without
having to solder
...
It can
happen anywhere, at any time
...


Discover DIY kits, tools, books, and more at makershed
Title: Massimo Banzi-Getting Started with Arduino -Make (2011)
Description: Massimo Banzi-Getting Started with Arduino -Make (2011)