30 Arduino™ Projects For The Evil Genius - Department of Control (PDFDrive) PDF
30 Arduino™ Projects For The Evil Genius - Department of Control (PDFDrive) PDF
30 Arduino
Projects for
™
the Evil Genius
Evil Genius™ Series
Simon Monk
ISBN: 978-0-07-174134-7
MHID: 0-07-174134-8
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-174133-0,
MHID: 0-07-174133-X.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use
names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designa-
tions appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. To
contact a representative please e-mail us at [email protected].
Trademarks: McGraw-Hill, the McGraw-Hill Publishing logo, Evil Genius™, and related trade dress are trademarks or registered trademarks of The
McGraw-Hill companies and/or its affiliates in the United States and other countries and may not be used without written permission. All other trade-
marks are the property of their respective owners. The McGraw-Hill Companies is not associated with any product or vendor mentioned in this book.
Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or mechanical
error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not
responsible for any errors or omissions or the results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGrawHill”) and its licensors reserve all rights in and to the work. Use of this
work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may
not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or
sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any
other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE
ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY IN-
FORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY
WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FIT-
NESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet
your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else
for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for
the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect,
incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been
advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises
in contract, tort or otherwise.
To my late father, Hugh Monk, from whom I inherited a love for electronics.
He would have had so much fun with all this.
About the Author
Simon Monk has a bachelor’s degree in cybernetics and computer science and a doctorate
in software engineering. He has been an active electronics hobbyist since his school days,
and is an occasional author in hobby electronics magazines.
Contents
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1 Quickstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Powering Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installing the Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Configuring Your Arduino Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Downloading the Project Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Project 1 Flashing LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Breadboard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 A Tour of Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Microcontrollers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
What’s on an Arduino Board? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The Arduino Family. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
The C Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3 LED Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Project 2 Morse Code S.O.S. Flasher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Project 3 Morse Code Translator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Project 4 High-Brightness Morse Code Translator . . . . . . . . . . . . . . . . . . . . . . . . 35
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 More LED Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Digital Inputs and Outputs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Project 5 Model Traffic Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Project 6 Strobe Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Project 7 S.A.D. Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Project 8 High-Powered Strobe Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Random Number Generation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Project 9 LED Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5 Sensor Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Project 10 Keypad Security Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Rotary Encoders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Project 11 Model Traffic Signal Using a Rotary Encoder . . . . . . . . . . . . . . . . . . 68
Sensing Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Project 12 Pulse Rate Monitor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
vii
viii 30 Arduino Projects for the Evil Genius
Measuring Temperature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Project 13 USB Temperature Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6 Light Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Project 14 Multicolor Light Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Seven-Segment LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Project 15 Seven-Segment LED Double Dice. . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Project 16 LED Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
LCD Displays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Project 17 USB Message Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7 Sound Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Project 18 Oscilloscope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Sound Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Project 19 Tune Player. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Project 20 Light Harp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Project 21 VU Meter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8 Power Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Project 22 LCD Thermostat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Project 23 Computer-Controlled Fan. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
H-Bridge Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Project 24 Hypnotizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Servo Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Project 25 Servo-Controlled Laser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
9 Miscellaneous Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Project 26 Lie Detector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Project 27 Magnetic Door Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Project 28 Infrared Remote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Project 29 Lilypad Clock. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Project 30 Evil Genius Countdown Timer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10 Your Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Circuits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Project Ideas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Appendix Components and Supplies . . . . . . . . . . . . . . . . . . 181
Suppliers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Starter Kit of Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Acknowledgments
I WOULD LIKE to thank my sons, Stephen and Matthew Monk, for their interest and
encouragement in the writing of this book, their helpful suggestions, and their field testing
of projects. Also, I could not have written this book without Linda’s patience and support.
I am grateful to Chris Fitzer for the loan of his oscilloscope, and his good grace after I
broke it! I also thank all the “techies” at Momote for taking an interest in the project and
humoring me.
Finally, I would like to thank Roger Stewart and Joya Anthony at McGraw-Hill, who
have been extremely supportive and enthusiastic, and have been a pleasure to work with.
ix
This page intentionally left blank
Introduction
ARDUINO INTERFACE BOARDS provide the Evil At this point, the Evil Genius might be
Genius with a low-cost, easy-to-use technology to wondering which top secret government
create their evil projects. A whole new breed of organization they need to break into in order to
projects can now be built that can be controlled acquire one. Well, disappointingly, no evil deeds at
from a computer. Before long, the computer- all are required to obtain one of these devices. The
controlled, servo-driven laser will be complete and Evil Genius needs to go no further than their
the world will be at the mercy of the Evil Genius! favorite online auction site or search engine. Since
This book will show the Evil Genius how to the Arduino is an open-source hardware design,
attach an Arduino board to their computer, to anyone is free to take the designs and create their
program it, and to connect all manner of own clones of the Arduino and sell them, so the
electronics to it to create projects, including the market for the boards is competitive. An official
computer-controlled, servo-driven laser mentioned Arduino costs about $30, and a clone often less
earlier, a USB-controlled fan, a light harp, a USB than $20.
temperature logger, a sound oscilloscope, and The name “Arduino” is reserved by the original
many more. makers. However, clone Arduino designs often
Full schematic and construction details are have the letters “duino” on the end of their name,
provided for every project, and most can be built for example, Freeduino or DFRduino.
without the need for soldering or special tools. The software for programming your Arduino is
However, the more advanced Evil Genius may easy to use and also freely available for Windows,
wish to transfer the projects from a plug-in Mac, and LINUX computers at no cost.
breadboard to something more permanent, and
instructions for this are also provided.
Arduino
Although Arduino is an open-source design for a
So, What Is Arduino? microcontroller interface board, it is actually rather
Well, Arduino is a small microcontroller board more than that, as it encompasses the software
with a USB plug to connect to your computer and development tools that you need to program an
a number of connection sockets that can be wired Arduino board, as well as the board itself. There is
up to external electronics, such as motors, relays, a large community of construction, programming,
light sensors, laser diodes, loudspeakers, electronics, and even art enthusiasts willing to
microphones, etc. They can either be powered share their expertise and experience on the
through the USB connection from the computer or Internet.
from a 9V battery. They can be controlled from the To begin using Arduino, first go to the Arduino
computer or programmed by the computer and site (www.arduino.cc) and download the software
then disconnected and allowed to work for Mac, PC, or LINUX. You can then either buy
independently. an official Arduino by clicking the Buy An
xi
xii 30 Arduino Projects for the Evil Genius
Arduino button or spend some time with your connection. When over the middle and bottom
favorite search engine or an online auction site to pins, the board will be powered from an external
find lower-cost alternatives. In the next chapter, power supply plugged into the socket below. On
step-by-step instructions are provided for installing the newer Duemilanove boards, there is no such
the software on all three platforms. jumper and the supply switches automatically from
There are, in fact, several different designs of USB to the 9V socket.
Arduino board. These are intended for different The power supply can be any voltage between
types of applications. They can all be programmed 7 and 12 volts. So a small 9V battery will work
from the same Arduino development software, and just fine for portable applications. Typically, while
in general, programs that work on one board will you are making your project, you will probably
work on all. power it from USB for convenience. When you are
In this book we mostly use the Arduino ready to cut the umbilical cord (disconnect the
Duemilanove, sometimes called Arduino 2009, USB lead), you will want to power the board
which is an update of the popular board, the independently. This may be with an external power
Diecimila. Duemilanove is Italian for 2009, the adaptor or simply with a 9V battery connected to a
year of its release. The older Diecimila name plug to fit the power socket.
means 10,000 in Italian, and was named that after There are two rows of connectors on the edges
10,000 boards had been manufactured. Most of the board. The row at the top of the diagram is
compatible boards such as the Freeduino are based mostly digital (on/off) pins, although any marked
on the Diecimila and Duemilanove designs. with “PWM” can be used as analog outputs. The
Most of the projects in this book will work with bottom row of connectors has useful power
a Diecimila, Duemilanove, or their clone designs, connections on the left and analog inputs on
apart from one project that uses the Arduino the right.
Lilypad. These connectors are arranged like this so that
When you are making a project with an so-called “shield” boards can be plugged on to the
Arduino, you will need to download programs onto main board in a piggyback fashion. It is possible to
the board using a USB lead between your buy ready-made shields for many different
computer and the Arduino. This is one of the most purposes, including:
convenient things about using an Arduino. Many I Connection to Ethernet networks
microcontroller boards use separate programming
I LCD displays and touch screens
hardware to get programs into the microcontroller.
With Arduino, it’s all contained on the board itself. I XBee (wireless data communications)
This also has the advantage that you can use the I Sound
USB connection to pass data back and forth I Motor control
between an Arduino board and your computer. For
I GPS tracking
instance, you could connect a temperature sensor
to the Arduino and have it repeatedly tell your I And many more
computer the temperature. You can also use prototyping shields to create
On the older Diecimila boards, you will find a your own shield designs. We will use these
jumper switch immediately below the USB socket. Protoshields in some of our projects. Shields
With the jumper fitted over the top two pins, the usually have through connectors on their pins,
board will receive its power from the USB which means that you can stack them on top of
Introduction xiii
each other. So a design might have three layers: an Most of the projects in this book can be
Arduino board on the bottom, a GPS shield on it, constructed without the need for soldering; instead
and then an LCD display shield on top of that. we use a breadboard. A breadboard is a plastic
block with holes in it with sprung metal
connections behind. Electronic components are
The Projects pushed through the holes at the front. These are
not expensive, and a suitable breadboard is also
The projects in this book are quite diverse. We
listed in the appendix. However, if you wish to
begin with some simple examples using standard
make your designs more permanent, the book
LEDs and also the ultra high-brightness Luxeon
shows you how to do that, too, using the
LEDs.
prototyping board.
In Chapter 5, we look at various sensor projects
Sources for all the components are listed in the
for logging temperature and measuring light and
appendix, along with some useful suppliers. The
pressure. The USB connection to the Arduino
only things you will need in addition to these
makes it possible to take the sensor readings in
components are an Arduino board, a computer,
these projects and pass them back to the computer,
some wire, and a piece of breadboard. The
where they can be imported into a spreadsheet and
software for all the projects is available for
charts drawn.
download from www.arduinoevilgenius.com.
We then look at projects using various types of
display technology, including an alphanumeric
LCD message board (again using USB to get Without Further Ado
messages from your computer), as well as seven-
segment and multicolor LEDs. The Evil Genius is not noted for their patience, so
in the next chapter we will show you how to get
Chapter 7 contains four projects that use sound
started with Arduino as quickly as possible. This
as well as a simple oscilloscope. We have a simple
chapter contains all the instructions for installing
project to play tunes from a loudspeaker, and build
the software and programming your Arduino
up to a light harp that changes the pitch and
board, including downloading the software for the
volume of the sound by waving your hand over
projects, so you will need to read it before you
light sensors. This produces an effect rather like
embark on your projects.
the famous Theremin synthesizer. The final project
in this chapter uses sound input from a In Chapter 2 we take a look at some of the
microphone. It is a VU meter that displays the essential theory that will help you build the
intensity of the sound on an LED display. projects described in this book, and go on to
design projects of your own. Most of the theory is
The final chapters contain a mixture of projects.
contained in this chapter, so if you are the kind of
Among others, there is, as we have already
Evil Genius who prefers to just make the projects
mentioned, an unfathomable binary clock using an
and find out how they work afterwards, you may
Arduino Lilypad board that indicates the time in an
prefer, after reading Chapter 1, to just to pick a
obscure binary manner only readable by an Evil
project and start building. Then if you get stuck,
Genius, a lie detector, a motor-controlled swirling
you can use the index or read some of the early
hypnotizer disk, and, of course, the computer-
chapters.
controlled-servo-guided laser.
This page intentionally left blank
CHAPTER 1
Quickstart
THIS IS A CHAPTER for the impatient Evil Genius. Arduino Duemilanove boards do not have this
Your new Arduino board has arrived and you are jumper and select the power source automatically.
eager to have it do something. If everything is working okay, the LED should
So, without further ado... blink once every two seconds. The reason that new
Arduino boards have this Blink sketch already
installed is to verify that the board works. If your
Powering Up board does not start to blink when connected,
check the position of the power jumper (if it has
When you buy an Arduino Diecimila or
one) and try a different USB socket, possibly on a
Duemilanove board, it is usually preinstalled with
different computer, as some USB sockets are
a sample Blink program that will make the little
capable of supplying more power than others.
built-in LED flash. Figure 1-1 shows an Arduino-
Also, clicking the Reset button should cause the
compatible board with the LED lit.
LED to flicker momentarily. If this is the case, but
The light-emitting diode (LED) marked L is the LED does not flash, then it may just be that the
wired up to one of the digital input-output sockets board has not been programmed with the Flash
on the board. It is connected to digital pin 13. This sketch; but do not despair, as once everything is
really limits pin 13 to being used as an output, but installed, we are going to modify and install that
the LED only uses a small amount of current, so script anyway as our first project.
you can still connect other things to that connector.
All you need to do to get your Arduino up and
running is supply it with some power. The easiest Installing the Software
way to do this is to plug in it into the Universal
Now we have our Arduino working, let’s get the
Serial Bus (USB) port on your computer. You will
software installed so that we can alter the Blink
need a type A-to-type B USB lead. This is the
program and send it down to the board. The exact
same type of lead that is normally used to connect
procedure depends on what operating system you
a computer to a printer.
use on your computer. But the basic principle is
If you are using the older Arduino Diecimila the same for all.
board, make sure that the power jumper is in the
Install the USB driver that allows the computer
USB position (see Figure 1-1). The jumper should
to talk to the Arduino’s USB port. It uses this for
connect together the two top pins to allow the
programming and sending messages.
board to be powered from the USB. The newer
1
2 30 Arduino Projects for the Evil Genius
Install the Arduino development environment, Select the Save option from the dialog, and save
which is the program that you run on your the Zip file onto your desktop. The folder
computer that enables you to write sketches and contained in the Zip file will become your main
download them to the Arduino board. Arduino directory, so now unzip it into C:\Program
The Arduino website (www.arduino.cc) contains Files\Arduino.
the latest version of the software. You can do this in Windows XP by right-
clicking the Zip file to show the menu in Figure
Installation on Windows 1-3 and selecting the Extract All option. This will
open the Extraction Wizard, shown in Figure 1-4.
Follow the download link on the Arduino home
page (www.arduino.cc) and select the download
for Windows. This will start the download of the
Zip archive containing the Arduino software, as
shown in Figure 1-2. You may well be
downloading a more recent version of the software
than the version 17 shown. This should not matter,
but if you experience any problems, refer back to
the instructions on the Arduino home page.
The Arduino software does not distinguish
between different versions of Windows. The
download should work for all versions, from
Windows XP onwards. The following instructions
are for Windows XP. Figure 1-2 Downloading the Arduino software
for Windows.
Chapter 1 ■ Quickstart 3
Figure 1-6 Windows Found New Hardware Figure 1-7 Setting the location of the USB
Wizard. drivers.
Files\Arduino\arduino-0017, and click the Arduino The next two sections describe this same
icon, as shown in Figure 1-8. The Arduino procedure for installing on Mac and LINUX
software will now start. computers, so if you are a Windows user, you can
Note that there is no shortcut created for the skip these sections.
Arduino program, so you may wish to select the
Arduino program icon, right-click, and create a Installation on Mac OS X
shortcut that you can then drag to your desktop.
The process for installing the Arduino software on
the Mac is a lot easier than on the PC.
probably already have the USB drivers installed, computer using the USB port or you will not be
the AVR-GCC libraries, and the Java environment able to select the serial port.
that the Arduino software needs. The serial port is set from the Tools menu, as
So, if you are lucky, all you will need to do is shown in Figure 1-11 for the Mac and in Figure
download the TGZ file for the Arduino software 1-12 for Windows—the list of ports for LINUX is
from the Arduino home page (www.arduino.cc), similar to the Mac.
extract it, and that is your working Arduino If you use many USB or Bluetooth devices with
directory. your Mac, you are likely to have quite a few
If, on the other hand, you are unlucky, then as a options in this list. Select the item in the list that
LINUX user, you are probably already adept at begins with “dev/tty.usbserial.”
finding support from the LINUX community for On Windows, the serial port can just be set to
setting up your system. The pre-requisites that you COM3.
will need to install are Java runtime 5 or later and
From the Tools menu, we can now select the
the latest AVR-GCC libraries.
board that we are going to use, as shown in Figure
Entering into Google the phrase “Installing 1-13. If you are using the newer Duemilanove,
Arduino on SUSE LINUX,” or whatever your choose the first option. However, if you are using
distribution of LINUX is, will, no doubt, find you the older Diecimila board, select the second
lots of helpful material. option.
7
8 30 Arduino Projects for the Evil Genius
Click the evil_genius.zip link to download a Zip using a bigger external LED and resistor rather
file of all the projects. If you are using Windows, than the tiny built-in LED.
unzip the file to My Documents\Arduino. On a
Mac and LINUX, you should unzip it to Software
Documents/Arduino in your home directory.
First, we need to load the Blink sketch into the
Once the files are installed, you will be able to
Arduino software. The Blink sketch is included as
access them from the File | Sketchbook menu on
an example when you install the Arduino
the Arduino software.
environment. So we can load it using the File
menu, as shown in Figure 1-14.
change the value in the parentheses to 200 so that will be a short pause and then the two red LEDs
it appears as: on the board will start flashing away furiously as
the sketch is uploaded onto the board. This should
delay(200);
take around 5 to 10 seconds.
This is changing the delay between turning the If this does not happen, check the serial port and
LED on and off from 1000 milliseconds (1 second) board type settings as described in the previous
to 200 milliseconds (1/5th of a second). In Chapter sections.
3 we will explore this sketch further, but for now, When the completed sketch has been installed,
we will just change the delay and download the the board will automatically reset, and if
sketch to the Arduino board. everything has worked, you will see the LED for
With the board connected to your computer, digital port 13 start to flash much more quickly
click the Upload button on the Arduino. This is than before.
shown in Figure 1-15. If everything is okay, there
Figure 1-16 Schematic diagram for an LED Figure 1-17 An LED connected to a serial
connected to the Arduino board. resistor.
Chapter 1 ■ Quickstart 11
We can build this project on a breadboard rather breadboard, as it does not go the whole width of
than with twisted wires. Figure 1-19 shows a the board.
photograph of this. Figure 1-20 makes it a little In addition to a breadboard, you will need some
easier to see how the components are positioned solid-core wire and some wire strippers or pliers to
and connected together. cut and remove the insulation from the ends of the
You will notice that at the edges of the wire. It is a good idea to have at least three
breadboard (top and bottom), there are two long different colors: red for all wires connected to the
horizontal strips. The connections on the back of positive side of the supply, black for negative, and
these long strips run at right angles to the normal some other color (orange or yellow) for other
strips of connections and are used to provide connections. This makes it much easier to
power to the components on the breadboard. understand the layout of the circuit. You can also
Normally, there is one for ground (0V or GND) buy prepared short lengths of solid-core wire in a
and one for the positive supply voltage (usually variety of colors. Note that it is not advisable to
5V). There are little linking wires between the left use multicore wire, as it will tend to bunch up
and right halves of the GND strip, as on this when you try to push it into the breadboard holes.
Possible sources of these materials are included design board and leave it permanently attached to
in the appendix. the breadboard.
We can straighten out the wires of our LED and
resistor and plug them into a breadboard. It is best
to use a reasonable-sized breadboard and attach the Summary
Arduino board to it. You probably do not want to We have created our first project, albeit a very
attach the board permanently, so I use a small simple one. In the next chapter we will get a bit
lump of adhesive putty. However, you may find it more background on the Arduino before moving
easier to dedicate one Arduino board to be your on to some more interesting projects.
This page intentionally left blank
CHAPTER 2
A Tour of Arduino
IN THIS CHAPTER, we look at the hardware of the processor, a kilobyte of random access memory
Arduino board and also of the microcontroller at (RAM) for holding data, a few kilobytes of
its heart. In fact, the board basically just provides erasable programmable read-only memory
support to the microcontroller, extending its pins to (EPROM) or Flash memory for holding our
the connectors so that you can connect hardware to programs, and it has input and output pins. These
them and providing a USB link for downloading input/output pins are what link the microcontroller
sketches, etc. to the rest of our electronics.
We also learn a few things about the C language Inputs can read both digital (is the switch on or
used to program the Arduino, something we will off?) and analog (what is the voltage at a pin?).
build on in later chapters as we start on some This enables us to connect many different types of
practical project work. sensors for light, temperature, sound, etc.
Although this chapter gets quite theoretical at Outputs can also be analog or digital. So, you
times, it will help you understand how your can set a pin to be on or off (0V or 5V) and this
projects work. However, if you would prefer just to can turn LEDs on and off directly, or you can use
get on with your projects, you may wish to skim the output to control higher-power devices such as
this chapter. motors. They can also provide an analog output
voltage. That is, you can set the output of a pin to
some particular voltage, allowing you to control
Microcontrollers the speed of a motor or the brightness of a light,
for example, rather than simply turning it on or off.
The heart of our Arduino is a microcontroller.
Practically everything else on the board is
concerned with providing the board with power
and allowing it to communicate with your desktop
What’s on an Arduino Board?
computer. Figure 2-1 shows our Arduino board—or in this
So what exactly do we get when we buy one of case an Arduino clone. Let us have a quick tour of
these little computers to use in our projects? the various components on the board.
15
16 30 Arduino Projects for the Evil Genius
5V (along with 3V, 6V, 9V, and 12V) is a bit of The 5V voltage regulator chip is actually quite
a standard voltage in electronics. 3, 6, and 9V are big for a surface-mount component. This is so that
standard because the voltage that you get from a it can dissipate the heat required to regulate the
single alkaline cell is 1.5V, and these are all voltage at a reasonably high current, which is
convenient multiples of 1.5V, which is what you useful when driving our external electronics.
get when you make a “battery” of two, three, six,
or eight cells. Power Connections
So if that is the case, you might be wondering Next, let us look at the connectors at the bottom of
why 5V? You cannot make that using 1.5V cells. Figure 2-1. You can read the connection names
Well, the answer lies in the fact that in the early next to the connectors.
days of computing, a range of chips became
The first is Reset. This does the same thing as
available, each of which contained logic gates.
pressing the Reset button on the Arduino. Rather
These chips used something called TTL
like rebooting a PC, it resets the microcontroller,
(Transistor-Transistor Logic), which was a bit
beginning its program from the start. The Reset
fussy about its voltage requirements and required
connector allows you to reset the microcontroller
Chapter 2 ■ A Tour of Arduino 17
by momentarily setting this pin high (connecting it ■ The height of the water (or if you prefer, the
to +5V). pressure generated by the pump). This is like
The rest of the pins in this section provide voltage in electronics.
different voltages (3.3, 5, GND, and 9), as labeled. ■ The resistance to flow offered by the
GND, or ground, just means zero volts. It is the constriction in the pipework
reference voltage to which all other voltages on the The more powerful the pump, the higher the
board are relative. water can be pumped and the greater the current
At this point, it would be useful to remind the that will flow through the system. On the other
reader about the difference between voltage and hand, the greater the resistance offered by the
current. There is no perfect analogy for the pipework, the lower the current.
behavior of electrons in a wire, but the author finds In the right half of Figure 2-2, we can see the
an analogy with water in pipes to be helpful, electronic equivalent of our pipework. In this case,
particularly in dealing with voltage, current, and current is actually a measure of how many
resistance. The relationship between these three electrons flow past a point per second. And yes,
things is called Ohm’s Law. resistance is the resistance to the flow of electrons.
Figure 2-2 summarizes the relationship Instead of height or pressure, we have a
between voltage, current, and resistance. The left concept of voltage. The bottom of the diagram is
side of the diagram shows a circuit of pipes, at 0V, or ground, and we have shown the top of
where the top of the diagram is higher up (in the diagram as being at 5V. So the current that
elevation) than the bottom of the diagram. So flows (I) will be the voltage difference (5) divided
water will naturally flow from the top of the by the resistance R.
diagram to the bottom. Two factors determine
Ohm’s Law is usually written as V ⫽ IR.
how much water passes any point in the circuit in
Normally, we know what V is and are trying to
a given time (the current):
calculate R or I, so we can do a bit of rearranging Digital 0 to 13. These can be used as either inputs
to have the more convenient I ⫽ V/R and R ⫽ V/I. or outputs. When using them as outputs, they
It is very important to do a few calculations behave rather like the supply voltages we talked
using Ohm’s Law when connecting things to your about earlier, except that these are all 5V and can
Arduino, or you may damage it if you ask it to be turned on or off from our sketch. So, if we turn
supply too much current. Generally, though, the them on from our sketch, they will be at 5V and if
Arduino boards are remarkably tolerant of we turn them off, they will be at 0V. As with the
accidental abuse. supply connectors, we have to be careful not to
exceed their maximum current capabilities.
So, going back to our Arduino power pins, we
can see that the Arduino board will supply us with These connections can supply 40 mA at 5V.
useful voltages of 3.3V, 5V, and 9V. We can use That is more than enough to light a standard LED,
any of those supplies to cause a current to flow, as but not enough to drive an electric motor directly.
long as we are careful not to make it a short circuit As an example, let us look at how we would
(no resistance to flow), which would cause a connect an LED to one of these digital
potentially large current to flow that could cause connections. In fact, let’s go back to Project 1 in
damage. In other words, we have to make sure that Chapter 1.
anything we connect to the supply has enough As a reminder, Figure 2-3 shows the schematic
resistance to prevent too much current from diagram for driving the LED that we first used in
flowing. As well as supplying a particular voltage, the previous chapter. If we were to not use a
each of those supply connections will have a resistor with our LED but simply connect the LED
maximum current that can be allowed to flow. between pin 12 and GND, then when we turned
Those currents are 50 mA (thousandths of an amp) digital output 12 on (5V), we might burn out the
for the 3.3V supply, and although it is not stated in LED, destroying it.
the Arduino specification, probably around 300
This is because LEDs have a very low resistance
mA for the 5V.
and will cause a very high current to flow unless
they are protected from themselves by using a
Analog Inputs resistor to limit the flow of current.
The next section of connections is labeled Analog
In 0 to 5. These six pins can be used to measure
the voltage connected to them so that the value can
be used in a sketch. Note that they measure a
voltage and not a current. Only a tiny current will
ever flow into them and down to ground because
they have a very large internal resistance.
Although labeled as analog inputs, these
connections can also be used as digital inputs or
outputs, but by default, they are analog inputs.
Digital Connections
We now switch to the top connector and start on
the right side (Figure 2-1). We have pins labeled Figure 2-3 LED and series resistor.
Chapter 2 ■ A Tour of Arduino 19
An LED needs about 10 mA to shine reasonably On the left side of the top connector in Figure
brightly. The Arduino can supply 50 mA, so there 2-1, there is another GND connection and a
is no problem there; we just need to choose a connection called AREF. AREF can be used to
sensible value of resistor. scale the readings for analog inputs. This is rarely
LEDs have the interesting property that no used and can safely be ignored.
matter how much current flows through them,
there will always be about 2V between their pins. Microcontroller
We can use this fact and Ohm’s Law to work out
Getting back to our tour of the Arduino board, the
the right value of resistor to use.
microcontroller chip itself is the black rectangular
We know that (at least when it’s on) the output device with 28 pins. This is fitted into a DIL
pin will be supplying 5V. Now, we have just said (dual in-line) socket so that it can be easily
that 2V will be “dropped” by our LED, leaving replaced. The 28-pin microcontroller chip used on
3V (5 – 2) across our current-limiting resistor. We Arduino Duemilanove is the ATmega328. Figure
want the current flowing around the circuit to be 2-4 is a block diagram showing the main features
10 mA, so we can see that the value for the of this device.
resistor should be
The heart, or perhaps more appropriately the
R ⫽ V/I brain, of the device is the CPU (central processing
R ⫽ 3V/10 mA unit). It controls everything that goes on within the
R ⫽ 3V/0.01 A device. It fetches program instructions stored in the
Flash memory and executes them. This might
R ⫽ 300 ⍀
involve fetching data from working memory
Resistors come in standard values, and the (RAM), changing it, and then putting it back. Or, it
closest value to 300 ⍀ is 270 ⍀. This means that may mean changing one of the digital outputs from
instead of 10 mA, the current will actually be 0 to 5 volts.
I ⫽ V/R
I ⫽ 3/270
I ⫽ 11.111 mA
These things are not critical, and the LED
would probably be equally happy with anything
between 5 and 30 mA, so 270 ⍀ will work just
fine.
We can also set one of these digital connections
to be an input, in which case, it works rather like
an analog input, except that it will just tell us if the
voltage at a pin is above a certain threshold
(roughly 2.5V) or not.
Some of the digital connections (3, 5, 6, 9, 10,
and 11) have the letters PWM next to them. These
can be used to provide a variable output voltage
rather than a simple 5V or nothing.
Figure 2-4 ATmega328 block diagram.
20 30 Arduino Projects for the Evil Genius
So, we start each word (apart from the first) with The next lines of the sketch are
an uppercase letter and remove the space; that
void setup()
gives us:
// run once, when the sketch starts
ledPin = 13 {
pinMode(ledPin, OUTPUT);
// sets the digital pin as output
The word ledPin is what is termed a variable.
}
When you want to use a variable for the first time
in a sketch, you have to tell the compiler what type
This is what is called a function, and in this
of variable it is. It may be an int, as is the case
case, the function is called setup. Every sketch
here, or a float, or a number of other types that we
must contain a setup function, and the lines of
will describe later in this chapter.
code inside the function surrounded by curly
An int is an integer—that is, a whole number— brackets will be carried out in the order that they
which is just what we need when referring to a are written. In this case, that is just the line starting
particular pin on the Arduino. There is, after all, no with pinMode.
pin 12.5, so it would not be appropriate to use a
A good starting point for any new project is to
floating point number (float).
copy this example project and then alter it to your
The syntax for a variable declaration is needs.
type variableName = value; We will not worry too much about functions at
this stage, other than to say that the setup function
So first we have the type (int), then a space, will be run every time the Arduino is reset,
then a variable name in bumpy case (ledPin), then including when the power is first turned on. It will
an equal sign, then a value, and finally a semicolon also be run every time a new sketch is
to indicate the end of the line: downloaded.
int ledPin = 13; In this case, the only line of code in setup is
pinMode(ledPin, OUTPUT);
As I mentioned, the compiler is fussy, so if you // sets the digital pin as output
forget the semicolon, you will receive an error
message when you compile the sketch. Try The first thing to mention is that we have a
removing the semicolon and clicking the Play different type of comment on the end of this line.
button. You should see a message like this: That is, the single-line comment. This begins with
error: expected unqualified-id before
a // and ends at the end of the line.
numeric constant The line can be thought of as a command to the
Arduino to use the ledPin as a digital output. If we
It’s not exactly “you forgot a semicolon,” and it had a switch connected to ledPin, we could set it
is not uncommon for error messages to be as an input using:
similarly misleading.
pinMode(ledPin, INPUT);
The words INPUT and OUTPUT are what are of digitalWrite, it is said to take two parameters:
called constants. They will actually be defined the Arduino pin to write to and the value to write.
within C to be a number. INPUT may be defined In our example, we pass the parameters of
as 0 and OUPUT as 1, but you never need to ledPin and HIGH to turn the LED on and then
actually see what number is used, as you always ledPin and LOW to turn it off again.
refer to them as INPUT or OUTPUT. Later in this
chapter, we will see two more constants, HIGH
Variables and Data Types
and LOW, that are used when setting the output of
a digital pin to +5V or 0V, respectively. We have already met the variable ledPin and
The next section of code is another function that declared it to be of type int. Most of the variables
every Arduino sketch must have; it is called loop: that you use in your sketches are also likely to be
ints. An int holds an integer number between
void loop() –32,768 and +32,767. This uses just two bytes of
{
data for each number stored from the 1024
digitalWrite(ledPin, HIGH);
available bytes of storage on an Arduino. If that
// sets the LED on
delay(1000); range is not enough, you can use a long, which
// waits for a second uses four bytes for each number and will give you
digitalWrite(ledPin, LOW); a range of numbers from –2,147,483,648 to
// sets the LED off +2,147,483,647.
delay(1000);
// waits for a second
Most of the time, an int represents a good
} compromise between precision and use of memory.
If you are new to programming, I would use ints
The function loop will be run continuously until for almost everything and gradually expand your
the Arduino is powered down. That is, as soon as it repertoire of data types as your experience grows.
finishes executing the commands it contains, it will Other data types available to you are
begin again. Remember that an Arduino board is summarized in Table 2-1.
capable of running 16 million commands per
One thing to consider is that if data types
second, so things inside the loop will happen
exceed their range, strange things happen. So if
frequently if you let them.
you have a byte variable with 255 in it and you
In this case, what we want the Arduino to keep add 1 to it, you get 0. More alarmingly, if you have
doing continuously is to turn the LED on, wait a an int variable with 32,767 and you add 1 to it, you
second, turn the LED off, and then wait another will end up with –32,768.
second. When it has finished doing this, it will
Until you are completely happy with these
begin again, turning the LED on. In this way it will
different data types, I would recommend sticking
go round the loop forever.
to int, as it works for practically everything.
By now, the command syntax for digitalWrite
and delay will be becoming more familiar.
Arithmetic
Although we can think of them as commands that
are sent to the Arduino board, they are actually It is fairly uncommon to need to do much in the
functions just like setup and loop, but in this case way of arithmetic in a sketch. Occasionally, you
they have what are called parameters. In the case will need to do a bit of scaling of, say, an analog
24 30 Arduino Projects for the Evil Genius
input to turn it into a temperature, or more might want to use Strings: when writing messages
typically, add 1 to a counter variable. to an LCD display or sending back serial text data
When you are performing some calculation, you over the USB connection.
need to be able to assign the result of the Strings are created using the following syntax:
calculation to a variable.
char* message = "Hello World";
The following lines of code contain two
assignments. The first gives the variable y the The char* word indicates that the variable
value 50 and the second gives the variable x the message is a pointer to a character. For now, we do
value of y + 100. not need to worry too much about how this works.
We will meet this later in the book when we look
y = 50;
x = y + 100; at interfacing with textual LCD displays.
The code for this is shown here: Often, when using an if statement, you want to
do one thing if the condition is true and a different
if (temperature < 15)
thing if it is false. You can do this by using the else
{
digitalWrite(ledPort, HIGH);
keyword, as shown in the following example. Note
} the use of nested parentheses to make it clear what
is being or’d with what.
The line or lines of code inside the curly braces if ((temperature < 15) || (temperature
will only be executed if the condition after the if > 20))
keyword is true. {
digitalWrite(ledPort, HIGH);
The condition has to be contained in
}
parentheses, and is what programmers call a
else
logical expression. A logical expression is like a {
mathematical sentence that must always return one digitalWrite(ledPort, LOW);
of two possible values: true or false. }
LED Projects
Hardware
Project 2
Morse Code S.O.S. Flasher The hardware is exactly the same as Project 1. So,
you can either just plug the resistor and LED
Morse code used to be a vital method of directly into the Arduino connectors or use a
communication in the 19th and 20th centuries. Its breadboard (see Chapter 1).
coding of letters as a series of long and short dots
meant that it could be sent over telegraph wires,
Software
over a radio link, and using signaling lights. The
letters S.O.S. (Save Our Souls) is still recognized Rather than start typing this project in from
as an international signal of distress. scratch, we will use Project 1 as a starting point.
In this project, we will make our LED flash the So if you have not already done so, please
sequence S.O.S. over and over again. complete Project 1.
For this project, you will need just the same If you have not already done so, download the
components as for Project 1. project code from www.arduinoevilgenius.com;
then you can also just load the completed sketch
for Project 1 from your Arduino Sketchbook and
download it to the board (see Chapter 1). However,
27
28 30 Arduino Projects for the Evil Genius
void loop() }
{
digitalWrite(ledPin, HIGH);
// S (...) first dot
This would all work, and feel free to try it;
delay(200); however, we are not going to leave it there. We are
digitalWrite(ledPin, LOW); going to alter our sketch to improve it, and at the
delay(200); same time make it a lot shorter.
digitalWrite(ledPin, HIGH);
We can reduce the size of the sketch by creating
// second dot
delay(200); our own function to replace the four lines of code
digitalWrite(ledPin, LOW); involved in any flash with one line.
delay(200); After the loop function’s final curly brace, add
digitalWrite(ledPin, HIGH);
the following code:
// third dot
delay(200); void flash(int duration)
digitalWrite(ledPin, LOW); {
delay(500); digitalWrite(ledPin, HIGH);
digitalWrite(ledPin, HIGH); delay(duration);
// O (—-) first dash digitalWrite(ledPin, LOW);
delay(500); delay(duration);
digitalWrite(ledPin, LOW); }
delay(500);
digitalWrite(ledPin, HIGH);
// second dash Now modify the loop function so that it looks
delay(500); like this:
digitalWrite(ledPin, LOW);
void loop()
delay(500);
{
digitalWrite(ledPin, HIGH);
flash(200); flash(200); flash(200);
// third dash
// S
delay(500);
delay(300);
digitalWrite(ledPin, LOW);
// otherwise the flashes run
delay(500);
together
digitalWrite(ledPin, HIGH);
flash(500); flash(500); flash(500);
// S (...) first dot
// O
delay(200);
flash(200); flash(200); flash(200);
digitalWrite(ledPin, LOW);
// S
delay(200);
delay(1000);
digitalWrite(ledPin, HIGH);
// wait 1 second before we start
// second dot
again
delay(200);
}
digitalWrite(ledPin, LOW);
Chapter 3 ■ LED Projects 29
LISTING PROJECT 2
void loop()
{
flash(200); flash(200); flash(200); // S
delay(300); // otherwise the flashes run together
flash(500); flash(500); flash(500); // O
flash(200); flash(200); flash(200); // S
delay(1000); // wait 1 second before we start again
}
commas. This is just a quirk of the C language. contrast, an array contains a list of values, and you
The compiler will soon tell you when you get it can access any one of those values by its position
wrong. in the list.
The first thing in the parentheses after “for” is a C, in common with the majority of programming
variable declaration. This specifies a variable to be languages, begins its index positions at 0 rather
used as a counter variable and gives it an initial than 1. This means that the first element is actually
value—in this case, 0. element zero.
The second part is a condition that must be true To illustrate the use of arrays, we could change
for us to stay in the loop. In this case, we will stay our Morse code example to use an array of flash
in the loop as long as “i” is less than 100, but as durations. We can then use a for loop to step
soon as “i” is 100 or more, we will stop doing the through each of the items in the array.
things inside the loop. First let’s create an array of ints containing the
The final part is what to do every time you have durations:
done all the things in the loop. In this case, that is
int durations[] = {200, 200, 200, 500,
increment “i” by 1 so that it can, after 100 trips
500, 500, 200, 200, 200}
around the loop, cease to be less than 100 and
cause the loop to exit. You indicate that a variable contains an array by
Another way of looping in C is to use the while placing [] after the variable name. If you are
command. The same example shown previously setting the contents of the array at the same time
could be accomplished using a while command, you are defining it, as in the previous example, you
as shown here: do not need to specify the size of the array. If you
are not setting its initial contents, then you need to
int i = 0;
specify the size of the array inside the square
while (i < 100)
{ brackets. For example:
flash(200);
int durations[10];
i ++;
}
Now we can modify our loop method to use the
array:
The expression in parentheses after while must
be true to stay in the loop. When it is no longer void loop()
true, the sketch will continue running the // run over and over again
commands after the final curly brace. {
for (int i = 0; i < 9; i++)
The curly braces are used to bracket together a {
group of commands. In programming parlance, flash(durations[i]);
they are known as a block. }
delay(1000);
// wait 1 second before we start
// again
Arrays }
Arrays are a way of containing a list of values.
The variables we have met so far have only
contained a single value, usually an int. By
Chapter 3 ■ LED Projects 31
An obvious advantage of this approach is that it computer to the Arduino board through the USB
is easy to change the message by simply altering cable.
the durations array. In Project 3, we will take the For this project, you will need just the same
use of arrays a stage further to make a more components as for Project 1 and 2. In fact, the
general-purpose Morse code flasher. hardware is exactly the same; we are just going to
modify the sketch of Project 1.
Project 3 CO M P O N E N TS A N D E Q U I P M E N T
Morse Code Translator
Description Appendix A
In this project, we are going to use the same
Arduino Diecimila or
hardware as for Projects 1 and 2, but we are going
Duemilanove board or clone 1
to write a new sketch that will let us type in a
D1 5-mm Red LED 23
sentence on our computer and have our Arduino
R1 270 Ω 0.5W metal film resistor 6
board convert that into the appropriate Morse code
dots and dashes.
Figure 3-1 shows the Morse code translator in
action. The contents of the message box are being
Hardware
flashed as dots and dashes on the LED. Please refer back to Project 1 for the hardware
To do this, we will make use of what we have construction for this project.
learned about arrays and strings, and also learn You can either just plug the resistor and LED
something about sending messages from our directly into the Arduino connectors, or use the
breadboard (see Chapter 1). You can even just TABLE 3-1 Morse Code Letters
change the ledPin variable in the sketch to be pin
13 so that you use the built-in LED and do not A .- N -. 0 ——-
need any external components at all. B -… O —- 1 .——
C -.-. P .--. 2 ..---
Software D -.. Q --.- 3 …--
E . R .-. 4 ….-
The letters in Morse code are shown in Table 3-1.
F ..-. S … 5 …..
Some of the rules of Morse code are that a dash G --. T - 6 -….
is three times as long as a dot, the time between
H …. U ..- 7 --…
each dash or dot is equal to the duration of a dot,
I .. V …- 8 ---..
the space between two letters is the same length as
J .--- W .-- 9 ----.
a dash, and the space between two words is the
K -.- X -..-
same duration as seven dots.
L .-.. Y -.--
For the sake of this project, we will not worry
M -- Z --..
about punctuation, although it would be an
interesting exercise for you to try adding this to the
sketch. For a full list of all the Morse characters, The sketch for this is shown in Listing Project 3.
see http://en.wikipedia.org/wiki/Morse_code. An explanation of how it all works follows.
LISTING PROJECT 3
char* letters[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", // A-I
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", // J-R
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." // S-Z
};
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
char ch;
if (Serial.available()) // is there anything to be read from USB?
Chapter 3 ■ LED Projects 33
{
ch = Serial.read(); // read a single letter
if (ch >= 'a' && ch <= 'z')
{
flashSequence(letters[ch - 'a']);
}
else if (ch >= 'A' && ch <= 'Z')
{
flashSequence(letters[ch - 'A']);
}
else if (ch >= '0' && ch <= '9')
{
flashSequence(numbers[ch - '0']);
}
else if (ch == ' ')
{
delay(dotDelay * 4); // gap between words
}
}
}
We keep track of our dots and dashes using At first sight, it might look strange to be
arrays of strings. We have two of these, one for subtracting one letter from another, but it is
letters and one for numerals. So to find out what perfectly acceptable to do this in C. So, for
we need to flash for the first letter of the alphabet example, “a” - “a” is 0, whereas “d” - “a” will give
(A), we will get the string letters[0]—remember, us the answer 3. So, if the letter that we read from
the first element of an array is element 0, not the USB connections was f, we will calculate “f” -
element 1. “a,” which gives us 5 as the position of the letters
The variable dotDelay is defined, so if we want array. Looking up letters[5] will give us the string
to make our Morse code flash faster or slower, we “..-.”. We pass this string to a function called
can change this value, as all the durations are flashSequence.
defined as multiples of the time for a dot. The flashSequence function is going to loop
The setup function is much the same as for our over each of the parts of the sequence and flash it
earlier projects; however, this time we are getting as either a dash or a dot. Strings in C all have a
communications from the USB port, so we must special code on the end of them that marks the end
add the command: of the string, and this is called NULL. So, the first
thing flashSequence does is to define a variable
Serial.begin(9600); called “i.” This is going to indicate the current
position in the string of dots and dashes, starting at
This tells the Arduino board to set the position 0. The while loop will keep going until we
communications speed through USB to be 9600 reach the NULL on the end of the string.
baud. This is not very fast, but fast enough for our
Inside the while loop, we first flash the current
Morse code messages. It is also a good speed to set
dot or dash using a function that we are going to
it to because that is the default speed used by the
discuss in a moment and then add 1 to “i” and go
Arduino software on your computer.
back round the loop flashing each dot or dash in
In the loop function, we are going to repeatedly turn until we reach the end of the string.
see if we have been sent any letters over the USB
The final function that we have defined is
connection and if we have to process the letter. The
flashDotOrDash’; this just turns the LED on and
Arduino function Serial.available() will be true if
then uses an if statement to either delay for the
there is a character to be turned into Morse code
duration of a single dot if the character is a dot, or
and the Serial.read() function will give us that
for three times that duration if the character is a
character, which we assign to a variable called
dash, before it turns the LED off again.
“ch” that we defined just inside the loop.
We then have a series of if statements that
Putting It All Together
determine whether the character is an uppercase
letter, a lowercase letter, or a space character Load the completed sketch for Project 3 from
separating two words. Looking at the first if your Arduino Sketchbook and download it onto
statement, we are testing to see if the character’s your board (see Chapter 1).
value is greater than or equal to “a” and less than To use the Morse code translator, we need to
or equal to “z.” If that is the case, we can find the use a part of the Arduino software called the Serial
sequence of dashes and dots to flash using the Monitor. This window allows you to type messages
letter array that we defined at the top of the sketch. that are sent to the Arduino board as well as see
We determine which sequence from the array to any messages that the Arduino board chooses to
use by subtracting “a” from the character in ch. reply with.
Chapter 3 ■ LED Projects 35
Arduino Diecimila or
Duemilanove board or clone 1
D1 Luxeon 1W LED 30
R1 270 ⍀ 0.5W metal film resistor 6
R2 4 ⍀ 1W resistor 16
T1 BD139 power transistor 41
Protoshield kit (optional) 3
Making a Shield
This is the first project that we have made that has
enough components to justify making an Arduino
Figure 3-7 Attaching leads to the Luxeon LED Shield circuit board to sit on top of the Arduino
without soldering. board itself. We are also going to use this hardware
with minor modifications in Project 6, so perhaps
Figure 3-8 shows the fully assembled it is time to make ourselves a Luxeon LED Shield.
breadboard.
Making your own circuit boards at home is
perfectly possible, but requires the use of noxious
Software chemicals and a fair amount of equipment. But
The only change in the software from Project 3 is fortunately, there is another great piece of Arduino-
that we are using digital output pin 11 rather than related open-source hardware called the Arduino
pin 12. Protoshield. If you shop around, these can be
obtained for $10 or less and will provide you with
a kit of all you need to make a basic shield. That
Putting It All Together
includes the board itself; the header connector pins
Load the completed sketch for Project 4 from your that fit into the Arduino; and some LEDs,
Arduino Sketchbook and download it onto your switches, and resistors. Please be aware that there
board (see Chapter 1). are several variations of the Protoshield board, so
Again, testing the project is the same as for you may have to adapt the following design if your
Project 3. You will need to open the Serial Monitor board is slightly different.
window and just start typing.
Figure 3-11 Assembled basic Protoshield. Figure 3-12 Project 4 Protoshield layout.
Congratulations! You have created your first In the next chapter, we are going to extend this
Arduino Shield, and it is one that we can reuse in by looking at some more LED-based projects
later projects. including a model traffic signal and a high power
strobe light.
41
42 30 Arduino Projects for the Evil Genius
int redPin = 2; Load the completed sketch for Project 5 from your
int yellowPin = 3; Arduino Sketchbook (see Chapter 1).
int greenPin = 4;
Test the project by holding down the button and
int buttonPin = 5;
make sure the LEDs all light in sequence.
int state = 0;
void setup()
{
Project 6
pinMode(redPin, OUTPUT); Strobe Light
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT); This project uses the same high-brightness Luxeon
pinMode(buttonPin, INPUT); LED as the Morse code translator. It adds to that a
} variable resistor, sometimes called a potentiometer.
This provides us with a control that we can rotate
void loop()
{
to control the flashing rate of the strobe light.
if (digitalRead(buttonPin))
{ This is a strobe light; it flashes
CAUTION
if (state == 0) brightly. If you have a health
{ condition such as epilepsy, you may wish to skip
setLights(HIGH, LOW, LOW); this project.
state = 1;
}
else if (state == 1)
CO M P O N E N TS A N D E Q U I P M E N T
{
setLights(HIGH, HIGH, LOW); Description Appendix
state = 2;
} Arduino Diecimila or
else if (state == 2) Duemilanove board or clone 1
{ D1 Luxeon 1W LED 30
setLights(LOW, LOW, HIGH);
state = 3; R1 270 ⍀ 0.5W metal film resistor 6
} R2 4 ⍀ 1W resistor 16
else if (state == 3)
T1 BD139 power transistor 41
{
setLights(LOW, HIGH, LOW); R3 100K linear potentiometer 17
state = 0; Protoshield kit (optional) 3
}
delay(1000); 2.1-mm power plug (optional) 49
} 9V battery clip (optional) 50
}
Making a Shield
If you want to make a shield for this project, you
can either adapt the shield for Project 4 or create a
new shield from scratch.
The layout of components on the Protoshield is
shown in Figure 4-7.
This is basically the same as for Project 4,
except that we have added the variable resistor.
The pins on a variable resistor are too thick to fit
into the holes on the Protoshield, so you can either Figure 4-8 Creating a battery lead.
attach it using wires or, as we have done here,
carefully solder the leads to the top surface where
they touch the board. To provide some mechanical
strength, the variable resistor can be glued in place
Project 7
first with a drop of Super Glue. The wiring for the S.A.D. Light
variable resistor to 5V, GND, and Analog 0 can be Seasonal affective disorder (S.A.D.) affects a great
made underneath the board out of sight. number of people, and research has shown that
Having made a shield, we can make the project exposure to a bright white light that mimics
independent of our computer by powering it from a daylight for 10 or 20 minutes a day has a
9V battery. beneficial effect. To use this project for such a
To power the project from a battery, we need to purpose, I would suggest the use of some kind of
make ourselves a small lead that has a PP3 battery diffuser such as frosted glass, as you should not
clip on one end and a 2.1-mm power plug on the stare directly at the point light sources of the
other. Figure 4-8 shows the semi-assembled lead. LEDs.
This is another project based on the Luxeon
high-brightness LEDs. We will use an analog input
connected to a variable resistor to act as a timer
control, turning the LED on for a given period set
by the position of the variable resistor’s slider.
We will also use an analog output to slowly raise
the brightness of the LEDs as they turn on and
then slowly decrease it as they turn off. To make
the light bright enough to be of use as a S.A.D.
light, we are going to use not just one Luxeon
LED but six.
At this point, the caring nature of this project
may be causing the Evil Genius something of an
identity crisis. But, fear not—in Project 8, we will
turn this same hardware into a fearsome high-
powered strobe light.
It is easier to solder two wires onto each LED The LEDs will get hot, so it is a good idea to
before fitting them onto the board. It is a good idea leave a gap between them and the perf board using
to color-code those leads—red for positive and the insulation on the wire to act as a spacer. The
black or blue for negative—so that you get the voltage regulator will also get hot but should be
LEDs in the correct way round. okay without a heatsink. The voltage regulator
integrator circuits (ICs) actually have built-in You may remember that analog inputs can also
thermal protection and will automatically reduce be used as digital outputs by adding 14 to their pin
the current if they start to get too hot. number. So in order to have 5V at one end of our
The screw terminals on the board are for the variable resistor and 0V at the other, we are going
power supply GND and 15V and a control input. to set the outputs of analog pins 0 and 4 (digital
When we connect this to the Arduino board, the pins 14 and 18) to 0V and 5V, respectively.
15V will come from the Vin pin on the Arduino,
which in turn is supplied from a 15V power Software
supply.
At the top of the sketch, after the variable used for
Our high-power LED module will be of use in pins, we have four other variables: startupSeconds,
other projects, so we are going to plug the variable turnOffSeconds, minOnSeconds, and
resistor directly into the Analog In strip of maxOnSeconds. This is common practice in
connectors on the Arduino board. The spacing of programming. By putting these values that we
pins on the variable resistor is 1/5 of an inch, might want to change into variables and making
which means that if the middle slider pin is in the them visible at the top of the sketch, it makes it
socket for Analog 2, the other two pins will be in easier to change them.
the sockets for Analog 0 and 4. You can see this
arrangement in Figure 4-12.
Chapter 4 I More LED Projects 51
LISTING PROJECT 7
int brightness = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
pinMode(14, OUTPUT); // Use Analog pins 0 and 4 for
pinMode(18, OUTPUT); // the variable resistor
digitalWrite(18, HIGH);
int analogIn = analogRead(analogPin);
int onTime = map(analogIn, 0, 1023, minOnSeconds, maxOnSeconds);
turnOn();
delay(onTime * 1000);
turnOff();
}
void turnOn()
{
brightness = 0;
int period = startupSeconds * 1000 / 256;
while (brightness < 255)
{
analogWrite(ledPin, 255 - brightness);
delay(period);
brightness ++;
}
}
void turnOff()
{
int period = turnOffSeconds * 1000 / 256;
while (brightness >= 0)
{
analogWrite(ledPin, 255 - brightness);
delay(period);
brightness —;
}
}
void loop()
{}
52 30 Arduino Projects for the Evil Genius
The variable startupSeconds determines how want to convert, the minimum input value (0 in
long it will take for the brightness of the LEDs to this case), the maximum input value (1023), the
be gradually raised until it reaches maximum minimum output value (300), and the maximum
brightness. Similarly, turnOffSeconds determines output value (1800).
the time period for dimming the LEDs. The
variables minOnSeconds and maxOnSeconds Putting It All Together
determine the range of times set by the variable
resistor. Load the completed sketch for Project 7 from your
Arduino Sketchbook and download it to the board
In this sketch, there is nothing in the loop
(see Chapter 1).
function. Instead all the code is in setup. So, the
light will automatically start its cycle when it is You now need to attach wires from the Vin,
powered up. Once it has finished, it will stay GND, and digital pin 11 of the Arduino board to
turned off until the reset button is pressed. the three screw terminals of the LED module
(Figure 4-12). Plug a 15V power supply into the
The slow turn-on is accomplished by gradually
board’s power socket and you are ready to try it.
increasing the value of the analog output by 1.
This is carried out in a while loop, where the delay To start the light sequence again, click the reset
is set to 1/255 of the startup time so that after 255 button.
steps maximum brightness has been achieved.
Slow turn-off works in a similar manner.
The time period at full brightness is set by the
Project 8
analog input. Assuming that we want a range of High-Powered Strobe Light
times from 5 to 30 minutes, we need to convert the For this project, you can use the six Luxeon LED
value of 0 to 1023 to a number of seconds between module of Project 7 or you can use the Luxeon
300 and 1800. Fortunately, there is a handy shield that we created for Project 4. The software
Arduino function that we can use to do this. The will be almost the same in both cases.
function map takes five arguments: the value you
LISTING PROJECT 8
void setup()
{
pinMode(ledPin, OUTPUT);
analogWrite(ledPin, 255);
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch == '0')
{
mode = 0;
analogWrite(ledPin, 255);
}
else if (ch > '0' && ch <= '9')
{
setPeriod(ch);
}
else if (ch == 'w' || ch == 's')
(continued)
54 30 Arduino Projects for the Evil Genius
{
mode = ch;
}
}
if (mode == 'w')
{
waveLoop();
}
else if (mode == 's')
{
strobeLoop();
}
}
void waveLoop()
{
static float angle = 0.0;
angle = angle + 0.01;
if (angle > 3.142)
{
angle = 0;
}
// analogWrite(ledPin, 255 - (int)255 * sin(angle)); // Breadboard
analogWrite(ledPin, (int)255 * sin(angle)); // Shield
delay(period / 100);
}
void strobeLoop()
{
//analogWrite(ledPin, 0); // breadboard
analogWrite(ledPin, 255); // shield
delay(10);
//analogWrite(ledPin, 255); // breadboard
analogWrite(ledPin, 0); // shield
delay(period);
}
Chapter 4 I More LED Projects 55
Putting It All Together and the following line will give x a value between
0 and 9:
Load the completed sketch for Project 8 from your
Arduino Sketchbook and download it to the board int x = random(10);
(see Chapter 1).
As we pointed out at the start of this section,
When you have installed the sketch and fitted
computers are deterministic, and actually our
the Luxeon shield or connected the bright six-
random numbers are not random at all, but a long
Luxeon panel, initially the lights will be off. Open
sequence of numbers with a random distribution.
the Serial Monitor window, type s, and press
You will actually get the same sequence of
RETURN. This will start the light flashing. Try the
numbers every time you run your script.
speed commands 1 to 9. Then try typing the w
command to switch to wave mode. A second function (randomSeed) allows you to
control this. The randomSeed function determines
where in its sequence of pseudo-random numbers
Random Number Generation the random number generator starts.
A good trick is to use the value of a
Computers are deterministic. If you ask them the
disconnected analog input, as this will float around
same question twice, you should get the same
at a different value and give at least 1000 different
answer. However, sometimes, you want chance to
starting points for our random sequence. This
take a hand. This is obviously useful for games.
wouldn’t do for the lottery, but is acceptable for
It is also useful in other circumstances—for most applications. Truly random numbers are very
example, a “random walk,” where a robot makes a hard to come by and involve special hardware.
random turn, then moves forward a random
distance or until it hits something, then reverses
and turns again, is much better at ensuring the Project 9
robot covers the whole area of a room than a more
fixed algorithm that can result in the robot getting
LED Dice
stuck in a pattern. This project uses what we have just learned about
The Arduino library includes a function for random numbers to create electronic dice with six
creating random numbers. LEDs and a button. Every time you press the
button, the LEDs “roll” for a while before settling
There are two flavors of the function random. It
on a value and then flashing it.
can either take two arguments (minimum and
maximum) or one argument (maximum), in which
case the minimum is assumed to be 0. CO M P O N E N TS A N D E Q U I P M E N T
So, the following line will give x a value D1-7 Standard red LEDs 23
between 1 and 6: R1-7 270 ⍀ 0.5W metal film resistor 6
S1 Miniature push-to-make switch 48
int x = random(1, 7);
R8 100K ⍀ 0.5W metal film resistor 13
56 30 Arduino Projects for the Evil Genius
LISTING PROJECT 9
int switchPin = 9;
int blank = 6;
void setup()
{
for (int i = 0; i < 7; i++)
{
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
randomSeed(analogRead(0));
}
void loop()
{
(continued)
58 30 Arduino Projects for the Evil Genius
if (digitalRead(switchPin))
{
rollTheDice();
}
delay(100);
}
void rollTheDice()
{
int result = 0;
int lengthOfRoll = random(15, 25);
for (int i = 0; i < lengthOfRoll; i++)
{
result = random(0, 6); // result will be 0 to 5 not 1 to 6
show(result);
delay(50 + i * 10);
}
for (int j = 0; j < 3; j++)
{
show(blank);
delay(500);
show(result);
delay(500);
}
}
We now have seven LEDs to initialize in the as an Evil Genius, you may like to omit that line
setup method, so it is worth putting them in an so that you can cheat at Snakes and Ladders!
array and looping over the array to initialize each The dicePatterns array determines which LEDs
pin. We also have a call to randomSeed in the should be on or off for any particular throw. So
setup method. If this was not there, every time we each throw element of the array is actually itself an
reset the board, we would end up with the same array of seven elements, each one being either
sequence of dice throws. As an experiment, you HIGH or LOW (1 or 0). When we come to display
may wish to try commenting out this line by a particular result of throwing the dice, we can just
placing a // in front of it and verifying this. In fact,
Chapter 4 I More LED Projects 59
loop over the array for the throw, setting each LED Summary
accordingly.
In this chapter we have used a variety of LEDs and
software techniques for lighting them in interesting
Putting It All Together
ways. In the next chapter we will investigate some
Load the completed sketch for Project 9 from your different types of sensors and use them to provide
Arduino Sketchbook and download it to the board inputs to our projects.
(see Chapter 1).
This page intentionally left blank
CHAPTER 5
Sensor Projects
SENSORS TURN REAL-WORLD measurements into Unfortunately, keypads do not usually have pins
electronic signals that we can then use on our attached, so we will have to attach some, and the
Arduino boards. The projects in this chapter are all only way to do that is to solder them on. So this is
about using light and temperature. another of our projects where you will have to do a
We also look at how to interface with keypads little soldering.
and rotary encoders.
Hardware
The schematic diagram for Project 10 is shown in
Project 10 Figure 5-1. By now, you will be used to LEDs; the
Keypad Security Code new component is the keypad.
This project would not be out of place in the lair of Keypads are normally arranged in a grid so that
any Evil Genius worth their salt. A secret code when one of the keys is pressed, it connects a row
must be entered on the keypad, and if it is correct, to a column. Figure 5-2 shows a typical
a green LED will light; otherwise, a red LED will arrangement for a 12-key keyboard with numbers
stay lit. In Project 27, we will revisit this project from 0 to 9 and * and # keys.
and show how it cannot just show the appropriate
The key switches are arranged at the
light, but also control a door lock.
intersection of row-and-column wires. When a key
is pressed, it connects a particular row to a
CO M P O N E N TS A N D E Q U I P M E N T particular column.
By arranging the keys in a grid like this, it
Description Appendix
means that we only need to use 7 (4 rows + 3
Arduino Diecimila or columns) of our digital pins rather than 12 (one for
Duemilanove board or clone 1
each key).
D1 Red 5-mm LED 23
However, it also means that we have to do a bit
D2 Green 5-mm LED 25
more work in the software to determine which
R1-2 270 ⍀ 0.5W metal film resistor 6 keys are pressed. The basic approach we have to
K1 4 by 3 keypad 54 take is to connect each row to a digital output and
0.1-inch header strip 55 each column to a digital input. We then put each
output high in turn and see which inputs are high.
61
62 30 Arduino Projects for the Evil Genius
Figure 5-3 shows how you can solder seven pins are bought in strips and can be easily snapped to
from a pin header strip onto the keypad so that you provide the number of pins required.
can then connect it to the breadboard. Pin headers Now, we just need to find out which pin on the
keypad corresponds to which row or column. If we
are lucky, the keypad will come with a datasheet
that tells us this. If not, we will have to do some
detective work with a multimeter. Set the
multimeter to continuity so that it beeps when you
connect the leads together. Then get some paper,
Figure 5-2 A 12-switch keypad. Figure 5-3 Soldering pins to the keypad.
Chapter 5 ■ Sensor Projects 63
Fortunately for us, Mark Stanley and Alexander On a Mac, you do not put the new library into
Brevig have created a library that you can use to the Arduino installation. Instead, you create a
connect to keypads that handles such things for us. folder called libraries in Documents/Arduino
This is a good opportunity to demonstrate (Figure 5-8) and put the whole library folder in
installing a library into the Arduino software. there. Incidentally, the Documents/Arduino
In addition to the libraries that come with the directory is also the default location where your
Arduino, many people have developed their own sketches are stored.
libraries and published them for the benefit of the Once we have installed this library into our
Arduino community. The Evil Genius is much Arduino directory, we will be able to use it with
amused by such altruism and sees it as a great any sketches that we write. But remember that on
weakness. However, the Evil Genius is not above Windows and LINUX, if you upgrade to a newer
using such libraries for their own devious ends. version of the Arduino software, you will have to
To make use of this library, we must first reinstall the libraries that you use.
download it from the Arduino website at this You can check that the library is correctly
address: www.arduino.cc/playground/Code/ installed by restarting the Arduino, starting a new
Keypad. sketch, and choosing the menu option Sketch |
Download the file Keypad.zip and unzip it. If Import Library | Keypad. This will then insert the
you are using Windows, you right-click and choose text “#include <Keypad.h>” into the top of the file.
Extract All and then save the whole folder into The sketch for the application is shown in
C:\Program Files\Arduino\Arduino-0017\ Listing Project 10. Note that you may well have to
hardware\libraries (Figure 5-7). change your keys, rowPins, and colPins arrays so
On LINUX, find the Arduino installation that they agree with the key layout of your keypad,
directory and copy the folder into hardware/ as we discussed in the hardware section.
libraries.
Chapter 5 ■ Sensor Projects 65
LISTING PROJECT 10
#include <Keypad.h>
int redPin = 9;
int greenPin = 8;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
setLocked(true);
}
void loop()
{
char key = keypad.getKey();
if (key == '*' || key == '#')
{
position = 0;
setLocked(true);
}
if (key == secretCode[position])
{
position ++;
}
if (position == 4)
{
setLocked(false);
}
delay(100);
}
{
if (locked)
{
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
}
else
{
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
}
}
This sketch is quite straightforward. The loop and round indefinitely without meeting any kind of
function checks for a key press. If the key pressed end stop, there is probably a rotary encoder behind
is a # or a * it sets the position variable back to 0. the knob.
If, on the other hand, the key pressed is one of the Some rotary encoders also incorporate a button
numerals, it checks to see if it is the next key so that you can turn the knob and then press. This
expected (secretCode[position]) is the key just is a particularly useful way of making a selection
pressed, and if it is, it increments position by one. from a menu when used with a liquid crystal
Finally, the loop checks to see if position is 4, and display (LCD) screen.
if it is, it sets the LEDs to their unlocked state.
A rotary encoder is a digital device that has two
outputs (A and B), and as you turn the knob, you
Putting It All Together get a change in the outputs that can tell you
Load the completed sketch for Project 10 from whether the knob has been turned clockwise or
your Arduino Sketchbook and download it to the counterclockwise.
board (see Chapter 1). Figure 5-9 shows how the signals change on A
If you have trouble getting this to work, it is and B when the encoder is turned. When rotating
most likely a problem with the pin layout on your clockwise, the pulses will change, as they would
keypad. So persevere with the multimeter to map moving left to right on the diagram; when moving
out the pin connections. counterclockwise, the pulses would be moving
right to left on the diagram.
So if A is low and B is low, and then B becomes
Rotary Encoders high (going from phase 1 to phase 2), that would
indicate that we have turned the knob clockwise. A
We have already met variable resistors: as you turn
clockwise turn would also be indicated by A being
the knob, the resistance changes. These used to be
low, B being high, and then A becoming high
behind most knobs that you could twiddle on
(going from phase 2 to phase 3), etc. However, if A
electronic equipment. There is an alternative, the
was high and B was low and then B went high, we
rotary encoder, and if you own some consumer
have moved from phase 4 to phase 3 and are,
electronics where you can turn the knob round
therefore, turning counterclockwise.
68 30 Arduino Projects for the Evil Genius
Project 11 Hardware
Model Traffic Signal The schematic diagram for Project 11 is shown in
Using a Rotary Encoder Figure 5-10. The majority of the circuitry is the
same as for Project 5, except that now we have a
This project uses a rotary encoder with a built-in rotary encoder.
push switch to control the sequence of the traffic
The rotary encoder works just as if there were
signals, and is based on Project 5. It is a much
three switches: one each for A and B and one for
more realistic version of a traffic signal controller
the push switch. Each of these switches requires a
and is really not far off the logic that you would
pull-down resistor.
find in a real traffic signal controller.
Since the schematic is much the same as for
Rotating the rotary encoder will change the
Project 5, it will not be much of a surprise to see
frequency of the light sequencing. Pressing the
that the breadboard layout (Figure 5-11) is similar
button will test the lights, turning them all on at
to the one for that project.
the same time, while the button is pressed.
The components are the same as for Project 5,
with the addition of the rotary encoder and pull-up
Software
resistors in place of the original push switch. The starting point for the sketch is the sketch for
Project 5. We have added code to read the encoder
and to respond to the button press by turning all
CO M P O N E N TS A N D E Q U I P M E N T the LEDs on. We have also taken the opportunity
Description Appendix to enhance the logic behind the lights to make
them behave in a more realistic way, changing
Arduino Diecimila or
Duemilanove board or clone 1
automatically. In Project 5, when you hold down
the button, the lights change sequence roughly
D1 5-mm Red LED 23
once per second. In a real traffic signal, the lights
D2 5-mm Yellow LED 24
stay green and red a lot longer than they are
D3 5-mm Green LED 25 yellow. So our sketch now has two periods:
R1-R3 270 Ω 0.5W metal film resistor 6 shortPeriod, which does not alter but is used when
R4-R6 100 KΩ 0.5W metal film the lights are changing, and longPeriod, which
resistor 13 determines how long they are illuminated for when
S1 Rotary encoder with push green or red. This longPeriod is the period that is
switch 57 changed by turning the rotary encoder.
Chapter 5 ■ Sensor Projects 69
The key to handling the rotary encoder lies in quickly will result in some changes not being
the function getEncoderTurn. Every time this is recognized correctly.
called, it compares the previous state of A and B If you want to use a rotary encoder for other
with their current state and if something has projects, you can just copy this function. The
changed, works out if it was clockwise or function uses the static modifier for the oldA and
counterclockwise and returns a –1 or 1, oldB variables. This is a useful technique that
respectively. If there is no change (the knob has allows the function to retain the values between
not been turned), it returns 0. This function must one call of the function and the next, where
be called frequently or turning the rotary controller normally it would reset the value of the variable
every time the function is called.
70 30 Arduino Projects for the Evil Genius
LISTING PROJECT 11
int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int aPin = 6;
int bPin = 7;
int buttonPin = 5;
int state = 0;
int longPeriod = 5000; // Time at green or red
int shortPeriod = 700; // Time period when changing
int targetCount = shortPeriod;
int count = 0;
void setup()
{
pinMode(aPin, INPUT);
pinMode(bPin, INPUT);
pinMode(buttonPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop()
{
count++;
if (digitalRead(buttonPin))
{
setLights(HIGH, HIGH, HIGH);
}
else
{
int change = getEncoderTurn();
int newPeriod = longPeriod + (change * 1000);
if (newPeriod >= 1000 && newPeriod <= 10000)
{
longPeriod = newPeriod;
}
if (count > targetCount)
{
setState();
count = 0;
}
}
delay(1);
}
int getEncoderTurn()
{
// return -1, 0, or +1
static int oldA = LOW;
Chapter 5 ■ Sensor Projects 71
int setState()
{
if (state == 0)
{
setLights(HIGH, LOW, LOW);
targetCount = longPeriod;
state = 1;
}
else if (state == 1)
{
setLights(HIGH, HIGH, LOW);
targetCount = shortPeriod;
state = 2;
}
else if (state == 2)
{
setLights(LOW, LOW, HIGH);
targetCount = longPeriod;
state = 3;
}
else if (state == 3)
{
setLights(LOW, HIGH, LOW);
targetCount = shortPeriod;
state = 0;
}
}
This sketch illustrates a useful technique that our analog inputs. This schematic for this is shown
lets you time events (turning an LED on for so in Figure 5-12.
many seconds) while at the same time checking With a fixed resistor of 100K, we can do some
the rotary encoder and button to see if they have rough calculations about the voltage range to
been turned or pressed. If we just used the Arduino expect at the analog input.
delay function with, say, 20,000, for 20 seconds,
In darkness, the LDR will have a resistance of
we would not be able to check the rotary encoder
2 M⍀, so with a fixed resistor of 100K, there will
or switch in that period.
be about a 20:1 ratio of voltage, with most of that
So what we do is use a very short delay (1 voltage across the LDR, so that would mean about
millisecond) but maintain a count that is 4V across the LDR and 1V at the analog pin.
incremented each time round the loop. Thus, if we
On the other hand, if the LDR is in bright light,
want to delay for 20 seconds, we stop when the
its resistance might fall to 20 K⍀. The ratio of
count has reached 20,000. This is less accurate
voltages would then be about 4:1 in favor of the
than a single call to the delay function because the
fixed resistor, giving a voltage at the analog input
1 millisecond is actually 1 millisecond plus the
of about 4V.
processing time for the other things that are done
inside the loop. A more sensitive photo detector is the
phototransistor. This functions like an ordinary
transistor except there is not usually a base
Putting It All Together
connection. Instead, the collector current is
Load the completed sketch for Project 11 from controlled by the amount of light falling on the
your Arduino Sketchbook and download it to the phototransistor.
board (see Chapter 1).
You can press the rotary encoder button to test
the LEDs and turn the rotary encoder to change
how long the signal stays green and red.
Sensing Light
A common and easy-to-use device for measuring
light intensity is the light-dependent resistor or
LDR. They are also sometimes called
photoresistors.
The brighter the light falling on the surface of
the LDR, the lower the resistance. A typical LDR
will have a dark resistance of up to 2 M⍀ and a
resistance when illuminated in bright daylight of
perhaps 20 K⍀.
We can convert this change in resistance to a
change in voltage by using the LDR, with a fixed
resistor as a voltage divider, connected to one of Figure 5-12 Using an LDR to measure light.
Chapter 5 ■ Sensor Projects 73
Project 12 Hardware
Pulse Rate Monitor The pulse monitor works as follows: Shine the
bright LED onto one side of your finger while the
This project uses an ultra-bright infrared (IR) LED
phototransistor on the other side of your finger
and a phototransistor to detect the pulse in your
picks up the amount of transmitted light. The
finger. It then flashes a red LED in time with your
resistance of the phototransistor will vary slightly
pulse.
as the blood pulses through your finger.
The schematic for this is shown in Figure 5-13
CO M P O N E N TS A N D E Q U I P M E N T
and the breadboard layout in Figure 5-15. We have
Description Appendix chosen quite a high value of resistance for R1
because most of the light passing through the
Arduino Diecimila or
Duemilanove board or clone 1 finger will be absorbed and we want the
phototransistor to be quite sensitive. You may need
D1 5-mm red LED 23
to experiment with the value of the resistor to get
D2 5-mm IR LED sender 940 nm 26
the best results.
R1 56 K⍀ 0.5W metal film resistor 12
It is important to shield the phototransistor from
R2 270 ⍀ 0.5W metal film resistor 6
as much stray light as possible. This is particularly
R4 39 ⍀ 0.5W metal film resistor 4
important for domestic lights that actually fluctuate
T1 IR phototransistor at 50Hz or 60Hz and will add a considerable
(same wavelength as D2) 36
amount of noise to our weak heart signal.
Software This script reads the raw signal from the analog
input and applies the smoothing function and then
The software for this project is quite tricky to get
writes both values to the Serial Monitor, where we
right. Indeed, the first step is not to run the entire
can capture them and paste them into a spreadsheet
final script, but rather a test script that will gather
for analysis. Note that the Serial Monitor’s
data that we can then paste into a spreadsheet and
communications is set to its fastest rate to
chart to test out the smoothing algorithm (more on
minimize the effects of the delays caused by
this later).
sending the data. When you start the Serial
The test script is provided in Listing Projet 12. Monitor, you will need to change the serial speed
to 115200 baud.
The smoothing function uses a technique called
LISTING PROJECT 12—TEST SCRIPT
“leaky integration,” and you can see in the code
int ledPin = 13; where we do this smoothing using the line:
int sensorPin = 0;
double value = alpha * oldValue + (1 -
double alpha = 0.75; alpha) * rawValue;
int period = 20;
double change = 0.0; The variable alpha is a number greater than 0
but less than 1 and determines how much
void setup() smoothing to do.
{
pinMode(ledPin, OUTPUT);
Put your finger into the sensor tube, start the
Serial.begin(115200); Serial Monitor, and leave it running for three or
} four seconds to capture a few pulses.
Then, copy and paste the captured text into a
void loop()
spreadsheet. You will probably be asked for the
{
static double oldValue = 0; column delimiter character, which is a comma. The
static double oldChange = 0; resultant data and a line chart drawn from the two
int rawValue = columns are shown in Figure 5-17.
analogRead(sensorPin);
The more jagged trace is from the raw data read
double value = alpha * oldValue
+ (1 - alpha) * rawValue;
from the analog port, and the smoother trace
clearly has most of the noise removed. If the
Serial.print(rawValue); smoothed trace shows significant noise—in
Serial.print(“,”); particular, any false peaks that will confuse the
Serial.println(value); monitor—increase the level of smoothing by
decreasing the value of alpha.
oldValue = value;
delay(period); Once you have found the right value of alpha
} for your sensor arrangement, you can transfer this
value into the real sketch and switch over to using
the real sketch rather than the test sketch. The real
sketch is provided in the following listing on the
next page.
76 30 Arduino Projects for the Evil Genius
LISTING PROJECT 12
There now just remains the problem of detecting
the peaks. Looking at Figure 5-17, we can see that
int ledPin = 13; if we keep track of the previous reading, we can
int sensorPin = 0;
see that the readings are gradually increasing until
double alpha = 0.75; the change in reading flips over and becomes
int period = 20; negative. So, if we lit the LED whenever the old
double change = 0.0;
change was positive but the new change was
void setup() negative, we would get a brief pulse from the LED
{ at the peak of each pulse.
pinMode(ledPin, OUTPUT);
}
void loop()
Putting It All Together
{
static double oldValue = 0;
Both the test and real sketch for Project 12 are in
static double oldChange = 0; your Arduino Sketchbook. For instructions on
int rawValue = downloading it to the board, see Chapter 1.
analogRead(sensorPin);
double value = alpha * oldValue As mentioned, getting this project to work is a
+ (1 - alpha) * rawValue; little tricky. You will probably find that you have to
change = value - oldValue;
get your finger in just the right place to start
digitalWrite(ledPin, (change < getting a pulse. If you are having trouble, run the
0.0 && oldChange > 0.0));
test script as described previously to check that
oldValue = value; your detector is getting a pulse and the smoothing
oldChange = change; factor alpha is low enough.
delay(period);
}
The author would like to point out that this Since the analog value “a” is given by:
device should not be used for any kind of real
medical application. a ⫽ V * (1023/5)
then
LISTING PROJECT 13
#include <EEPROM.h>
#define ledPin 13
#define analogPin 0
#define maxReadings 255
#define beta 4090 // from your thermistor's datasheet
#define resistance 33
float readings[maxReadings];
int lastReading = EEPROM.read(0);
boolean loggingOn = false;
long period = 300;
long count = 0;
char mode = 'C';
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Ready");
}
void loop()
{
(continued)
80 30 Arduino Projects for the Evil Genius
if (Serial.available())
{
char ch = Serial.read();
if (ch == 'r' || ch == 'R')
{
sendBackdata();
}
else if (ch == 'x' || ch == 'X')
{
lastReading = 0;
EEPROM.write(0, 0);
Serial.println("Data cleared");
}
else if (ch == 'g' || ch == 'G')
{
loggingOn = true;
Serial.println("Logging started");
}
else if (ch > '0' && ch <= '9')
{
setPeriod(ch);
}
else if (ch == 'c' or ch == 'C')
{
Serial.println("Mode set to deg C");
mode = 'C';
}
else if (ch == 'f' or ch == 'F')
{
Serial.println("Mode set to deg F");
mode = 'F';
}
else if (ch == '?')
{
reportStatus();
}
}
if (loggingOn && count > period)
{
logReading();
count = 0;
}
count++;
delay(1000);
}
void sendBackdata()
{
loggingOn = false;
Serial.println("Logging stopped");
Serial.println("------ cut here ---------");
Chapter 5 ■ Sensor Projects 81
void logReading()
{
if (lastReading < maxReadings)
{
long a = analogRead(analogPin);
float temp = beta / (log(((1025.0 * resistance / a) - 33.0) / 33.0) +
(beta / 298.0)) - 273.0;
storeReading(temp, lastReading);
lastReading++;
}
else
{
Serial.println("Full! logging stopped");
loggingOn = false;
}
}
(continued)
82 30 Arduino Projects for the Evil Genius
void reportStatus()
{
Serial.println("----------------");
Serial.println("Status");
Serial.print("Sample period\t");
Serial.println(period / 60);
Serial.print("Num readings\t");
Serial.println(lastReading);
Serial.print("Mode degrees\t");
Serial.println(mode);
Serial.println("----------------");
}
all occurrences of its name anywhere in the sketch lastReading in the first byte of EEPROM and then
are replaced by its value. It is very much a matter the actual reading data in the 256 bytes that follow.
of personal taste whether you use #define or a Each temperature reading is kept in a float, and
variable. if you remember from Chapter 2, a float occupies
Fortunately, reading and writing EEPROM 4 bytes of data. Here we had a choice: We could
happens just one byte at a time. So if we want to either store all 4 bytes or find a way to encode the
write a variable that is a byte or a char, we can just temperature into a single byte. We decided to take
use the functions EEPROM.write and the latter route, as it is easier to do.
EEPROM.read, as shown in the example here: The way we encode the temperature into a
char letterToWrite = 'A';
single byte is to make some assumptions about our
EEPROM.write(0, myLetter); temperatures. First, we assume that any
temperature in Centigrade will be between –20 and
char letterToRead; ⫹40. Anything higher or lower would likely
letterToRead = EEPROM.read(0); damage our Arduino board anyway. Second, we
assume that we only need to know the temperature
The 0 in the parameters for read and write is the to the nearest quarter of a degree.
address in the EEPROM to use. This can be any
With these two assumptions, we can take any
number between 0 and 1023, with each address
temperature value we get from the analog input,
being a location where one byte is stored.
add 20 to it, multiply it by 4, and still be sure that
In this project we want to store both the position we always have a number between 0 and 240.
of the last reading taken (in the lastReading Since a byte can hold a number between 0 and
variable) and all the readings. So we will record 255, that just fits nicely.
Chapter 5 ■ Sensor Projects 83
When we take our numbers out of EEPROM, time as the USB connector is connected if you
we need to convert them back to a float, which we want the logger to keep logging after you
can do by reversing the process, dividing by 4 and disconnect the USB lead.
then subtracting 20. Finally, we can type the G command to start
Both encoding and decoding the values are logging. We can then unplug the USB lead and
wrapped up in the functions storeReading and leave our logger running on batteries. After waiting
getReading. So, if we decided to take a different 10 or 15 minutes, we can plug it back in and see
approach to storing the data, we would only have what data we have by opening the Serial Monitor
to change these two functions. and typing the R command, the results of which
are shown in Figure 5-21. Select all the data,
Putting It All Together including the Time and Temp headings at the top.
Copy the text to the clipboard (press CTRL-C on
Load the completed sketch for Project 13 from
Windows and LINUX, ALT-C on Macs), open a
your Arduino Sketchbook and download it to the
spreadsheet in a program such as Microsoft Excel,
board (see Chapter 1).
and paste it into a new spreadsheet (Figure 5-22).
Now open the Serial Monitor (Figure 5-20), and
Once in the spreadsheet, we can even draw a
for test purposes, we will set the temperature
chart using our data.
logger to log every minute by typing 1 in the Serial
Monitor. The board should respond with the
message “Sample period set to: 1 mins.” If we
Summary
wanted to, we could then change the mode to
Fahrenheit by typing F into the Serial Monitor. We now know how to handle various types of
Now we can check the status of the logger by sensors and input devices to go with our
typing ?. knowledge of LEDs. In the next section we will
In order to unplug the USB cable, we need to look at a number of projects that use light in
have an alternative source of power, such as the various ways and get our hands on some more
battery lead we made back in Project 6. You need advanced display technologies, such as LCD text
to have this plugged in and powered up at the same panels and seven-segment LEDs.
Light Projects
IN THIS CHAPTER, we look at some more projects If you cannot find a four-pin RGB (Red, Green,
based on lights and displays. In particular, we look Blue) LED, you can use a six-pin device instead.
at how to use multicolor LEDs, seven-segment Simply connect the separate anodes together,
LEDs, LED matrix displays, and LCD panels. referring to the datasheet for the component.
Hardware
Project 14
Figure 6-1 shows the schematic diagram for
Multicolor Light Display
Project 14 and Figure 6-2 the breadboard layout.
This project uses a high-brightness, three-color It’s a simple schematic diagram. The rotary
LED in combination with a rotary encoder. encoder has pull-down resistors for the direction
Turning the rotary encoder changes the color sensors and the push switch. For more detail on
displayed by the LED.
rotary encoders and how they work, see Chapter 5.
Each LED has its own series resistor to limit the
CO M P O N E N TS A N D E Q U I P M E N T current to about 30 mA per LED.
85
86 30 Arduino Projects for the Evil Genius
LISTING PROJECT 14
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
int aPin = 6;
int bPin = 7;
int buttonPin = 5;
long colors[48]= {
0xFF2000, 0xFF4000, 0xFF6000, 0xFF8000, 0xFFA000, 0xFFC000, 0xFFE000, 0xFFFF00,
0xE0FF00, 0xC0FF00, 0xA0FF00, 0x80FF00, 0x60FF00, 0x40FF00, 0x20FF00, 0x00FF00,
0x00FF20, 0x00FF40, 0x00FF60, 0x00FF80, 0x00FFA0, 0x00FFC0, 0x00FFE0, 0x00FFFF,
0x00E0FF, 0x00C0FF, 0x00A0FF, 0x0080FF, 0x0060FF, 0x0040FF, 0x0020FF, 0x0000FF,
0x2000FF, 0x4000FF, 0x6000FF, 0x8000FF, 0xA000FF, 0xC000FF, 0xE000FF, 0xFF00FF,
(continued)
88 30 Arduino Projects for the Evil Genius
void setup()
{
pinMode(aPin, INPUT);
pinMode(bPin, INPUT);
pinMode(buttonPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop()
{
if (digitalRead(buttonPin))
{
isOn = ! isOn;
delay(200); // de-bounce
}
if (isOn)
{
int change = getEncoderTurn();
color = color + change;
if (color < 0)
{
color = 47;
}
else if (color > 47)
{
color = 0;
}
setColor(colors[color]);
}
else
{
setColor(0);
}
delay(1);
}
int getEncoderTurn()
{
// return -1, 0, or +1
static int oldA = LOW;
static int oldB = LOW;
int result = 0;
int newA = digitalRead(aPin);
int newB = digitalRead(bPin);
if (newA != oldA || newB != oldB)
{
Chapter 6 ■ Light Projects 89
The 48 colors in the array are chosen from just Seven-segment LEDs (see Figure 6-4) have
such a table, and are a range of colors more or less largely been superseded by backlit LCD displays
spanning the spectrum from red to violet. (see later in this chapter), but they do find uses
from time to time. They also add that “Evil
Putting It All Together Genius” feel to a project.
Figure 6-5 shows the circuit for driving a single
Load the completed sketch for Project 14 from
seven-segment display.
your Arduino Sketchbook and download it to the
board (see Chapter 1).
Seven-Segment LEDs
There was a time when the height of fashion was
an LED watch. This required the wearer to press a
button on the watch for the time to magically
appear as four bright red digits. After a while, the
inconvenience of having to use both limbs to tell
the time overcame the novelty of a digital watch,
and the Evil Genius went out and bought an LCD
watch instead. This could only be read in bright
sunlight.
A single seven-segment LED is not usually a through the base of the transistor and out through
great deal of use. Most projects will want two or the emitter, it allows a much greater current to
four digits. When this is the case, we will not have flow through from the collector to the emitter. We
enough digital output pins to drive each display have met this kind of transistor before in Project 4,
separately and so the arrangement of Figure 6-6 is where we used it to control the current to a high-
used. power Luxeon LED.
Rather like our keyboard scanning, we are going We do not need to limit the current that flows
to activate each display in turn and set the through the collector to the emitter, as this is
segments for that before moving on to the next already limited by the series resistors for the
digit. We do this so fast that the illusion of all LEDs. However, we do need to limit the current
displays being lit is created. flowing into the base. Most transistors will
Each display could potentially draw the current multiply the current by a factor of 100 or more, so
for eight LEDs at once, which could amount to we only need to allow about 2 mA to flow through
160 mA (at 20 mA per LED)—far more than we the base to fully turn on the transistor.
can take from a digital output pin. For this reason, Transistors have the interesting property that
we use a transistor that is switched by a digital under normal use, the voltage between base and
output to enable each display in turn. emitter is a fairly constant 0.6V no matter how
The type of transistor we are using is called a much current is flowing. So, if our Arduino pin
bipolar transistor. It has three connections: the supplies 5V, 0.6 of that will be across the
emitter, base, and collector. When a current flows
Chapter 6 ■ Light Projects 91
Figure 6-6 Driving more than one seven-segment LED from an Arduino board.
switch each display on in turn, we must control the connect between the Arduino board connectors and
positive supply to each of the two common anodes the breadboard. This does mean that there are
in turn. This is in contrast to how we controlled the relatively long and bare resistor leads, so take care
power to the Luxeon LED in Project 4, where we to ensure that none of them are touching each
controlled the power on the ground side of the other. This also accounts for the apparently random
circuit. This all means that we are going to use a allocation of Arduino pins to segments on the LED
different type of transistor. Instead of the NPN display. They are arranged like that for ease of
(negative-positive-negative) transistor we used connection.
before, we need to use a PNP (positive-negative-
positive) transistor. You will notice the different Software
position of the arrow in the circuit symbol for the
transistor to indicate this. We use an array to contain the pins that are
connected to each of the segments “a” to “g” and
If we were using a common cathode seven-
the decimal point. We also use an array to
segment display, then we would have an NPN
determine which segments should be lit to display
transistor, but at the bottom of the circuit rather
any particular digit. This is a two-dimensional
than at the top.
array, where each row represents a separate digit (0
The breadboard layout and photograph of the to 9) and each column a segment (see Listing
project are shown in Figures 6-8 and 6-9. Project 15).
To reduce the number of wires required, the
seven-segment display is placed close to the
Arduino board so that the resistors can directly
Chapter 6 ■ Light Projects 93
LISTING PROJECT 15
byte digits[10][8] = {
// a b c d e f g .
{ 1, 1, 1, 1, 1, 1, 0, 0}, // 0
{ 0, 1, 1, 0, 0, 0, 0, 0}, // 1
{ 1, 1, 0, 1, 1, 0, 1, 0}, // 2
{ 1, 1, 1, 1, 0, 0, 1, 0}, // 3
{ 0, 1, 1, 0, 0, 1, 1, 0}, // 4
{ 1, 0, 1, 1, 0, 1, 1, 0}, // 5
{ 1, 0, 1, 1, 1, 1, 1, 0}, // 6
{ 1, 1, 1, 0, 0, 0, 0, 0}, // 7
{ 1, 1, 1, 1, 1, 1, 1, 0}, // 8
{ 1, 1, 1, 1, 0, 1, 1, 0} // 9
};
void setup()
{
for (int i=0; i < 8; i++)
{
pinMode(segmentPins[i], OUTPUT);
}
pinMode(displayPins[0], OUTPUT);
pinMode(displayPins[0], OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
static int dice1;
static int dice2;
if (digitalRead(buttonPin))
{
dice1 = random(1,7);
dice2 = random(1,7);
}
updateDisplay(dice1, dice2);
}
digitalWrite(displayPins[1], HIGH);
setSegments(value2);
delay(5);
}
void setSegments(int n)
{
for (int i=0; i < 8; i++)
{
digitalWrite(segmentPins[i], ! digits[n][i]);
}
}
To drive both displays, we have to turn each a single lens so that they appear to be one dot. We
display on in turn, setting its segments can then light either one or both LEDs to make a
appropriately. So our loop function must keep the red, green, or orange color.
values that are displayed in each display in The completed project is shown in Figure 6-10.
separate variables: dice1 and dice2.
This project makes use of one of these devices
To throw the dice, we use the random function, and allows multicolor patterns to be displayed on it
and whenever the button is pressed, a new value over the USB connection. As projects go, this one
will be set for dice1 and dice2. This means that the involves a lot of components and will use almost
throw will also depend on how long the button is every connection pin of the Arduino.
pressed for, so we do not need to worry about
seeding the random number generator.
CO M P O N E N TS A N D E Q U I P M E N T
Description Appendix
Putting It All Together
Arduino Diecimila or
Load the completed sketch for Project 15 from
Duemilanove board or clone 1
your Arduino Sketchbook and download it to the
8 by 8 LED array (two-color) 34
board (see Chapter 1).
R1-16 100 ⍀ 0.5W metal film resistor 5
IC1 4017 decade counter 46
Project 16 T1-8 2N7000 42
together and a separate positive connection to each pulse at the “clock” pin. It also has a “reset” pin
LED in the row. that sets the count back to 0. So instead of needing
To drive the matrix, we have to do the same an Arduino board output for each row, we just
kind of trick that we did with the two-digit, need two outputs: one for clock and one for reset.
seven-segment display in Project 15 and switch Each of the outputs of the 4017 is connected to
between columns, each time setting the appropriate a field effect transistor (FET). The only reason that
row of LEDs on and off to create the illusion that we have used an FET rather than a bipolar
all the LEDs are lit at the same time. Actually, transistor is that we can connect the gate of the
only a maximum of 16 (8 red ⫹ 8 green) are on at FET directly to an Arduino board output without
any instant. having to use a current-limiting resistor.
There are 24 leads on the LED array, and only Note that we do not use the first output of the
17 pins on the Arduino that we can easily use (D2- 4017. This is because this pin is on as soon as the
13 and A0-5). So we are going to use an integrated 4017 is reset and this would lead to that column
circuit called a decade counter to control each of being enabled for longer than it should be, making
the columns in turn. that column appear brighter than the others.
The 4017 decade counter has ten output pins, To build this project on the breadboard, we
which take it in turn to go high whenever there is a actually need a bigger breadboard than we have
Chapter 6 ■ Light Projects 97
LISTING PROJECT 16
int row = 0;
int col = 0;
void setup()
{
pinMode(clockPin, OUTPUT);
pinMode(resetPin, OUTPUT);
for (int i = 0; i < 8; i++)
{
pinMode(greenPins[i], OUTPUT);
pinMode(redPins[i], OUTPUT);
}
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch == 'x')
{
clear();
}
if (ch >= 'a' and ch <= 'g')
{
col = 0;
row = ch - 'a';
}
else if (ch >= '0' and ch <= '3')
{
byte pixel = ch - '0';
pixels[row][col] = pixel;
col++;
}
}
refresh();
}
void refresh()
{
pulse(resetPin);
delayMicroseconds(2000);
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
int redPixel = pixels[col][row] & 2;
int greenPixel = pixels[col][row] & 1;
digitalWrite(greenPins[col], greenPixel);
digitalWrite(redPins[col], redPixel);
}
pulse(clockPin);
(continued)
100 30 Arduino Projects for the Evil Genius
delayMicroseconds(1500);
}
}
void clear()
{
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
pixels[row][col] = 0;
}
}
}
function is like the delay function, but allows for the row (a–h) followed immediately by eight
shorter delays to be made. digits. Each digit will be 0 for off, 1 for green, 2
Apart from that, the code is fairly for red, and 3 for orange. So typing a12121212
straightforward. will set the top row to alternating red and green.
When designing patterns to display, it is a good
idea to write out the lines in a text editor or word
Putting It All Together
processor and then paste the entire pattern into the
Load the completed sketch for Project 16 from Serial Monitor.
your Arduino Sketchbook and download it to the You might like to try entering the following:
board (see Chapter 1).
x
You can now try out the project. As soon as it is
a11222211
connected to the USB port and has reset, you b11222211
should see a test pattern of a green outer ring with c11222211
a red ring inside that and then a block of orange in d11111111
the center. e11111111
f11222211
Open the Arduino software’s Serial Monitor and g11222211
type x. This should clear the display. You can now h11111111
change each line of the display by entering a letter
Chapter 6 ■ Light Projects 101
or LCD Displays
x If our project needs to display more than a few
a22222222
numeric digits, we likely want to use an LCD
b12333321
display module. These have the advantage that
c11211211
d11122111 they come with built-in driver electronics, so a lot
e11233211 of the work is already done for us and we do not
f12333321 have to poll round each digit, setting each segment.
g22222222
There is also something of a standard for these
h11111111
devices, so there are lots of devices from different
manufacturers that we can use in the same way.
or
The devices to look for are the ones that use the
x HD44780 driver chip.
a11111111
LCD panels can be quite expensive from retail
b22212221
electronic component suppliers, but if you look on
c11212121
d22212121 the Internet, they can often be bought for a few
e11212121 dollars, particularly if you are willing to buy a few
f22212221 at a time.
g11111111
Figure 6-13 shows a module that can display
h11111111
two rows of 16 characters. Each character is made
up of an array of 7 by 5 segments. So it is just as
This is a really good project for the Evil Genius
well that we do not have to drive each segment
to experiment with. You may like to try and
separately.
produce an animation effect by changing the pixels
array while in the loop.
103
104 30 Arduino Projects for the Evil Genius
LISTING PROJECT 17
#include <LiquidCrystal.h>
void setup()
{
Serial.begin(9600);
lcd.begin(2, 20);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Evil Genius");
lcd.setCursor(0,1);
lcd.print("Rules");
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch == '#')
{
lcd.clear();
}
else if (ch == '/')
{
lcd.setCursor(0,1);
}
else
{
lcd.write(ch);
}
}
}
Chapter 6 ■ Light Projects 105
Sound Projects
AN ARDUINO BOARD can be used to both generate on the Y-axis (vertical axis) of a cathode ray tube
sounds as an output and receive sounds as an input while a timebase mechanism sweeps left to right on
using a microphone. In this chapter, we have the X-axis and then flips back when it reaches the
various “musical instrument” type projects and end. The result will look something like Figure 7-1.
also projects that process sound inputs. These days, cathode ray tubes have largely been
Although not strictly a “sound” project, our first replaced by digital oscilloscopes that use LCD
project is to create a simple oscilloscope so that we displays, but the principles remain the same.
can view the waveform at an analog input. This project reads values from the analog input
and sends them over USB to your computer.
Rather than be received by the Serial Monitor, they
Project 18 are received by a little program that displays them
Oscilloscope in an oscilloscope-like manner. As the signal
changes, so does the shape of the waveform.
An oscilloscope is a device that allows you to see
an electronic signal so that it appears as a Note that as oscilloscopes go, this one is not
waveform. A traditional oscilloscope works by going to win any prizes for accuracy or speed, but
amplifying a signal to control the position of a dot it is kind of fun.
107
108 30 Arduino Projects for the Evil Genius
CO M P O N E N TS A N D E Q U I P M E N T Hardware
LISTING PROJECT 18
To run the software, change directory in your
terminal or command prompt to the directory
#define CHANNEL_A_PIN 0 where you downloaded scope.rb. Then just type:
The amplitude of the signal, as displayed in frequency. If you do this, the sound produced is
Figure 7-1, has a resolution of one pixel per rough and grating. This is called a square wave. To
sample step, there being 256 steps. So if you produce a more pleasing tone, you need a signal that
connect the two test leads together, you should see is more like a sine wave (see Figure 7-5).
a horizontal line halfway across the window. This Generating a sine wave requires a little bit of
corresponds to 0V and is 128 pixels from the top thought and effort. A first idea may be to use the
of the screen, as the window is 256 pixels high. analog output of one of the pins to write out the
This means that since the signal is about two-thirds waveform. However, the problem is that the analog
of the window, the amplitude of the signal is about outputs from an Arduino are not true analog
3V peak to peak. outputs but PWM outputs that turn on and off very
You will notice that the sample rate changes rapidly. In fact, their switching frequency is at an
quite a lot, something that reinforces that this is the audio frequency, so without a lot of care, our
crudest of oscilloscopes and should not be relied signal will sound as bad as a square wave.
on for anything critical. A better way is to use a digital-to-analog
To alter the timebase, change the value in the converter, or DAC as they are known. A DAC has a
delayMicroseconds function. number of digital inputs and produces an output
voltage proportional to the digital input value.
Fortunately, it is easy to make a simple DAC—all
Sound Generation you need are resistors.
You can generate sounds from an Arduino board by Figure 7-6 shows a DAC made from what is
just turning one of its pins on and off at the right called an R-2R resistor ladder.
Project 19
Tune Player
This project will play a series of musical notes
through a miniature loudspeaker using a DAC to
approximate a sine wave.
CO M P O N E N TS A N D E Q U I P M E N T
Description Appendix
Figure 7-6 DAC using an R-2R ladder.
Arduino Diecimila or
Duemilanove board or clone 1
C1 100nF non-polarized 20
C2 100 F, 16V electrolytic 22
R1-5 10 K⍀ 0.5W metal film resistor 9
TABLE 7-1 Analog Output from Digital Inputs
R6-8 4.7 K⍀ 0.5W metal film resistor 8
D3 D2 D1 D0 Output R9 1 M⍀ 0.5W metal film resistor 15
0 0 0 0 0 R10 100 K⍀ linear potentiometer 13
0 0 0 1 1 IC1 TDA7052 1W audio amplifier 47
0 0 1 0 2 Miniature 8 ⍀ loudspeaker 59
0 0 1 1 3
0 1 0 0 4 If you can get a miniature loudspeaker with
0 1 0 1 5 leads for soldering to a PCB, then this can be
0 1 1 0 6 plugged directly into the breadboard. If not, you
0 1 1 1 7 will either have to solder short lengths of solid-
core wire to the terminals or, if you do not have
1 0 0 0 8
access to a soldering iron, carefully twist some
1 0 0 1 9
wires round the terminals.
1 0 1 0 10
1 0 1 1 11
1 1 0 0 12
1 1 0 1 13
1 1 1 0 14
1 1 1 1 15
Chapter 7 ■ Sound Projects 113
LISTING PROJECT 19
// Scale
//char* song = "A B C D E F G a b c d e f g";
// Jingle Bells
//char* song = "E E EE E E EE E G C D EEEE F F F F F E E E E D D E DD GG E E EE
E E EE E G C D EEEE F F F F F E E E G G F D CCCC";
void setup()
{
for (int i = 0; i < 4; i++)
{
pinMode(dacPins[i], OUTPUT);
}
}
void loop()
Chapter 7 ■ Sound Projects 115
{
int i = 0;
char ch = song[0];
while (ch != 0)
{
if (ch == ' ')
{
delay(75);
}
else if (ch >= 'A' and ch <= 'G')
{
playNote(lowToneDurations[ch - 'A']);
}
else if (ch >= 'a' and ch <= 'g')
{
playNote(highToneDurations[ch - 'a']);
}
i++;
ch = song[i];
}
delay(5000);
}
The playNote function calls setOutput to set the You might like to change the tune played from
value of the four digital pins connected to the “Jingle Bells.” To do this, just comment out the
resistor ladder. The & (and) operator is used to line starting with “char* song =” by putting // in
mask the value so that we only see the value of the front of it and then define your own array.
bit we are interested in. The notation works as follows. There are two
Tunes are played from an array of characters, octaves, and high notes are lowercase “a” to “g”
each character corresponding to a note, and a space and low notes “A” to “G.” For a longer duration
corresponding to the silence between notes. The note, just repeat the note letter without putting a
main loop looks at each letter in the song variable space in between.
and plays it. When the whole song is played, there You will have noticed that the quality is not
is a pause of five seconds and then the song begins great. It is still a lot less nasty than using a square
again. wave, but is a long way from the tunefulness of a
The Evil Genius will find this project useful for real musical instrument, where each note has an
inflicting discomfort on his or her enemies. “envelope” where the amplitude (volume) of the
note varies with the note as it is played.
Putting It All Together
Load the completed sketch for Project 19 from
your Arduino Sketchbook and download it to the
board (see Chapter 1).
Chapter 7 ■ Sound Projects 117
Project 20 Hardware
Light Harp The volume of the sound will be controlled using a
PWM output (D6) connected to the volume control
This project is really an adaptation of Project 19
input of the TDA7052. We want to eliminate all
that uses two light sensors (LDRs): one that
traces of the PWM pulses so we can pass the
controls the pitch of the sound, the other to control
output through a low-pass filter consisting of R11
the volume. This is inspired by the Theremin
and C3. This allows only slow changes in the
musical instrument that is played by mysteriously
signal to get past. One way to think of this is to
waving your hands about between two antennae. In
pretend that the capacitor C3 is a bucket that is
actual fact, this project produces a sound more like
filled with charge from resistor R11. Rapid
a bagpipe than a harp, but it is quite fun.
fluctuations in the signal will have little effect, as
there is a smoothing (integration) of the signal.
CO M P O N E N TS A N D E Q U I P M E N T Figures 7-10 and 7-11 show the schematic
Description Appendix diagram and breadboard layout for the project and
you can see the final project in Figure 7-12.
Arduino Diecimila or
Duemilanove board or clone 1 The LDRs, R14 and R15, are positioned at
C1 100nF un-polarized 20 opposite ends of the breadboard to make it easier
to play the instrument with two hands.
C2, C3 100 F, 16V electrolytic 22
R1-5 10 K⍀ 0.5W metal film
resistor 9 Software
R6-8 4.7 K⍀ 0.5W metal film The software for this project has a lot in common
resistor 8
with Project 19 (see Listing Project 20).
R9, R11 1 M⍀ 0.5W metal film resistor 15
The main differences are that the pitchDelay
R10 100 K⍀ 0.5W metal film
period is set by the value of the analog input 0.
resistor 13
This is then scaled to the right range using the map
R12, R13 47 K⍀ 0.5W metal film
function. Similarly, the volume voltage is set by
resistor 11
reading the value of analog input 1, scaling it using
R14, R15 LDR 19
map, and then writing it out to PWM output 6. It
IC1 TDA7052 1W audio amplifier 47 would be possible to just use the LDR R14 to
Miniature 8 ⍀ loudspeaker 59 directly control the output of the resistor ladder,
but this way gives us more control over scaling and
offsetting the output, and we wanted to illustrate
If you can get a miniature loudspeaker with smoothing a PWM signal to use it for generating a
leads for soldering to a PCB, then this can be steady output.
plugged directly into the breadboard. If not, you
will either have to solder short lengths of solid-
core wire to the terminals or, if you do not have
access to a soldering iron, carefully twist some
solid-core wires round the terminals.
118 30 Arduino Projects for the Evil Genius
LISTING PROJECT 20
int pitchInputPin = 0;
int volumeInputPin = 1;
int volumeOutputPin = 6;
int count = 0;
void setup()
{
for (int i = 0; i < 4; i++)
{
pinMode(dacPins[i], OUTPUT);
}
pinMode(volumeOutputPin, OUTPUT);
}
(continued)
120 30 Arduino Projects for the Evil Genius
void loop()
{
int pitchDelay = map(analogRead(pitchInputPin), 0, 1023, 10, 60);
int volume = map(analogRead(volumeInputPin), 0, 1023, 10, 70);
for (int i = 0; i < 32; i++)
{
setOutput(sin16[i]);
delayMicroseconds(pitchDelay);
}
if (count == 10)
{
analogWrite(volumeOutputPin, volume);
count = 0;
}
count++;
}
Hardware
CO M P O N E N TS A N D E Q U I P M E N T
The schematic diagram for this project is shown in
Description Appendix
Figure 7-14. The bar graph LED package has
Arduino Diecimila or separate connections for each LED. These are each
Duemilanove board or
driven through a current-limiting resistor.
clone 1
R1, R3, R4 10 K⍀ 0.5W metal film
The microphone will not produce a strong
resistor 9 enough signal on its own to drive the analog input.
R2 100 K⍀ 0.5W metal film
So to boost the signal, we use a simple single-
resistor 13 transistor amplifier. We use a standard arrangement
R5-14 270 ⍀ 0.5W metal film
called collector-feedback bias, where a proportion
resistor 6 of the voltage at the collector is used to bias the
R10 10 K⍀ 0.5W metal film
transistor on so that it amplifies in a loosely linear
resistor 9 way rather than just harshly switching on and off.
C1 100 nF 20 The breadboard layout is shown in Figure 7-15.
10 Segment bar graph With so many LEDs, a lot of wires are required.
display 35
S1 Push to make switch 48 Software
Electret microphone 60
The sketch for this project (Listing Project 21)
uses an array of LED pins to shorten the setup
function. This is also used in the loop function,
where we iterate over each LED deciding whether
to turn it on or off.
122 30 Arduino Projects for the Evil Genius
LISTING PROJECT 21
void setup()
{
for (int i = 0; i < 10; i++)
{
pinMode(ledPins[i], OUTPUT);
}
pinMode(switchPin, INPUT);
}
void loop()
{
if (digitalRead(switchPin))
{
showPeak = ! showPeak;
peakValue = 0;
delay(200); // debounce switch
}
int value = analogRead(soundPin);
int topLED = map(value, 0, 1023, 0, 11) - 1;
if (topLED > peakValue)
{
peakValue = topLED;
}
for (int i = 0; i < 10; i++)
{
digitalWrite(ledPins[i], (i <= topLED || (showPeak && i == peakValue)));
}
}
At the top of the loop function, we check to see The level of sound is read from analog pin 0,
if the switch is depressed; if it is, we toggle the and then we use the map function to convert from
mode. The ! command inverts a value, so it will a range of 0 to 1023 down to a number between 0
turn true into false and false into true. For this and 9, which will be the top LED to be lit. This is
reason, it is sometimes referred to as the adjusted slightly by extending the range up to 0 to
“marketing operator.” After changing the mode, we 11 and then subtracting 1. This prevents the two
reset the maximum value to 0 and then delay for bottom-most LEDs being permanently lit due to
200 milliseconds to prevent keyboard bounce from the transistor bias.
changing the mode straight back again.
124 30 Arduino Projects for the Evil Genius
Power Projects
HAVING LOOKED AT LIGHT and sound, the Evil If the reader decides to use this project to switch
Genius now turns their attention to controlling mains electricity, they should only do so if they
power. In essence, that means turning things on really know what they are doing and exercise
and off and controlling their speed. This mostly extreme caution. Mains electricity is very
applies to motors and lasers and the long-awaited dangerous and kills about 500 people a year in the
Servo-Controlled Laser project. United States alone. Many more suffer painful and
damaging burns.
Project 22 CO M P O N E N TS A N D E Q U I P M E N T
LCD Thermostat
Description Appendix
The temperature in the Evil Genius’ lair must be
Arduino Diecimila or
regulated, as the Evil Genius is particularly
Duemilanove board or clone 1
susceptible to chills. This project uses an LCD
R1 33 K⍀ thermistor beta = 4090 18
screen and a thermistor temperature sensor to both
R2 33 K⍀ 0.5W metal film resistor 10
display the current temperature and the set
temperature. It uses a rotary encoder to allow the R3-5 100 K⍀ 0.5W metal film resistor 13
set temperature to be changed. The rotary R6 270 ⍀ 0.5W metal film resistor 6
encoder’s button also acts as an override switch. R7 1 K⍀ 0.5W metal film resistor 7
When the measured temperature is less than the D1 5-mm red LED 23
set temperature, a relay is activated. Relays are D2 1N4004 38
old-fashioned electromagnetic components that T1 BC548 40
activate a mechanical switch when a current flows 5V relay 61
through a coil of wire. They have a number of
LCD module HD44780 58
advantages. First, they can switch high currents
Header pin strip 55
and voltages, making them suitable for controlling
mains equipment. They also electrically isolate the
control side (the coil) from the switching side so
that the high and low voltages never meet, which is
definitely a good thing.
125
126 30 Arduino Projects for the Evil Genius
LISTING PROJECT 22
#include <LiquidCrystal.h>
void setup()
{
lcd.begin(2, 20);
pinMode(ledPin, OUTPUT);
pinMode(relayPin, OUTPUT);
pinMode(aPin, INPUT);
pinMode(bPin, INPUT);
pinMode(buttonPin, INPUT);
lcd.clear();
}
void loop()
{
static int count = 0;
measuredTemp = readTemp();
if (digitalRead(buttonPin))
{
override = ! override;
updateDisplay();
delay(500); // debounce
}
int change = getEncoderTurn();
setTemp = setTemp + change * 0.1;
if (count == 1000)
{
updateDisplay();
updateOutputs();
count = 0;
}
count ++;
}
int getEncoderTurn()
{
// return -1, 0, or +1
static int oldA = LOW;
static int oldB = LOW;
int result = 0;
int newA = digitalRead(aPin);
int newB = digitalRead(bPin);
if (newA != oldA || newB != oldB)
{
// something has changed
if (oldA == LOW && newA == HIGH)
Chapter 8 I Power Projects 129
{
result = -(oldB * 2 - 1);
}
}
oldA = newA;
oldB = newB;
return result;
}
float readTemp()
{
long a = analogRead(analogPin);
float temp = beta / (log(((1025.0 * resistance / a) - 33.0) / 33.0) +
(beta / 298.0)) - 273.0;
return temp;
}
void updateOutputs()
{
if (override || measuredTemp < setTemp - hysteresis)
{
digitalWrite(ledPin, HIGH);
digitalWrite(relayPin, HIGH);
}
else if (!override && measuredTemp > setTemp + hysteresis)
{
digitalWrite(ledPin, LOW);
digitalWrite(relayPin, LOW);
}
}
void updateDisplay()
{
lcd.setCursor(0,0);
lcd.print("Actual: ");
lcd.print(adjustUnits(measuredTemp));
lcd.print(" o");
lcd.print(mode);
lcd.print(" ");
lcd.setCursor(0,1);
if (override)
{
lcd.print(" OVERRIDE ON ");
}
else
(continued)
130 30 Arduino Projects for the Evil Genius
{
lcd.print("Set: ");
lcd.print(adjustUnits(setTemp));
lcd.print(" o");
lcd.print(mode);
lcd.print(" ");
}
}
occurs when you have a simple on-off control plus the hysteresis value. Similarly, as the
system. When the temperature falls below the set temperature falls, the power is not reapplied the
point, the power is turned on and the room heats moment it falls below the set point, but only when
until it is above the set point, and then the room it falls below the set point minus the hysteresis
cools until the temperature is below the set point value.
again, at which point the heat is turned on again, We do not want to update the display
and so on. This may take a little time to happen, continuously, as any tiny changes in the reading
but when the temperature is just balanced at the would result in the display flickering wildly. So
switch-over temperature, this hunting can be
frequent. High-frequency switching like this is
undesirable because turning things on and off tends
to wear them out. This is true of relays as well.
One way to minimize this effect is to introduce
something called hysteresis, and you may have
noticed a variable called hysteresis in the sketch
that is set to a value of 0.25°C.
Figure 8-3 shows how we use a hysteresis value
to prevent high-frequency hunting.
As the temperature rises with the power on, it
approaches the set point. However, it does not turn
off the power until it has exceeded the set point Figure 8-3 Hysteresis in control systems.
Chapter 8 I Power Projects 131
instead of updating the display every time round The completed project is shown in Figure 8-4.
the main loop, we just do it one time in 1000. This To test the project, turn the rotary encoder, setting
still means it will update three or four times per the set temperature to slightly above the actual
second. To do this, we use the technique of having temperature. The LED should be on. Then put your
a counter variable that we increment each time finger onto the thermistor to warm it up. If all is
round the loop. When it gets to 1000, we update well, then when the set temperature is exceeded,
the display and reset the counter to 0. the LED should turn off and you will hear the
Using lcd.clear() each time we change the relay click.
display would also cause it to flicker. So we You can also test the operation of the relay by
simply write the new temperatures on top of the connecting a multimeter in continuity test (beep)
old temperatures. This is why we pad the mode to the switched output leads.
“OVERRIDE ON” message with spaces so that I cannot stress enough that if you intend to use
any text that was previously displayed at the edges your relay to switch mains electricity, first put this
will be blanked out. project onto a properly soldered Protoshield.
Second, be very careful and check and double-
Putting It All Together check what you are doing. Mains electricity kills.
Load the completed sketch for Project 22 from You must only test the relay with low voltage
your Arduino Sketchbook and download it to the unless you are going to make a proper soldered
board (see Chapter 1). project from this design.
LISTING PROJECT 23
void setup()
{
pinMode(motorPin, OUTPUT);
analogWrite(motorPin, 0);
Serial.begin(9600);
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch >= ‘0’ && ch <= ‘9’)
Figure 8-6 Schematic diagram for Project 23. {
int speed = ch - ‘0’;
analogWrite(motorPin, speed
Putting It All Together * 28);
}
Load the completed sketch for Project 23 from }
your Arduino Sketchbook and download it to the }
board (see Chapter 1).
There are so few components in this project that
you could twist a few wires together and fit them
directly into the Arduino board, thus doing away
with the breadboard altogether.
H-Bridge Controllers +V
CO M P O N E N TS A N D E Q U I P M E N T Hardware
LISTING PROJECT 24
int t1Pin = 5;
int t3Pin = 6;
int speeds[] = {20, 40, 80, 120, 160, 180, 160, 120, 80, 40, 20,
-20, -40, -80, -120, -160, -180, -160, -120, -80, -40, -20};
int i = 0;
void setup()
{
pinMode(t1Pin, OUTPUT);
digitalWrite(t1Pin, LOW);
pinMode(t3Pin, OUTPUT);
digitalWrite(t3Pin, LOW);
}
void loop()
{
int speed = speeds[i];
i++;
if (i == 22)
{
i = 0;
}
drive(speed);
delay(1500);
}
void allOff()
{
digitalWrite(t1Pin, LOW);
digitalWrite(t3Pin, LOW);
delay(1);
}
Before turning any transistor on, all the provide them with is power (which, for many
transistors are turned off using the allOff function. devices, can be 5V) and a control signal that we
In addition, the allOff function includes a slight can generate from the Arduino board.
delay to ensure that the transistors are properly off Over the years, the interface to servos has
before anything is turned on. become standardized. The servo must receive a
The sketch uses an array, speeds, to control the continuous stream of pulses at least every 20
disk’s progression in speed. This makes the disk milliseconds. The angle that the servo maintains is
spin faster and faster in one direction, and then determined by the pulse width. A pulse width of
slow until it eventually reverses direction and then 1.5 milliseconds will set the servo at its midpoint,
starts getting faster and faster in that direction and or 90 degrees. A pulse of 1.75 milliseconds will
so on. You may need to adjust this array for your normally swing it round to 180 degrees, and a
particular motor. The speeds you will need to shorter pulse of 1.25 milliseconds will set the
specify in the array will vary from motor to motor, angle to 0 degrees.
so you will probably need to adjust these values.
LISTING PROJECT 25
#include <Servo.h>
int laserPin = 4;
Servo servoV;
Servo servoH;
int x = 90;
int y = 90;
int minX = 10;
int maxX = 170;
int minY = 50;
int maxY = 130;
void setup()
{
servoH.attach(3);
servoV.attach(2);
pinMode(laserPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
char ch;
if (Serial.available())
{
ch = Serial.read();
if (ch == '0')
{
digitalWrite(laserPin, LOW);
}
else if (ch == '1')
{
digitalWrite(laserPin, HIGH);
}
else if (ch == '-')
{
delay(100);
}
else if (ch == 'c')
{
x = 90;
y = 90;
}
else if (ch == 'l' || ch == 'r' || ch == 'u' || ch == 'd')
{
(continued)
142 30 Arduino Projects for the Evil Genius
moveLaser(ch, 1);
}
else if (ch == 'L' || ch == 'R' || ch == 'U' || ch == 'D')
{
moveLaser(ch, 5);
}
}
servoH.write(x);
servoV.write(y);
}
Open up the Serial Monitor and type the The top and bottom sides of the shield are
following sequence. You should see the laser trace shown in Figures 8-17 and 8-18.
the letter A, as shown in Figure 8-16:
1UUUUUU—RRRR—DDDDDD—0UUU—1LLLL—0DDD
Summary
Making a Shield In the previous chapters we have built up our
knowledge to understand how to use light, sound,
Creating a shield is no problem at all for this
and various sensors on the Arduino. We have also
project. The bottom servo can be glued in place on
learned how to control the power to motors and to
one edge of the board. The pin headers are
use relays. This covers nearly everything we are
soldered in place near the 5V and GND lines that
likely to want to do with our Arduino board, so in
run down the center of the shield so that they can
the next chapter, we can put all these things
be connected easily to the positive and negative
together to create some wider-ranging projects.
pins on the servo connectors.
Chapter 8 I Power Projects 143
Figure 8-16 Writing the letter A with the laser. Figure 8-17 Servo laser shield.
Miscellaneous Projects
THIS CHAPTER IS JUST a collection of projects that 9-1) uses an effect known as galvanic skin
we can build. They do not illustrate any particular response. As a person becomes nervous—for
point except that Arduino projects are great fun to example, when telling a lie—their skin resistance
make. decreases. We can measure this resistance using an
analog input and use an LED and buzzer to
indicate an untruth.
Project 26 We use a multicolor LED that will display red
Lie Detector to indicate a lie, green to indicate a truth, and blue
to show that the lie detector should be adjusted by
How can an Evil Genius be sure that their
twiddling the variable resistor.
prisoners are telling the truth? By using a lie
detector, of course. This lie detector (see Figure
145
146 30 Arduino Projects for the Evil Genius
CO M P O N E N TS A N D E Q U I P M E N T Hardware
}
setColor(green);
Project 27
} Magnetic Door Lock
This project (Figure 9-4) is based on Project 10,
void setColor(long rgb) but extends it so that when the correct code is
{ entered, it lights a green LED in addition to
int red = rgb >> 16; operating a small solenoid. The sketch is also
int green = (rgb >> 8) & 0xFF; improved so that the secret code can be changed
int blue = rgb & 0xFF; without having to modify and install a new script.
analogWrite(redPin, 255 - red);
The secret code is stored in EEPROM, so if the
analogWrite(greenPin, 255 - green);
analogWrite(bluePin, 255 - blue);
power is disconnected, the code will not be lost.
}
CO M P O N E N TS A N D E Q U I P M E N T
void beep()
{ Description Appendix
// 5 Khz for 1/5th second
Arduino Diecimila or
for (int i = 0; i < 1000; i++)
Duemilanove board or clone 1
{
digitalWrite(buzzerPin, HIGH); D1 Red 5-mm LED 23
delayMicroseconds(100); D2 Green 5-mm LED 25
digitalWrite(buzzerPin, LOW);
R1-3 270 ⍀ 0.5W metal film resistor 6
delayMicroseconds(100);
} K1 4 x 3 keypad 54
} 0.1-inch header strip 55
T1 BC548 40
5V solenoid (< 100 mA) 66
D3 1N4004 38
Chapter 9 ■ Miscellaneous Projects 149
components. Like relays, the solenoid is an If the solenoid can be mounted on the
inductive load and therefore liable to generate a breadboard, this is all well and good. If not, you
back EMF, which diode D3 protects against. will need to attach leads to it that connect it to the
The solenoid is controlled by T1, so be careful breadboard.
to select a solenoid that will not draw more than
100 mA, which is the maximum collector current Software
of the transistor.
The software for this project is, as you would
We are using a very low power solenoid, and expect, similar to that of Project 10 (see Project
this would not keep intruders out of the Evil Listing 27).
Genius’ lair. If you are using a more substantial
solenoid, a BD139 transistor would be better.
LISTING PROJECT 27
#include <Keypad.h>
#include <EEPROM.h>
int redPin = 9;
int greenPin = 8;
int solenoidPin = 10;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
loadCode();
flash();
updateOutputs();
}
void loop()
{
char key = keypad.getKey();
if (key == '*' && ! locked)
{
// unlocked and * pressed so change code
position = 0;
getNewCode();
updateOutputs();
}
if (key == '#')
{
locked = true;
position = 0;
updateOutputs();
}
if (key == secretCode[position])
{
position ++;
}
if (position == 4)
{
locked = false;
updateOutputs();
}
delay(100);
}
void updateOutputs()
{
if (locked)
{
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(solenoidPin, HIGH);
}
else
(continued)
152 30 Arduino Projects for the Evil Genius
{
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(solenoidPin, LOW);
}
}
void getNewCode()
{
flash();
for (int i = 0; i < 4; i++ )
{
char key;
key = keypad.getKey();
while (key == 0)
{
key = keypad.getKey();
}
flash();
secretCode[i] = key;
}
saveCode();
flash();flash();
}
void loadCode()
{
if (EEPROM.read(0) == 1)
{
secretCode[0] = EEPROM.read(1);
secretCode[1] = EEPROM.read(2);
secretCode[2] = EEPROM.read(3);
secretCode[3] = EEPROM.read(4);
}
}
void saveCode()
{
EEPROM.write(1, secretCode[0]);
EEPROM.write(2, secretCode[1]);
EEPROM.write(3, secretCode[2]);
EEPROM.write(4, secretCode[3]);
EEPROM.write(0, 1);
}
void flash()
{
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, HIGH);
delay(500);
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
}
Chapter 9 ■ Miscellaneous Projects 153
Since we can now change the secret code, we If you forget your secret code, unfortunately,
have changed the loop function so that if the * key turning the power to the project on and off will not
is pressed while the lock is in its unlocked state, reset it to 1234. Instead, you will have to comment
the next four keys pressed will be the new code. out the line:
Since each character is exactly one byte in loadCode();
length, the code can be stored directly in the
EEPROM memory. We use the first byte of in the setup function, so that it appears as shown
EEPROM to indicate if the code has been set. If it here:
has not been set, the code will default to 1234.
Once the code has been set, the first EEPROM // loadCode();
We use the EEPROM memory to store the The IR transmitter is an IR LED. These work
remote control codes so that they are not lost when just like a regular red LED, but in the invisible IR
the Arduino board is disconnected. end of the spectrum. On some devices, you can see
a slight red glow when they are on.
CO M P O N E N TS A N D E Q U I P M E N T Figure 9-9 shows the breadboard layout for this
project.
Description Appendix
Arduino Diecimila or
Software
Duemilanove board or clone 1
R1 100 ⍀ 0.5W metal film resistor 5 Ken Shirriff has created a library that you can use
D1 IR LED sender 26 to do just about anything you would want to with
an IR remote. We are going to use this library
IC1 IR remote control receiver 37
rather than reinvent the wheel.
We first looked at installing a library in Chapter
Hardware 5. To make use of this library, we must first
download it from http://arcfn.com/2009/08/
The IR remote receiver is a great little module that
multi-protocol-infrared-remote-library.html.
combines an infrared photodiode, with all the
amplification filtering and smoothing needed to Download the file IRRemote.zip and unzip it. If
produce a digital output from the IR message. This you are using Windows, you right-click and choose
output is fed to digital pin 9. The schematic Extract All and then save the whole folder into
diagram (see Figure 9-8) shows how simple this C:\Program Files\Arduino\Arduino-0017\hardware\
package is to use, with just three pins, GND, +V, libraries.
and the output signal.
On LINUX, find the Arduino installation only uses a small part of the library concerned
directory and copy the folder into with capturing and sending the raw pulses of data.
hardware/libraries. (See Listing Project 28.)
On a Mac, you do not put the new library into Infrared remote controls send a series of pulses
the Arduino installation. Instead, you create a at a frequency of between 36 and 40kHz. Figure
folder called “libraries” in Documents/Arduino and 9-10 shows the trace from an oscilloscope.
put the whole library folder in there. A bit value of 1 is represented by a pulse of
Once we have installed this library into our square waves at 36 to 40kHz and a 0 by a pause in
Arduino directory, we will be able to use it with which no square waves are sent.
any sketches that we write.
Ken’s library is essentially the last word in
decoding and sending IR commands. It will
attempt to match the different protocol standards
from different manufacturers. Our sketch actually
LISTING PROJECT 28
#include <EEPROM.h>
#include <IRremote.h>
int irRxPin = 9;
IRrecv irrecv(irRxPin);
IRsend irsend;
decode_results results;
int codeLength = 0;
int currentCode = 0;
void setup()
{
Serial.begin(9600);
Serial.println("0-9 to set code memory, s - to send");
irrecv.enableIRIn();
setCodeMemory(0);
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch >= '0' && ch <= '9')
{
setCodeMemory(ch - '0');
}
else if (ch == 's')
{
sendIR();
}
}
if (irrecv.decode(&results))
{
storeCode();
irrecv.resume();
}
}
void setCodeMemory(int x)
{
currentCode = x;
Serial.print("Set current code memory to: ");
Chapter 9 ■ Miscellaneous Projects 157
Serial.println(currentCode);
irrecv.resume();
}
void storeCode()
{
// write the code to EEPROM, first byte is length
int startIndex = currentCode * (RAWBUF + 1);
int len = results.rawlen - 1;
EEPROM.write(startIndex, (unsigned byte)len);
for (int i = 0; i < len; i++)
{
if (results.rawbuf[i] > 255)
{
EEPROM.write(startIndex + i + 1, 255);
}
else
{
EEPROM.write(startIndex + i + 1, results.rawbuf[i]);
}
}
Serial.print("Saved code, length: ");
Serial.println(len);
}
void sendIR()
{
// construct a buffer from the saved data in EEPROM and send it
int startIndex = currentCode * (RAWBUF + 1);
int len = EEPROM.read(startIndex);
unsigned int code[RAWBUF];
for (int i = 0; i < len; i++)
{
int pulseLen = EEPROM.read(startIndex + i + 2);
if (i % 2)
{
code[i] = pulseLen * USECPERTICK + MARK_EXCESS;
}
else
{
code[i] = pulseLen * USECPERTICK - MARK_EXCESS;
}
}
irsend.sendRaw(code, len, f);
Serial.print("Sent code length: ");
Serial.println(len);
}
158 30 Arduino Projects for the Evil Genius
Project 29
Lilypad Clock
The Arduino Lilypad works in much the same way
as the Duemilanove board, but instead of a boring
rectangular circuit board, the Lilypad is circular
and designed to be stitched into clothing using
conductive thread. Even an Evil Genius appreciates
beauty when they see it. So this project is built into
a photo frame to show off the natural beauty of the
electronics (see Figure 9-11). A magnetic reed
switch is used to adjust the time.
This is a project where you have to use a
soldering iron.
CO M P O N E N TS A N D E Q U I P M E N T
Description Appendix
Figure 9-13 Close-up of LED attached to a Figure 9-14 Bottom side of Lilypad board.
resistor.
Chapter 9 ■ Miscellaneous Projects 161
LISTING PROJECT 30
#include <EEPROM.h>
byte digits[10][8] = {
// a b c d e f g .
{ 1, 1, 1, 1, 1, 1, 0, 0}, // 0
{ 0, 1, 1, 0, 0, 0, 0, 0}, // 1
{ 1, 1, 0, 1, 1, 0, 1, 0}, // 2
{ 1, 1, 1, 1, 0, 0, 1, 0}, // 3
{ 0, 1, 1, 0, 0, 1, 1, 0}, // 4
{ 1, 0, 1, 1, 0, 1, 1, 0}, // 5
{ 1, 0, 1, 1, 1, 1, 1, 0}, // 6
{ 1, 1, 1, 0, 0, 0, 0, 0}, // 7
{ 1, 1, 1, 1, 1, 1, 1, 0}, // 8
{ 1, 1, 1, 1, 0, 1, 1, 0} // 9
};
void setup()
{
for (int i=0; i < 8; i++)
{
pinMode(segmentPins[i], OUTPUT);
}
for (int i=0; i < 4; i++)
{
pinMode(displayPins[i], OUTPUT);
}
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(aPin, INPUT);
pinMode(bPin, INPUT);
selectedTimeIndex = EEPROM.read(0);
timerMinute = times[selectedTimeIndex] / 100;
timerSecond = times[selectedTimeIndex] % 100;
(continued)
166 30 Arduino Projects for the Evil Genius
void loop()
{
if (digitalRead(buttonPin))
{
stopped = ! stopped;
digitalWrite(buzzerPin, LOW);
while (digitalRead(buttonPin)) {};
EEPROM.write(0, selectedTimeIndex);
}
updateDisplay();
}
void process()
{
for (int i = 0; i < 100; i++) // tweak this number between flicker and blur
{
int change = getEncoderTurn();
if (stopped)
{
changeSetTime(change);
}
else
{
updateCountingTime();
}
}
if (timerMinute == 0 && timerSecond == 0)
{
digitalWrite(buzzerPin, HIGH);
}
{
selectedTimeIndex += change;
if (selectedTimeIndex < 0)
{
selectedTimeIndex = numTimes;
}
else if (selectedTimeIndex > numTimes)
{
selectedTimeIndex = 0;
}
timerMinute = times[selectedTimeIndex] / 100;
timerSecond = times[selectedTimeIndex] % 100;
}
void updateCountingTime()
{
static unsigned long lastMillis;
unsigned long m = millis();
if (m > (lastMillis + 1000) && (timerSecond > 0 || timerMinute > 0))
{
digitalWrite(buzzerPin, HIGH);
delay(10);
digitalWrite(buzzerPin, LOW);
if (timerSecond == 0)
{
timerSecond = 59;
timerMinute —;
}
else
{
timerSecond —;
}
lastMillis = m;
}
}
void setSegments(int n)
{
for (int i = 0; i < 8; i++)
{
digitalWrite(segmentPins[i], ! digits[n][i]);
(continued)
168 30 Arduino Projects for the Evil Genius
}
}
int getEncoderTurn()
{
// return -1, 0, or +1
static int oldA = LOW;
static int oldB = LOW;
int result = 0;
int newA = digitalRead(aPin);
int newB = digitalRead(bPin);
if (newA != oldA || newB != oldB)
{
// something has changed
if (oldA == LOW && newA == HIGH)
{
result = -(oldB * 2 - 1);
}
}
oldA = newA;
oldB = newB;
return result;
}
The timer will always be in one of two states. It Putting It All Together
will either be stopped, in which case, turning the
Load the completed sketch for Project 30 from
rotary encoder will change the time, or it can be
your Arduino Sketchbook and download it to the
running, in which case it will be counting down.
board (see Chapter 1).
Pressing the button on the rotary encoder will
toggle between the two states.
Rather than make the rotary encoder change the Summary
time one second per rotation step, we have an
array of standard times that fit with the egg- This is the final chapter containing projects. The
cooking habits of the Evil Genius. This array can author hopes that in trying the projects in this
be edited and extended, but if you change its book, the Evil Genius’ appetite for experimentation
length, you must alter the numTimes variable and design has been stirred and they will have the
accordingly. urge to design some projects of their own.
The EEPROM library is used to store the last The next chapter sets out to help you in the
used time so that each time the project is powered process of developing your own projects.
up, it will remember the last time used.
The project makes a little chirp as each second
ticks by. You may wish to disable this. You will
find the relevant lines of code to comment out or
delete this in the updateCountTime function.
CHAPTER 10
Your Projects
SO, YOU HAVE TRIED your hand at some of the projects in this book, it does not normally matter
author’s projects and hopefully learned something how the connection is made. The arrangement of
along the way. Now it’s time to start developing the actual wires does not matter as long as all the
your own projects using what you have learned. points are connected.
You will be able to borrow bits of design from the Schematic diagrams have a few conventions that
projects in this book, but to help you along, this are worth pointing out. For instance, it is common
chapter gets you started with some design and to place GND lines near the bottom of the diagram
construction techniques. and higher voltages near the top of the diagram.
This allows someone reading the schematic to
visualize the flow of charge through the system
Circuits from higher voltages to lower voltages.
The author likes to start a project with a vague Another convention in schematic diagrams is to
notion of what he wants to achieve and then start use the little bar symbol to indicate a connection to
designing from the perspective of the electronics. GND where there is not enough room to draw all
The software usually comes afterwards. the connections.
The way to express an electronic circuit is to Figure 10-1, originally from Project 5, shows
use a schematic diagram. The author has included three resistors, all with one lead connected to the
schematic diagrams for all the projects in this GND connection of the Arduino board. In the
book, so even if you are not very familiar with corresponding breadboard layout (Figure 10-2),
electronics, you should now have seen enough you can see that the connections to GND go
schematics to understand roughly how they relate through three wires and three strips of breadboard
to the breadboard layout diagrams also included. connector block.
There are many different tools for drawing
Schematic Diagrams schematic diagrams. Some of them are integrated-
electronics CAD (computer-aided design) products
In a schematic diagram, connections between
that will go on to lay out the tracks on a printed
components are shown as lines. These connections
circuit board for you. By and large, these create
will use the connective strips beneath the surface
fairly ugly-looking diagrams, and the author
of the breadboard and the wires connecting one
prefers to use pencil and paper or general-purpose
breadboard strip to another. For the kinds of
drawing software. All the diagrams for this book
169
170 30 Arduino Projects for the Evil Genius
Transistors
Browse through any component catalog and you
will find literally thousands of different transistor
types. In this book, the list has been simplified to
what’s shown in Table 10-2.
The basic switch circuit for a transistor is shown
in Figure 10-5.
The current flowing from base to emitter (b to
e) controls the larger current flowing from the
collector to emitter. If no current flows into the
base, then no current will flow through the load. In
most transistors, if the load had zero resistance, the
current flowing into the collector would be 50 to
200 times the base current. However, we are going
to be switching our transistor fully on or fully off,
so the load resistance will always limit the
Figure 10-5 Basic transistor switch circuit.
collector current to the current required by the
load. Too much base current will damage the
transistor and also rather defeat the objective of R ⫽ V/I
controlling a bigger current with a smaller one, so R ⫽ (5 ⫺ 0.6)/30 ⫽ 147 ⍀
the base will have a resistor connected to it.
The – 0.6 is because one characteristic of
When switching from an Arduino board, the
bipolar transistors is that there is always a voltage
maximum current of an output is 40 mA, so we
of about 0.6V between base and emitter when a
could choose a resistor that allows about 30 mA to
transistor is turned on.
flow when the output pin is high at 5V. Using
Ohm’s Law: Therefore, using a 150 ⍀ base resistor, we could
control a collector current of 40 to 200 times
30 mA, or 1.2 A to 6 A, which is more than
■ Joystick ■ Breadboard
■ Graphic LCD touch screen display If you intend to solder, then you will also need
■ Wi-Fi ■ Soldering iron (duh)
■ Lead-free alloy solder
Buying Components
Thirty years ago, the electronic enthusiast living in Component Box
even a small town would be likely to have the
When you first start designing your own projects,
choice of several radio/TV repair and spare stores
it will take you some time to gradually build up
where they could buy components and receive
your stock of components. Each time you are
friendly advice. These days, there are a few retail
finished with a project, a few more components
outlets that still sell components, like RadioShack
will find their way back to your stock.
in the United States and Maplins in the UK, but the
Internet has stepped in to fill the gap, and it is now It is useful to have a basic stock of components
easier and cheaper than ever to buy components. so that you do not have to keep ordering things
when you just need a different value resistor. You
With international component suppliers such as
will have noticed that most of the projects in this
RS and Farnell you can fill a virtual shopping
book tend to use values of resistor, like 100 ⍀,
basket online and have the components arrive in a
1 K⍀, 10 K⍀, etc. You actually don’t need that
day or two. Shop around, because prices vary
many different components to cover most of the
considerably between suppliers for the same
bases for a new project.
components.
A good starting kit of components is listed in
You will find eBay to be a great source of
the appendix.
components. If you don’t mind waiting a few
weeks for your components to arrive, there are Boxes with compartments that can be labeled
great bargains to be had from China. You often save a lot of time in selecting components,
have to buy large quantities, but may find it especially resistors that do not have their value
cheaper to get 50 of a component from China than written on them.
5 locally. That way, you have some spares for your
component box.
176 30 Arduino Projects for the Evil Genius
Multimeter
A big problem with electrons is that you cannot
see the little monkeys. A multimeter allows you to
see what they are up to. It allows you to measure
voltage, current, resistance, and often other
features too like capacitance and frequency. A
cheap $10 multimeter is perfectly adequate for
Figure 10-7 Soldering iron and solder.
almost any purpose. The professionals use much
more solid and accurate meters, but that’s not
The basic steps for soldering are necessary for most purposes.
1. Wet the sponge in the soldering iron stand. Multimeters, such as the one shown in Figure
2. Allow the iron to come up to temperature. 10-8, can be either analog or digital. You can tell
more from an analog meter than you can a digital,
3. Tin the tip of the iron by pressing the solder
as you can see how fast a needle swings over and
against it until it melts and covers the tip.
how it jitters, something that is not possible with a
4. Wipe the tip on the wet sponge—this digital meter, where the numbers just change.
produces a satisfying sizzling sound, but also However, for a steady voltage, it is much easier to
cleans off the excess solder. You should now read a digital meter, as an analog meter will have a
have a nice bright silver tip. number of scales, and you have to work out which
5. Touch the iron to the place where you are scale you should be looking at before you take the
going to solder to heat it; then after a short reading.
pause (a second or two), touch the solder to You can also get autoranging meters, which,
the point where the tip of the iron meets the once you have selected whether you are measuring
thing you are soldering. The solder should current or voltage, will automatically change
flow like a liquid, neatly making a joint. ranges for you as the voltage or current increases.
6. Remove the solder and the soldering iron, This is useful, but some would argue that thinking
putting the iron back in its stand, being very about the range of voltage before you measure it is
careful that nothing moves in the few seconds actually a useful step.
that the solder will take to solidify. If To measure voltage using a multimeter:
something does move, then touch the iron to it
1. Set the multimeter range to voltage (start at a
again to reflow the solder; otherwise, you can
range that you know will be higher than the
get a bad connection called a dry joint.
voltage you are about to measure).
Above all, try not to heat sensitive (or 2. Connect the black lead to GND. A crocodile
expensive) components any longer than necessary, clip on the negative lead makes this easier.
especially if they have short leads.
3. Touch the red lead to the point whose voltage
you want to measure. For instance, to see if an
Arduino digital output is on or off, you can
178 30 Arduino Projects for the Evil Genius
etc., but also to test for accidental short circuits on As you can see from Figure 10-10, the screen
a circuit board or broken connections in a wire. showing the waveform is displayed over the top of
Resistance measurement is occasionally useful, a grid. The vertical grid is in units of some fraction
particularly if you want to determine the resistance of volts, which on this screen is 2V per division.
of an unmarked resistor, for instance. So the voltage of the square wave in total is 2.5 ⫻
2, or 5V.
Some meters also have diode and transistor test
connections, which can be useful to find and The horizontal axis is the time axis, and this
discard transistors that have burned out. is calibrated in seconds—in this case, 500
microseconds (mS) per division. So the length of
one complete cycle of the wave is 1000 mS, that
Oscilloscope
is, 1 millisecond, indicating a frequency of 1KHz.
In Project 18, we built a simple oscilloscope. They
are an indispensable tool for any kind of
electronics design or test where you are looking at Project Ideas
a signal that changes over time. They are a
The Arduino Playground on the main Arduino
relatively expensive bit of equipment, and there are
website (www.arduino.cc) is a great source of
various types. One of the most cost-effective types
ideas for projects. Indeed, it even has a section
is similar in concept to Project 19. That
specifically for project ideas, divided into easy,
oscilloscope just sends its readings across to a
medium, or difficult.
computer that is responsible for displaying them.
If you type “Arduino project” into your favorite
Entire books have been written about using an
search engine or YouTube, you will find no end of
oscilloscope effectively, and every oscilloscope is
interesting projects that people have embarked on.
different, so we will just cover the basics here.
Another source of inspiration is the component allowed to gestate in the mind of the Evil Genius.
catalog, either online or on paper. Browsing After exploring all the options and mulling
through, you might come across an interesting everything over, the Evil Genius’ project will start
component and wonder what you could do with it. to take shape!
Thinking up a project is something that should be
APPENDIX
ALL OF THE PARTS USED in this book are readily components like laser diode modules, their prices
available through the Internet. However, sometimes can be ten times what you can find elsewhere on
it is a little difficult to track down exactly what you the Internet. Their main role is to supply to
are looking for. For this reason, this appendix lists professionals.
the components along with some order codes for Some smaller suppliers specialize in providing
various suppliers. This is information that will components for home constructors building
become inaccurate with time, but the big suppliers microcontroller projects like ours. They do not
like Farnell and RS will usually list an item as “no have the range of components, but do often have
longer stocked” and offer alternatives. more exotic and fun components at reasonable
prices. A prime example of this is Sparkfun
Electronics, but there are many others out there.
Suppliers
Sometimes, when you find you just need a
There are so many component suppliers out there couple of components, it’s great to be able to go to
that it feels a little unfair to list the few that the a local store and pick them up. RadioShack in the
author knows. So have a look around on the United States and Maplins in the UK stock a range
Internet, as prices vary considerably between of components, and are great for this purpose.
suppliers. The sections that follow list components by
I have listed order codes for Farnell and RS type, along with some possible sources and order
because they are international, but also carry a codes where available.
fantastically broad range of stock. There is very
little that you cannot buy from them. They can be
surprisingly cheap for common components, like
resistors and semiconductors, but for unusual
181
182 30 Arduino Projects for the Evil Genius
Code Description RS
Resistors
Capacitors
Semiconductors
Other suppliers to check, especially for LEDs, etc., include eBay, Sparkfun, Robotshop.com, and Adafruit.
184 30 Arduino Projects for the Evil Genius
Other
Local stores like RS and Maplins allow you to see components before you buy, and are good for components like
power supplies and computer fans, which will usually be cheaper than the big professional suppliers.
Appendix ■ Components and Supplies 185
187
188 30 Arduino Projects for the Evil Genius
flashing LED (Project 1), 8–11 metal oxide semiconductor field effect transistors,
high-brightness Morse code translator (Project 4), 135–136
35–40 microcontrollers, 15, 19–20
high-powered strobe light (Project 8), 52–55 model traffic signal (Project 5), 41–44
LED array (Project 16), 95–101 model traffic signal using a rotary encoder
LED dice (Project 9), 55–59 (Project 11), 68–72
model traffic signal (Project 5), 41–44 modules, 174–175
Morse code S.O.S. flasher (Project 2), 27–31 Morse code letters, 32
Morse code translator (Project 3), 31–35 Morse code S.O.S. flasher (Project 2), 27–29
S.A.D. light (Project 7), 47–52 Morse code translator (high-brightness—Project 4),
seven-segment LED double dice (Project 15), 35–38
91–95 making a shield for, 38–40
seven-segment LEDs, 89–91 Morse code translator (Project 3), 31–35
strobe light (Project 6), 44–47 MOSFETs, 135–136
libraries, installing into Arduino software, 64, 65, multicolor light display (Project 14), 85–89
154–155, 161 multimeter, 177–179
lie detector (Project 26), 145–148
light harp (Project 20), 117–120 O
light-dependent resistors, 72 Ohm’s Law, 17–18
lights OmniGraffle, 171
LED array (Project 16), 95–101 operators, 25
multicolor light display (Project 14), 85–89 marketing operator, 123
seven-segment LED double dice (Project 15), oscillator, 20
91–95 oscilloscope (Project 18), 107–111
strobe light (high-powered—Project 8), 52–55 oscilloscopes, 179
strobe light (Project 6), 44–46 outputs, 15
USB message board (Project 17), 102–105 analog output from digital inputs, 112
Lilypad. See Arduino Lilypad digital, 41
Lilypad clock (Project 29), 159–162
LINUX, installing software on, 5–6 P
logical expressions, 25 parameters, 23
logical operators, 25 PCBs. See Protoshield circuit boards
loops, 23, 29–30 perf board, 48
layout, 50
M photoresistors, 72
Mac OS X, installing software on, 4–5 phototransistors, 72, 73–74
magnetic door lock (Project 27), 148–153 piezobuzzers, 146–147
mains electricity, 110, 125 playNote function, 113–116
mains hum, 110 pliers, 176
marketing operator, 123 PNP transistors, 92
measuring current, 178 power
measuring resistance, 179 computer-controlled fan (Project 23), 132–133
measuring temperature, 77 hypnotizer (Project 24), 134–138
measuring voltage, 177–178 LCD thermostat (Project 22), 125–131
memory, 15, 19–20 servo-controlled laser (Project 25), 138–143
message board, 102–105 power connections, 16–18
190 30 Arduino Projects for the Evil Genius