Arduino A Quick Start Guide
User Manual:
Open the PDF directly: View PDF .
Page Count: 284 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Contents
- Acknowledgments
- Preface
- The Parts You Need
- Getting Started with Arduino
- Eight Arduino Projects
- Building Binary Dice
- Building a Morse Code Generator Library
- Sensing the World Around Us
- What You Need
- Measuring Distances with an Ultrasonic Sensor
- Increasing Precision Using Floating-Point Numbers
- Increasing Precision Using a Temperature Sensor
- Transferring Data Back to Your Computer Using Processing
- Representing Sensor Data
- Building the Application's Foundation
- Implementing Serial Communication in Processing
- Visualizing Sensor Data
- What If It Doesn't Work?
- Exercises
- Building a Motion-Sensing Game Controller
- Tinkering with the Wii Nunchuk
- Networking with Arduino
- What You Need
- Using Your PC to Transfer Sensor Data to the Internet
- Registering an Application with Twitter
- Tweeting Messages with Processing
- Networking Using an Ethernet Shield
- Emailing from the Command Line
- Emailing Directly from an Arduino
- Detecting Motion Using a Passive Infrared Sensor
- Bringing It All Together
- What If It Doesn't Work?
- Exercises
- Creating Your Own Universal Remote Control
- Controlling Motors with Arduino
- Appendixes
- Index

Download from Wow! eBook <www.wowebook.com>

What Readers Are Saying About
Arduino: AQuick-Start Guide
The most comprehensive book on the Arduino platform Ihave read.
Loaded with excellent examples and references, Arduino: AQuick-Start
Guide gets beginners up and running in no time and provides experi-
enced developers with awealth of inspiration for their own projects.
Haroon Baig
Creator of the Twitwee Clock, http://www.haroonbaig.com
Excellently paced for those who have never experimented with elec-
tronics or microcontrollers before and packed with valuable tidbits
even for advanced Arduino tinkerers.
Georg Kaindl
Creator, Arduino DHCP, DNS, and Bonjour libs
The Arduino platform is agreat way for anyone to get into embedded
systems, and this book is the road map. From first baby steps to com-
plex sensors and even game controllers, there is no better way to get
going on the Arduino.
T o n y Williamitis
Senior embedded systems engineer
Irecommend this engaging and informative book to software develop-
ers who want to learn the basics of electronics, as well as to anyone
looking to interface their computers with the physical world.
René Bohne
Software developer and creator of LumiNet
Download from Wow! eBook <www.wowebook.com>

Arduino
AQuick-Start Guide
Maik Schmidt
The Pragmatic Bookshelf
Raleigh, North Carolina Dallas, Texas
Download from Wow! eBook <www.wowebook.com>

Many of the designations used by manufacturers and sellers to distinguish their prod-
ucts are claimed as trademarks. Where those designations appear in this book, and The
Pragmatic Programmers, LLC was aware of atrademark claim, the designations have
been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The
Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g
device are trademarks of The Pragmatic Programmers, LLC.
Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result from
the use of information (including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team
create better software and have more fun. For more information, as well as the latest
Pragmatic titles, please visit us at http://www.pragprog.com.
The team that produced this book includes:
Editor: Susannah Pfalzer
Indexing: Potomac Indexing, LLC
Copy edit: Kim W i m p s e t t
Layout: Samuel Langhorne
Production: Janet Furlow
Customer support: Ellie Callahan
International: Juliet Benda
Copyright ©2011 Pragmatic Programmers, LLC.
All rights reserved.
No part of this publication may be reproduced, stored in aretrieval system, or transmit-
ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior consent of the publisher.
Printed in the United States of America.
ISBN-10: 1-934356-66-2
ISBN-13: 978-1-934356-66-1
Printed on acid-free paper.
P1.0 printing, Janurary, 2011
V e r s i o n : 2011-1-24
Download from Wow! eBook <www.wowebook.com>
For Yvonne.
The greatest little sister on earth.
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>

Contents
Acknowledgments 11
Preface 13
Who Should Read This Book ................. 14
What’s in This Book . . . . . . . . . . . . . . . . . . . . . . 14
Arduino Uno and the Arduino Platform . . . . . . . . . . . 16
Code Examples and Conventions ............... 16
Online Resources . . . . . . . . . . . . . . . . . . . . . . . . 17
The Parts Y o u Need 18
Starter Packs . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Complete Parts List ....................... 19
IGetting Started with Arduino 22
1W e l c o m e to the Arduino 23
1.1 What Y o u Need ..................... 24
1.2 What Exactly Is an Arduino? ............. 24
1.3 Exploring the Arduino Board ............. 25
1.4 Installing the Arduino IDE ............... 31
1.5 Meeting the Arduino IDE . . . . . . . . . . . . . . . . 33
1.6 Compiling and Uploading Programs ......... 38
1.7 W o r k i n g with LEDs ................... 41
1.8 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 43
1.9 Exercises ......................... 44
2Inside the Arduino 46
2.1 What Y o u Need ..................... 46
2.2 Managing Projects and Sketches . . . . . . . . . . . 47
2.3 Changing Preferences . . . . . . . . . . . . . . . . . . 48
2.4 Using Serial Ports . . . . . . . . . . . . . . . . . . . . 49
2.5 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 60
2.6 Exercises ......................... 61
Download from Wow! eBook <www.wowebook.com>

CONTENTS 8
II Eight Arduino Projects 62
3 Building Binary Dice 63
3.1 What Y o u Need ..................... 63
3.2 W o r k i n g with Breadboards ............... 64
3.3 Using an LED on aBreadboard . . . . . . . . . . . . 66
3.4 First V e r s i o n of aBinary Die . . . . . . . . . . . . . . 69
3.5 W o r k i n g with Buttons . . . . . . . . . . . . . . . . . . 74
3.6 Adding Our Own Button . . . . . . . . . . . . . . . . 79
3.7 Building aDice Game . . . . . . . . . . . . . . . . . . 80
3.8 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 86
3.9 Exercises ......................... 87
4 Building a Morse Code Generator Library 88
4.1 What Y o u Need ..................... 88
4.2 Learning the Basics of Morse Code . . . . . . . . . . 88
4.3 Building aMorse Code Generator . . . . . . . . . . . 89
4.4 Fleshing Out the Generator’s Interface . . . . . . . . 91
4.5 Outputting Morse Code Symbols . . . . . . . . . . . 92
4.6 Installing and Using the Telegraph Class . . . . . . 94
4.7 Final Touches . . . . . . . . . . . . . . . . . . . . . . 97
4.8 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 99
4.9 Exercises ......................... 100
5Sensing the W o r l d Around Us 102
5.1 What Y o u Need ..................... 103
5.2 Measuring Distances with an Ultrasonic Sensor . . 104
5.3 Increasing Precision Using Floating-Point Numbers 110
5.4 Increasing Precision Using aTemperature Sensor .113
5.5 TransferringData Back to Y o u r Computer Using Pro-
cessing . . . . . . . . . . . . . . . . . . . . . . . . . . 119
5.6 Representing Sensor Data ............... 123
5.7 Building the Application’s Foundation . . . . . . . . 125
5.8 Implementing Serial Communication in Processing 126
5.9 V i s u a l i z i n g Sensor Data . . . . . . . . . . . . . . . . 128
5.10 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 131
5.11 Exercises ......................... 131
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

CONTENTS 9
6 Building a Motion-Sensing Game Controller 132
6.1 What Y o u Need ..................... 133
6.2 W i r i n g Up the Accelerometer . . . . . . . . . . . . . . 134
6.3 Bringing Y o u r Accelerometer to Life ......... 135
6.4 Finding and Polishing Edge V a l u e s . . . . . . . . . . 137
6.5 Building Y o u r Own Game Controller ......... 140
6.6 W r i t i n g Y o u r Own Game . . . . . . . . . . . . . . . . 144
6.7 More Projects . . . . . . . . . . . . . . . . . . . . . . 152
6.8 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 153
6.9 Exercises ......................... 153
7Tinkeringwith the Wii Nunchuk 154
7.1 What Y o u Need ..................... 154
7.2 W i r i n g aW i i Nunchuk ................. 155
7.3 Talking to aNunchuk . . . . . . . . . . . . . . . . . . 156
7.4 Building aNunchuk Class ............... 159
7.5 Using Our Nunchuk Class ............... 162
7.6 Rotating a Colorful Cube . . . . . . . . . . . . . . . . 163
7.7 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 169
7.8 Exercises ......................... 169
8Networking with Arduino 170
8.1 What Y o u Need ..................... 171
8.2 Using Y o u r PC to TransferSensor Data to the Inter-
net ............................. 172
8.3 Registering an Application with Twitter ....... 174
8.4 Tweeting Messages with Processing . . . . . . . . . . 175
8.5 Networking Using an Ethernet Shield . . . . . . . . 179
8.6 Emailing from the Command Line . . . . . . . . . . 186
8.7 Emailing Directly from an Arduino . . . . . . . . . . 188
8.8 Detecting Motion Using aPassive Infrared Sensor .192
8.9 Bringing It All Together ................. 196
8.10 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 199
8.11 Exercises ......................... 201
9Creating Y o u r Own Universal Remote Control 202
9.1 What Y o u Need ..................... 203
9.2 Understanding Infrared Remote Controls . . . . . . 204
9.3 Grabbing Remote Control Codes . . . . . . . . . . . 205
9.4 Building Y o u r Own Apple Remote . . . . . . . . . . . 209
9.5 Controlling Devices Remotely with Y o u r Browser . . 212
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

CONTENTS 10
9.6 Building an Infrared Proxy ............... 214
9.7 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 221
9.8 Exercises ......................... 222
10 Controlling Motors with Arduino 223
10.1 What Y o u Need ..................... 223
10.2 Introducing Motors ................... 224
10.3 First Steps with aServo Motor . . . . . . . . . . . . 225
10.4 Building aBlaminatr . . . . . . . . . . . . . . . . . . 228
10.5 What If It Doesn’t W o r k ? . . . . . . . . . . . . . . . . 233
10.6 Exercises ......................... 234
III Appendixes 236
A Basics of Electronics 237
A.1 Current, V o l t a g e , and Resistance . . . . . . . . . . . 237
A.2 Learning How to Solder ................. 241
B Advanced Arduino Programming 247
B.1 The Arduino Programming Language ......... 247
B.2 Bit Operations . . . . . . . . . . . . . . . . . . . . . . 249
C Advanced Serial Programming 251
C.1 Learning More About Serial Communication . . . . 251
C.2 Serial Communication Using V a r i o u s Programming
Languages . . . . . . . . . . . . . . . . . . . . . . . . 253
D Bibliography 266
Index 267
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

Acknowledgments
W r i t i n g books doesn’t get easier the more often Ido it—I think there
will never be atime when Ican do it on my own. Iwill always depend
on the help of others, and a lot of wonderful people contributed to this
book.
Ihave to start by thanking my unbelievably talented editor, Susannah
Davidson Pfalzer. Only because of her insightful advice, her patience,
and her encouragement have Ifinished this book. Iowe her so much!
Also, the Pragmatic Bookshelf team again has been amazingly profes-
sional, and my publishers have been very sympathetic when Iwent
through some hard times. I am so thankful for that!
This book would not have been possible without the stunning work of
the whole Arduino team! Thank you so much for creating the Arduino!
Abig “thank-you!” goes to all the people who contributed material to
this book: Christian Rattat took all the book’s photos, Kaan Karaca
created the Blaminatr’s display, and Tod E. Kurt kindly allowed me to
use his excellent Ccode for accessing an Arduino via serial port.
Ihave created all circuit diagrams with Fritzing,1and I’d like to thank
the Fritzing team for making such agreat tool available for free!
For an author, there’s nothing more motivating than feedback. I’d like
to thank my reviewers: René Bohne, Stefan Christoph, Georg Kaindl,
Kaan Karaca, Christian Rattat, Stefan Rödder, Christoph Schwaeppe,
Federico Tomassetti, and Tony W i l l i a m i t i s . This book is so much better
because of your insightful comments and suggestions! I am also grate-
ful to all readers who have sent in errata during the beta book period.
When Ihad written the first half of this book, my mother passed away
in February 2010. It has been one of the hardest times in my life, and
1. http://fritzing.org/
Download from Wow! eBook <www.wowebook.com>

ACKNOWLEDGMENTS 12
without the support of my family and my friends, Iwould have never
finished this book. W e miss you so much, Mom!
Finally, I’d like to thank Tanjafor giving me confidence and for bringing
fun back into my life when Ineeded it most!
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

Preface
W e l c o m e to the Arduino, and welcome to the exciting world of physical
computing! Arduino2is an open source project consisting of both hard-
ware and software. It was originally created to give designers and artists
aprototyping platform for interaction design courses. Today hobby-
ists and experts all over the world use it to create physical computing
projects, and you can too.
The Arduino lets us get hands-on again with computers in away we
haven’t been able to since the 1980s, when you could build your own
computer. And Arduino makes it easier than ever to develop hand-
crafted electronics projects ranging from prototypes to sophisticated
gadgets. Gone are the days when you had to learn lots of theory about
electronics and arcane programming languages before you could even
get an LED blinking. Y o u can create your first Arduino project in afew
minutes without needing advanced electrical engineering course work.
In fact, you don’t need to know anything about electronics projects to
read this book, and you’ll get your hands dirty right from the begin-
ning. Y o u ’ l l not only learn how to use some of the most important elec-
tronic parts in the first pages, you’ll also learn how to write the software
needed to bring your projects to life.
This book dispenses with theory and stays hands-on throughout. I’ll
explain all the basics you need to build the book’s projects, and every
chapter has atroubleshooting section to help when things go wrong.
This book is a quick-start guide that gets you up to speed quickly and
enables you to immediately create your own projects.
2. http://arduino.cc
Download from Wow! eBook <www.wowebook.com>

WHOSHOULD READ THISBOOK 14
Who Should Read This Book
If you are interested in electronics—and especially in building your
own toys, games, and gadgets—then this book is for you. Although the
Arduino is anice tool for designers and artists, only software developers
are able to unleash its full power. So, if you’ve already developed some
software—preferably with C/C++ or Java—then you’ll get alot out of
this book.
But there’s one more thing: you have to build, try, and modify the
projects in this book. Have fun. Don’t worry about making mistakes.
The troubleshooting sections—and the hands-on experience you’ll gain
as you become more confident project by project—will make it all worth-
while. Reading about electronics without doing the projects yourself
isn’t even half the battle (you know the old saying: we remember 5per-
cent of what we hear, 10 percent of what we write, and 95 percent of
what we personally suffer). And don’t be afraid: you really don’t need
any previous electronics project experience!
If you’ve never written apiece of software before, start with aprogram-
ming course or read abeginner’s book about programming first (Learn
to Program [Pin06]is anice starting point). Then, learn to program in
Cwith The CProgramming Language [KR98]or in C++ with The C++
Programming Language [Str00].
What’s in This Book
This book consists of three parts (“Getting Started with Arduino,” “Eight
Arduino Projects,” and the appendixes). In the first part, you’ll learn all
the basics you need to build the projects in the second part, so read the
chapters in order and do all the exercises. The chapters in the second
part also build on each other, reusing techniques and code from earlier
chapters.
Here’s ashort walk-through:
•The book starts with the basics of Arduino development. Y o u ’ l l
learn how to use the IDE and how to compile and upload pro-
grams. Y o u ’ l l quickly build your first project—electronic dice—that
shows you how to work with basic parts such as LEDs, buttons,
and resistors. By implementing aMorse code generator, you’ll see
how easy it is to create your own Arduino libraries.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WHAT’SINTHISBOOK 15
•Then you’ll learn how to work with analog and digital sensors.
Y o u ’ l l use atemperature sensor and an ultrasonic sensor to build
avery accurate digital metering ruler. Then you’ll use athree-axis
accelerometer to build your own motion-sensing game controller,
together with acool breakout game clone.
•In electronics, you don’t necessarily have to build gadgets yourself.
Y o u can also tinker with existing hardware, and you’ll see how
easy it is to take full control of Nintendo’s W i i Nunchuk so you
can use it in your own applications.
•Using aNunchuk to control applications or devices is nice, but
often it’s more convenient to have awireless remote control. So,
you’ll learn how to build your own universal remote control that
you can even control using aweb browser.
•Speaking of web browsers: connecting the Arduino to the Inter-
net is easy, so you’ll build aburglar alarm that sends you an
email whenever someone is moving in your living room during your
absence.
•Finally, you’ll work with motors by creating afun device for your
next software project. It connects to your continuous integration
system, and whenever the build fails, it moves an arrow to point
to the name of the developer who is responsible.
•In the appendixes, you’ll learn about the basics of electricity and
soldering. Y o u ’ l l also find advanced information about program-
ming aserial port and programming the Arduino in general.
Every chapter starts with adetailed list of all parts and tools you need
to build the chapter’s projects. Every chapter contains lots of photos
and diagrams showing how everything fits together. Y o u ’ l l get inspired
with descriptions of real-world Arduino projects in sidebars throughout
the book.
Things won’t always work out as expected, and debugging circuits can
be adifficult and challenging task. So in every chapter you’ll find a
“What If It Doesn’t W o r k ? ” section that explains the most common prob-
lems and their solutions.
Before you read the solutions in the “What If It Doesn’t W o r k ? ” sec-
tions, though, try to solve the problems yourself, because that’s the
most effective way of learning. In the unlikely case that you don’t run
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

ARDUINO UNOANDTHEARDUINO PLATFORM 16
into any problems, you’ll find alist of exercises to build your skills at
the end of every chapter.
All the projects in this book have been tested on the Arduino Uno, the
Arduino Duemilanove, and with the Arduino IDE versions 18 to 21. If
possible, you should always use the latest version.
Arduino Uno and the Arduino Platform
After releasing several Arduino boards and Arduino IDE versions, the
Arduino team decided to specify aversion 1.0 of the platform. It will
be the reference for all future developments, and they announced it
on the first day of 2010.3Since then, they have released the Arduino
Uno, and they have also improved the IDE and its supporting libraries
step-by-step.
At the moment of this writing, it is still not completely clear what
Arduino 1.0 will look like. The Arduino team tries to keep this release as
backward compatible as possible. This book is up-to-date for the new
Arduino Uno boards. All the projects will also work with older Arduino
boards such as the Duemilanove or Diecimila. This book is current for
version 21 of the Arduino platform. Y o u can follow the progress of the
Arduino platform online.4
Code Examples and Conventions
Although this is abook about open source hardware and electronics,
you will find alot of code examples. W e need them to bring the hardware
to life and make it do what we want it to do.
W e use C/C++ for all programs that will eventually run on the Arduino.
For applications running on our PC, we use Processing,5but in Sec-
tion C.2,Serial Communication Using V a r i o u s Programming Languages,
on page 253,you’ll also learn how to use several other programming
languages to communicate with an Arduino.
Whenever you find aslippery road icon beside aparagraph, slow down
and read carefully. They announce difficult or dangerous techniques.
3. http://arduino.cc/blog/2010/01/01/uno-punto-zero/
4. http://code.google.com/p/arduino/issues/list?q=milestone=1.0
5. http://processing.org
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

ONLINE RESOURCES 17
Online Resources
This book has its own web page at http://pragprog.com/titles/msard where
you can download the code for all examples (if you have the ebook ver-
sion of this book, clicking the little gray box above each code example
downloads that source file directly). Y o u can also participate in adis-
cussion forum and meet other readers and me. If you find bugs, typos,
or other annoyances, please let me and the world know about them on
the book’s errata page.6
On the web page you will also find alink to aFlickr7photo set. It
contains all the book’s photos in high resolution. There you can also
see photos of reader projects, and we’d really like to see photos of your
projects, too!
Let’s get started!
6. http://www.pragprog.com/titles/msard/errata
7. http://flickr.com
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

The Parts Y o u Need
Here’s alist of the parts you need to work through all the projects in
this book. In addition, each chapter lists the parts you’ll need for that
chapter’s projects, so you can try projects chapter-by-chapter without
buying all the components at once. Although there look to be alot of
components here, they’re all fairly inexpensive, and you can buy all the
parts you need for all the projects in this book for about $200.
Starter P a c k s
Many online shops sell Arduino components and electronic parts. Some
of the best are Makershed8and Adafruit.9They have awesome starter
packs, and I strongly recommend buying one of these.
The best and cheapest solution is to buy the Arduino Projects Pack from
Makershed (product code MSAPK). It contains nearly all the parts you
need to build the book’s examples, as well as many more useful parts
that you can use for your own side projects. If you buy the Arduino
Projects Pack, you’ll need to buy these additional parts separately:
•Parallax PING))) sensor
•TMP36 temperature sensor from Analog Devices
•ADXL335 accelerometer breakout board
• 6 pin 0.1" standard header
•Nintendo Nunchuk controller
• A Passive Infrared Sensor
•An infrared LED
•An infrared receiver
•An Ethernet shield
8. http://makershed.com
9. http://adafruit.com
Download from Wow! eBook <www.wowebook.com>

COMPLETE PARTSLIST 19
Alternatively, Adafruit also sells an Arduino Starter Pack (product ID
170). It’s cheaper, but it doesn’t contain as many parts. For example, it
doesn’t have aProtoshield or atilt sensor.
All shops constantly improve their starter packs, so it’s agood idea to
scan their online catalogs carefully.
Complete P a r t s List
If you prefer to buy parts piece by piece (or chapter by chapter) rather
than astarter pack, here is alist of all the parts used in the book. Each
chapter also has aparts list and photo with all parts needed for that
chapter. Suggested websites where you can buy the parts are listed here
for your convenience, but many of these parts are available elsewhere
also, so feel free to shop around.
Good shops for buying individual components parts are RadioShack,10
Digi-Key,11sparkfun,12and Mouser.13
•An Arduino board such as the Uno, Duemilanove, or Diecimila
available from Adafruit (product ID 50) or Makershed (product
code MKSP4).
• A standard A-B USB cable for USB 1.1 or 2.0. Y o u might already
have afew. If not, you can order it at RadioShack (catalog number
55011289).
• A half-size breadboard from Makershed (product code MKKN2) or
from Adafruit (product ID 64).
•Three LEDs (four additional ones are needed for an optional exer-
cise). Buying LEDs one at a time isn’t too useful; abetter idea is
to buy apack of 20 at RadioShack (catalog number 276-1622).
•One 100Ωresistor, two 10kΩresistors, and three 1kΩresistors.
It’s also not too useful to buy single resistors; buy avalue pack
such as catalog number 271-308 from RadioShack.
•Two pushbuttons. Don’t buy asingle button switch; buy at least
four instead, available at RadioShack (catalog number 275-002).
10. http://radioshack.com
11. http://digikey.com
12. http://sparkfun.com
13. http://mouser.com
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

COMPLETE PARTSLIST 20
•Some wires, preferably breadboard jumper wires. Y o u can buy
them at Makershed (product code MKSEEED3) or Adafruit (prod-
uct ID 153).
• A Parallax PING))) sensor (product code MKPX5) from Makershed.
• A Passive Infrared Sensor (product code MKPX6) from Makershed.
• A TMP36 temperature sensor from Analog Devices.14Y o u can get
it from Adafruit (product ID165).
•An ADXL335 accelerometer breakout board. Y o u can buy it at
Adafruit (product ID 163).
• A 6 pin 0.1" standard header (included, if you order the ADXL335
from Adafruit). Alternatively, you can order from sparkfun (search
for breakaway headers). Usually, you can only buy stripes that
have more pins. In this case, you have to cut it accordingly.
• A Nintendo Nunchuk controller. Y o u can buy it at nearly every toy
store or at http://www.amazon.com/,for example.
•An Arduino Ethernet shield (product code MKSP7) from Maker-
shed.
•An infrared sensor such as the PNA4602. Y o u can buy it aAdafruit
(product ID 157) or Digi-Key (search for PNA4602).
•An infrared LED. Y o u can get it from RadioShack (catalog number
276-143) or from sparkfun (search for infrared LED).
• A 5V servo motor such as the Hitec HS-322HD or the V i g o r Hex-
tronic. Y o u can get one from Adafruit (product id 155) or sparkfun.
Search for standard servos with an operating voltage of 4.8V–6V.
For some of the exercises, you’ll need some optional parts:
•An Arduino Proto Shield from Adafruit (product ID 51) or Maker-
shed (product code MKAD6). Y o u ’ l l also need atiny breadboard
(product code MKKN1 at Makershed). Ihighly recommend this
shield!
• A piezo speaker or buzzer. Search for piezo buzzer at RadioShack
or get it from Adafruit (product ID 160).
14. http://www.analog.com/en/sensors/digital-temperature-sensors/tmp36/products/product.html
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

COMPLETE PARTSLIST 21
• A tilt sensor. Get it from Adafruit (product ID 173), or buy it at
Mouser (part number 107-2006-EV).
For the soldering tutorial, you need the following things:
• A 25W–30W soldering iron with atip (preferably 1/16") and a sol-
dering stand.
•Standard 60/40 solder (rosin-core) spool for electronics work. It
should have a0.031" diameter.
• A sponge.
Y o u can find these things in every electronics store, and many have
soldering kits for beginners that contain some useful additional tools.
Take alook at Adafruit (product ID 136) or Makershed (product code
MKEE2).
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>
Part I
Getting Started with Arduino
Download from Wow! eBook <www.wowebook.com>

Chapter 1
W e l c o m e to the Arduino
The Arduino was originally built for designers and artists—people with
little technical expertise. Even without programming experience, the
Arduino enabled them to create sophisticated design prototypes and
some amazing interactive artworks. So, it should come as no surprise
that the first steps with the Arduino are very easy, even more so for
people with astrong technical background.
But it’s still important to get the basics right. Y o u ’ l l get the most out
of working with the Arduino if you’re familiar with the Arduino board
itself, with its development environment, and with techniques such as
serial communication.
One thing to understand before getting started is physical computing.If
you have worked with computers before, you might wonder what this
means. After all, computers are physical objects, and they accept input
from physical keyboards and mice. They output sound and video to
physical speakers and displays. So, isn’t all computing physical com-
puting in the end?
In principle, regular computing is asubset of physical computing: key-
board and mouse are sensors for real-world inputs, and displays or
printers are actuators.But controlling special sensors and actuators,
using aregular computer is very difficult. Using an Arduino, it’s apiece
of cake to control sophisticated and sometimes even weird devices.
In the rest of this book, you’ll learn how, and in this chapter you’ll
get started with physical computing by learning how to control the
Arduino, what tools you need, and how to install and configure them.
Then we’ll quickly get to the fun part: you’ll develop your first program
for the Arduino.
Download from Wow! eBook <www.wowebook.com>

WHAT YOUNEED 24
1.1 What Y o u Need
•An Arduino board such as the Uno, Duemilanove, or Diecimila.
• A USB cable to connect the Arduino to your computer.
•An LED.
•The Arduino IDE (see Section 1.4,Installing the Arduino IDE,on
page 31). Y o u will need it in every chapter, so after this chapter,
I’ll no longer mention it explicitly.
1.2 What Exactly Is an Arduino?
Beginners often get confused when they discover the Arduino project.
When looking for the Arduino, they hear and read strange names such
as Uno, Duemilanove, Diecimila, LilyPad, or Seeduino. The problem is
that there is no such thing as “the Arduino.”
Acouple of years ago the Arduino team designed amicrocontroller
board and released it under an open source license. Y o u could buy fully
assembled boards in afew electronics shops, but people interested in
electronics could also download its schematic1and build it themselves.
Over the years the Arduino team improved the board’s design and
released several new versions. They usually had Italian names such
as Uno, Duemilanove, or Diecimila, and you can find alist of all boards
that were ever created by the Arduino team online.2
Figure 1.1,on the following page shows asmall selection of Arduinos.
They may differ in their appearance, but they have alot in common,
and you can program them all with the same tools and libraries.
The Arduino team did not only constantly improve the hardware design.
They also invented new designs for special purposes. For example, they
created the Arduino LilyPad3to embed amicrocontroller board into
textiles. Y o u can use it to build interactive T-shirts, for example.
In addition to the official boards, you can find countless Arduino clones
on the W e b . Everybody is allowed to use and change the original board
design, and many people created their very own version of an Arduino-
compatible board. Among many others, you can find the Freeduino,
1. http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
2. http://arduino.cc/en/Main/Boards
3. http://arduino.cc/en/Main/ArduinoBoardLilyPad
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 25
Figure 1.1: Y o u can choose fom many different Arduinos.
Seeduino, Boarduino, and the amazing Paperduino,4an Arduino clone
without aprinted circuit board. All its parts are attached to an ordinary
piece of paper.
Arduino is aregistered trademark—only the official boards are named
“Arduino.”—so clones usually have names ending with “duino.” Y o u
can use every clone that is fully compatible with the original Arduino to
build all the book’s projects.
1.3 Exploring the Arduino Board
In Figure 1.2,on the next page, you can see aphoto of an Arduino Uno
board and its most important parts. I’ll explain them one by one. Let’s
start with the USB connector. To connect an Arduino to your computer,
4. http://lab.guilhermemartins.net/2009/05/06/paperduino-prints/
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 26
Digital I/O Pins
Power Jack
USB Connector
Reset
Button
Micro-
Controller
Power Supply
Analog Input Pins
Figure 1.2: The Arduino’s most important components
you just need an USB cable. Then you can use the USB connection for
various purposes:
•Upload new software to the board (you’ll see how to do this in
Section 1.6,Compiling and Uploading Programs,on page 38).
•Communicate with the Arduino board and your computer (you’ll
learn that in Section 2.4,Using Serial Ports,on page 49).
•Supply the Arduino board with power.
As an electronic device, the Arduino needs power. One way to power it
is to connect it to acomputer’s USB port, but that isn’t agood solution
in some cases. Some projects don’t necessarily need acomputer, and it
would be overkill to use awhole computer just to power the Arduino.
Also, the USB port only delivers 5volts, and sometimes you need more.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 27
Figure 1.3: Y o u can power an Arduino with an AC adapter.
In these situations, the best solution usually is an AC adapter (see
Figure 1.3)supplying 9volts (the recommended range is 7V to 12V).5
Y o u need an adapter with a2.1 mm barrel tip and a positive center (you
don’t need to understand what that means right now; just ask for it in
your local electronics store). Plug it into the Arduino’s power jack, and
it will start immediately, even if it isn’t connected to acomputer. By the
way, even if you connect the Arduino to an USB port, it will use the
external power supply if available.
Please note that older versions of the Arduino board (Arduino-NG and
Diecimila) don’t switch automatically between an external power supply
and a USB supply. They come with apower selection jumper labeled
PWR_SEL, and you manually have to set it to EXT or USB, respectively
(see Figure 1.4,on the next page).
Now you know two ways to supply the Arduino with power. But the
Arduino isn’t greedy and happily shares its power with other devices.
At the bottom of Figure 1.2,on the preceding page, you can see several
sockets (sometimes I’ll also call them pins,because internally they are
connected to pins in the microcontroller) related to power supply:
•Using the pins labeled 3V3 and 5V,you can power external devices
connected to the Arduino with 3.3 volts or 5volts.
5. http://www.arduino.cc/playground/Learning/WhatAdapter
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 28
Jumper
Figure 1.4: Older Arduinos have apower source selection jumper.
•Two ground pins labeled Gnd allow your external devices to share
acommon ground with the Arduino.
•Some projects need to be portable, so they’ll use aportable power
supply such as batteries. Y o u connect an external power source
such as a battery pack to the Vin and Gnd sockets.
If you connect an AC adapter to the Arduino’s power jack, you can
supply the adapter’s voltage through this pin.
On the lower right of the board, you see six analog input pins named
A0–A5. Y o u can use them to connect analog sensors to the Arduino.
They take sensor data and convert it into anumber between 0 and
1023. In Chapter 5,Sensing the W o r l d Around Us,on page 102,we’ll
use them to connect atemperature sensor to the Arduino.
At the board’s top are 14 digital IO pins named D0–D13. Depending on
your needs, you can use these pins for both digital input and output,
so you can read the state of apushbutton or switch to turn on and off
an LED (we’ll do this in Section 3.5,W o r k i n g with Buttons,on page 74).
Six of them (D3, D5, D6, D9, D10, and D11) can also act as analog
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 29
Analog and Digital Signals
Nearly all physical processes are analog. Whenever y o u
observe anatural phenomenon such as electricity or sound,
y o u ’ r e actually receiving an analog signal. One of the most
important properties of these analog signals is that they are
continuous. For e v e r y given point in time, y o u can measure the
strength of the signal, and in principle y o u could register e v e n
the tiniest v a r i a t i o n of the signal.
But although w e live in an analog w o r l d , w e are also living
in the digital age. When the first computers w e r e built a f e w
decades ago, people quickly realized that it’s m u c h easier to
w o r k with real-world information when it’s represented as num-
bers and not as an analog signal such as v o l t a g e or v o l u m e . For
example, it’s m u c h easier to m a n i p u l a t e sounds using a com-
puter whenthe sound w a v e s are stored as a sequence of num-
bers. Every number in this sequence could represent the signal’s
loudness at a certain point in time.
So instead of storing the complete analog signal (as is done
on records), w e measure the signal only at certain points in
time (see Figure 1.5,on the f o l l o w i n g page). W e call this pro-
cess sampling, and the v a l u e s w e store are called samples.The
frequency w e use to determine new samples is called sampling
r a t e .For an audio CD, the sampling r a t e is 44.1 kHz: w e g a t h e r
44,100 samples per second.
W e also have to limit the samples to acertain r a n g e . On an
audio CD, e v e r y sample uses 16 bits. In Figure 1.5,on the next
page, the r a n g e is denoted b y two dashed lines, and w e had
to cut off a peak at the beginning of the signal.
Although y o u can connect both analog and digital devices to
the Arduino, y o u usually don’t have to think m u c h aboutit. The
Arduino automatically performs the conversion from analog to
digital, and vice v e r s a , f o r y o u .
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXPLORING THEARDUINO BOARD 30
70 1 2 3 4 5 6
Figure 1.5: Digitizing an analog signal
output pins. In this mode, they convert values from 0to 255 into an
analog voltage.
All these pins are connected to amicrocontroller. A microcontroller com-
bines aCPU with some peripheral functions such as IO channels. Many
different types of microcontrollers are available, but the Arduino usu-
ally comes with an ATmega328 or an ATmega168. Both are 8-bit micro-
controllers produced by acompany named Atmel.
Although modern computers load programs from ahard drive, micro-
controllers usually have to be programmed. That means you have to
load your software into the microcontroller via acable, and once the
program has been uploaded, it stays in the microcontroller until it gets
overwritten with anew program. Whenever you supply power to the
Arduino, the program currently stored in its microcontroller gets exe-
cuted automatically. Sometimes you want the Arduino to start right
from the beginning. W i t h the reset button on the right side of the board,
you can do that. If you press it, everything gets reinitialized, and the
program stored in the microcontroller starts again (we use it in Sec-
tion 3.4,First V e r s i o n of a Binary Die,on page 69).
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

INSTALLING THEARDUINO IDE 31
In this section, we had acloser look at the Arduino Uno, the newest
Arduino board. But several other types are available, and although
they’re the same in principle, they differ in some details. The Arduino
Mega25606has many more IO pins than all other Arduinos and uses
the powerful ATmega2560 microcontroller, while the Arduino Nano7
was designed to be used on abreadboard, so it doesn’t have any sock-
ets. From my experience, beginners should start with one of the “stan-
dard” boards, that is, with an Uno or aDuemilanove.
1.4 Installing the Arduino IDE
To make it as easy as possible to get started with the Arduino, the
Arduino developers have created asimple but useful integrated devel-
opment environment (IDE). It runs on many different operating sys-
tems. Before you can create your first projects, you have to install it.
Installing the Arduino IDE on Wi ndow s
The Arduino IDE runs on all the latest versions of Microsoft W i n d o w s ,
such as W i n d o w s XP, W i n d o w s V i s t a , and W i n d o w s 7. Installing the
software is easy, because it comes as a self-contained ZIP archive,8so
you don’t even need an installer. Download the archive, and extract it
to alocation of your choice.
Before you first start the IDE, you must install drivers for the Arduino’s
USB port. This process depends on the Arduino board you’re using and
on your flavor of W i n d o w s , but you always have to plug the Arduino
into aUSB port first to start the driver installation process.
On W i n d o w s V i s t a , driver installation usually happens automatically.
Lean back and watch the hardware wizard’s messages pass by until it
says that you can use the newly installed USB hardware.
W i n d o w s XP and W i n d o w s 7may not find the drivers on Microsoft’s
update sites automatically. Sooner or later the hardware wizard asks
you for the path to the right drivers after you have told it to skip auto-
matic driver installation from the Internet. Depending on your Arduino
board, you have to point it to the right location in the Arduino installa-
tion directory. For the Arduino Uno and the Arduino Mega 2560, choose
6. http://arduino.cc/en/Main/ArduinoBoardMega2560
7. http://arduino.cc/en/Main/ArduinoBoardNano
8. http://arduino.cc/en/Main/Software
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

INSTALLING THEARDUINO IDE 32
Arduino UNO.inf (respectively, Arduino MEGA 2560.inf)in the drivers direc-
tory. For older boards such as the Duemilanove, Diecimila, or Nano,
choose the drivers/FTDI USB Drivers directory
After the drivers have been installed, you can start the Arduino exe-
cutable from the archive’s main directory by double-clicking it. Follow
the instructions on the screen to install the IDE.
Please note that the USB drivers don’t change as often as the Arduino
IDE. Whenever you install anew version of the IDE, check whether you
have to install new drivers, too. Usually, it isn’t necessary.
Installing the Arduino IDE on Mac OS X
The Arduino IDE is available as a disk image for the most recent Mac
OS X.9Download it, double-click it, and then drag the Arduino icon to
your Applications folder.
If you’re using an Arduino Uno or an Arduino Mega 2560, you are
done and can start the IDE. Before you can use the IDE with an older
Arduino such as the Duemilanove, Diecimila, or Nano, you have to
install drivers for the Arduino’s serial port. Auniversal binary is in the
disk image—double-click the FTDIUSBSerialDriver_10_4_10_5_10_6.pkg file for
your platform, and follow the installation instructions on the screen.
When installing anew version of the Arduino IDE, you usually don’t
have to install the FTDI drivers again (only when amore recent version
of the drivers is available).
Installing the Arduino IDE on Linux
Installation procedures on Linux distributions are still not very homo-
geneous. The Arduino IDE works fine on nearly all modern Linux ver-
sions, but the installation process heavily differs from distribution to
distribution. Also, you often have to install additional software (the Java
virtual machine, for example) that comes preinstalled with other oper-
ating systems.
It’s best to check the official documentation10and look up the instruc-
tions for your preferred system.
Now that we have the drivers and the IDE installed, let’s see what it has
to offer.
9. http://arduino.cc/en/Main/Software
10. http://www.arduino.cc/playground/Learning/Linux
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

MEETING THEARDUINO IDE 33
Figure 1.6: The Arduino IDE is well arranged.
1.5 Meeting the Arduino IDE
If you have used an IDE such as Eclipse, Xcode, or Microsoft V i s u a l Stu-
dio before, you’d better lower your expectations, because the Arduino
IDE is really simple. It mainly consists of an editor, acompiler, aloader,
and a serial monitor (see Figure 1.6 or, even better, start the IDE on
your computer).
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

MEETING THEARDUINO IDE 34
V e r i f y
Stop
New
Open
Save
Upload
Serial Monitor
Figure 1.7: The IDE’s toolbar gives you quick access to important func-
tions.
It has no advanced features such as a debugger or code completion.
Y o u can change only afew preferences, and as a Java application it
does not fully integrate into the Mac desktop. It’s still usable, though,
and even has decent support for project management.
In Figure 1.7,you can see the IDE’s toolbar that gives you instant
access to the functions you’ll need most:
•W i t h the V e r i f y button, you can compile the program that’s cur-
rently in the editor. So, in some respects, “Verify” is abit of a
misnomer, because clicking the button does not only verify the
program syntactically. It also turns it into arepresentation suit-
able for the Arduino board.
•The New button creates anew program by emptying the content
of the current editor window. Before that happens, the IDE gives
you the opportunity to store all unsaved changes.
•W i t h Open, you can open an existing program from the file system.
•Save saves the current program.
•When you click the Upload button, the IDE compiles the current
program and uploads it to the Arduino board you have chosen in
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

MEETING THEARDUINO IDE 35
Power
Status LED
Serial
Communication
Figure 1.8: The Arduino board comes with several LEDs.
the IDE’s Tools >Serial Port menu (you’ll learn more about this in
Section 1.6,Compiling and Uploading Programs,on page 38).
•The Arduino can communicate with acomputer via aserial con-
nection. Clicking the Serial Monitor button opens aserial monitor
window that allows you to watch the data sent by an Arduino and
also to send data back.
•The Stop button stops the serial monitor.
Although using the IDE is easy, you might run into problems or want to
look up something special. In such cases, take alook at the Help menu.
It points to many useful resources at the Arduino’s website that provide
quick solutions not only to all typical problems but also to reference
material and tutorials.
To get familiar with the IDE’s most important features, we’ll create a
simple program that makes an light-emitting diode (LED) blink. An
LED is acheap and efficient light source, and the Arduino already
comes with several LEDs. One LED shows whether the Arduino is cur-
rently powered, and two other LEDs blink when data is transmitted or
received via aserial connection (see them in Figure 1.8).
In our first little project, we’ll make the Arduino’s status LED blink.
The status LED is connected to digital IO pin 13. Digital pins act as a
kind of switch and can be in one of two states: HIGH or LOW. If set to
HIGH, the output pin is set to 5volts, causing acurrent to flow through
the LED, so it lights up. If it’s set back to LOW, the current flow stops,
and the LED turns off. Y o u do not need to know exactly how electricity
works at the moment, but if you’re curious, take alook at Section A.1,
Current, V o l t a g e , and Resistance,on page 237.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

MEETING THEARDUINO IDE 36
Open the IDE, and enter the following code in the editor:
Download we l co m e /H e ll o Wo r l d /H e l lo Wo r l d. p de
Line 1const unsigned int LED_PIN =13;
-const unsigned int PAUSE =500;
-
-void setup() {
5pinMode(LED_PIN, OUTPUT);
-}
-
-void loop() {
-digitalWrite(LED_PIN, HIGH);
10 delay(PAUSE);
-digitalWrite(LED_PIN, LOW);
-delay(PAUSE);
-}
Let’s see how this works and dissect the program’s source code piece by
piece. In the first two lines we define two int constants using the const
keyword. LED_PIN refers to the number of the digital IO pin we’re using,
and P A U S E defines the length of the blink period in milliseconds.
Every Arduino program needs afunction named setup(), and ours starts
in line 4. Afunction definition always adheres to the following scheme:
<return value type> <function name> ’(’ <list of parameters> ’)’
In our case the function’s name is setup(), and its return value type is
v o i d :it returns nothing. setup( ) doesn’t expect any arguments, so we left
the parameter list empty. Before we continue with the dissection of our
program, you should learn abit more about the Arduino’s data types.
Arduino Data Typ es
Every piece of data you store in an Arduino program needs atype.
Depending on your needs, you can choose from the following:
•boolean values take up one byte of memory and can be true or f a l s e .
•char variables take up one byte of memory and store numbers
from -128 to 127. These numbers usually represent characters
encoded in ASCII; that is, in the following example, c1 and c2 have
the same value:
char c1 ='A';
char c2 =65;
Note that you have to use single quotes for char literals.
•b y t e variables use one byte and store values from 0to 255.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

MEETING THEARDUINO IDE 37
•An int variable needs two bytes of memory; you can use it to store
numbers from -32,768 to 32,767. Its unsigned pendant unsigned
int also consumes two bytes of memory but stores numbers from
0to 65,535.
•For bigger numbers, use long.It consumes four bytes of mem-
ory and stores values from -2,147,483,648 to 2,147,483,647. The
unsigned variant unsigned long also needs four bytes but ranges
from 0to 4,294,967,295.
•float and double are the same at the moment, and you can use
these types for storing floating-point numbers. Both use four bytes
of memory and are able to store values from -3.4028235E+38 to
3.4028235E+38.
•Y o u need v o i d only for function declarations. It denotes that a
function doesn’t return avalue.
•Arrays store collections of values having the same type:
int values[2]; // Atwo-element array
int values[0] =42; // Set the first element
int values[1] =-42; // Set the second element
int more_values[] = { 42, -42 };
int first =more_values[0]; // first == 42
In the preceding example, the arrays v a l u e s and more_values con-
tain the same elements. W e have used only two different ways of
initializing an array. Note that the array index starts at 0, and keep
in mind that uninitialized array elements contain random values.
• A string is an array of char values. The Arduino environment sup-
ports the creation of strings with some syntactic sugar—all these
declarations create strings with the same contents.
char string1[8] = { 'A', 'r', 'd', 'u', 'i', 'n', 'o', '\0' };
char string2[] =
"Arduino"
;
char string3[8] =
"Arduino"
;
char string4[] = { 65, 114, 100, 117, 105, 110, 111, 0};
Strings should always be terminated by azero byte. When you
use double quotes to create astring, the zero byte will be added
automatically. That’s why you have to add one byte to the size of
the corresponding array.
In Section 8.7,Emailing Directly from an Arduino,on page 188,
you’ll learn how to use the Arduino’s new String class.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

COMPILING ANDUPLOADINGPROGRAMS 38
Arduino calls setup( ) once when it boots, and we use it for initializing the
Arduino board and all the hardware we have connected to it. W e use
the pinMode( ) method to turn pin 13 into an output pin. This makes
sure the pin is able to provide enough current to light up an LED. The
default state of apin is INPUT, and both INPUT and OUTPUT are predefined
constants.11
Another mandatory function named loop( ) begins in line 8. It contains
the main logic of aprogram, and the Arduino calls it in an infinite loop.
Our program’s main logic has to turn on the LED connected to pin 13
first. To do this, we use digitalWrite( ) and pass it the number of our pin
and the constant HIGH.This means the pin will output 5volts until
further notice, and the LED connected to the pin lights up.
The program then calls delay( ) and waits for 500 milliseconds doing
nothing. During this pause, pin 13 remains in HIGH state, and the LED
continues to burn. The LED is eventually turned off when we set the
pin’s state back to LOW using digitalWrite( ) again. W e wait another 500
milliseconds, and then the loop( ) function ends. The Arduino starts it
again, and the LED blinks.
In the next section, you’ll learn how to bring the program to life and
transfer it to the Arduino.
1.6 Compiling and Uploading Programs
Before you compile and upload aprogram to the Arduino, you have to
configure two things in the IDE: the type of Arduino you’re using and
the serial port your Arduino is connected to.
Identifying the Arduino type is easy, because it is printed on the board.
Popular types are Uno, Duemilanove, Diecimila, Nano, Mega, Mini, NG,
BT, LilyPad, Pro, or Pro Mini. In some cases, you also have to check
what microcontroller your Arduino uses—most have an ATmega168 or
an ATmega328. Y o u can find the microcontroller type printed on the
microcontroller itself. When you have identified the exact type of your
Arduino, choose it from the Tools >Board menu.
Now you have to choose the serial port your Arduino is connected
to from the Tools >Serial Port menu. On Mac OS X, the name of
the serial port starts with /dev/cu.usbserial or /dev/cu.usbmodem (on my
11. See http://arduino.cc/en/Tutorial/DigitalPins for the official documentation.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

COMPILING ANDUPLOADINGPROGRAMS 39
MacBook Pro, it’s /dev/cu.usbmodemfa141). On Linux systems, it should
be /dev/ttyUSB0,/dev/ttyUSB1,or something similar depending on the
number of USB ports your computer has.
On W i n d o w s systems, it’s abit more complicated to find out the right
serial port, but it’s still not difficult. Go to the Device Manager, and
look for USB Serial Port below the Ports (COM &LPT) menu entry (see
Figure 1.9,on the following page). Usually the port is named COM1,
COM2, or something similar.
After you have chosen the right serial port, click the V e r i f y button, and
you should see the following output in the IDE’s message area (the
Arduino IDE calls programs sketches):
Binary sketch size: 1010 bytes (of a32256 byte maximum)
This means the IDE has successfully compiled the source code into
1,010 bytes of machine code that we can upload to the Arduino. If you
see an error message instead, check whether you have typed in the
program correctly (when in doubt, download the code from the book’s
website).12Depending on the Arduino board you’re using, the byte max-
imum may differ. On an Arduino Duemilanove, it’s usually 14336, for
example.
Now click the Upload button, and after a few seconds, you should see
the following output in the message area:
Binary sketch size: 1010 bytes (of a32256 byte maximum)
This is exactly the same message we got after compiling the program,
and it tells us that the 1,010 bytes of machine code were transferred
successfully to the Arduino. In case of any errors, check whether you
have selected the correct Arduino type and the correct serial port in the
Tools menu.
During the upload process, the TX and RX LEDs will flicker for afew
seconds. This is normal, and it happens whenever the Arduino and
your computer communicate via the serial port. When the Arduino
sends information, it turns on the TX LED. When it gets some bits,
it turns on the RX LED. Because the communication is pretty fast, the
LEDs start to flicker, and you cannot identify the transmission of a
single byte (if you can, you are probably an alien).
12. http://www.pragprog.com/titles/msard
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH LEDS41
Figure 1.10: What’s happening on pin 13 while the LED blinks.
As soon as the code has been transmitted completely, the Arduino exe-
cutes it. In our case, this means the status LED starts to blink. It turns
on for half asecond, then it turns off for half asecond, and so on.
In Figure 1.10,you can see adiagram showing the activity on the pin
while the program is running. The pin starts in LOW state and does not
output any current. W e set it to HIGH in the software using digitalWrite( )
and let it output 5volts for 500 milliseconds. Finally, we set it back to
LOW for 500 milliseconds and repeat the whole process.
Admittedly, the status LED does not look very spectacular. So, in the
next section, we’ll attach a “real” LED to the Arduino.
1.7 W o r k i n g with LEDs
The LEDs that come with the Arduino are nice for testing purposes, but
you should not use them in your own electronics projects. They all have
aspecific meaning, and it’s bad style to use them in adifferent context.
Also, they are very small and not very bright, so it’s agood idea to get
some additional LEDs and learn how to connect them to the Arduino.
It’s really easy.
W e will not use the same type of LEDs that are mounted on the Arduino
board. They are surface-mounted devices (SMD) that are difficult to
handle. Y o u will rarely work with SMD parts, because for most of them
you need special equipment and a lot of experience. They save costs
as soon as you start mass production of an electronic device, but pure
hobbyists won’t need them often.
The LEDs that we need are through-hole parts; you can see some in
Figure 1.11,on the following page. They are named through-hole parts
because they are mounted to acircuit board through holes. That’s
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH LEDS42
Figure 1.11: Acollection of through-hole LEDs
why they usually have one or more long wires. First you put the wires
through holes in aprinted circuit board. Then you usually bend, sol-
der, and cut them to attach the part to the board. Where available, you
can also plug them into sockets as we have them on the Arduino or
on breadboards (you’ll learn more about breadboards in Section 3.2,
W o r k i n g with Breadboards,on page 64).
In Figure 1.12,on the following page, you can see how to attach an
LED to an Arduino. Put the short connector of the LED to the ground
pin (GND) and the longer one to pin 13. Y o u can do that while the blink
sketch is still running. Both the status LED and the external LED will
start to blink.
Make absolutely sure that you’re using pin 13! If you connect the LED
to any other pin, it will probably be destroyed. The reason is that pin
13 has an internal resistor that the other pins don’t have (you’ll learn
more about this in Chapter 3,Building Binary Dice,on page 63).
That’s it! Y o u ’ v e just added your first external electronics part to your
Arduino, and you have created your first physical computing project.
Y o u ’ v e written some code, and it makes the world abit brighter. Y o u r
very own digital version of “fiat lux.”13
Y o u will need the theory and skills you have learned in this chapter
for nearly every Arduino project. In the next chapter, you’ll see how to
gain more control over LEDs, and you’ll learn how to benefit from more
advanced features of the Arduino IDE.
13. http://en.wikipedia.org/wiki/Fiat_lux
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WHAT IFITDOESN’TWORK?43
Figure 1.12: Connect an LED to the Arduino.
1.8 What If It Doesn’t W o r k ?
Don’t panic! If it doesn’t work, you’ve probably attached the LED in the
wrong way. When assembling an electronics project, parts fall into two
categories: those you can mount any way you like and those that need
aspecial direction. An LED has two connectors: an anode (positive)
and a cathode (negative). It’s easy to mix them up, and my science
teacher taught me the following mnemonic: the cathode is necative. It’s
also easy to remember what the negative connector of an LED is: it is
shorter, minus, less than. If you are a more positive person, then think
of the anode as being bigger plus more. Y o u can alternatively identify a
LED’s connectors using its case. On the negative side the case is flat,
while it’s round on the positive side.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXERCISES 44
Choosing the wrong serial port or Arduino type also is acommon mis-
take. If you get an error message such as “Serial port already in use”
when uploading asketch, check whether you have chosen the right
serial port from the Tools >Serial Port menu. If you get messages
such as “Problem uploading to board” or “programmer is not respond-
ing,” check whether you have chosen the right Arduino board from the
Tools >Board menu.
Y o u r Arduino programs, like all programs, will contain bugs. Typos and
syntax errors will be detected by the compiler. In Figure 1.13,on the fol-
lowing page, you can see atypical error message. Instead of pinMode(),
we called pinMod(), and because the compiler did not find afunction
having that name, it stopped with an error message. The Arduino IDE
highlights the line, showing the error with ayellow background, and
prints ahelpful error message.
Other bugs might be more subtle and sometimes you have to care-
fully study your code and use some plain old debugging techniques (in
Debug It! Find, Repair, and Prevent Bugs in Y o u r Code [But09]you can
find plenty of useful advice on this topic).
It might happen—although it’s rare—that you actually have adamaged
LED. If none of the tricks mentioned helps, try another LED.
1.9 Exercises
•Trydifferent blink patterns using more pauses and vary the pause
length (they don’t necessarily have to be all the same). Also, exper-
iment with very short pauses that make the LED blink at a high
frequency. Can you explain the effect you’re observing?
•Let the LED output your name in Morse code.14
14. http://en.wikipedia.org/wiki/Morse_code
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

Chapter 2
Inside the Arduino
For simple applications, all you have learned about the Arduino IDE in
the preceding chapter is sufficient. But soon your projects will get more
ambitious, and then it will come in handy to split them into separate
files that you can manage as a whole. So in this chapter, you’ll learn
how to stay in control over bigger projects with the Arduino IDE.
Usually, bigger projects need not only more software but also more
hardware—you will rarely use the Arduino board in isolation. For exam-
ple, you will use many more sensors than you might imagine, and you’ll
have to transmit the data they measure back to your computer. To
exchange data with the Arduino, you’ll use its serial port. This chapter
explains everything you need to know about serial communication. To
make things more tangible, you’ll learn how to turn your computer into
avery expensive light switch that lets you control an LED using the
keyboard.
2.1 What Y o u Need
To try this chapter’s examples, you need only afew things:
•An Arduino board such as the Uno, Duemilanove, or Diecimila
• A USB cable to connect the Arduino to your computer
•An LED (optional)
• A software serial terminal such as Putty (for W i n d o w s users) or
screen for Linux and Mac OS Xusers (optional)
Download from Wow! eBook <www.wowebook.com>

MANAGINGPROJECTS AND SKETCHES 47
2.2 Managing Projects and Sketches
Modern software developers can choose from avariety of development
tools that automate repetitive and boring tasks. That’s also true for
embedded systems like the Arduino. Y o u can use integrated develop-
ment environments (IDEs) to manage your programs, too. The most
popular one has been created by the Arduino team.
The Arduino IDE manages all files belonging to your project. It also pro-
vides convenient access to all the tools you need to create the binaries
that will run on your Arduino board. Conveniently, it does so unob-
trusively. For example, you might have noticed that the Arduino IDE
stores all code you enter automatically. This is to prevent beginners
from losing data or code accidentally (not to mention that even the pros
lose data from time to time, too).
Organizing all the files belonging to aproject automatically is one of
the most important features of an IDE. Under the hood, the Arduino
IDE creates adirectory for every new project, and it stores all the files
belonging to the project in this directory. To add new files to aproject,
click the tabs button on the right to open the tabs pop-up menu, and
then choose New Tab (see Figure 2.1). To add an existing file, use the
Sketch >Add File menu item.
As you might have guessed already from the names of the menu items,
the Arduino IDE calls projects sketches.If you do not choose aname,
it gives them aname starting with sketch_.Y o u can change the name
whenever you like using the Save As command. If you do not save a
sketch explicitly, the IDE stores it in apredefined folder you can look
Figure 2.1: The tabs menu in action
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

CHANGING PREFERENCES 48
up in the preferences menu. Y o u can change this behavior so that the
IDE asks you for aname when you create anew sketch. Whenever you
get lost, you can check what folder the current sketch is in using the
Sketch >Show Sketch Folder menu item.
The IDE uses directories not only to organize projects. It also stores
some interesting things in the following folders:
•The examples folder contains sample sketches that you can use as
abasis for your own experiments. Get to them via the File >Open
dialog box. Take some time to browse through them, even if you
do not understand anything you see right now.
•The libraries directory contains libraries for various purposes and
devices. Whenever you use anew sensor, for example, chances are
good that you have to copy asupporting library to this folder.
The Arduino IDE makes your life easier by choosing reasonable defaults
for alot of settings. But it also allows you to change most of these
settings, and you’ll see how in the next section.
2.3 Changing Preferences
For your early projects, the IDE’s defaults might be appropriate, but
sooner or later you’ll want to change some things. As you can see in
Figure 2.2,on the following page, the IDE lets you change only afew
preferences directly. But the dialog box refers to afile named prefer-
ences.txt containing more preferences. This file is aJava properties file
consisting of key/value pairs. Here you see afew of them:
...
editor.external.bgcolor=#168299
preproc.web_colors=true
editor.font.macosx=Monaco,plain,10
sketchbook.auto_clean=true
update.check=true
build.verbose=true
upload.verbose=true
...
Most of these properties control the user interface; that is, they change
fonts, colors, and so on. But they can also change the application’s
behavior. For example, you can enable more verbose output for opera-
tions such as compiling or uploading asketch. Edit preferences.txt, and
set both build.verbose and upload.verbose to true.Then load the blinking
LED sketch from Chapter 1,W e l c o m e to the Arduino,on page 23 and
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 49
Figure 2.2: The IDE lets you change some preferences.
compile it again. The output in the message panel should look similar
to Figure 2.3,on the following page (in recent versions of the IDE, you
can achieve the same effect by holding down the Shift key when you
click the V e r i f y / C o m p i l e or Upload button in the toolbar).
Note that the IDE updates some of the preferences’ values when it
shuts down. So before you change any preferences directly in the pref-
erences.txt file, you have to stop the Arduino IDE first.
Now that you’re familiar with the Arduino IDE, let’s do some program-
ming. W e ’ l l make the Arduino talk to the outside world.
2.4 Using Serial P o r t s
Arduino makes many stand-alone applications possible—projects that
do not involve any additional computers. In such cases you need to con-
nect the Arduino to acomputer once to upload the software, and after
that, it needs only apower supply. More often, people use the Arduino
to enhance the capabilities of acomputer using sensors or by giving
access to additional hardware. Usually, you control external hardware
via aserial port, so it is agood idea to learn how to communicate seri-
ally with the Arduino.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 51
The Arduino Programming Language
P e o p l e sometimes seem to be a bit irritated when it comes to
the language the Arduino gets programmed in. That’s m a i n l y
because the typical sample sketches look as if they w e r e writ-
ten in alanguage that has been exclusively designed f o r pro-
gramming the Arduino. But that’s not the case—it is plain old
C++ (which implies that it supports C, too).
Every Arduino uses an A V R microcontroller designed b y acom-
pany named Atmel. (Atmel says that the name A V R does not
stand f o r anything.) These microcontrollers are v e r y popular,
and m a n y hardware projects use them. One of the reasons
f o r their popularity is the excellent tool chain that comes with
them. It is based on the GNU C++ compiler tools and has been
optimized f o r generating code f o r A V R microcontrollers.
That means y o u f e e d C++ code to the compiler that is not
translated into m a c h i n e code f o r y o u r computer but f o r an A V R
microcontroller. This technique is called cross-compiling and is
the usual w a y to program embedded devices.
Although the standards for serial communication have changed over
the past few years (for example, we are using USB today, and our com-
puters no longer have RS232 connectors), the basic working principles
remain the same. In the simplest case, we can connect two devices
using only three wires: acommon ground, aline for transmitting data
(TX), and one for receiving data (RX).
Device #1
GND
TX
RX
Device #2
GND
TX
RX
Serial communication might sound abit old-school, but it’s still the
preferred way for hardware devices to communicate. For example, the
Sin USB stands for “serial”—and when was the last time you saw a
parallel port? (Perhaps this is agood time to clean up the garage and
throw out that old PC that you wanted to turn into amedia center
someday....)
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 52
For uploading software, the Arduino has aserial port, and we can use it
to connect the Arduino to other devices, too (in Section 1.6,Compiling
and Uploading Programs,on page 38,you learn how to look up the
serial port your Arduino is connected to). In this section, we will use
it to control Arduino’s status LED using our computer’s keyboard. The
LED should be turned on when you press 1, and it should be turned
off when you press 2. Here’s all the code we need:
Download we l c o m e / Le dS wi tc h / L e d S w it ch .p de
Line 1const unsigned int LED_PIN =13;
-const unsigned int BAUD_RATE =9600;
-
-void setup() {
5pinMode(LED_PIN, OUTPUT);
-Serial.begin(BAUD_RATE);
-}
-
-void loop() {
10 if (Serial.available() >0) {
-int command =Serial.read();
-if (command == '1') {
-digitalWrite(LED_PIN, HIGH);
-Serial.println(
"LED on"
);
15 }else if (command == '2') {
-digitalWrite(LED_PIN, LOW);
-Serial.println(
"LED off"
);
-}else {
-Serial.print(
"Unknown command: "
);
20 Serial.println(command);
-}
-}
-}
As in our previous examples, we define aconstant for the pin the LED
is connected to and set it to OUTPUT mode in the setup( ) function. In
line 6, we initialize the serial port using the begin( ) function of the Serial
class, passing abaud rate of 9600 (you can learn what abaud rate is in
Section C.1,Learning More About Serial Communication,on page 251).
That’s all we need to send and receive data via the serial port in our
program.
So, let’s read and interpret the data. The loop( ) function starts by calling
Serial’s available( ) method in line 10. available( ) returns the number of
bytes waiting on the serial port. If any data is available, we read it
using Serial.read(). read( ) returns the first byte of incoming data if data
is available and -1 otherwise.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 53
F a s h i o n a b l e LEDs
Both pervasive and w e a r a b l e computing got v e r y popular o v e r
the past y e a r s , so T - s h i r t s with an equalizer are still cool but not
that exciting any longer.∗But b y using a f e w LEDs, y o u can cre-
ate some astonishing accessories f o r the ladies. For example,
J a p a n e s e engineers have created LED e y e l a s h e s . †
This particular product does not use an Arduino, but with the
Lilypad,‡y o u can easily create similar things y o u r s e l f . Y o u have
to be extremely careful with LEDs, because most of them are
v e r y bright and can cause serious damage to y o u r e y e s !
∗.http://www.thinkgeek.com/tshirts-apparel/interactive/8a5b/
†.http://blog.makezine.com/archive/2009/10/led_eyelashes.html
‡.http://www.arduino.cc/en/Main/ArduinoBoardLilyPad
If the byte we have read represents the character 1, we switch on the
LED and send back the message “LED on” over the serial port. W e use
Serial.println(), which adds a carriage return character (ASCII code 13)
followed by anewline (ASCII code 10) to the text.
If we received the character 2, we switch off the LED. If we received an
unsupported command, we send back acorresponding message and
the command we did not understand. Serial.print( ) works exactly like
Serial.println(), but it does not add carriage return and newline characters
to the message.
Let’s see how the program works in practice. Compile it, upload it to
your Arduino, and then switch to the serial monitor (optionally you can
attach an LED to pin 13; otherwise, you can only control the Arduino’s
status LED). At first glance, nothing has happened. That’s because we
have not sent acommand to the Arduino yet. Enter a 1 in the text box,
and then click the Send button. Two things should happen now: the
LED is switched on, and the message “LED on” appears in the serial
monitor window (see Figure 2.4,on the next page). W e are controlling a
LED using our computer’s keyboard!
Play around a bit with the commands 1 and 2, and also observe what
happens when you send an unknown command. If you type in an
uppercase A,for example, the Arduino will send back the message
“Unknown command: 65.” The number 65 is the ASCII code of the let-
ter A, and the Arduino outputs the data it got in its most basic form.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 54
Figure 2.4: The Arduino IDE’s serial monitor
That’s the default behavior of Serial’s print( ) method, and you can change
it by passing aformat specifier to your function calls. To see the effect,
replace line 20 with the following statements:
Serial.println(command, DEC);
Serial.println(command, HEX);
Serial.println(command, OCT);
Serial.println(command, BIN);
Serial.println(command, BYTE);
The output looks as follows when you send the character Aagain:
Unknown command: 65
41
101
1000001
A
Depending on the format specifier, Serial.println( ) automatically converts
abyte into another representation. DEC outputs abyte as a decimal
number, HEX as a hexadecimal number, and so on. Note that such an
operation usually changes the length of the data that gets transmitted.
The binary representation of the single byte 65, for example, needs 7
bytes, because it contains seven characters.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 55
Numbering Systems
It’s an evolutionary accident that 10 is the basis for our numbering
system. If we had only four fingers on each hand, it’d be probably eight,
and we’d probably have invented computers afew centuries earlier.
For thousands of years, people have used denominational number sys-
tems, and we represent anumber like 4711 as follows:
4×103+7×102+1×101+1×100
This makes arithmetic operations very convenient. But when working
with computers that only interpret binary numbers, it’s often advanta-
geous to use numbering systems based on the numbers 2(binary), 8
(octal), or 16 (hexadecimal).
For example, the decimal number 4711 can be represented in octal and
hexadecimal as follows:
•1×84+1×83+1×82+4×81+7×80=011147
•1×163+2×162+6×161+7×160=0x1267
In Arduino programs, you can define literals for all these numbering
systems:
int decimal =4711;
int binary =B1001001100111;
int octal =011147;
int hexadecimal =0x1267;
Binary numbers start with a B character, octal numbers with a0, and
hexadecimal numbers start with 0x.
Using Different Serial T e r m i n a l s
For trivial applications, the IDE’s serial monitor is sufficient, but you
cannot easily combine it with other applications, and it lacks some
features (for example, it could not send newline characters in older IDE
versions). That means you should have an alternative serial terminal to
send data, and you can find plenty of them for every operating system.
Serial T e r m i n a l s f o r Wi ndows
Putty1is an excellent choice for W i n d o w s users. It is free, and it comes
as an executable that does not even have to be installed. Figure 2.5,on
the following page shows how to configure it for communication on a
serial port.
1. http://www.chiark.greenend.org.uk/~sgtatham/putty/
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 56
Figure 2.5: Configuring Putty to make it work with Arduino
After you have configured Putty, you can open aserial connection to the
Arduino. In Figure 2.6,on the next page, you can see the corresponding
dialog box. Click Open, and you’ll see an empty terminal window.
Now press 1 and 2 a few times to switch on and off the LED. In Fig-
ure 2.7,on the following page, you can see atypical session.
Serial T e r m i n a l s f o r Linux and Mac OS X
Linux and Mac users can use the screen command to communicate
with the Arduino on aserial port. Check which serial port the Arduino
is connected to (for example, in the IDE’s Tools >Board menu), and
then run acommand like this (with an older board the name of the
serial port might be something like /dev/cu.usbserial-A9007LUY, and on
Linux systems it might be /dev/ttyUSB1 or something similar):
$screen /dev/cu.usbmodemfa141 9600
screen expects the name of the serial port and the baud rate to be used.
In Figure 2.8,on page 58,you can see atypical session. To quit the
screen command, press Ctrl-a followed by Ctrl-k.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 58
Figure 2.8: The screen command communicates with Arduino.
W e can now communicate with the Arduino, and this has great impli-
cations: whatever is controlled by the Arduino can also be controlled
by your computer, and vice versa. Switching LEDs on and off is not too
spectacular, but try to imagine what’s possible now. Y o u could move
robots, automate your home, or create interactive games.
Here are some more important facts about serial communication:
•The Arduino’s serial receive buffer can hold up to 128 bytes. When
sending large amounts of data at high speed, you have to synchro-
nize sender and receiver to prevent data loss. Usually, the receiver
sends an acknowledgment to the sender whenever it is ready to
consume anew chunk of data.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGSERIAL PORTS 59
Exciting LED Projects
From what y o u have seen in this and the preceding sections,
y o u might think that LEDs are useful but not v e r y exciting. Y o u
can use them f o r showing adevice’s status or e v e n to build a
complete TV set, but that’s something y o u are used to.
But LEDs are the basis f o r some really spectacular projects. One
of the most amazing ones is the BEDAZZLER.∗The BEDAZZLER is
anonlethal w e a p o n that uses blinking LEDs to cause nausea,
dizziness, headache, flash blindness, e y e pain, and v o m i t i n g .
Originally it has been developed f o r the military, but now it is
available as an open source project.†
All scientific curiosity aside, y o u should k e e p in mind that the
BEDAZZLER is aw e a p o n . Do not use it as a toy, and do not target
it at humans or animals.
∗.http://www.instructables.com/id/Bedazzler-DIY-non-lethal-weaponry/
†.http://www.ladyada.net/make/bedazzler/
•Y o u can control many devices using serial communication, but the
regular Arduino has only one serial port. If you need more, take a
look at the Arduino Mega 2560, which has four serial ports.2
• A Universal Asynchronous Receiver/Transmitter (UART)3device
supports serial communication on the Arduino. This device han-
dles serial communication while the CPU can take care of other
tasks. This greatly improves the system’s overall performance.
The UART uses digital pins 0(RX) and 1 (TX), which means you
cannot use them for other purposes when communicating on the
serial port. If you need them, you can disable serial communica-
tion using Serial.end().
•W i t h the SoftwareSerial4library, you can use any digital pin for
serial communication. It has some serious limitations regarding
speed and reliability, and it does not support all functions that
are available when using aregular serial port.
2. http://arduino.cc/en/Main/ArduinoBoardMega2560
3. http://en.wikipedia.org/wiki/UART
4. http://www.arduino.cc/en/Reference/SoftwareSerial
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WHAT IFITDOESN’TWORK?60
Figure 2.9: Awrong baud rate creates alot of garbage.
In this chapter, you saw how to communicate with the Arduino using
the serial port, which opens the door to awhole new world of physical
computing projects (see Section C.1,Learning More About Serial Com-
munication,on page 251 for more details about serial communication).
In the next chapters, you’ll learn how to gather interesting facts about
the real world using sensors, and you’ll learn how to change the real
world by moving objects. Serial communication is the basis for letting
you control all these actions using the Arduino and your PC.
2.5 What If It Doesn’t W o r k ?
If anything goes wrong with the examples in this chapter, you should
take alook at Section 1.8,What If It Doesn’t W o r k ? ,on page 43 first.
If you still run into problems, it may be because of some issues with
serial communication. For example, you might have set the wrong baud
rate; in Figure 2.9,you can see what’s happening in such acase.
Make sure that the baud rate you have set in your call to Serial.begin( )
matches the baud rate in the serial monitor.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

EXERCISES 61
2.6 Exercises
•Add new commands to the sample program. For example, the com-
mand 3could make the LED blink for awhile.
•Tryto make the commands more readable; that is, instead of 1,
use the command on, and instead of 2, use off.
If you have problems solving this exercise, read Chapter 4,Build-
ing a Morse Code Generator Library,on page 88 first.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>
Part II
Eight Arduino Projects
Download from Wow! eBook <www.wowebook.com>

Chapter 3
Building Binary Dice
Things will really start to get interesting now that you’ve learned the
basics of Arduino development. Y o u now have the skills to create your
first complex, stand-alone projects. After you have worked through this
chapter, you’ll know how to work with LEDs, buttons, breadboards,
and resistors. Combining these parts with an Arduino gives you nearly
endless opportunities for new and cool projects.
Our first project will be creating an electronic die. While regular dice
display their results using one to six dots, ours will use LEDs instead.
For our first experiments, asingle LED has been sufficient, but for
the dice we need more than one. Y o u need to connect several external
LEDs to the Arduino. Because you cannot attach them all directly to
the Arduino, you’ll learn how to work with breadboards. Also, you need
abutton that rolls the dice, so you’ll learn how to work with pushbut-
tons, too. To connect pushbuttons and LEDs to the Arduino, you need
another important electronic part: the resistor. So, at the end of the
chapter, you’ll have many new tools in your toolbox.
3.1 What Y o u Need
1. Ahalf-size breadboard
2. Three LEDs (for the exercises you’ll need additional LEDs)
3. Two 10kΩresistors (see Section A.1,Current, V o l t a g e , and Resis-
tance,on page 237 to learn more about resistors)
4. Three 1kΩresistors
5. Two pushbuttons
6. Some wires
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BREADBOARDS 64
!
"
#$
%
&
&
Figure 3.1: All the parts you need for this chapter
7. An Arduino board such as the Uno, Duemilanove, or Diecimila
8. AUSB cable to connect the Arduino to your computer
9. Atilt sensor (optional)
Figure 3.1 shows the parts needed to build the projects in this chapter.
Y o u ’ l l find such photos in most of the following chapters. The numbers
in the photo correspond to the numbers in the parts list. The photos do
not show standard parts such as the Arduino board or an USB cable.
3.2 W o r k i n g with Breadboards
Connecting parts such as LEDs directly to the Arduino is only an option
in the most trivial cases. Usually, you will prototype your projects on a
breadboard that you connect to the Arduino. Abreadboard “emulates”
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BREADBOARDS 65
Figure 3.2: Acollection of breadboards
acircuit board. Y o u don’t have to solder parts to the board; instead,
you can simply plug them into it.
Breadboards come in various types and sizes (in Figure 3.2,you can
see two of them), but they all work the same way. They have alot of
sockets that you can use for plugging in through-hole parts or wires.
That alone wouldn’t be abig deal, but the sockets are connected in a
special way. In Figure 3.3,on the next page, you can see how.
As you can see, most sockets are connected in columns. If one socket
of acolumn is connected to apower supply, then automatically all the
other sockets in this column are powered, too. On the bigger board
in the photo, you can also see four rows of connected sockets. This
is convenient for bigger circuits. Usually, you connect one row to your
power supply and one to the ground. This way, you can distribute power
and ground to any point on the board. Now let’s see how to put parts
on abreadboard.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGANLED ONABREADBOARD 66
Figure 3.3: How sockets on abreadboard are connected
3.3 Using an LED on aBreadboard
Up to now, we used the LEDs that are installed on the Arduino board,
and we connected one LED directly to the Arduino. In this section, we’ll
plug an LED into abreadboard and then connect the breadboard to the
Arduino.
In Figure 3.4,on the following page, you can see aphoto of our final cir-
cuit. It consists of an Arduino, abreadboard, an LED, three wires, and a
1kΩresistor (more on that part in afew minutes). Connect the Arduino
to the breadboard using two wires. Connect pin 12 with the ninth col-
umn of the breadboard, and connect the ground pin with the tenth
column. This automatically connects all sockets in column 9to pin 12
and all sockets in column 10 to the ground. This choice of columns was
arbitrary, and you could have used other columns instead.
Plug the LED’s negative connector (the shorter one) into column 10 and
its positive connector into column 9. When you plug in parts or wires
into abreadboard, you have to press them firmly until they slip in. Y o u
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

USINGANLED ONABREADBOARD 68
Figure 3.5: Aresistor in various processing stages
might need more than one try, especially on new boards, and it often
comes in handy to shorten the connectors before plugging them into the
breadboard. Make sure that you can still identify the negative and the
positive connector after you have shortened them. Shorten the negative
one abit more, for example. Also wear safety glasses to protect your
eyes when cutting the connectors!
The things we have done until now have been straightforward. That is,
in principle we have only extended the Arduino’s ground pin and its
IO pin number 12. Why do we have to add a resistor, and what is a
resistor? Aresistor limits the amount of current that flows through an
electric connection. In our case, it protects the LED from consuming too
much power, because this would destroy the LED. Y o u always have to
use aresistor when powering an LED! In Section A.1,Current, V o l t a g e ,
and Resistance,on page 237,you can learn more about resistors and
their color bands. In Figure 3.5,you can see aresistor in various stages:
regular, bent, and cut.
Y o u might ask yourself why we didn’t have to use aresistor when we
connected the LED directly to the Arduino. The answer is simple: pin
13 comes with an internal resistor of 1kΩ.Now that we use pin 12, we
have to add our own resistor.
W e don’t want to fiddle around too much with the connectors, so we
build the circuit as shown in Figure 3.6,on the next page. That is, we
use both sides of the breadboard by connecting them with ashort wire.
Note that the resistor bridges the sides, too.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

FIRSTVERSION OFABINARYDIE 69
Figure 3.6: Y o u can use both sides of abreadboard.
3.4 First V e r s i o n of aBinary Die
Y o u ’ r e certainly familiar with regular dice displaying results in arange
from one to six. To emulate such dice exactly with an electronic device,
you’d need seven LEDs and some fairly complicated business logic.
W e ’ l l take ashortcut and display the result of adie roll in binary.
For abinary die, we need only three LEDs that represent the current
result. W e turn the result into abinary number, and for every bit that is
set, we will light up acorresponding LED. The following diagram shows
how the die results are mapped to LEDs (a black triangle stands for a
shining LED).
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

FIRSTVERSION OFABINARYDIE 70
=
=
=
=
=
=
W e already know how to control asingle LED on abreadboard. Con-
trolling three LEDs is similar and requires only more wires, LEDs, 1kΩ
resistors, and pins. In Figure 3.7,on the following page, you can see
the first working version of abinary die.
The most important difference is the common ground. When you need
ground for asingle LED, you can connect it to the LED directly. But
we need ground for three LEDs now, so we’ll use the breadboard’s rows
for the first time. Connect the row marked with ahyphen (-) to the
Arduino’s ground pin, and all sockets in this row will work as ground
pins, too. Then you can connect this row’s sockets to the LEDs using
short wires.
Everything else in this circuit should look familiar, because we only had
to clone the basic LED circuit from the previous section three times.
Note that we have connected the three circuits to pins 10, 11, and 12.
The only thing missing is some software:
Download BinaryDice/BinaryDice.pde
Line 1const unsigned int LED_BIT0 =12;
-const unsigned int LED_BIT1 =11;
-const unsigned int LED_BIT2 =10;
-
5void setup() {
-pinMode(LED_BIT0, OUTPUT);
-pinMode(LED_BIT1, OUTPUT);
-pinMode(LED_BIT2, OUTPUT);
-
10 randomSeed(analogRead(A0));
-long result =random(1, 7);
-output_result(result);
-}
-
15 void loop() {
-}
-
-void output_result(const long result) {
-digitalWrite(LED_BIT0, result &B001);
20 digitalWrite(LED_BIT1, result &B010);
-digitalWrite(LED_BIT2, result &B100);
-}
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

FIRSTVERSION OFABINARYDIE 72
More LEDs, Dice, and Cubes
Building binary dice is fun, and it’s an easy project e v e n f o r
beginners. But what about the opposite—reading real dice?
Steve Hoefer∗has built a dice reader using an Arduino, and
it’s really impressive. He uses five pairs of infrared emitters
and receivers to “scan” adie’s surface. It’s af a i r l y advanced
project, and y o u can learn alot from it.
Another interesting project is an LED cube: building a cube con-
sisting of LEDs.†It’s surprisingly difficult to control more than a
f e w LEDs, but y o u can produce astonishing results.
∗.http://grathio.com/2009/08/dice-reader-version-2.html
†.http://arduinofun.com/blog/2009/12/02/led-cube-and-arduino-lib-build-it/
This is all the code we need to implement the first version of binary
dice. As usual, we define some constants for the output pins the LEDs
are connected to. In the setup( ) function, we set all the pins into OUTPUT
mode. For the dice, we need random numbers in the range between one
and six. The r a n d o m ( ) function returns random numbers in aspecified
range using apseudorandom number generator. In line 10, we initialize
the generator with some noise we read from analog input pin A0 (see
the sidebar on the next page to learn why we have to do that). Y o u might
wonder where the constant A0 is from. Since version 19, the Arduino
IDE defines constants for all analog pins named A0,A1, and so on.
Then we actually generate anew random number between one and six
and output it using the output_result( ) function. (the seven in the call to
r a n d o m ( ) is correct, because it expects the upper limit plus one).
The function output_result( ) takes anumber and outputs its lower three
bits by switching on or off our three LEDs accordingly. Here we use the
&operator and binary literals. The &operator takes two numbers and
combines them bitwise. When two corresponding bits are 1, the result
of the &operator is 1, too. Otherwise, it is 0. The Bprefix allows you to
put binary numbers directly into your source code. For example, B11 is
the same as 3.
Y o u might have noticed that the loop( ) function was left empty, and
you might wonder how such dice work. It’s pretty simple: whenever
you restart the Arduino, it outputs anew number, and to roll the dice
again, you have to press the reset button.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

FIRSTVERSION OFABINARYDIE 73
Generating Random Numbers
Some computing problems are surprisingly difficult, and cre-
ating good r a n d o m numbers is one of them. After all, one
of the most important properties of acomputer is determinis-
tic behavior. Still, w e often need—at least seemingly—random
behavior f o r av a r i e t y of purposes, r a n g i n g from ga m e s to cryp-
tographic algorithms.
The most popular approach (used in Arduino’s r a n d o m ( ) func-
tion, f o r example) is to create pseudorandom numbers.∗They
seem to be r a n d o m , but they actually are the result of af o r -
m u l a . Different kinds of algorithms exist, but usually each new
pseudorandom number is calculated from its predecessors.
This implies that y o u need an initialization v a l u e to create the
first r a n d o m number of the sequence. This initialization v a l u e
is called ar a n d o m seed, and to create different sequences
of pseudorandom numbers, y o u have to use different r a n d o m
seeds.
Creating pseudorandom numbers is cheap, but if y o u know the
algorithm and the r a n d o m seed, y o u can easily predict them.
So, y o u shouldn’t use them f o r cryptographic purposes.
In the real w o r l d , y o u can find countless r a n d o m processes, and
with the Arduino, it’s easy to measure them to create real r a n -
dom numbers. Often it’s sufficient to read some r a n d o m noise
from analog pin 0 and pass it as the r a n d o m seed to the r a n -
domSeed( ) function. Y o u can also use this noise to create real
r a n d o m numbers; there is e v e n alibrary f o r that purpose.†
If y o u need strong r a n d o m numbers, the Arduino is a perfect
device f o r creating them. Y o u can find m a n y projects that
observe natural processes solely to create r a n d o m numbers.
One of them w a t c h e s an hourglass using the Arduino, f o r exam-
ple.‡
∗.http://en.wikipedia.org/wiki/Pseudo-random_numbers
†.http://code.google.com/p/tinkerit/wiki/TrueRandom
‡.http://www.circuitlake.com/usb-hourglass-sand-timer.html
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BUTTONS 74
Compile the code, upload it to the Arduino, and play abit with your
binary dice. Y o u have mastered your first advanced electronics project!
Enjoy it for amoment!
So, whenever you want to see anew result, you have to reset the
Arduino. That’s probably the most pragmatic user interface you can
build, and for afirst prototype, this is OK. But often you need more
than one button, and it’s also more elegant to add your own button
anyway. So, that’s what we’ll do in the next section.
3.5 W o r k i n g with Buttons
In this section, we’ll add our own pushbutton to our binary dice, so
we no longer have to abuse the Arduino’s reset button to roll the dice.
W e ’ l l start small and build acircuit that uses apushbutton to control
asingle LED.
So, what exactly is apushbutton? Here are three views of atypical
pushbutton that can be used as the Arduino’s reset button.
Connected
Connected
T o p Front Side
It has four connectors that fit perfectly on abreadboard (at least after
you have straightened them with apair of pliers). Two opposite pins
connect when the button is pushed; otherwise, they are disconnected.
In Figure 3.8,on the following page, you can see asimple circuit using a
pushbutton. Connect pin 7(chosen completely arbitrarily) to the push-
button, and connect the pushbutton via a10kΩresistor to ground.
Then connect the 5volts power supply to the other pin of the button.
All in all, this approach seems straightforward, but why do we need a
resistor again? The problem is that we expect the pushbutton to return
adefault value (LOW)in case it isn’t pressed. But when the button isn’t
pressed, it would not be directly connected to ground and would flicker
because of static and interference. Alittle bit of current flows through
the resistor, and this helps prevent random noise from changing the
voltage that the input pin sees.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BUTTONS 75
Figure 3.8: Asimple pushbutton circuit
When the button is pressed, there will still be 5volts at the Arduino’s
digital pin, but when the button isn’t pressed, it will cleanly read the
connection to ground. W e call this apull-down r e s i s t o r ; a pull-up r e s i s t o r
works exactly the other way around. That is, you have to connect the
Arduino’s signal pin to power through the pushbutton and connect the
other pin of the pushbutton to ground using aresistor.
Now that we’ve eliminated all this ugly unstable real-world behavior, we
can return to the stable and comforting world of software development.
The following program checks whether apushbutton is pressed and
lights an LED accordingly:
Download BinaryDice/SimpleButton/SimpleButton.pde
const unsigned int BUTTON_PIN =7;
const unsigned int LED_PIN =13;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
const int BUTTON_STATE =digitalRead(BUTTON_PIN);
if (BUTTON_STATE == HIGH)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN, LOW);
}
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BUTTONS 76
W e connect the button to pin 7 and the LED to pin 13 and initialize the
pins accordingly in the setup( ) function. In loop(), we read the current
state of the pin connected to the button. If it is HIGH,we turn the LED
on. Otherwise, we turn it off.
Upload the program to the Arduino, and you’ll see that the LED is on
as long as you press the button. As soon as you release the button,
the LED turns off. This is pretty cool, because now we nearly have
everything we need to control our dice using our own button. But before
we proceed, we’ll slightly enhance our example and turn the button into
areal light switch.
To build alight switch, we start with the simplest possible solution.
Do not change the current circuit, and upload the following program to
your Arduino:
Download BinaryDice/UnreliableSwitch/UnreliableSwitch.pde
Line 1const unsigned int BUTTON_PIN =7;
-const unsigned int LED_PIN =13;
-
-void setup() {
5pinMode(LED_PIN, OUTPUT);
-pinMode(BUTTON_PIN, INPUT);
-}
-
-int led_state =LOW;
10
-void loop() {
-const int CURRENT_BUTTON_STATE =digitalRead(BUTTON_PIN);
-
-if (CURRENT_BUTTON_STATE == HIGH) {
15 led_state =(led_state == LOW) ?HIGH :LOW;
-digitalWrite(LED_PIN, led_state);
-}
-}
W e begin with the usual pin constants, and in setup( ) we set the modes
of the pins we use. In line 9, we define aglobal variable named led_state
to store the current state of our LED. It will be LOW when the LED is
on and HIGH otherwise. In loop(), we check the button’s current state.
When we press the button, its state switches to HIGH, and we toggle the
content of led_state.That is, if led_state was HIGH, we set it to LOW, and
vice versa. At the end, we set the physical LED’s state to our current
software state accordingly.
Our solution is really simple, but unfortunately, it does not work. Play
around with it abit, and you’ll quickly notice some annoying behavior.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BUTTONS 77
If you press the button, for example, the LED sometimes will turn on
and then off immediately. Also, if you release it, the LED will often
remain in amore or less arbitrary state; that is, sometimes it will be on
and sometimes off.
The problem is that the Arduino executes the loop( ) method over and
over again. Although the Arduino’s CPU is comparatively slow, this
would happen very often—no matter if we currently press the button
or not. But if you press it and keep it pressed, its state will constantly
be HIGH, and you’d constantly toggle the LED’s state (because this hap-
pens so fast it seems like the LED’s constantly on). When you release
the button, the LED is in amore or less arbitrary state.
To improve the situation, we have to store not only the LED’s current
state but also the pushbutton’s previous state:
Download BinaryDice/MoreReliableSwitch/MoreReliableSwitch.pde
const unsigned int BUTTON_PIN =7;
const unsigned int LED_PIN =13;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
}
int old_button_state =LOW;
int led_state =LOW;
void loop() {
const int CURRENT_BUTTON_STATE =digitalRead(BUTTON_PIN);
if (CURRENT_BUTTON_STATE != old_button_state &&
CURRENT_BUTTON_STATE == HIGH)
{
led_state =(led_state == LOW) ?HIGH :LOW;
digitalWrite(LED_PIN, led_state);
}
old_button_state =CURRENT_BUTTON_STATE;
}
After initializing the button and LED pins, we declare two variables
now: old_button_state stores the previous state of our pushbutton, and
led_state stores the LED’s current state. Both can be either HIGH or LOW.
In the loop( ) function, we still have to read the current button state,
but now we not only check whether it is HIGH. W e also check whether
it has changed since the last time we read it. Only when both conditions
are met do we toggle the LED’s state. So, we no longer turn the LED
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WORKING WITH BUTTONS 78
Button pressed Button released
5 V
0 V
Figure 3.9: Mechanical switches have to be debounced.
on and off over and over again as long as the button is pressed. At
the end of our program, we have to store the button’s current state in
old_button_state.
Upload our new version, and you’ll see that this solution works much
better than our old one. But you will still find some edge cases when
the button does not fully behave as expected. Problems mainly occur in
the moment you release the button.
The cause of these problems is that mechanical buttons bounce for a
few milliseconds when you press them. In Figure 3.9,you can see a
typical signal produced by amechanical button. Right after you have
pressed the button, it doesn’t emit aclear signal. To overcome this
effect, you have to debounce the button. It’s usually sufficient to wait
ashort period of time until the button’s signal stabilizes. Debouncing
makes sure that we react only once to apush of the button. In addition
to debouncing, we still have to store the current state of the LED in a
variable. Here’s how to do that:
Download BinaryDice/DebounceButton/DebounceButton.pde
Line 1const unsigned int BUTTON_PIN =7;
-const unsigned int LED_PIN =13;
-
-void setup() {
5pinMode(LED_PIN, OUTPUT);
-pinMode(BUTTON_PIN, INPUT);
-}
-
-int old_button_state =LOW;
10 int led_state =LOW;
-
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

ADDING OUROWNBUTTON 79
-void loop() {
-const int CURRENT_BUTTON_STATE =digitalRead(BUTTON_PIN);
-if (CURRENT_BUTTON_STATE != old_button_state &&
15 CURRENT_BUTTON_STATE == HIGH)
-{
-led_state =(led_state == LOW) ?HIGH :LOW;
-digitalWrite(LED_PIN, led_state);
-delay(50);
20 }
-old_button_state =CURRENT_BUTTON_STATE;
-}
This final version of our LED switch differs from the previous one in
only asingle line: to debounce the button, we wait for 50 milliseconds
in line 19 before we enter the main loop again.
This is everything you need to know about pushbuttons for now. In the
next section, we’ll use two buttons to turn our binary dice into areal
game.
3.6 Adding Our Own Button
Up to now, we had to abuse the Arduino’s reset button to control the
dice. This solution is far from optimal, so we’ll add our own buttons. In
Figure 3.10,on page 81,you can see that we need to change our cur-
rent circuit only slightly. Actually, we don’t have to change the existing
parts at all; we only need to add some things. First we plug abutton
into the breadboard and connect it to pin 7. Then we connect the but-
ton to the ground via a10kΩresistor and use asmall piece of wire to
connect it to the 5volts pin. That’s all the hardware we need. Here’s the
corresponding software:
Download BinaryDice/DiceWithButton/DiceWithButton.pde
const unsigned int LED_BIT0 =12;
const unsigned int LED_BIT1 =11;
const unsigned int LED_BIT2 =10;
const unsigned int BUTTON_PIN =7;
void setup() {
pinMode(LED_BIT0, OUTPUT);
pinMode(LED_BIT1, OUTPUT);
pinMode(LED_BIT2, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
randomSeed(analogRead(A0));
}
int current_value =0;
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

BUILDINGADICEGAME 80
int old_value =0;
void loop() {
current_value =digitalRead(BUTTON_PIN);
if (current_value != old_value && current_value == HIGH) {
output_result(random(1, 7));
delay(50);
}
old_value =current_value;
}
void output_result(const long result) {
digitalWrite(LED_BIT0, result &B001);
digitalWrite(LED_BIT1, result &B010);
digitalWrite(LED_BIT2, result &B100);
}
That’s aperfect merge of the original code and the code needed to con-
trol adebounced button. As usual, we initialize all pins we use: three
output pins for the LEDs and one input pin for the button. W e also
initialize the random seed, and in the loop( ) function we wait for new
button presses. Whenever the button gets pressed, we roll the dice and
output the result using the LEDs. W e ’ v e replaced the reset button with
our own!
Now that we know how easy it is to add a pushbutton, we’ll add another
one in the next section to turn our simple dice into agame.
3.7 Building aDice Game
Turning our rudimentary dice into afull-blown game requires adding
another pushbutton. W i t h the first one we can still roll the dice, and
with the second one we can program aguess. When we roll the dice
again and the current result equals our guess, the three LEDs on the
die will blink. Otherwise, they will remain dark.
To enter aguess, press the guess button the right number of times.
If you think the next result will be a3, for example, press the guess
button three times and then press the start button.
To add another button to the circuit, do exactly the same thing as for
the first one. In Figure 3.11,on page 82,you can see that we have
added yet another button circuit to the breadboard. This time we’ve
connected it to pin 5.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

BUILDINGADICEGAME 81
Figure 3.10: Our binary dice with its own start button
Now we need some code to control the new button, and you might be
tempted to copy it from our last program. After all, we copied the hard-
ware design also, right? In the real world, some redundancy is totally
acceptable, because we actually need two physical buttons, even if they
are in principle the same. In the world of software, redundancy is ano-
go, so we won’t copy our debounce logic but use alibrary1that was writ-
ten for this purpose. Download the library, and unpack its content into
~/Documents/Arduino/libraries (on aMac) or My Documents\Arduino\libraries
(on aW i n d o w s box). Usually that’s all you have to do, but it never
1. http://www.arduino.cc/playground/Code/Bounce
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

BUILDINGADICEGAME 83
hurts to read the installation instructions and documentation on the
web page.
Here’s the final version of our binary dice code:
Download BinaryDice/DiceGame/DiceGame.pde
Line 1#include <Bounce.h>
-
-const unsigned int LED_BIT0 =12;
-const unsigned int LED_BIT1 =11;
5const unsigned int LED_BIT2 =10;
-const unsigned int START_BUTTON_PIN =5;
-const unsigned int GUESS_BUTTON_PIN =7;
-const unsigned int BAUD_RATE =9600;
-
10 void setup() {
-pinMode(LED_BIT0, OUTPUT);
-pinMode(LED_BIT1, OUTPUT);
-pinMode(LED_BIT2, OUTPUT);
-pinMode(START_BUTTON_PIN, INPUT);
15 pinMode(GUESS_BUTTON_PIN, INPUT);
-randomSeed(analogRead(A0));
-Serial.begin(BAUD_RATE);
-}
-
20 const unsigned int DEBOUNCE_DELAY =20;
-Bounce start_button(START_BUTTON_PIN, DEBOUNCE_DELAY);
-Bounce guess_button(GUESS_BUTTON_PIN, DEBOUNCE_DELAY);
-int guess =0;
-
25 void loop() {
-handle_guess_button();
-handle_start_button();
-}
-
30 void handle_guess_button() {
-if (guess_button.update()) {
-if (guess_button.read() == HIGH) {
-guess =(guess %6) +1;
-output_result(guess);
35 Serial.print(
"Guess: "
);
-Serial.println(guess);
-}
-}
-}
40
-void handle_start_button() {
-if (start_button.update()) {
-if (start_button.read() == HIGH) {
-const int result =random(1, 7);
45 output_result(result);
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

BUILDINGADICEGAME 84
-Serial.print(
"Result: "
);
-Serial.println(result);
-if (guess >0) {
-if (result == guess) {
50 Serial.println(
"You win!"
);
-hooray();
-}else {
-Serial.println(
"You lose!"
);
-}
55 }
-delay(2000);
-guess =0;
-}
-}
60 }
-
-void output_result(const long result) {
-digitalWrite(LED_BIT0, result &B001);
-digitalWrite(LED_BIT1, result &B010);
65 digitalWrite(LED_BIT2, result &B100);
-}
-
-void hooray() {
-for (int i = 0; i < 3; i++) {
70 output_result(7);
-delay(500);
-output_result(0);
-delay(500);
-}
75 }
Admittedly that is alot of code, but we know most of it already, and the
new parts are fairly easy. In the first line, we include the Bounce library
we’ll use later to debounce our two buttons. Then we define constants
for all the pins we use, and in the setup( ) method, we initialize all our
pins and set the random seed. W e also initialize the serial port, because
we’ll output some debug messages.
The Bounce library declares aclass named Bounce, and you have to cre-
ate a Bounce object for every button you want to debounce. That’s what
happens in lines 21 and 22. The constructor of the Bounce class expects
the number of the pin the button is connected to and the debounce
delay in milliseconds. Finally, we declare and initialize avariable named
guess that stores our current guess.
Our loop( ) function has been reduced to two function calls. One is
responsible for dealing with guess button pushes, and the other one
handles pushes of the start button. In handle_guess_button(), we use the
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

BUILDINGADICEGAME 85
Figure 3.12: W e have awinner!
Bounce class for the first time. To determine the current state of our
guess_button object, we have to call its update( ) method. Afterward, we
read its current status using the read( ) method.
If the button was pressed, its state is set to HIGH, and we increment
the guess variable. To make sure that the guess is always in the range
between 1 and 6, we use the modulus operator (%) in line 33. This
operator divides two values and returns the remainder. For 6, it returns
values between 0 and 5, because when you divide anumber by 6, the
remainder is always between 0 and 5. Add 1to the result, and you get
values between 1 and 6. Finally, we output the current guess using the
three LEDs, and we also print it to the serial port.
The handling of the start button in handle_start_button( ) works exactly
the same as the handling of the guess button. When the start button
was pressed, we calculate anew result and output it on the serial port.
Then we check whether the user has entered aguess (guess is greater
than zero in this case) and whether the user has guessed the right
result. In either case, we print amessage to the serial port, and if the
user guessed right, we also call the hooray( ) method. hooray( ) lets all
three LEDs blink several times.
Report erratum
this copy is (P1.0 printing, Ja nu ra r y, 2011)
Download from Wow! eBook <www.wowebook.com>

WHAT IFITDOESN’TWORK?86
At the end of the method, we wait for two seconds until the game starts
again, and we set back the current guess to zero.
After you’ve uploaded the software to the Arduino, start the IDE’s serial
monitor. It will print the current value of the guess variable whenever
you press the guess button. Press the start button, and the new result
appears. In Figure 3.12,on the preceding page, you can see atypical
output of our binary dice.
In this chapter, you completed your first really complex Arduino project.
Y o u needed abreadboard, LEDs, buttons, resistors, and wires, and you
wrote anontrivial piece of software to make all the hardware come to
life.
In the next chapter, we’ll write an even more sophisticated program for
generating Morse code. Y o u ’ l l also learn how to create your own Arduino
libraries that you can easily share with the rest of the world.
3.8 What If It Doesn’t W o r k