ARDUINO PROJECTS BOOK
THE ARDUINO PROJECTS BOOK
EDITORS Projecs and ex by Scot Fizgerald and Michael Shiloh Addiional ex review by Tom Igoe DESIGN AND ART DIRECTION TODO Giorgio Olivero, Mario Ciardulli, Vanessa Poli, Michelle Nebiolo odo.o.i DIGITAL FABRICATION AND PROJECT MANAGEMENT Oficine Arduino Torino Kaia De Coi, Enrico Bassi ADVISORS AND SUPPORTERS Massimo Banzi, Gianluca Marino, Smar Projecs PROJECT TESTERS AND PROOFREADERS Michael Shiloh, Michelle Nebiolo, Kaia De Coi, Alessandro Bua, Federico Vanzai, David Mellis THANKS Big hanks o he enire Arduino user communiy or heir coninued conribuions, suppor, and eedback. Special hanks o he Frizing eam: some o he elecronic componens illusraions used in he book are aken or modified rom he open-source Frizing projec (www.rizing.org). Hearel hanks o Paul Badger or he CapaciiveSensor library used in Projec 13.
The ex o he Arduino Projecs Book is licensed unde r a Creaive Commons Atribuion-NonCommercial-ShareAlike 3.0 License 2012 by Arduino LLC. This means ha you can copy, reuse, adap and build upon he ex o his book non-commercially while atribuing he original work (bu no in any way ha suggess ha we endorse you or your use o he work) and only i he resuls are ransmited under he same Creaive Commons license. Full license erms: creaivecommons.org/licenses/by-nc-sa/3.0/ © 2012 Arduino LLC. The Arduino name and logo are rademarks o Arduino, regisered in he US and in he res o he world. Oher produc and company names menioned herein are rademarks o heir respecive companies. The inormaion in his book is disribued on an “As Is” basis wihou any urher warranies. While every precauion has been aken in he design o his book, neiher he auhors nor Arduino LLC shall have any liabiliy o any person or eniy wih respec o any loss or damage caused or declared o be caused direcly or indirecly by he insrucions conained in his book or by he sofware and hardware described in i. This book canno be sold separaely rom The Arduino Sarer Ki. Designed, prined and bound in Torino, Ialy Sepember 2012
INDEX
4
�� INTRODUCTION
20
�1
Ge o Know Your Tools
32
�2
Spaceship Inerface
42
�3
Love-o-Meer
52
�4
Color Mixing Lamp
62
�5
Mood Cue
70
�6
Ligh Theremin
78
�7
Keyboard Insrumen
86
�8
Digial Hourglass
94
�9
Moorized Pinwheel
102
1�
Zoerope
114
11
Crysal Ball
124
12
Knock Lock
136
13
Touchy-feely Lamp
144
14
Tweak he Arduino Logo
156
15
Hacking Butons
162
A/Z GLOSSARY
�� Everyone, every day, uses echnology. Mos o us leave he programming o engineers because we hink coding and elecronics are complicaed and difficul; acually, hey can be un and exciing aciviies. Thanks o Arduino, designers, ariss, hobbyiss and sudens o all ages are learning o creae hings ha ligh up, move, and respond o people, animals, plans, and he res o he world. Over he years Arduino has been used as he “brain” in housands o projecs, one more creaive han he las. A worldwide communiy o makers has gahered around his open-source plaorm, moving rom personal compuing o personal abricaion, and conribuing o a new world o paricipaion, cooperaion and sharing. Arduino is open and simple. I’s ounded on lessons we’ve learned eaching our own classes: i you sar wih he assumpion ha learning o make digial echnologies is simple and accessible, you can make i so. Suddenly elecronics and code become creaive ools ha anyone can use – like brushes and pain. This book walks you hrough he basics in a hands-on way, wih creaive projecs you build by learning. Once you’ve masered he basics, you’ll have a palete o sofware and circuis ha you can use o creae somehing beauiul, and make someone smile wih wha you inven.
BECOME EXTRAORDINARY
WELCOME TO ARDUINO! ARDUINO MAKES IT AS EASY AS POSSIBLE TO PROGRAM TINY COMPUTERS CALLED MICROCONTROLLERS, WHICH ARE WHAT MAKE OBJECTS INTERACTIVE
You are surrounded by dozens o hem every day: hey are embedded in imers, hermosas, oys, remoe conrols, microwave ovens, even some oohbrushes. They jus do one specific ask, and i you hardly noice hem – which is ofen he case – i’s because hey are doing i well. They have been programmed o sense and conrol aciviy using sensors and acuaors. Sensors listen to the physical world. They conver energy ha you give off when you press butons, or wave your arms, or shou, ino elecrical signals. Butons and knobs are sensors ha you ouch wih your fingers, bu here are many oher kinds o sensors. Actuators take action in the physical world. They conver elecrical energy back ino physical energy, like ligh and hea and movemen. Microcontrollers listen to sensors and talk to actuators. They decide wha o do based on a program ha you wrie. Microconrollers and he elecronics you atach o hem are jus he skeleon o your projecs, hough. You’ll need o bring skills you probably already have o pu some flesh on he bones. For example, in one o he projecs we sugges, you’ll make an arrow and atach i o a moor, and pu hem boh in a box wih a knob, so you can make a meer o ell people wheher you’re busy or no. In anoher, you’ll pu some lighs and a il swich on a cardboard rame o make an hourglass. Arduino can make your projects responsive, but only you can make them beautiful. We’ll provide some suggesions along he way as o how you migh do ha. Arduino was designed o help you ge hings done. To make ha happen, we kep he background maerial on programming and elecronics o a minimum. I you decide you wan o know more abou hese aspecs, here are los o good guides available. We’ll provide a couple o reerences, and you can find more online a: arduino.cc/sarerki
6
Introduction Welcome o Arduino!
+ PARTS IN YOUR KIT
+
+
-
-
+
+
-
-
Breadboard - A board on which you can build elecronic circuis. I’s like a pach panel, wih rows o holes ha allow you o connec wires and componens ogeher. Versions ha require soldering are available, as well as he solder-less ype used here.
Capaciors - These componens sore and release elecrical energy in a circui. When he
Arduino Uno - The microconroller develop-
circui’s volage is higher han wha is sored in
men board ha will be a he hear o your
he capacior, i allows curren o flow in, giv-
projecs. I’s a simple compuer, bu one ha
ing he capacior a charge. When he circui’s
has no way or you o inerac wih i ye. You
volage is lower, he sored charge is released.
will be building he circuis and ineraces or
Ofen placed across power and ground close o
ineracion, and elling he microconroller how
a sensor or moor o help smooh flucuaions
o inerace wih oher componens.
in volage.
Batery Snap - Used o connec a 9V batery o
DC moor - Convers elecrical energy ino me-
power leads ha can be easily plugged ino a
chanical energy when elecriciy is applied o
breadboard or your Arduino.
is leads. Coils o wire inside he moor become magneized when curren flows hrough hem.
7
These magneic fields atrac and repel magnes, causing he shaf o spin. I he direcion o he elecriciy is reversed, he moor will spin in he opposie direcion.
-
+
Diode - Ensures elecriciy only flows in one di-
Jumper wires - Use hese o connec compo-
recion. Useul when you have a moor or oher
nens o each oher on he breadboard, and o
high curren/volage load in your circui. Di-
he Arduino.
odes are polarized, meaning ha he direcion ha hey’re placed in a circui maters. Placed one way, hey allow curren o pass hrough. Placed he oher way, hey block i. The anode side generally connecs o he poin o higher energy in your circui. The cahode ypically connecs o he poin o lower energy, or o
-
+
ground. The cahode is usually marked wih a band on one side o he componen’s body.
Ligh Emiting Diodes (LEDs) - A ype o diode ha illuminaes when elecriciy passes hrough i. Like all diodes, elecriciy only flows in one direcion hrough hese componens. You’re probably amiliar wih hese as indicaors on a variey o elecronic devices. The anode, which ypically connecs o power, is usually he longer leg, and he cahode is he shorer leg.
Gels (red, green, blue) - These filer ou differen wavelenghs o ligh. When used in con juncion wih phooresisors, hey cause he sensor o only reac o he amoun o ligh in he filered color.
H-bridge - A circui ha allows you o conrol
Liquid Crysal Display (LCD) - A ype o alpha-
he polariy o he volage applied o a load,
numeric or graphic display based on liquid crys-
usually a moor. The H-bridge in he ki is an in-
als. LCDs are available in a many sizes, shapes,
egraed circui, bu i could also be consruc-
and syles. Yours has 2 rows wih 16 characers
ed wih a number o discree componens.
each.
8
Introduction Welcome o Arduino!
Male header pins - These pins fi ino emale sockes, like hose on a breadboard. They help make connecing hings much easier.
Poeniomeer - A variable resisor wih hree pins. Two o he pins are conneced o he ends o a fixed resisor. The middle pin, or wiper, moves across he resisor, dividing i ino wo halves. When he exernal sides o he poeniomeer are conneced o volage and ground,
Opocoupler - This allows you o connec wo
he middle leg will give he difference in volage
circuis ha do no share a common power
as you urn he knob. Ofen reerred o as a po.
supply. Inernally here is a small LED ha, when illuminaed, causes a phoorecepor inside o close an inernal swich. When you apply volage o he + pin, he LED lighs and he inernal swich closes. The wo oupus replace a swich in he second circui.
Pushbutons - Momenary swiches ha close a circui when pressed. They snap ino breadboards easily. These are good or deecing on/ off signals.
Piezo - An elecrical componen ha can be used o deec vibraions and creae noises.
Resisors - Resis he flow o elecrical energy in a circui, changing he volage and curren
Phooresisor - (also called a phoocell, or lighdependen resisor). A variable resisor ha changes is resisance based on he amoun o ligh ha alls on is ace.
as a resul. Resisor values are measured in ohms (represened by he Greek omega characer: Ω). The colored sripes on he sides o resisors indicae heir value (see resisor color code able).
9
ling high curren/high volage componens like moors. One pin connecs o ground, anoher o he componen being conrolled, and he hird connecs o he Arduino. When he componen receives volage on he pin conneced o an Arduino, i closes he circui beween he ground and he oher componen.
Servo moor - A ype o geared moor ha can only roae 180 degrees. I is conrolled by sending elecrical pulses rom your Arduino. These pulses ell he moor wha posiion i should move o.
Temperaure sensor - Changes is volage ou-
USB Cable - This allows you o connec your
pu depending on he emperaure o he com-
Arduino Uno o your personal compuer or
ponen. The ouside legs connec o power and
programming. I also provides power o he Ar-
ground. The volage on he cener pin changes
duino or mos o he projecs in he ki.
as i ges warmer or cooler.
Til sensor - A ype o swich ha will open or close depending on is orienaion. Typically hey are hollow cylinders wih a meal ball inside ha will make a connecion across wo leads when iled in he proper direcion.
Transisor - A hree legged device ha can operae as an elecronic swich. Useul or conrol-
UNCONNECTED WIRES
TRANSISTOR
PUSHBUTTON
TILT SWITCH
MOSFET
MOTOR
RESISTOR
PHOTO RESISTOR
POTENTIOMETER
LED
DIODE
PIEZO
POLARIZED CAPACITOR
CAPACITOR
BATTERY
In his book we will show you circuis boh wih realisic illusraions and wih schemaic diagrams. Illusraions will give you an idea o wha he breadboard GROUND
migh look like in one possible implemenaion o he projec. Schemaics, insead, use symbols o capure he essence o circuis: hey presen he componens and he ways hey are conneced in a clear, succinc, and unambiguous orm, bu no heir physical organizaion. Schemaics and schemaic symbols are how we communicae abou circuis. A s you explore he world
CONNECTED WIRES
o elecronics you will discover ha some books and websies only provide schemaic d iagrams, so learning o read ci rcuis his way is a valuable skill. Here are he symbols we will be using hroughou he book.
TABLE OF SYMBOLS
11
THE BOARD Power connector
Reset Button
This is how you power your
Reses he ATmega
Arduino when i's no plugged
microconroller.
ino a USB por or power. Can accep volages beween 7-12V. USB port
TX and RX LEDs
Used or powering your
These LEDs indicae communi-
Arduino Uno, uploading your
caion beween your Arduino
skeches o your Arduino, and
and your compuer. Expec
or communicaing wih your
hem o licker rapidly during
Arduino skech (via Serial.
skech upload as well as during
prinln() ec.)
serial communicaion. Useul or debugging.
Digital pins
Use hese pins wih digialRead(), digialWrie(), and analogWrie(). analogWrie() works only on he pins wih he PWM symbol.
Pin 13 LED
The only acuaor buil-i o your Arduino Uno. Besides being a handy arge or your irs blink skech, his LED is very useul or debugging.
GND and 5V pins
ATmega microcontroller
Use hese pins o provide +5V
The hear o your Arduino Uno.
power and groun d o your circuis. Analog in
Power LED
Use hese pins wih
Indicaes ha your Arudino
analogRead().
is receiving power. Useul or debugging.
12
Introduction Welcome o Arduino!
Your Sarer Ki includes a precu, easy-o-assemble wooden base ha will make working on all your projecs – wheher hey are rom his book or no – even easier. To build i, ake he wood shee ou o he box and ollow he insrucions on he righ. Be careul o use only he pars ha are shown, bu don’ misplace any o he oher pieces: you’ll need hem or some o he projecs laer.
❶ Le’s sar!
Take he wood shee and careully separae he pieces.
❹ Secure your Arduino Uno o he base using 3 screws. Be careul no o overighens.
13
❷
❸
Go on unil you’ve separaed all he pars.
Place he pieces marked wih an “A” ino he holes in he corners, in order o creae he ee o he base.
❺
❻
Careully peel he backing rom he breadboard.
Sick he breadboard on he wooden shee, nex o he Arduino UNO.
14
Introduction Welcome o Arduino!
�
THINGS YOU NEED TO SUPPLY
9V batery
A box ha you can make holes ino
Small ligh source like a flashligh
Basic ools like a screwdriver
Conducive maerial like
9V batery powered componen
aluminum oil or copper mesh
Any batery powered elecronic device wih a leas one swich or pushbuton ha you’re will-
Colored paper
ing o hack ino will do he job.
Scissors
Soldering iron and solder (necessary only in Projec 15)
An old CD or DVD Tape and glue
SETTING UP WELCOME TO ARDUINO! BEFORE YOU START CONTROLLING THE WORLD AROUND YOU, YOU’LL NEED TO DOWNLOAD THE IDE TO PROGRAM YOUR BOARD
The Arduino IDE allows you o wrie programs and upload hem o your Arduino. Download he laes version o he IDE rom:
arduino.cc/download Have your Arduino board and USB cable near your compuer. Don’ plug hem in jus ye.
Follow he appropriae procedures in he nex pages or Windows, Mac OS X or Linux.
The online version o his guide is available a: arduino.cc/guide
16
Introduction Seting Up
Online version
WINDOWS INSTALLATION
INSTRUCTION FOR:
arduino.cc/windows
❶
When he download o he IDE finishes, unzip he downloaded file. Make sure o preserve he older srucure. Double-click he
WINDOWS 7, VISTA,
older o open i. There should be a ew files and sub-olders
AND XP
inside.
❷
Connec he Arduino o your compuer wih he USB cable. Your Arduino will auomaically draw power rom eiher he USB connecion o he compuer or an exernal power supply. The green power ligh (labeled PWR) should urn on.
❸
Windows should iniiae is driver insallaion process when he board is plugged in. Your compuer won’ be able o find he drivers by isel, so you’ll need o ell i where hey are locaed. — Click on he Sar Menu and open he Conrol Panel. — Navigae o “Sysem and Securiy”. Open he Device Manager. — In Windows XP, look or he lising named "Pors (COM & LPT)" and righ click on he "USB device" por; in Visa and Windows 7, righ click on "Unknown device" under "Oher devices". — Choose "Updae Driver Sofware". — On Windows XP and Windows 7, you will be asked wheher o insall auomaically or "wih a pah". Chose he second opion, "wih a pah". On Windows Visa proceed direcly o he nex sep. — Selec he “Browse my compuer or Driver sofware” opion. — Navigae o he older you unzipped in he earlier sep. Locae and selec he “Drivers” older in he main Arduino older (no he “FTDI USB Drivers” sub-direcory). Press “OK” and “Nex” o proceed. — I you are promped wih a warning dialog abou no passing Windows Logo esing, click “Coninue Anyway”. — Windows now will ake over he driver insallaion. In he Device Manager, you should now see a por lising similar o “Arduino UNO (COM4)”.
Congraulaions! You've insalled he Arduino IDE on your compuer.
17
Online version
MAC OS X INSTALLATION
INSTRUCTION FOR:
arduino.cc/mac
❶
When he download o he IDE finished, double-click he .zip fle.
❷
Copy he Arduino applicaion ino he Applicaions older, or
❸
Connec he board o he compuer wih he USB cable. The
❹
You do no need o insall any drivers o work wih he board.
This will expand he Arduino applicaion.
OS X 10.5 AND LATER
wherever else you wish o insall he sofware.
green power LED (labeled PWR) should urn on.
Depending on he version o OS X ha you are running, you migh ge a dialog box asking i you wish o open he “Nework Preerences”. Click he “Nework Preerences...” buton, and hen click “Apply”.
❺
The Uno will show up as “No Configured”, bu i is sill working. You can qui he Sysem Preerences.
Congraulaions! You have Arduino all se up and you're ready o sar making projecs.
LINUX INSTALLATION
I you’re using Linux, please visi he websie or insrucions:
arduino.cc/linux
18
Introduction Seting Up
COMMUNICATING WITH THE ARDUINO
❶
Now ha you’ve insalled he Arduino IDE and made sure your compuer can alk o he board, i’s ime o make sure you can upload a program. Double-click he Arduino applicaion o open i. I he IDE loads in he wrong language, you can change his in he applicaion preerences. Look or “Language Suppor” on his page or deails: arduino.cc/ide
❷
Navigae o he LED blink example skech ('skech' is wha Arduino programs are called). I's locaed under: FILE > EXAMPLES > 01.BASICS > BLINK
❸
A window wih some ex in i should have opened. Leave he window be or now, and selec your board under: TOOLS > BOARD menu
❹
Choose he serial por your Arduino is conneced o rom he TOOLS > SERIAL PORT menu. — On Windows. This is likely o be he COM wih he highes number. There is no harm in guessing wrong, and i i doesn’ work, ry he nex one. To find ou, you can disconnec your Arduino board and re-open he menu; he enry ha disappears should be he Arduino board. Reconnec he board and selec ha serial por. — On Mac. This should be somehing wih /dev/ty.usbmodem in i. There are usually wo o hese; selec eiher one.
Fig. 1
❺
To upload he Blink skech o your Arduino, press he UPLOAD oggle in he op lef corner o he window. See Fig. 1.
19
❻
You should see a bar indicaing he progress o he upload near he lower lef corner o he Arduino IDE, and he lighs labeled TX and RX on he Arduino board will be blinking. I he upload is successul, he IDE will display he message DONE UPLOADING.
❼
A ew seconds afer he upload has compleed, you should see he yellow LED wih an L nex o i sar blinking. See Fig. 2.
I his is he case, congraulaions! You’ve successully programmed he Arduino o blink is onboard LED! Someimes your brand new Arduino is already programmed wih he Blink skech, so you can’ ell i you are ruly in conrol. I his is he case, change he delay ime by changing he number in he parenhesis o 100, and upload he Blink skech again. Now he LED should blink much aser. Fig. 2
Congraulaions! You really are in conrol! Now i’s ime o move on o Projec 1. (You needn’ save any changes you have made.)
ADDITIONAL INFORMATION
I you have problems wih any o he seps oulined above, please see he roubleshooing suggesions:
arduino.cc/rouble While you’re geting ready o build your projecs, you can look a he ollowing page or addiional inormaion abou he Arduino’s programming environmen:
arduino.cc/ide You migh also wan o look a: — he examples or using various sensors and acuaors
arduino.cc/uorial — he reerence or he Arduino language
arduino.cc/examples
�1
R O T S I S E R H C T I W S
INGREDIENTS
M H O D E L
0 2 2
21
GET TO KNOW YOUR TOOLS YOU’LL MAKE A SIMPLE CIRCUIT WITH SOME SWITCHES, AN LED, AND A RESISTOR
Discover: basic electrical theory, how a breadboard works, components in series and parallel
Time: 30 MINUTES Level:
Elecriciy is a ype o energy, much like hea, graviy, or ligh. Elecrical energy flows hrough conducors, like wire. You can conver elecrical energy ino oher orms o energy o do somehing ineresing, like urn on a ligh or make some noise ou o a speaker. The componens you migh use o do his, like speakers or ligh bulbs, are elecrical ransducers. Transducers change oher ypes o energy ino elecrical energy and vice versa. Things ha conver oher orms o energy ino elecrical energy are ofen called sensors, and hings ha conver elecrical energy ino oher orms o energy are someimes called acuaors. You will be building circuis o move elecriciy hrough differen componens. Circuis are closed loops o wire wih a power source (like a batery) and somehing o do somehing useul wih he energy, called a load. In a circui, elecriciy flows rom a poin o higher poenial energy (usually reerred o as power or +) o a poin o lower poenial energy. Ground (ofen represened wih a - or GND) is generally he poin o leas poenial energy in a circui. In he circuis you are building, elecriciy only flows in one direcion. This ype o circui is called direc curren, or DC. In alernaing curren (AC) circuis elecriciy changes is direcion 50 or 60 imes a second (depending on where you live). This is he ype o elecriciy ha comes rom a wall socke. There are a ew erms you should be amiliar wih when working wih elecrical circuis. Curren (measured in amperes, or amps; wih he A symbol) is he amoun o elecrical charge flowing pas a specific poin in your circui. Volage (measured in vols; wih he V symbol) is he difference in energy beween one poin in a circui and anoher. And finally, resisance (measured in ohms; wih he Ω symbol)
is how much a componen resiss he flow o elecrical energy.
Project 01
22
Ge o Know Your Tools
One way o imagine his is o hink abou a rockslide going down a cliff, as shown in Fig. 1. The higher he cliff, he more energy he rocks will have when hey hi he botom. The heigh o he cliff is like he volage in a circui: he higher he volage a he energy source, he more energy you have o use. The more rocks you have, he more energy is being carried down he cliff. The number o rocks is like he curren in an elecrical circui. The rocks go hrough bushes on he side o he cliff, losing some energy in he process; he energy is used up o crush he bushes. The bushes are like resisors in a circui, offering resisance o he elecrical flow and convering i ino oher orms o energy.
Rockslide as a meaphor or Current (I)
elecrical curren low. Fig. 1
Voltage (V) Resistance (R)
There needs o be a complee pah rom he energy source
A COUPLE OF THINGS ABOUT CIRCUITS
(power) o he poin o leas energy (ground) o make a circui. I here’s no pah or he energy o ravel, he circui won’ work. All he elecrical energy ges used up in a circui by he componens in i. Each componen convers some o he energy ino
+5V
5V
anoher orm o energy. In any circui, all o he volage is con1 1
2 3
vered o anoher orm o energy (ligh, hea, sound, ec.). The flow o curren a a specific poin in a circui will always be he same coming in and going ou. Elecrical curren will seek he pah o leas resisance o ground. Given wo possible pahs, more o he elecrical curren will go down he pah wih less resisance. I you have a connec-
4
GND
ion ha connecs power and ground ogeher wih no resisance, you will cause a shor circui, and he curren will ry o ollow ha pah. In a shor circui, he power source and wires
The curren a (1) = curren a (2)
conver he elecrical energy ino ligh and hea, usually as sparks
+ curren a (3) = curren a (4).
or an explosion. I you’ve ever shored a batery and seen sparks,
Fig. 2
you know how dangerous a shor circui can be.
23
WHAT’S A BREADBOARD?
The breadboard is he primary place you will be building circuis. The one ha comes in your ki is solderless, so named because you don’ have o solder anyhing ogeher, sor o like LEGO in elecronic orm. The horizonal and verical rows o he breadboard, as shown in Fig. 3, carry elecricriciy hrough hin meal connecors under he plasic wih holes.
The 5 holes in each horizontal row are connected electrically through metal strips inside the breadboard.
The vertical strips that run the length of the breadboard are electrically connected. The strips are usually used for power and ground connections.
The op o a breadboard and he connecions
The middle row breaks the connection between the two sides of the board.
+
-
+
POWER BUS
POWER BUS
underneah. Fig. 3 PROTOTYPING AREA
Conductive metal strips.
The conducive plaes inside a breadboard. Fig. 4
-
24
Project 01 Ge o Know Your Tools
CIRCUIT DRAWINGS
Throughou hese projecs, you’ll see wo views o circuis: one in breadboard view (like in Fig. 5), ha looks like he suff in your ki. The oher is a schemaic view (like in Fig. 6), which is a more absrac way o showing he relaionships beween componens in a circui. Schemaics don’ always show where componens are placed relaive o each oher, bu hey show how hey are conneced.
+
-
+
-
+
-
+
-
Circui illusraion. Fig. 5
Schemaic view Fig. 6
25
YOUR FIRST COMPONENTS
An LED, or ligh-emiting diode, is a componen ha convers elecrical energy ino ligh energy. LEDs are polarized componens, which means hey only allow elecriciy o flow hrough hem in one direcion. The longer leg on he LED is E D O H T A C
-
E D O N A
+
called an anode, i will connec o power. The shorer leg is a cahode and will connec o ground. When volage is applied o he anode o he LED, and he cahode is conneced o ground, he LED emis ligh. A resisor is is a componen ha resiss he flow o elecrical energy (see he componens lis or an explanaion on he colored sripes on he side). I convers some o he elecrical energy ino hea. I you pu a resisor in series wih a componen like an LED, he resisor will use up some o he elecrical energy and he LED will receive less energy as a resul. This allows you o supply componens wih he amoun o energy hey need. You use a resisor in series wih he LED o keep i rom receiving oo much volage. Wihou he resisor, he LED would be brigher or a ew momens, bu quickly burn ou. A swich inerrups he flow o elecriciy, breaking he circui when open. When a swich is closed, i will complee a circui. There are many ypes o swiches. The ones in your ki are called momenary swiches, or pushbutons, because hey are only closed when pressure is applied.
SWITCH CONNECTIONS
SWITCH SCHEMATIC VIEW
These two pins of a switch are connected to each other
A - Toggle switch symbol These two are not. They form the switch
B - Pushbuon symbol
The swich Fig. 7
26
Project 01 Ge o Know Your Tools
BUILD THE CIRCUIT
+
-
+
-
+
-
+
-
Fig. 8
Your first interactive circui t, using a switch, a resi stor and an LED. Arduino is just the power source for this circuit; in later projects, you'll connect its input and output pins t o control more compl ex circuits.
Fig. 9
27
You’re going o use he Arduino in his projec, bu only as a source o power. When plugged ino a USB por or a 9-vol baery, he Arduino will provide 5 vols beween is 5V pin and is ground pin ha you can use. 5V = 5 vols, you’ll see i writen his way a lo.
❶
I your Arduino is conneced o a batery or compuer via USB,
❷
Connec a red wire o he 5V pin on he Arduino, and pu he
unplug i beore building he circui!
oher end in one o he long bus lines in your breadboard. Connec ground on he Arduino o he adjacen bus line wih a black wire. I’s helpul o keep your wire color consisen (red or power, black or ground) hroughou your circui.
❸
Now ha you have power on your board, place your swich across he cener o he board. The swich will si across he cener in one direcion. The bend in he legs o he swich poin o he cener o he board.
❹
Use a 220-ohm resisor o connec power o one side o he swich. The illusraions in his book use 4 bands. Your ki may have a mix o 4 and 5 band resisors. Use he illusraion on he side o check or he righ one or his projec. Look a page 41 or a deailed explanaion o he color codes or resisors. On he oher side o he swich, connec he anode (long leg) o he LED. Wih a wire connec he cahode (shor leg) o he LED o ground. When you’re ready, plug he USB cable ino he Arduino.
USE IT
Once everyhing is se o go, press he buton. You should see he LED ligh up. Congraulaions, you jus made a circui! Once you’ve ired o pressing he buton o urn he ligh on, i’s ime o shake hings up by adding a second buton.
You’ll be placing componens on he breadboard in series and in parallel. Componens in series come one afer anoher. Componens in parallel run side by side.
28
Project 01 Ge o Know Your Tools
Series circuit COMPONENTS IN SERIES COME ONE AFTER ANOTHER
Once you’ve removed your power source add a swich nex o he one already on your breadboard. Wire hem ogeher in series as shown in Fig. 10. Connec he anode (long leg) up he These wo elemens are in series
LED o he second swich. Connec he LED cahode o ground. Power up he Arduino again: now o urn on he LED, you need o press boh swiches. Since hese are in series, hey boh need o be closed or he circui o be compleed.
+
-
+
-
+
-
+
-
ALWAYS REMOVE POWER BEFORE CHANGING ANYTHING IN YOUR CIRCUIT
The wo swiches are in series. This means ha he same elecrical curren lows hrough boh o hem, so ha hey boh have o be pressed or he LED o ligh up. Fig. 10
Fig. 11
29
Parallel circuit COMPONENTS IN PARALLEL RUN SIDE BY SIDE
Now ha you’ve masered he ar o hings in series, i’s ime o wire up swiches in parallel. Keep he swiches and LED where hey are, bu remove he connecion beween he wo These wo elemens are in parallel
swiches. Wire boh swiches o he resisor. Atach he oher end o boh swiches o he LED, as shown in Fig. 12. Now when you press eiher buton, he circui is compleed and he ligh urns on.
These wo swiches are in parallel. This means ha he elecrical curren is spli beween hem. I eiher swich is pressed, he LED will ligh up. Fig. 12
Fig. 13
+
-
+
-
+
-
+
-
Project 01
30
Ge o Know Your Tools
UNDERSTANDING OHM’S LAW
V = I
R
*
I = V / R
R = V / I
V
V
V I
V
R I
R
I
R
I
R
Current, voltage, and resistance are all related. When you
You can use his circle o
change one o hese in a circui, i affecs he ohers. The rela-
remember he relaionships
ionship beween hem is known as Ohm's Law, named or Georg
beween volage, curren, and
Simon Ohm, who discovered i.
resisance. Pu your inger over
VOLTAGE �V� = CURRENT �I�
any o he hree, and you see
When measuring amperage in he circuis you’ll be building, values
how i relaes o he oher wo.
will be in he milliamp range. Tha’s housandhs o one amp.
RESISTANCE �R�
*
In he circui shown in Fig. 5, you’re supplying 5 vols. The resisor offers 220 ohms resisance. To find he amperage used by he LED, replace he values in he equaion. You should have 5=I*220. Dividing boh sides o he equaion by 220, you’ll find ha I = .023. Tha’s 23 housandhs o an amp, or 23 milliamps (23 mA) used by he LED. Tha value is jus abou he maximum you can saely use wih hese LEDs, which is why you used a 220-ohm resisor. You can expand his projec in a number o ways, eiher by creaing your own swich (wo pieces o oil wih wire work well), or creaing a combinaion o swiches and LEDs in parallel and series. Wha happens when you pu hree or our LEDs in series? Wha happens when hey are in parallel? Why does i behave he way i does? A mulimeer is a ool ha can veriy he amoun o resisance, curren, and volage in your circui. While i’s no necessary o use one or hese projecs, i can be a useul par o any engineer’s oolbox. There’s a good descripion o how o use one online a arduino.cc/mulimeer
You’ve learned abou he elecrical properies o volage, curren, and resisance while building a circui on a breadboard. Wih some componens like LEDs, resisors and swiches, you creaed he simples ineracive sysem: a user presses he buton, he lighs urn on. These undamenals o working wih elecronics will be reerenced and expanded upon in he upcoming projecs.
Fig. 14 - A mulimeer
�2
R O T S I S E R H C T I W S
INGREDIENTS
M H O D E L
0 2 2
R O T S I S E R M H O L I K 0 1
33
SPACESHIP INTERFACE YOUR ARDUINO IS GOING TO STAR IN A SCIENCE FICTION MOVIE
Discover: digital input and output, your first program, variables
Time: 45 MINUTES
Builds on projec: 1
Level:
Now ha you’ve go he basics o elecriciy under conrol, i’s ime o move ono conrolling hings wih your Arduino. In his projec, you’ll be building somehing ha could have been a spaceship inerace in a 1970s science ficion movie. You’ll make a cool conrol panel wih a swich and lighs ha urn on when you press he swich. You can decide wheher he lighs mean “Engage Hyperdrive” or “Fire he lasers!”. A green LED will be on, unil you press a buton. When he Arduino ges a signal rom he buton, he green ligh will urn off and 2 oher lighs will sar blinking. The Arduino’s digial pins can read only wo saes: when here is volage on an inpu pin, and when here’s no. This kind o inpu is normally called digial (or someimes binary, or wo-saes). These saes are commonly reerred o as
HIGH and LOW. HIGH is he same as saying “here’s volage here!” and LOW means “here’s no volage on his pin!”. When you urn an OUTPUT pin HIGH using a command called digialWrie(), you’re urning i on. Measure he volage beween he pin and ground, you’ll ge 5 vols. When you urn an OUTPUT pin
LOW, you’re urning i off. The Arduino’s digial pins can ac as boh inpus and oupus. In your code, you’ll configure hem depending on wha you wan heir uncion o be. When he pins are oupus, you can urn on componens like LEDs. I you configure he pins as inpus, you can check i a swich is being pressed or no. Since pins 0 and 1 are used or communicaing wih he compuer, i’s bes o sar wih pin 2.
34
Project 02 Spaceship Inerface
BUILD THE CIRCUIT
Fig. 1
Fig. 2
+
-
+
-
+
-
+
-
35
❶
Wire up your breadboard o he Arduino’s 5V and ground connecions, jus like he previous projec. Place he wo red LEDs and one green LED on he breadboard. Atach he cahode (shor leg) o each LED o ground hrough a 220-ohm resisor. Connec he anode (long leg) o he green LED o pin 3. Connec he red LEDs’ anodes o pins 4 and 5, respecively.
❷
Place he swich on he breadboard jus as you did in he previous projec. Atach one side o power, and he oher side o digial pin 2 on he Arduino. You’ll also need o add a 10k-ohm resisor rom ground o he swich pin ha connecs o he Arduino. Tha pull-down resisor connecs he pin o ground when he swich is open, so i reads LOW when here is no volage coming in hrough he swich.
You can cover he breadboard he emplae provided in he ki. Or you can decorae i o make your own launch sysem. The lighs urning on and off mean nohing by hemselves, bu when you pu hem in a conrol panel and give hem labels, hey gain meaning. Wha do you wan he green LED o mean? Wha do he flashing red LEDs mean? You decide!
❶
❷
Fold he pre-cu paper as shown.
Place he olded paper over he breadboard. The hree LEDs and pushbuon will help keep i in place.
36
Project 02 Spaceship Inerface
THE CODE
Some noes beore you sar
Every Arduino program has wo main uncions. Funcions are pars o a compuer program ha run specific commands. Funcions have unique names, and are “called” when needed. The necessary uncions in an Arduino program are called seup() and loop(). These uncions need o be declared, which means ha you need o ell he Arduino wha hese uncions will do.
seup() and loop() are declared as you see on he righ. In his program, you’re going o creae a variable beore you ge ino he main par o he program. Variables are names you give o places in he Arduino’s memory so you can keep rack o wha is happening. These values can change depending on your program’s insrucions. Variable names should be descripive o whaever value hey are soring. For example, a variable named swichSae ells you wha i sores: he sae o a swich. On he oher hand, a variable named “x” doesn’ ell you much abou wha i sores. To creae a variable, you need o declare wha type i is. The
Le’s sar coding
data type in will hold a whole number (also called an integer );
ha’s any number wihou a decimal poin. When you declare a variable, you usually give i an iniial value as well. The declaraion o he variable as every saemen mus end wih a semicolon (;).
Conigure pin uncionaliy
The seup() runs once, when he Arduino is firs powered on. This is where you configure he digial pins o be eiher inpus or oupus using a uncion named pinMode(). The pins conneced o LEDs will be OUTPUTs and he swich pin will be an INPUT.
Creae he loop uncion
The loop() runs coninuously afer he seup() has compleed. The loop() is where you’ll check or volage on he inpus, and urn oupus on and off. To check he volage level on a digial inpu, you use he uncion digialRead() ha checks he chosen pin or volage. To know wha pin o check,
digialRead() expecs an argument. Argumens are inormaion ha you pass o uncions, elling hem how hey should do heir job. For example,
digialRead() needs one argumen: wha pin o check. In your program, digialRead() is going o check he sae o
37
void seup(){ }
{ Curly brackets } Any code you wrie inside he curly brackes will be execued when he uncion is called.
void loop(){ }
1 in swichSae = 0;
2 void seup(){ 3
pinMode(3,OUTPUT);
4
pinMode(4,OUTPUT);
5
pinMode(5,OUTPUT);
6
pinMode(2,INPUT);
Case sensitivity Pay atenion o he case sensiiviy in your code. For example, pinMode is he name o a command, bu pinmode will produce an error.
7 }
8 void loop(){ 9
swichSae = digialRead(2);
10
// his is a commen
Comments I you ever wan o include naural language in your program, you can leave a commen. Commens are noes you leave or yoursel ha he compuer ignores. To wrie a commen, add wo slashes // The compuer will ignore anyhing on he line afer hose slashes.
38
Project 02 Spaceship Inerface
pin 2 and sore he value in he swichSae variable. I here’s volage on he pin when digialRead() is called, he
swichSae variable will ge he value HIGH (or 1). I here is no volage on he pin, swichSae will ge he value LOW (or 0).
The i saemen
Above, you used he word i o check he sae o somehing (namely, he swich posiion). An
i() saemen in
programming compares wo hings, and deermines wheher he comparison is rue or alse. Then i perorms acions you ell i o do. When comparing wo hings in programming, you use wo equal signs ==. I you use only one sign, you will be seting a value insead o comparing i.
Build up your spaceship
digialWrie() is he command ha allows you o send 5V or 0V o an oupu pin. digialWrie() akes wo argumens: wha pin o conrol, and wha value o se ha pin, HIGH or LOW. I you wan o urn he red LEDs on and he green LED off inside your i() saemen, your code would look like his .
I you run your program now,
You’ve old he Arduino wha o do when he swich is open.
he lighs will change when you
Now define wha happens when he swich is closed. The i()
press he swich. Tha’s prety
saemen has an opional else componen ha allows or
nea, bu you can add a litle more
somehing o happen i he original condiion is no me. In his
complexiy o he program or a
case, since you checked o see i he swich was LOW, wrie code
more ineresing oupu.
or he HIGH condiion afer he else saemen. To ge he red LEDs o blink when he buton is pressed, you’ll need o urn he lighs off and on in he else saemen you jus wroe. To do his, change he code o look like his.
Now your program will flash he
Afer seting he LEDs o a cerain sae, you’ll wan he Arduino
red LEDs when he swich buton
o pause or a momen beore changing hem back. I you don’
is pressed.
wai, he lighs will go back and orh so as ha i will appear as i hey are jus a litle dim, no on and off. This is because he Arduino goes hrough is loop() housands o imes each second, and he LED will be urned on and off quicker han we can perceive. The delay() uncion les you sop he Arduino rom execuing anyhing or a period o ime. delay() akes an argumen ha deermines he number o milliseconds beore i execues he nex se o code. There are 1000 milliseconds in one second. delay(250) will pause or a quarer second.
39
11
if (swichSae if (swichSae == LOW LOW) ) {
12
// he buton is no pressed
13
digialWrie(3, digialWrie (3, HIGH HIGH); ); // green LED
14
digialWrie(4, digialWrie (4, LOW LOW); );
// red LED
15
digialWrie(5, digialWrie (5, LOW LOW); );
// red LED
16
}
17
else { else {
i he swichSae is LOW: urn he green LED on urn he red LEDs off i he swichSae is HIGH: urn he green LED off urn he red LEDs on
// he buton is pressed
18
digialWrie(3, digialWrie (3, LOW LOW); );
19
digialWrie(4, digialWrie (4, LOW LOW); );
20
digialWrie(5, digialWrie (5, HIGH HIGH); );
21
delay(250); delay (250);
22
// oggle he LEDs
23
digialWrie(4, digialWrie (4, HIGH HIGH); );
24
digialWrie(5, digialWrie (5, LOW LOW); );
25
delay(250); delay (250); // wai for a quarer second
26
I can be helpul o wrie ou he flow o your program in pseudocode: a way o describing wha you wan he program o do in plain language, bu srucured in a way ha makes i easy o o wrie a real program rom i. In his case you’re going o deermine i swichSae is HIGH (meaning he buton is pressed) or no. I he swich is pressed, you’ll urn he green LED off and he red ones on. In pseudocode, he saemen could look like his:
// wai for a quarer second
}
27 } // go back o he beginning of he loop
40
Project 02 Spaceship Inerface
USE IT
Once your Arduino is programmed, you should see he green ligh urn on. When you press he swich, he red lighs will sar flashing, and he green ligh will urn off. Try changing he ime o he wo delay() uncions; noice wha happens o he lighs and how he response o he sysem changes depending on he speed o he flashing. When you call a delay() in your program, i sops all oher uncionaliy. No sensor readings will happen unil ha ime period has passed. While delays are ofen useul, when designing your own projecs make sure hey are no unnecessarily inerering wih your inerace.
How would you ge he red LEDs o be blinking when your program sars? How could you make a larger, or more complex inerace or your inersellar advenures wih LEDs and swiches?
When you sar creaing an inerace or your projec, hink abou wha people’s expecaions are while using i. When hey press a buton, will hey wan immediae eedback? Should here be a delay beween heir acion and wha he Arduino does? Try and place yoursel in he shoes o a differen user while you design, and see i your expecaions mach up o he realiy o your projec.
In his projec, you creaed your firs Arduino program o conrol he behavior o some LEDs based on a swich. You’ve used variables, an i()...else saemen, and uncions o read he sae o an inpu and conrol oupus.
41
HOW TO READ RESISTOR COLOR CODES
Resisor values are marked using colored bands, according o a code developed in he 1920s, when i was oo difficul o wrie numbers on such iny objecs. Each color corresponds o a number, like you see in he able below. Each resisor has eiher 4 or 5 bands. In he 4-band ype, he firs wo bands indicae he firs wo digis o he value while he hird one indicaes he number o zeroes ha ollow (echnically i reprens he power o en). The las band specifies he olerance: in he example below, gold indicaes ha he resisor value can be 10k ohm plus or minus 5%.
4 BAND
1
0
x 10 3
± 5
= 10,000 Ω = 10k Ω ± 5%
1 st DIGIT
2 nd DIGIT
3 rd DIGIT
MULTIPLIER
0
0
0
0
1
1
1
1
±1 %
2
2
2
2
±2 %
3
3
3
3
±5%
GOLD
4
4
4
4
±10%
SILVER
5
5
5
5
6
6
6
6
7
7
7
8
8
8
9
9
9
5 BAND
1
0
0
x 10 2 ± 5
TOLERANCE
= 10,000 Ω = 10k Ω ±5%
RESISTORS INCLUDED
5 BAND
IN THE STARTER KIT 4 BAND
You’ll find either a 4 band or
220 Ω
560 Ω
4.7k Ω
a 5 band version.
5 BAND
4 BAND
1k Ω
10k Ω
1M Ω
10M Ω
�3
R O T S I S E R M H O D E L
INGREDIENTS
0 2 2
R O S N E S E R U T A R E P M E T
43
LOVE�O�METER TURN THE ARDUINO INTO A LOVE MACHINE. USING AN ANALOG INPUT, YOU’RE GOING TO REGISTER JUST HOW HOT YOU REALLY ARE!
Discover: analog Input, using the serial monitor
Time: 45 MINUTES
Builds on projecs: 1, 2
Level:
While swiches and butons are grea, here’s a lo more o he physical world han on and off. Even hough he Arduino is a digial ool, i’s possible or i o ge inormaion rom analog sensors o measure hings like emperaure or ligh. To do his, you’ll ake advanage o he Arduino’s buil-in Analog-o-Digial Converer (ADC). Analog in pins A0-A5 can repor back a value beween 0-1023, which maps o a range rom 0 vols o 5 vols. You’ll be using a emperaure sensor o measure how warm your skin is. This componen oupus a changing volage depending on he emperaure i senses. I has hree pins: one ha connecs o ground, anoher ha connecs o power, and a hird ha oupus a variable volage o your Arduino. In he skech or his projec, you’ll read he sensor’s oupu and use i o urn LEDs on and off, indicaing how warm you are. There are several differen models o emperaure sensor. This model, he TMP36, is convenien because i oupus a volage ha changes direcly proporional o he emperaure in degrees Celsius. The Arduino IDE comes wih a ool called he serial monior ha enables you o repor back resuls rom he microconroller. Using he serial monior, you can ge inormaion abou he saus o sensors, and ge an idea abou wha is happening in your circui and code as i runs.
Serial monior Fig. 1
44
Project 03 Love-o-Meer
BUILD THE CIRCUIT
Fig. 2
+
-
+
-
+
-
+
-
Fig. 3
In his projec, you need o check he ambien emperaure o he room beore proceeding. You’re checking hings manually righ now, bu his can also be accomplished hrough calibraion. I’s possible o use a buton o se he baseline emperaure, or o have he Arduino ake a sample beore saring he loop() and use ha as he reerence poin. Projec 6 ges ino deails abou his, or you can look a he Calibraion example ha comes bundled wih he Arduino sofware:
arduino.cc/calibraion
45
❶
Jus as you’ve been doing in he earlier projecs, wire up your
❷
Atach he cahode (shor leg) o each o he LEDs you’re using o
breadboard so you have power and ground.
ground hrough a 220-ohm resisor. Connec he anodes o he LEDs o pins 2 hrough 4. These will be he indicaors or he projec.
❸
Place he TMP36 on he breadboard wih he rounded par acing away rom he Arduino (he order o he pins is imporan!) as shown in Fig. 2. Connec he lef pin o he fla acing side o power, and he righ pin o ground. Connec he cener pin o pin A0 on your Arduino. This is analog inpu pin 0.
Creae an inerace or your sensor or people inerac wih. A paper cuou in he shape o a hand is a good indicaor. I you’re eeling lucky, creae a se o lips or someone o kiss, see how well ha lighs hings up! You migh also wan o label he LEDs o give hem some meaning. Maybe one LED means you’re a cold fish, wo LEDs means you’re warm and riendly, and hree LEDs means you’re oo ho o handle!
❶
❷
Cu ou a piece o paper ha will i over he breadboard.
Place he cuou over he breadboard so ha he lips cover
Draw a se o lips where he sensor will be, and cu some
he sensor and he LEDs i ino he holes. Press he lips o
circles or he LEDs o pass hrough.
see how ho you are!
46
Project 03 Love-o-Meer
THE CODE
A pair o useul consans
Constants are similar o variables in ha hey allow you o
uniquely name hings in he program, bu unlike variables hey canno change. Name he analog inpu or easy reerence, and creae anoher named consan o hold he baseline emperaure. For every 2 degrees above his baseline, an LED will urn on. You’ve already seen he in daaype, used here o ideniy which pin he sensor is on. The emperaure is being sored as a float, or floaing-poin number. This ype o number has a decimal poin, and is used or numbers ha can be expressed as racions.
Iniialize he serial por o
In he seup you’re going o use a new command, Serial.
he desired speed
begin(). This opens up a connecion beween he Arduino and he compuer, so you can see he values rom he analog inpu on your compuer screen. The argumen 9600 is he speed a which he Arduino will communicae, 9600 bis per second. You will use he Arduino IDE’s serial monior o view he inormaion you choose o send rom your microconroller. When you open he IDE’s serial monior veriy ha he baud rae is 9600.
Iniialize he digial pin
Nex up is a or() loop o se some pins as oupus. These are
direcions and urn o
he pins ha you atached LEDs o earlier. Insead o giving hem unique names and yping ou he pinMode() uncion or each one, you can use a or() loop o go hrough hem all quickly. This is a handy rick i you have a large number o similar hings you wish o ierae hrough in a program. Tell he or() loop o run hrough pins 2 o 4 sequenially.
Read he emperaure sensor
In he loop(), you’ll use a local variable named sensorVal o sore he reading rom your sensor. To ge he value rom he sensor, you call analogRead() ha akes one argumen: wha pin i should ake a volage reading on. The value, which is beween 0 and 1023, is a represenaion o he volage on he pin.
Send he emperaure sensor
The uncion Serial.prin() sends inormaion rom he
values o he compuer
Arduino o a conneced compuer. You can see his inormaion in your serial monior. I you give Serial.prin() an argumen in quoaion marks, i will prin ou he ex you yped. I you give i a variable as an argumen, i will prin ou he value o ha variable.
47
1 cons in sensorPin = A0; 2 cons floa baselineTemp = 20.0;
3 void seup(){ 4
Serial.begin(9600); // open a serial por
5
for(in pinNumber = 2; pinNumber<5; pinNumber++){
6
pinMode(pinNumber,OUTPUT);
7
digialWrie(pinNumber, LOW);
8
}
9 }
10 void loop(){ 11
in sensorVal = analogRead(sensorPin);
12
Serial.prin(“Sensor Value: “);
13
Serial.prin(sensorVal);
for() loop tutorial
arduino.cc/or
48
Project 03 Love-o-Meer
Conver sensor reading o
Wih a litle mah, i’s possible o figure ou wha he real volage
volage
on he pin is. The volage will be a value beween 0 and 5 vols, and i will have a racional par (or example, i migh be 2.5 vols), so you’ll need o sore i inside a floa. Creae a variable named volage o hold his number. Divide sensorVal by 1024.0 and muliply by 5.0. The new number represens he volage on he pin. Jus like wih he sensor value, you’ll prin his ou o he serial monior.
Conver he vol age o
I you examine he sensor’s datasheet, here is inormaion abou
emperaure and send he
he range o he oupu volage. Daashees are like manuals
value o he compuer
or elecronic componens. They are writen by engineers, or oher engineers. The daashee or his sensor explains ha every 10 millivols o change rom he sensor is equivalen o a emperaure change o 1 degree Celsius. I also indicaes ha he sensor can read emperaures below 0 degrees. Because o his, you’ll need o creae an offse or values below reezing (0 degrees). I you ake he volage, subrac 0.5, and muliply by 100, you ge he accurae emperaure in degrees Celsius. Sore his new number in a floaing poin variable called emperaure. Now ha you have he real emperaure, prin ha ou o he serial monior oo. Since he emperaure variable is he las hing you’re going o be prining ou in his loop, you’re going o use a slighly differen command: Serial.prinln(). This command will creae a new line in he serial monior afer i sends he value. This helps make hings easier o read in when hey are being prined ou.
Turn o LEDs or a low
Wih he real emperaure, you can se up an i()...else
emperaure
saemen o ligh he LEDs. Using he baseline emperaure as a saring poin, you’ll urn on one LED on or every 2 degrees o emperaure increase above ha baseline. You’re going o be looking or a range o values as you move hrough he emperaure scale.
49
14
// conver he ADC reading o volage
15
floa volage = (sensorVal/1024.0) * 5.0;
16
Serial.prin(“, Vols: “);
17
Serial.prin(volage);
18
Serial.prin(“, degrees C: “);
Starter Kit datasheets
19
// conver he volage o emperaure in degrees
arduino.cc/kidaashees
20 floa emperaure = (volage - .5) * 100; 21
Serial.prinln(emperaure);
22
if(emperaure < baselineTemp){
23
digialWrie(2, LOW);
24
digialWrie(3, LOW);
25
digialWrie(4, LOW);
50
Project 03 Love-o-Meer
Turn on one LED or a low
The && operaor means “and”, in a logical sense. You can check
emperaure
or muliple condiions: “i he emperaure is 2 degrees greaer han he baseline, and i is less han 4 degrees above he baseline.”
Turn on wo LEDs or a
I he emperaure is beween wo and our degrees above he
medium emperaure
baseline, his block o code urns on he LED on pin 3 as well.
Turn on hree LEDs or a high emperaure
The Analog-o-Digial Converer can only read so as, so you should pu a small delay a he very end o your loop(). I you read rom i oo requenly, your values will appear erraic.
USE IT
Wih he code uploaded o he Arduino, click he serial monior icon. You should see a sream o values coming ou, ormated like his : Sensor: 200, Vols: .70, degrees C: 17 Try puting your fingers around he sensor while i is plugged ino he breadboard and see wha happens o he values in he serial monior. Make a noe o wha he emperaure is when he sensor is lef in he open air. Close he serial monior and change he baselineTemp consan in your program o he value you observed he emperaure o be. Upload your code again, and ry holding he sensor in your fingers. As he emperaure rises, you should see he LEDs urn on one by one. Congraulaions, ho suff!
51
26
}else if if(emperaure (emperaure >= baselineTemp+2 && emperaure < baselineTemp+4){
27
digialWrie(2, digialWrie (2, HIGH HIGH); );
28
digialWrie(3, digialWrie (3, LOW LOW); );
29
digialWrie(4, digialWrie (4, LOW LOW); );
30
}else if if(emperaure (emperaure >= baselineTemp+4 && emperaure < baselineTemp+6){
31
digialWrie(2, digialWrie (2, HIGH HIGH); );
32
digialWrie(3, digialWrie (3, HIGH HIGH); );
33
digialWrie(4, digialWrie (4, LOW LOW); );
34
}else if if(emperaure (emperaure >= baselineTemp+6){
35
digialWrie(2, digialWrie (2, HIGH HIGH); );
36
digialWrie(3, digialWrie (3, HIGH HIGH); );
37
digialWrie(4, digialWrie (4, HIGH HIGH); );
38
}
39
delay(1); delay (1);
40 }
Creae an inerace or wo people o es heir compaibiliy wih each oher. You ge o decide wha compaibiliy means, and how you’ll sense i. Perhaps hey have o hold hands and generae hea? Maybe hey have o hug? Wha do you hink?
Expanding he ypes o inpus you can read, you’ve used analogRead() analogR ead() and he serial monior o rack changes inside your Arduino. Now i’s possible o read a large number o analog sensors and inpus.
�4
R O T S I S E R M H O D E L
INGREDIENTS
0 2 2
R O T S I S E R M H O L I K 0 1
R O T S I S E R O T O H P
L E G
53
COLOR MIXING LAMP USING A TRI�COLOR LED AND THREE PHOTORESISTORS, YOU’LL CREATE A LAMP THAT SMOOTHLY CHANGES COLORS DEPENDING ON EXTERNAL LIGHTING CONDITIONS
Discover: analog output, mapping values
Time: 45 MINUTES
Builds on projecs: 1, 2, 3
Level:
Blinking LEDs can be un, bu wha abou ading hem, or mixing colors? You migh expec ha i’s jus a mater o providing less volage o an LED o ge i o ade. The Arduino can’ vary he oupu volage on is pins, i can only oupu 5V. Hence you’ll need o use a echnique called Pulse Widh Modulaion (PWM) o ade LEDs. PWM rapidly urns he oupu pin high and low over a fixed period o ime. The change happens aser han he human eye can see. I’s similar o he way movies work, quickly flashing a number o sill images o creae he illusion o moion. When you’re rapidly urning he pin HIGH and LOW, i’s as i you were changing he volage. The percenage o ime a pin is
HIGH in a period is called duty cycle. When he pin is HIGH or hal o he period and LOW or he oher hal, he duy cycle is 50%. A lower duy cycle gives you a dimmer LED han a higher duy cycle. The Arduino Uno has six pins se aside or PWM (digial pins 3,
5, 6, 9, 10, and 11), hey can be idenified by he ~ nex o heir number on he board.
For inpus in his projec, you’ll be using phooresisors (sensors ha change heir resisance depending on he amoun o ligh ha his hem, also known as phoocells or ligh-dependen resisors). I you connec one end o he resisor o your Arduino, you can measure he change in resisance by checking he volage on he pin.
54
Project 04 Color Mixing Lamp
BUILD THE CIRCUIT
Fig. 1
Fig. 2
Fig. 3
+
-
+
-
+
-
+
-
55
❶
Wire up your breadboard so you have power and ground on boh
❷
Place he hree phooresisors on he breadboard so hey cross
sides, jus like he earlier projecs.
he cener divide rom one side o he oher, as shown in Fig. 1. Atach one end o each phooresisor o power. On he oher side, atach a 10-kilohm resisor o ground. This resisor is in series wih he phooresisor, and ogeher hey orm a volage divider. The volage a he poin where hey mee is proporional o he raio o heir resisances, according o Ohm’s Law (see Projec 1 or more on Ohm’s Law). As he resisance o he phooresisor changes when ligh his i, he volage a his juncion changes as well. On he same side as he resisor, connec he phooresisors o Analog In pins 0, 1, and 2 wih hookup wire.
❸
Take he hree colored gels and place one over each o he phooresisors. Place he red gel over he phooresisor conneced o A0, he green over he one conneced o A1, and he blue over he one conneced o A2. Each o hese filers les only ligh o a specific wavelengh hrough o he sensor i’s covering. The red filer passes only red ligh, he green filer passes only green ligh, and he blue filer passes only blue ligh. This allows you o deec he relaive color levels in he ligh ha his your sensors.
❹
The LED wih 4 legs is a common cahode RGB LED. The LED has separae red, green, and blue elemens inside, and one common ground (he cahode). By creaing a volage difference beween he cahode and he volage coming ou o he Arduino’s PWM pins (which are conneced o he anodes hrough 220-ohm resisors), you’ll cause he LED o ade beween is hree colors. Make noe o wha he longes pin is on he LED, place i in your breadboard, and connec ha pin o ground. Connec he oher hree pins o digial pins 9, 10 and 11 in series wih 220-ohm resisors. Be sure o connec each LED lead o he correc PWM
R -
B
G
pin, according o he figure on he lef.
56
Project 04 Color Mixing Lamp
THE CODE
Useul consans
Se up consans or he pins you’re using or inpu and oupu, so you can keep rack o which sensor pairs wih which color on he LED. Use cons in or he daaype.
Variables o sore he sensor
Add variables or he incoming sensor values and or he oupu
readings as well as he ligh
values you’ll be using o ade he LED. You can use he in
level o each LED
daaype or all he variables.
Seing he direcion o he
In he seup(), begin serial communicaion a 9600 bps. Jus
digial pins and seing up
like in he previous example, you will use his o see he values o
he serial por
he sensors in he serial monior. Addiionally, you will be able o see he mapped values you’ll use o ade he LED. Also, define he LED pins as oupus wih pinMode().
Reading he value o each
In he loop() read he sensor values on A0, A1, and A2 wih
ligh sensor
analogRead() and sore he value in he appropriae variables. Pu a small delay() beween each analogRead() as he ADC akes a millisecond o do is work.
Repor he sensor readings
Prin ou he sensor values on one line.
o he compuer
The “\” is he equivalen o pressing he “ab” key on he keyboard.
57
1 cons in greenLEDPin = 9; 2 cons in redLEDPin = 11; 3 cons in blueLEDPin = 10;
4 cons in redSensorPin = A0; 5 cons in greenSensorPin = A1; 6 cons in blueSensorPin = A2;
7 in redValue = 0; 8 in greenValue = 0; 9 in blueValue = 0;
10 in redSensorValue = 0; 11 in greenSensorValue = 0; 12 in blueSensorValue = 0;
13 void seup() { 14
Serial.begin(9600);
15
pinMode(greenLEDPin,OUTPUT);
16
pinMode(redLEDPin,OUTPUT);
17
pinMode(blueLEDPin,OUTPUT);
18 }
19 void loop() { 20
redSensorValue = analogRead(redSensorPin);
21
delay(5);
22
greenSensorValue = analogRead(greenSensorPin);
23
delay(5);
24
blueSensorValue = analogRead(blueSensorPin);
25
Serial.prin(“Raw Sensor Values \ Red: “);
26
Serial.prin(redSensorValue);
27
Serial.prin(“\ Green: “);
28
Serial.prin(greenSensorValue);
29
Serial.prin(“\ Blue: “);
30
Serial.prinln(blueSensorValue);
58
Project 04 Color Mixing Lamp
Convering he sensor
The uncion o change he LED’s brighness via PWM is called
readings
analogWrie(). I needs wo argumens: he pin o wrie o, and a value beween 0-255. This second number represens he duy cycle he Arduino will oupu on he specified pin. A value o 255 will se he pin HIGH all he ime, making he atached LED as brigh as i can be. A value o 127 will se he pin HIGH hal he ime o he period, making he LED dimmer. 0 would se he pin LOW all he ime, urning he LED off. To conver he sensor reading rom a value beween 0-1023 o a value beween 0-255 or analogWrie(), divide he sensor reading by 4.
Repor he calculaed LED
Prin ou he new mapped values on heir own line.
ligh levels
Se he LED ligh levels
USE IT
Once you have your Arduino programmed and wired up, open he serial monior. The LED will probably be an o-whie color, depending on he predominan color o he ligh in your room. Look a he values coming rom he sensors in he serial monior, i you’re in an environmen wih sable lighing, he number should probably be airly consisen. Turn o he ligh in he room you’re in and see wha happens o he values o he sensors. Wih a lashligh, illuminae each o he sensors individually and noice how he values change in he serial monior, and noice how he LED’s color changes. When he phooresisors are covered wih a gel, hey only reac o ligh o a cerain wavelengh. This will give you he opporuniy o change each o he colors independenly.
59
31
redValue = redSensorValue/4;
32
greenValue = greenSensorValue/4;
33
blueValue = blueSensorValue/4;
34
Serial.prin(“Mapped Sensor Values \ Red: “);
35
Serial.prin(redValue);
36
Serial.prin(“\ Green: “);
37
Serial.prin(greenValue);
38
Serial.prin(“\ Blue: “);
39
Serial.prinln(blueValue);
40
analogWrie(redLEDPin, redValue);
41
analogWrie(greenLEDPin, greenValue);
42
analogWrie(blueLEDPin, blueValue);
43 }
You may noice ha he phooresisor’s oupu doesn’ range all he way rom 0 o 1023. Tha’s okay or his projec, bu or a more deailed explanaion o how o calibrae or he range you’re reading, see Projec 6. You’ll probably noice ha he LED’s ading is no linear. When he LED is abou a hal brighness, i appears o sop geting much brigher. This is because our eyes don’ perceive brighness linearly. The brighness o he ligh depends no only on he level ha you analogWrie() bu also on he disance o he ligh rom he diffuser, he disance o your eye rom he ligh, and he brighness o he ligh relaive o oher ligh in he room.
How could you use his o le you know i i’s a nice day ouside while you’re working inside? Wha oher sors o sensors can you use o conrol he LED’s color?
60
Project 04 Color Mixing Lamp
The LED on is own is prety nea, bu i’s no much o a lamp. However, here are a number o differen ways you can diffuse he ligh o make i resemble somehing like a radiional incandescen. A ping pong ball wih a hole cu ou or he LED o slide ino makes or a nice diffuser. Oher ways include covering he ligh in ranslucen glue, or sanding he surace o he ligh. No mater wha roue you ake, you’re going o lose a leas a litle brighness when i’s diffused, bu i will probably look a lo nicer.
No longer limied o jus urning lighs on and off, you now have conrol over how brigh or dim somehing will be. analogWrie() is he uncion ha allows you o PWM componens atached o pins 3, 5, 6, 9, 10, or 11, varying he duy cycle.
The ping pong ball cu in order o accommodae he LED Fig.4
�5
R E T E M O I T N E T O P
MALE HEADER PIN (3 pins)
INGREDIENTS
R O T O M
M R A
R O T I C A P A C
O V R E S
R O T O M
F U 0 0 1
63
MOOD CUE USE A SERVO MOTOR TO MAKE A MECHANICAL GAUGE TO POINT OUT WHAT SORT OF MOOD YOU’RE IN THAT DAY
Discover: mapping values, servo motors, using built-in libraries
Time: 1 HOUR
Builds on projecs: 1, 2, 3, 4
Level:
Servo moors are a special ype o moor ha don’ spin around in a circle, bu move o a specific posiion and say here unil you ell hem o move again. Servos usually only roae 180 degrees (one hal o a circle). Combining one o hese moors wih a litle cardboard craf, you’ll be able o le people know i hey should come and ask or your help on heir nex projec or no. Similar o he way you used pulses o PWM an LED in he Color Mixing Lamp Projec, servo moors expec a number o pulses ha ell hem wha angle o move o. The pulses always come a he same ime inervals, bu he widh varies beween 1000 and 2000 microseconds. While i’s possible o wrie code o generae hese pulses, he Arduino sofware comes wih a library ha allows you o easily conrol he moor. Because he servo only roaes 180 degrees, and your analog inpu goes rom 0-1023, you’ll need o use a uncion called map() o change he scale o he values coming rom he poeniomeer. One o he grea hings abou he Arduino communiy are he alened people who exend is uncionaliy hrough addiional sofware. I’s possible or anyone o wrie libraries o exend he Arduino’s uncionaliy. There are libraries or a wide variey o sensors and acuaors and oher devices ha users have conribued o he communiy. A sofware library expands he uncionaliy o a programming environmen. The Arduino sofware comes wih a number o libraries ha are useul or working wih hardware or daa. One o he included libraries is designed o use wih servo moors. In your code, you’ll impor he library, and all o is uncionaliy will be available o you.
64
Project 05 Mood Cue
BUILD THE CIRCUIT
Fig. 1
Fig. 2
+
-
+
-
+
-
+
-
65
❶
Atach 5V and ground o one side o your breadboard rom he
❷
Place a poeniomeer on he breadboard, and connec one side
Arduino.
o 5V, and he oher o ground. A poeniomeer is a ype o volage divider. As you urn he knob, you change he raio o he volage beween he middle pin and power. You can read his change on an analog inpu. Connec he middle pin o analog pin 0. This will conrol he posiion o your servo moor.
❸
The servo has hree wires coming ou o i. One is power (red), one is ground (black), and he hird (whie) is he conrol line ha will receive inormaion rom he Arduino. Plug hree male headers ino he emale ends o he servo wires (see Fig. 3). Connec he headers o your breadboard so ha each pin is in a differen row. Connec 5V o he red wire, ground o he black wire, and he whie wire o pin 9.
❹
When a servo moor sars o move, i draws more curren han i i were already in moion. This will cause a dip in he volage on your board. By placing a 100u capacior across power and ground righ nex o he male headers as shown in Fig. 1, you can smooh ou any volage changes ha may occur. You can also place a capacior across he power and ground going ino your poeniomeer. These are called decoupling capaciors because hey reduce, or decouple, changes caused by he componens rom he res o he circui. Be very careul o make sure you are connecing he cahode o ground (ha’s he side wih a black sripe down he side) and he anode o power. I you pu he capaciors in backwards, hey can explode.
Your servo moor comes wi h emale connecors, so you’ll need o add header pins o connec i o he breadboard. Fig. 3
66
Project 05 Mood Cue
THE CODE
Impor he library
To use he servo library, you’ll firs need o impor i. This makes he addiions rom he library available o your skech.
Creaing he Servo objec
To reer o he servo, you’re going o need o creae a named insance o he servo library in a variable. This is called an objec. When you do his, you’re making a unique name ha will have all he uncions and capabiliies ha he servo library offers. From his poin on in he program, every ime you reer o myServo, you’ll be alking o he servo objec.
Variable declaraion
Se up a named consan or he pin he poeniomeer is atached o, and variables o hold he analog inpu value and angle you wan he servo o move o.
Associaing he Servo objec
In he seup(), you’re going o need o ell he Arduino wha
wih he Arduino pin,
pin your servo is atached o.
iniializing he serial por Include a serial connecion so you can check he values rom he poeniomeer and see how hey map o angles on he servo moor.
Reading he poeniomeer
In he loop(), read he analog inpu and prin ou he value o
value
he serial monior.
Mapping poeniomeer
To creae a usable value or he servo moor rom your analog
value o he servo values
inpu, i’s easies o use he map() uncion. This handy uncion scales numbers or you. In his case i will change values beween 0-1023 o values beween 0-179. I akes five argumens : he number o be scaled (here i’s poVal), he minimum value o he inpu (0), he maximum value o he inpu (1023), he minimum value o he oupu (0), and he maximum value o he oupu (179). Sore his new value in he angle variable. Then, prin ou he mapped value o he serial monior.
Roaing he servo
Finally, i’s ime o move he servo. The command servo.
wrie() moves he moor o he angle you speciy. A he end o he loop() pu a delay so he servo has ime o move o is new posiion.
67
1 #include
2 Servo myServo;
3 in cons poPin = A0; 4 in poVal; 5 in angle;
6 void seup() { 7 myServo.atach(9);
8
Serial.begin(9600);
9 }
10 void loop() { 11
poVal = analogRead(poPin);
12
Serial.prin(“poVal: “);
13
Serial.prin(poVal);
14
angle = map(poVal, 0, 1023, 0, 179);
15
Serial.prin(“, angle: “);
16
Serial.prinln(angle);
17
myServo.wrie(angle);
18
delay(15);
19 }
Noe ha #include insracions have no semicolon a he end o he line.
68
Project 05 Mood Cue
USE IT
Once your Arduino has been programmed and powered up, open he serial monior. You should see a sream o values similar o his:
poVal : 1023, angle : 179 poVal : 1023, angle : 179 When you urn he poeniomeer, you should see he numbers change. More imporanly, you should see your servo moor move o a new posiion. Noice he relaionship beween he value o poVal and angle in he serial monior and he posiion o he servo. You should see consisen resuls as you urn he po. One nice hing abou using poeniomeers as analog inpus is ha hey will give you a ull range o values beween 0 and 1023. This makes hem helpul in esing projecs ha use analog inpu.
Servo moors are regular moors wih a number o gears and some circuis inside. The mechanics inside provide eedback o he circui, so i is always aware o is posiion. While i may seem like his is a limied range o moion, i’s possible o ge i o make a wide variey o differen kinds o movemens wih some addiional mechanics. There are a number o resources ha describe mechanisms in deail like robives.com/
mechs and he book Making Things Move by Dusyn Robers.
The poeniomeer is no he only sensor you can use or conrolling he servo. Using he same physical seup (an arrow poining o a number o differen indicaors) and a differen sensor, wha sor o indicaor can you make? How would his work wih emperaure (like in he Love-o-Meer)? Could you ell he ime o day wih a phooresisor? How does mapping values come ino play wih hose ypes o sensors?
Servo moors can easily be conrolled by he Arduino using a library, which is a collecion o code ha exends a programming environmen. Someimes i is necessary o repurpose values by mapping hem rom one scale o anoher.
69
Now ha you’re up and running wih moion, i’s ime o le people know i you’re available o help hem on heir projecs, or i you wan o be lef alone o plan your nex creaion. Wih scissors, cu ou a piece o cardboard in he shape o an arrow. Posiion your servo o 90 degrees (check he angle value in he serial monior i you’re unsure). Tape he arrow so i’s oriened in he same direcion as he moor’s body. Now you should be able o roae he arrow 180 degrees when urning he poeniomeer. Take a piece o paper ha is larger han he servo wih he arrow atached and draw a hal circle on i. On one end o he circle, wrie “Say Ou”. On he oher end, wrie “Come in”. Pu “Knock please!” in he middle o he arc. Place he servo wih he arrow on op o he paper. Congraulaions, you’ve go a way o ell people jus how busy you are wih your projecs!
N I E M O C
E S A E L P
S T A Y O U T
K C O N K
❶
❷
Aach a paper arrow o he servo arm.
Design a paper base and place i under he servo.
�6
O Z E I P
INGREDIENTS
R O T S I S E R O T O H P
R O T S I S E R M H O L I K 0 1
71
LIGHT THEREMIN TIME TO MAKE SOME NOISE! USING A PHOTORESISTOR AND A PIEZO ELEMENT, YOU’RE GOING TO MAKE A LIGHT�BASED THEREMIN
Discover: making sound with the tone() function, calibrating analog sensors
Time: 45 MINUTES
Builds on projecs: 1, 2, 3, 4
Level:
A heremin is an insrumen ha makes sounds based on he movemens o a musician’s hands around he insrumen. You’ve probably heard one in scary movies. The heremin deecs where a perormer’s hands are in relaion o wo anennas by reading he capaciive change on he anennas. These anennas are conneced o analog circuiry ha creae he sound. One anenna conrols he requency o he sound and he oher conrols volume. While he Arduino can’ exacly replicae he myserious sounds rom his insrumen, i is possible o emulae hem using he one() uncion. Fig. 1 shows he difference beween he pulses emited by analogWrie() and one(). This enables a ransducer like a speaker or piezo o move back and orh a differen speeds. PERI OD
Notice how the signal is low most of the time,
PWM 50: analogWrite(50)
but the frequency is the same as PWM 200. PERI OD
Notice how the voltage is high most of the
PWM 200: analogWrite(200)
time, but the frequency is the same as PWM 50. PERI OD
The duty cycle is 50% (on half the time, off half
TONE 440: tone(9,440)
the time), but the frequency changes.
PERI OD
Same duty cycle as Tone 440; but twice the
TONE 880: tone(9,880)
frequency.
Fig. 1
10 MI LL IS ECONDS
72
Project 06 Ligh Theremin
Insead o sensing capaciance wih he Arduino, you’ll be using a phooresisor o deec he amoun o ligh. By moving your hands over he sensor, you’ll change he amoun o ligh ha alls on he phooresisor’s ace, as you did in Projec 4. The change in he volage on he analog pin will deermine wha requency noe o play. You’ll connec he phooresisors o he Arduino using a volage divider circui like you did in Projec 4. You probably noiced in he earlier projec ha when you read his circui using analogRead(), your readings didn’ range all he way rom 0 o 1023. The fixed resisor connecing o ground limis he low end o he range, and he brighness o your ligh limis he high end. Insead o setling or a limied range, you’ll calibrae he sensor readings geting he high and low values, mapping hem o sound requencies using he map() uncion o ge as much range ou o your heremin as possible. This will have he added benefi o adjusing he sensor readings whenever you move your circui o a new environmen, like a room wih differen ligh condiions.
A piezo is a small elemen ha vibraes when i receives elecriciy. When i moves, i displaces air around i, creaing sound waves.
BUILD THE CIRCUIT
Fig. 2
+
-
+
-
+
-
+
-
73
Fig. 3
Tradiional heremins can conrol he requency and he volume o sound. In his example, You’ll be able o conrol he requency only. While you can’ conrol he volume hrough he Arduino, i is possible o change he volage level ha ges o he speaker manually. Wha happens i you pu a poeniomeer in series wih pin 8 and he piezo? Wha abou anoher phooresisor?
❶
On your breadboard, connec he ouer bus lines o power and
❷
Take your piezo, and connec one end o ground, and he oher
❸
Place your phooresisor on he breadboard, connecing one
ground.
o digial pin 8 on he Arduino.
end o 5V. Connec he oher end o he Arduino’s analogIn pin 0, and o ground hrough a 10-kilohm resisor. This circui is he same as he volage divider circui in Projec 4.
74
Project 06 Ligh Theremin
THE CODE
Creae variables or
Creae a variable o hold he analogRead() value rom he
calibraing he sensor
phooresisor. Nex, creae variables or he high and low values. You’re going o se he iniial value in he sensorLow variable o 1023, and se he value o he sensorHigh variable o 0. When you firs run he program, you’ll compare hese numbers o he sensor’s readings o find he real maximum and minimum values.
Name a consan or your
Creae a consan named ledPin. You’ll use his as an indicaor
calibraion indicaor
ha your sensor has finished calibraing. For his projec, use he on-board LED conneced o pin 13.
Se digial pin direcion and
In he seup(), change he pinMode() o ledPin o OUTPUT,
urn i high
and urn he ligh on.
Use a while() loop or
The nex seps will calibrae he sensor’s maximum and minimum
calibraion
values. You’ll use a while() saemen o run a loop or 5 seconds. while() loops run unil a cerain condiion is me. In his case you’re going o use he millis() uncion o check he curren ime. millis() repors how long he Arduino has been running since i was las powered on or rese.
Compare sensor values or
In he loop, you’ll read he value o he sensor; i he value is less
calibraion
han sensorLow (iniially 1023), you’ll updae ha variable. I i is greaer han sensorHigh (iniially 0), ha ges updaed.
Indicae calibraion has
When 5 seconds have passed, he while() loop will end. Turn off
inished
he LED atached o pin 13. You’ll use he sensor high and low values jus recorded o scale he requency in he main par o your program.
75
1 in sensorValue; 2 in sensorLow = 1023; 3 in sensorHigh = 0;
4 cons in ledPin = 13;
5 void seup() {
6
pinMode(ledPin, OUTPUT);
7
digialWrie(ledPin, HIGH);
8
while (millis() < 5000) {
while()
arduino.cc/while
9
sensorValue = analogRead(A0);
10
if (sensorValue > sensorHigh) {
11
sensorHigh = sensorValue;
12
}
13
if (sensorValue < sensorLow) {
14
sensorLow = sensorValue;
15
}
16
}
17
digialWrie(ledPin, LOW);
18 }
76
Project 06 Ligh Theremin
Read and sore he sensor
In he loop(), read he value on A0 and sore i in sensorValue.
value Map he sensor value o a
Creae a variable named pich. The value o pich is going
requency
o be mapped rom sensorValue. Use sensorLow and
sensorHigh as he bounds or he incoming values. For saring values or oupu, ry 50 o 4000. These numbers se he range o requencies he Arduino will generae.
Play he requency
Nex, call he one() uncion o play a sound. I akes hree argumens : wha pin o play he sound on (in his case pin 8), wha requency o play (deermined by he pich variable), and how long o play he noe (ry 20 milliseconds o sar). Then, call a delay() or 10 milliseconds o give he sound some ime o play.
USE IT
When you irs power he Arduino on, here is a 5 second window or you o calibrae he sensor. To do his, move your hand up and down over he phooresisor, changing he amoun o ligh ha reaches i. The closer you replicae he moions you expec o use while playing he insrumen, he beer he calibraion will be. Aer 5 seconds, he calibraion will be complee, and he LED on he Arduino will urn o. When his happens, you should hear some noise coming rom he piezo! As he amoun o ligh ha alls on he sensor changes, so should he requency ha he piezo plays.
77
19 void loop() { 20
sensorValue = analogRead(A0);
21
in pich = map(sensorValue,sensorLow,sensorHigh, 50, 4000);
22
one(8,pich,20);
23
delay(10);
24 }
The range in he map() uncion ha deermines he pich is prety wide, ry changing he requencies o find ones ha are he righ fi or your musical syle.
The one() uncion operaes very much like he PWM in analogWrie() bu wih one significan difference. In analogWrie() he requency is fixed; you change he raio o he pulses in ha period o ime o vary he duy cycle. Wih one() you’re sill sending pulses, bu changing he requency o hem. one() always pulses a a 50% duy cycle (hal he ime he pin is high, he oher hal he ime i is low).
The one() uncion gives you he abiliy o generae differen requencies when i pulses a speaker or piezo. When using sensors in a volage divider circui, you probably won’ ge a ull range o values beween 0-1023. By calibraing sensors, i’s possible o map your inpus o a useable range.
�7
R O T S I S E R
H C T I W S
INGREDIENTS
O Z E I P
M H O L I K 0 1
R O T S I S E R M H O G E M 1
R O T S I S E R M H O 0 2 2
79
KEYBOARD INSTRUMENT WITH FEW RESISTORS AND BUTTONS YOU ARE GOING TO BUILD A SMALL MUSICAL KEYBOARD
Discover: resistor ladders, arrays
Time: 45 MINUTES
Builds on projecs: 1, 2, 3, 4, 6
Level:
While i’s possible o simply hook up a number o momenary swiches o digial inpus o key o differen ones, in his projec, you’ll be consrucing somehing called a resisor ladder . This is a way o read a number o swiches using he analog inpu. I’s a helpul echnique i you find yoursel shor on digial inpus. You’ll hook up a number o swiches ha are conneced in parallel o analog in 0. Mos o hese will connec o power hrough a resisor. When you press each buton, a differen volage level will pass o he inpu pin. I you press wo butons a he same ime, you’ll ge a unique inpu based on he relaionship beween he wo resisors in parallel.
A resisor ladder and ive swiches as analog inpu. Fig. 1
80
Project 07 Keyboard Insrumen
BUILD THE CIRCUIT
The arrangemen o resisors and swiches eeding ino an analog inpu is called a resisor ladder. Fig. 2
Fig. 3
+
-
+
-
+
-
+
-
81
❶
Wire up your breadboard wih power and ground as in he previous projecs. Connec one end o he piezo o ground. Connec he oher end o pin 8 on your Arduino.
❷
Place your swiches on he breadboard as shown in he circui. The arrangemen o resisors and swiches eeding ino an analog inpu is called a resisor ladder. Connec he firs one direcly o power. Connec he second, hird and ourh swiches o power hrough a 220-ohm, 10-kilohm and 1-megohm resisor, respecively. Connec all he swiches’ oupus ogeher in one juncion. Connec his juncion o ground wih a 10-kilohm resisor, and also connec i o Analog In 0. Each o hese acs as a volage divider.
Think abou an enclosure or he keyboard. While old analog synhesizers had wires poking ou all over he place, your keyboard is sleek and digial. Prepare a small piece o cardboard ha can be cu ou o accommodae your butons. Label he keys, so you know wha noes are riggered by each key.
❶
❷
Draw and cu a piece o paper wih holes or he our
Posiion he paper over he buons and piezo.
buons and piezo. Decorae i o look like a piano keyboard.
Enjoy your creaion!
82
Project 07 Keyboard Insrumen
THE CODE
The array
In his program, you’ll need o keep a lis o requencies you wan o play when you press each o your butons. You can sar ou wih he requencies or middle C, D, E and F (262Hz, 294Hz, 330Hz, and 349Hz). To do his, you’ll need a new kind o variable called an array. An array is a way o sore differen values ha are relaed o each oher, like he requencies in a musical scale, using only one name. They are a convenien ool or you o quickly and efficienly access inormaion. To declare an array, sar as you would wih a variable, bu ollow he name wih a pair o square brackes: []. Afer he equals sign, you’ll place your elemens in curly brackes. To read or change he elemens o he array, you reerence he individual elemen using he array name and hen he index o he iem you wan o address. The index reers o he order in which he iems appear when he array is creaed. The firs iem in he array is iem 0, he second is iem 1, and so orh.
Creae an arra y o
Se up an array o our noes using he requencies lised above.
requencies
Make his array a global variable by declaring i beore he
seup().
Begin serial communicaion
In your seup(), sar serial communicaion wih he compuer.
Read he analog value and
In he loop(), declare a local variable o hold he value
send i o he serial monior
read on pin A0. Because each swich has a differen resisor value connecing i o power, each will have a differen value associaed wih i. To see he values, add he line Serial.
prinln(keyVal) o send o he compuer. Use an i()...else saemen o
Using an i()...else saemen, you can assign each value o a
deermine wha noe o play
differen one. The values included in he example program are ballpark figures or hese resisor sizes. As all resisors have some olerance or error, hese may no work exacly or you. Use he inormaion rom he serial monior o adjus as necessary.
83
in butons[6]; in butons[6]; // se up an array wih 6 inegers
in butons[0] in butons[0] = 2; // give he firs elemen of he array he value 2
in noes[] noes[] = {262,294,330,349}; 1 in
2 void seup seup() () { 3
Serial. Serial .begin begin(9600); (9600);
4 }
5 void loop loop() () { 6
in keyVal in keyVal = analogRead analogRead(A0); (A0);
7
Serial. Serial .prinln prinln(keyVal); (keyVal);
8
if(keyVal if (keyVal == 1023){
9 10
one(8, one (8, noes[0]); }
84
Project 07 Keyboard Insrumen
Play he noes ha correspond
Afer each i() saemen, call he one() uncion. The
o he analog value
program reerences he array o deermine wha requency o play. I he value o A0 maches one o your i saemens, you can ell he Arduino o play a one. I’s possible your circui is a litle “noisy” and he values may flucuae a litle bi while pressing a swich. To accommodae or his variaion, i’s a good idea o have a small range o values o check agains. I you use he comparison “&&”, you can check muliple saemens o see i hey are rue. I you press he firs buton, noes[0] will play. I you press he second, noes[1] will play, and i you press he hird, noes[2] will play. This is when arrays become really handy.
Sop playing he one when
Only one requency can play on a pin a any given ime, so i
nohing is pressed
you’re pressing muliple keys, you’ll only hear one sound. To sop playing noes when here is no buton being pressed, call he noTone() uncion, providing he pin number o sop playing sound on.
USE IT
I your resisors are close in value o he values in he example program, you should hear some sounds rom he piezo when you press he buons. I no, check he serial monior o make sure each o he buons is in a range ha corresponds o he noes in he i()... else saemen. I you’re hearing a sound ha seems o suer, ry increasing he range a lile bi. Press muliple butons a he same ime, and see wha sor o values you ge in he serial monior. Use hese new values o rigger even more sounds. Experimen wih differen requencies o expand your musical oupu. You can find requencies o musical noes on his page: arduino.cc/requencies
I you replace he swiches and resisor ladder wih analog sensors, can you use he addiional inormaion hey give you o creae a more dynamic insrumen? You could use he value o change he duraion o a noe or, like in he Theremin Projec, creae a sliding scale o sounds.
85
11
else if if(keyVal (keyVal >= 990 && keyVal <= 1010){
12
one(8, one (8, noes[1]);
13
}
14
else if if(keyVal (keyVal >= 505 && keyVal <= 515){
15
one(8, one (8, noes[2]);
16
}
17
else if if(keyVal (keyVal >= 5 && keyVal <= 10){
18
one(8, one (8, noes[3]);
19
}
20
else{ else {
21 22
noTone(8); noTone (8); }
23 }
The one() uncion is un or generaing sounds, bu i does have a ew limiaions. I can only creae square waves, no smooh sine waves or riangles. Square waves don’ look much like waves a all. As you saw in Fig. 1 in Projec 6, i’s a series o on and off pulses. As you sar your band, keep some hings in mind : only one one can play a a ime and one() will inerere wih analogWrie() on pins 3 and 11.
Arrays are useul or grouping Arrays grouping similar similar ypes o inormai inormaion on ogeher; hey are accessed by index numbers which reer o individual elemens. Resisor ladders are an easy way o ge more digial inpus ino a sysem by plugging ino an analog inpu.
�8
R O T S I S E R
H C T I W S
INGREDIENTS
D E L
M H O L I K 0 1
R O T S I S E R M H O 0 2 2
87
DIGITAL HOURGLASS IN THIS PROJECT, YOU’LL BUILD A DIGITAL HOURGLASS THAT TURNS ON AN LED EVERY TEN MINUTES. KNOW HOW LONG YOU’RE WORKING ON YOUR PROJECTS BY USING THE ARDUINO’S BUILT�IN TIMER Discover: long data type, creating a timer
Time: 30 MINUTES
Builds on projecs: 1, 2, 3, 4
Level:
Up o now, when you’ve waned somehing o happen a a specific ime inerval wih he Arduino, you’ve used delay(). This is handy, bu a litle confining. When he Arduino calls delay(), i reezes is curren sae or he duraion o he delay. Tha means here can be no oher inpu or oupu while i’s waiing. Delays are also no very helpul or keeping rack o ime. I you waned o do somehing every 10 seconds, having a 10 second delay would be airly cumbersome.
The millis() uncion helps o solve hese problems. I keeps rack o he ime your Arduino has been running in milliseconds. You used i previously in Projec 6 when you creaed a imer or calibraion. So ar you’ve been declaring variables as in. An in (ineger) is a 16-bi number, i holds values beween -32,768 and 32,767. Those may be some large numbers, bu i he Arduino is couning 1000 imes a second wih millis(), you’d run ou o space in less han a minue. The long daaype holds a 32-bi number (beween -2,147,483,648 and 2,147,483,647). Since you can’ run ime backwards o ge negaive numbers, he variable o sore millis() ime is called an unsigned
long. When a daaype is called unsigned, i is only posiive. This allows you o coun even higher. An unsigned long can coun up o 4,294,967,295. Tha’s enough space or milis() o sore ime or almos 50 days. By comparing he curren millis() o a specific value, you can see i a cerain amoun o ime has passed. When you urn your hourglass over, a il swich will change is sae, and ha will se off anoher cycle o LEDs urning on. The il swich works jus like a regular swich in ha i is an on/off sensor. You’ll use i here as a digial inpu. Wha makes il swiches unique is ha hey deec orienaion. Typically hey have a small caviy inside he housing ha has a meal
88
Project 08 Digial Hourglass
ball. When iled in he proper way, he ball rolls o one side o he caviy and connecs he wo leads ha are in your breadboard, closing he swich. Wih six LEDs, your hourglass will run or an hour, jus as is name implies.
BUILD THE CIRCUIT
Fig. 1
Fig. 2
+
-
+
-
+
-
+
-
89
❶
Connec power and ground o your breadboard.
❷
Connec he anode (longer leg) o six LEDs o digial pins 2-7.
❸
Connec one lead o he il swich o 5V. Connec he oher o
Connec he LEDs o ground hrough 220-ohm resisors.
a 10-kilohm resisor o ground. Connec he juncion where hey mee o digial pin 8.
You don’ need o have your Arduino ehered o he compuer or his o work. Try building a sand wih some cardboard or syrooam and power he Arduino wih a batery o make a porable version. You can creae a cover wih some numeric indicaors alongside he lighs.
Til swiches are grea, inexpensive ools or deermining he orienaion o somehing. Acceleromeers are anoher ype o il sensor, bu hey give ou much more inormaion. They are also significanly more expensive. I you’re jus looking o see i somehing is up or down, a il sensor works grea.
90
Project 08 Digial Hourglass
THE CODE
Declare a named consan
You’re going o need a number o global variables in your program o ge his all working. To sar, creae a consan named swichPin. This will be he name o he pin your il swich is on.
Creae a variable o hold he
Creae a variable o ype unsigned long, This will hold he ime
ime
an LED was las changed.
Name variables or he inpus
Creae a variable or he swich sae, and anoher o hold he
and oupus
previous swich sae. You’ll use hese wo o compare he swich’s posiion rom one loop o he nex. Creae a variable named led. This will be used o coun which LED is he nex one o be urned on. Sar ou wih pin 2.
Declare a variable describing
The las variable you’re creaing is going o be he inerval
he inerval beween evens
beween each LED urning on. This will be be a long daaype. In 10 minues (he ime beween each LED urning on) 600,000 milliseconds pass. I you wan he delay beween lighs o be longer or shorer, his is he number you change.
Se he direcion o your
In your seup(), you need o declare he LED pins 2-7 as
digial pins
oupus. A or() loop declares all six as OUTPUT wih jus 3 lines o code. You also need o declare swichPin as an INPUT.
Check he ime since he
When he loop() sars, you’re going o ge he amoun o ime
program sared running
he Arduino has been running wih millis() and sore i in a local variable named currenTime.
Evaluae he amoun o
Using an i() saemen, you’ll check o see i enough ime has
ime ha has passed since
passed o urn on an LED. Subrac he currenTime rom he
he previous loop()
previousTime and check o see i i is greaer han he inerval variable. I 600,000 milliseconds have passed (10 minues), you’ll se he variable previousTime o he value o currenTime.
91
1 cons in swichPin = 8;
2 unsigned long previousTime = 0;
3 in swichSae = 0; 4 in prevSwichSae = 0;
5 in led = 2;
6 long inerval = 600000;
7 void seup() { 8
for(in x = 2;x<8;x++){
9
pinMode(x, OUTPUT);
10
}
11
pinMode(swichPin, INPUT);
12 }
13 void loop(){ 14
unsigned long currenTime = millis();
15
if(currenTime - previousTime > inerval) {
16
previousTime = currenTime;
92
Project 08 Digial Hourglass
Turn on an LED, prepare or
previousTime indicaes he las ime an LED was urned on.
he nex one
Once you’ve se previousTime, urn on he LED, and incremen he led variable. The nex ime you pass he ime inerval, he nex LED will ligh up.
Check o see i all lighs
Add one more i saemen in he program o check i he LED on
are on
pin 7 is urned on. Don’ do anyhing wih his ye. You’ll decide wha happens a he end o he hour laer.
Read he value o he swich
Now ha you’ve checked he ime, you’ll wan o see i he swich has changed is sae. Read he swich value ino he
swichSae variable. Rese he variables o heir
Wih an i() saemen, check o see i he swich is in a differen
deauls i necessary
posiion han i was previously. The != evaluaion checks o see i swichSae does no equal prevSwichSae. I hey are differen, urn he LEDs off, reurn he led variable o he firs pin, and rese he imer or he LEDs by seting previousTime o currenTime.
Se he curren sae o he
A he end o he loop(), save he swich sae in
previous sae
prevSwichSae , so you can compare i o he value you ge or swichSae in he nex loop().
USE IT
Once you’ve programmed he board, check he ime on a clock. Aer 10 minues have passed, he irs LED should have urned on. Every 10 minues aer ha, a new ligh will urn on. A he end o an hour, all six ligh should be on. When you lip he circui over, and cause he il swich o change is sae, he lighs will urn o and he imer will sar again.
93
17
digialWrie(led, HIGH);
18
led++;
19
if(led == 7){
20
}
21
}
22
swichSae = digialRead(swichPin);
23
if(swichSae != prevSwichSae){
24
for(in x = 2;x<8;x++){
25
digialWrie(x, LOW);
26
}
27
led = 2;
28
previousTime = currenTime;
29
}
30
prevSwichSae = swichSae;
31 }
When he clock reaches one hour and all six lighs are on, hey jus say on. Can you hink o a way o ge your atenion when he hour is up? Sound or flashing he lighs are boh good indicaors. The led variable can be checked o see i all he lighs are on, ha’s a good place o check or grabbing someone’s atenion. Unlike an hourglass filled wih sand, he lighs go eiher up or down depending on he orienaion o he swich. Can you figure ou how you can use he swichSae variable o indicae wha direcion he lighs should go?
To measure he amoun o ime beween evens, use he millis() uncion. Because he numbers i generaes are larger han wha you can sore in an in, you should use he daaype unsigned long or soring is values.
�9
P A N S Y R E T T A B
H C T I W S
R O T S I S E R
T E F S O M
INGREDIENTS
M H O L I K 0 1
9v baery
7 0 0 4 N 1 E D O I D
R O T O M
Y R E T T A B
95
MOTORIZED PINWHEEL GET THE ARDUINO TO SPIN A COLORFUL PINWHEEL USING A MOTOR
Discover: transistors, high current/voltage loads
Time: 45 MINUTES
Builds on projecs: 1, 2, 3, 4
Level:
Conrolling moors wih an Arduino is more complicaed han jus conrolling LEDs or a couple o reasons. Firs, moors require more curren han he Arduino’s oupu pins can supply, and second, moors can generae heir own curren hrough a process called inducion, which can damage your circui i you don’ plan or i. However, moors make i possible o move physical hings, making your projecs much more exciing. They’re worh he complicaions! Moving hings akes a lo o energy. Moors ypically require more curren han he Arduino can provide. Some moors require a higher volage as well. To sar moving, and when i has a heavy load atached, a moor will draw as much curren as i can. The Arduino can only provide 40 milliamps (mA) rom is digial pins, much less han wha mos moors require o work.
Transisors are componens ha allow you o conrol high curren and high volage power sources rom he low curren oupu o he Arduino. There are many differen kinds, bu hey work on he same principle. You can hink o ransisors as digial swiches. When you provide volage o one o he ransisor’s pins, called he gae, i closes he circui beween he oher wo pins, called he source and drain. This way, you can urn a higher curren/volage moor on and off wih your Arduino.
Moors are a ype o inducive device. Inducion is a process by which a changing elecrical curren in a wire can generae a changing magneic field around he wire. When a moor is given elecriciy, a ighly wound coil inside he housing o copper creaes a magneic field. This field causes he shaf (he par ha sicks ou o he housing) o spin around.
96
Project 09 Moorized Pinwheel
The reverse is also rue: a moor can generae elecriciy when he shaf is spun around. Try ataching an LED o he wo leads o your moor, hen spin he shaf wih your hand. I nohing happens, spin he shaf he oher way. The LED should ligh up. You’ve jus made a iny generaor ou o your moor. When you sop supplying energy o a moor, i will coninue o spin, because i has ineria. When i’s spinning, i will generae a volage in he opposie direcion han he curren you gave i. You saw his effec when you made your moor ligh up an LED. This reverse volage, someimes called back-volage, can damage your ransisor. For his reason, you should pu a diode in parallel wih he moor, so ha he back volage passes hrough he diode. The diode will only allow elecriciy o flow in one direcion, proecing he res o he circui.
BUILD THE CIRCUIT
Fig. 1
Fig. 2
97
❶
Connec power and ground o your breadboard hrough he
❷
Add a momenary swich o he board, connecing one side o
Arduino.
power, and he oher side o digial pin 2 on he Arduino. Add a 10-kilohm pull-down resisor o ground on he oupu pin o he swich.
❸
When using circuis wih differen volages, you have o connec heir grounds ogeher o provide a common ground. Plug he 9V batery snap ino your breadboard. Connec ground rom he batery o ground o your Arduino on he breadboard wih a jumper, as shown in Fig. 1. Then atach he moor’s ree lead o he 9V power.
❹
Place he ransisor on he board. Look a he componen so ha he meal ab is acing away rom you. Connec digial pin 9 o he lef pin on he ransisor. This pin is called he gae. A change in volage on he gae makes a connecion beween he oher wo pins. Connec one end o he moor o he middle pin o he ransisor. This pin is called he drain. When he Arduino acivaes he ransisor by supplying volage o he gae, his pin will be conneced o he hird pin, called he source. Connec he source o ground.
❺
Nex, connec he moor’s volage supply o he moor and breadboard. The las componen o be added is he diode. The diode is a polarized componen, i can go only one way in he circui. Noice ha he diode has a sripe on one end. Tha end is he negaive end, or cahode, o he diode. The oher end is he posiive end, or anode. Connec he anode o he diode o he ground o he moor and he cahode o he diode o he power o he moor. See Fig. 1. This may seem backwards, and in ac, i is. The diode will help preven any back-volage generaed by he moor rom going back ino your circui. Remember, back volage will flow in he opposie direcion o he volage ha you supply.
LEDs are diodes oo, in case you were wondering why heir leads were also called anodes and cahodes. There are many kinds o diodes, bu hey all share one rai. They allow curren o flow rom anode o cahode, bu no he reverse.
98
Project 09 Moorized Pinwheel
THE CODE
Name your consans and
The code is remarkably similar o he code you firs used or
variables
urning on an LED. Firs o all, se up some consans or he swich and moor pins and a variable named swichSae o hold he value o he swich.
Declare he pins’ direcion
In your seup(), declare he pinMode() o he moor ( OUTPUT) and swich (INPUT) pins.
Read he inpu, pull he
Your loop() is sraighorward. Check he sae o he swich-
oupu high i pressed
Pin wih digialRead(). I he swich is pressed, urn he moorPin HIGH. I i is no pressed, urn he pin LOW. When HIGH, he ransisor will acivae, compleing he moor circui. When LOW, he moor will no spin.
Moors have an opimal operaing volage. They will work on as litle as 50% o he raed volage and as much as 50% over ha number. I you vary he volage, you can change he speed a which he moor roaes. Don’ vary i oo much, hough, or you will burn ou your moor. Moors require special consideraion when being conrolled by a microconroller. Typically he microconroller canno provide enough curren and/or volage o power a moor. Because o his, you use ransisors o inerace beween he wo. I’s also smar o use diodes o preven damaging your circui.
99
1 cons in swichPin = 2; 2 cons in moorPin = 9; 3 in swichSae = 0;
4 void seup() { 5
pinMode(moorPin, OUTPUT);
6
pinMode(swichPin, INPUT);
7 }
8 void loop(){ 9
swichSae = digialRead(swichPin);
10
if (swichSae == HIGH) {
11
digialWrie(moorPin, HIGH);
12
}
13
else {
14 15
digialWrie(moorPin, LOW); }
16 }
Transisors are solid sae devices, hey have no moving pars. Because o his, you can swich hem on and off very quickly. Try hooking up a poeniomeer o an analog inpu and use ha o PWM he pin ha conrols he ransisor. Wha do you hink will happen o he moor’s speed i you vary he volage i’s geting? Using your paterns on your spinner, can you ge differen visual effecs?
100
Project 09 Moorized Pinwheel
USE IT
Assemble he CD hub as shown in sep 1, and atach i o he moor as shown in sep 2. Atach he die-cu paper patern o a CD as shown in sep 3. Snap he CD o he hub and secure wih a drop o glue. Allow o ry beore proceeding. Plug a 9V batery o your batery snap. Power your Arduino over USB. When you press he swich on he breadboard, he moor will spin very rapidly.
❶ Snap par C ino par B, and hen genly press par D on o hem.
❸ Place he paper disk on he CD and secure i using he laps on he back.
101
Wih he moor spinning as as as i does, you can probably make a prety large spinner. Be careul ha i doesn’ fly off and poke someone in he eye. Experimen wih differen paterns on he ouside o creae visual effecs.
❷ Genly press he moor sha ino he hole in he back o par B.
❹ Aach he CD o he cross ormed by pars B and D. Use a drop o glue o keep he CD rom coming o.
1�
P A N S H C T I W S
R E T E M O I T N E T O P
INGREDIENTS
R O T S I S E R E G D I R B H
M H O L I K 0 1
Y R E T T A B
9v baery
R O T O M
Y R E T T A B
103
ZOETROPE CREATE MOVING IMAGES IN FORWARD AND REVERSE WITH YOUR ARDUINO WHEN YOU CONNECT A MOTOR TO AN H�BRIDGE AND SOME STILL IMAGES
Discover: H-bridges
Time: 30 MINUTES
Builds on projecs: 1, 2, 3, 4, 9
Level:
Beore he inerne, elevision, even beore movies, some o he firs moving images were creaed wih a ool called a zoerope. Zoeropes creae he illusion o moion rom a group o sill images ha have small changes in hem. They are ypically cylinders wih slis cu in he side. When he cylinder spins and you look hrough he slis, your eyes perceive he sill images on he oher side o he wall o be animaed. The slis help keep he images rom becoming a big blur, and he speed a which he images appear provide cause he images o appear o move. Originally, hese novelies were spun by hand, or wih a cranking mechanism. In his projec, you’ll build your own zoerope ha animaes a carnivorous plan. You’ll power he moion wih a moor. To make his sysem even more advanced, you’ll add a swich ha les you conrol direcion, anoher o urn i off and on, and a poeniomeer o conrol he speed. In he Moorized Pinwheel Projec you go a moor o spin in one direcion. I you were o ake power and ground on he moor and flip heir orienaion, he moor would spin in he opposie direcion. I’s no very pracical o do ha everyime you wan o spin somehing in a differen direcion, so you’ll be using a componen called an H-bridge o reverse he polariy o he moor.
H-bridges are a ype o componen known as inegraed circuis (IC). ICs are componens ha hold large circuis in a iny package. These can help simpliy more complex circuis by placing hem in an easily replaceable componen. For example, he H-bridge you’re using in his example has a number o ransisors buil in. To build he circui inside he H-bridge you would probably need anoher breadboard.
Project 10
104
Zoerope
1
16
Wih an IC, you can access he circuis hrough he pins ha
2
15
3
14
come ou he sides. Differen ICs have differen numbers o pins,
4
13
and no all o hem are used in every circui. I’s someimes con-
5
12
venien o reer o he pins by number insead o uncion. When
6
11
7
10
looking a an IC, he par wih a dimple is reerred o as he op .
8
9
Fig. 1
You can ideniy pin numbers by couning rom he op-lef in a “U” direcion like in Fig. 1.
BUILD THE CIRCUIT
+
-
+
-
9V
Fig. 2
Fig. 3
+
-
+
-
105
❶
Connec power and ground rom one side o your breadboard
❷
Add 2 momenary swiches o he breadboard, connecing one
o he Arduino.
side o each o power. Add a 10Kohm pull-down resisor in series wih ground on he oupu pin o boh swiches. The swich on pin 4 will conrol direcion, he swich on pin 5 will urn he moor on and off.
❸
Connec he poeniomeer o he breadboard. Wire 5V o one side and ground o he oher. Atach he cener pin o analog inpu 0 on he Arduino. This will be used o conrol he speed o he moor.
❹
Place he H-bridge on your breadboard so i sraddles he cener (see Fig. 2 or deail o placemen). Connec pin 1 o he H-bridge o digial pin 9 on he Arduino. This is he enable pin on he H-bridge. When i receives 5V, i urns he moor on, when i receives 0V, i urns he moor off. You will use his pin o PWM he H-bridge, and adjus he speed o he moor.
❺
Connec pin 2 on he H-bridge o digial pin 3 on he Arduino. Connec pin 7 o digial pin 2. These are he pins you will use o communicae wih he H-bridge, elling i which direcion o spin. I pin 3 is LOW and pin 2 is HIGH, he moor will spin in one direcion. I pin 2 is LOW and pin 3 is HIGH, he moor will spin in he opposie direcion. I boh he pins are HIGH or LOW a he same ime, he moor will sop spinning.
❻
The H-bridge ge is power rom pin 16, plug ha ino 5V. Pins 4
❼
Atach your moor o pins 3 and 6 on he H-bridge. These wo
and 5 boh go o ground.
pins will swich on and off depending on he signals you send o pins 2 and 7.
❽
Plug he batery connecor (wihou he batery atached!) o he oher power rails on your breadboard. Connec ground rom your Arduino o he batery’s ground. Connec pin 8 rom he H-bridge o he batery power. This is he pin ha he H-bridge powers he moor rom. Make sure you do no have your 9V and 5V power lines conneced. They mus be separae, only ground should be conneced beween he wo.
106
Project 10 Zoerope
THE CODE
Name your consans
Creae consans or he oupu and inpu pins.
Creae variables or remem-
Use variables o hold he values rom your inpus. You’ll be doing
bering program sae
sae change deecion or boh swiches, comparing he sae rom one loop o he nex, similar o he Hourglass Projec. So, in addiion o soring he curren sae, you’ll need o record he previous sae o each swich.
Creae variables or moor
moorDirecion keeps rack o which direcion he moor is
conrol
spinning, and moorPower keeps rack o wheher he moor is spinning or no.
Declare he digial pins as
In seup(), se he direcion o each inpu and oupu pin.
inpus and oupus
Turn he moor o
Turn he enable pin LOW o sar, so he moor isn’ spinning righ away.
Read sensor inormaion
In your loop(), read he sae o he On/Off swich and sore i in he onOffSwichSae variable.
107
1 cons in conrolPin1 = 2; 2 cons in conrolPin2 = 3; 3 cons in enablePin = 9; 4 cons in direcionSwichPin = 4; 5 cons in onOffSwichSaeSwichPin = 5; 6 cons in poPin = A0;
7 in onOffSwichSae = 0; 8 in previousOnOffSwichSae = 0; 9 in direcionSwichSae = 0; 10 in previousDirecionSwichSae = 0;
11 in moorEnabled = 0; 12 in moorSpeed = 0; 13 in moorDirecion = 1;
14 void seup(){ 15
pinMode(direcionSwichPin, INPUT);
16
pinMode(onOffSwichSaeSwichPin, INPUT);
17
pinMode(conrolPin1, OUTPUT);
18
pinMode(conrolPin2, OUTPUT);
19
pinMode(enablePin, OUTPUT);
20
digialWrie(enablePin, LOW);
21 }
22 void loop(){ 23
onOffSwichSae = digialRead(onOffSwichSaeSwichPin);
24
delay(1);
25
direcionSwichSae = digialRead(direcionSwichPin);
26
moorSpeed = analogRead(poPin)/4;
108
Project 10 Zoerope
Check i on/o sensor has
I here is a difference beween he curren swich sae and he
changed
previous, and he swich is currenly HIGH, se he moorPower variable o 1. I i is LOW, se he variable o 0. Read he values o he direcion swich and poeniomeer. Sore he values in heir respecive variables.
Check o see i he direcion
Check o see i he direcion swich is currenly in a differen
has changed
posiion han i was previously.I i is differen, change he moor direcion variable. There are only 2 ways or he moor o spin, so you’ll wan o alernae he variable beween wo saes. One way o accomplish his is by using he inversion operaor like so:
moorDirecion =!moorDirecion. Change he pins o urn
The moorDirecion variable deermines which direcion he
he moor in he proper
moor is urning. To se he direcion, you se he conrol pins
direcion
seting one HIGH and he oher LOW. When moorDirecion changes, reverse he saes o he conrol pins. I he direcion swich ges pressed, you’ll wan o spin he moor in he oher direcion by reversing he sae o he
conrolPins.
PWM he moor i i is
I he moorEnabled variable is 1, se he speed o he moor using
enabled
analogWrie() o PWM he enable pin. I moorEnabled is 0, hen urn he moor off by seting he analogWrie value o 0.
Save he curren saes or
Beore exiing he loop(), save he curren sae o he swiches
he nex loop()
as he previous sae or he nex run hrough he program.
109
27
if(onOffSwichSae != previousOnOffSwichSae){
28
if(onOffSwichSae == HIGH){
29
moorEnabled = !moorEnabled;
30 31
32
} }
if (direcionSwichSae != previousDirecionSwichSae) {
33
if (direcionSwichSae == HIGH) {
34
moorDirecion = !moorDirecion;
35
}
36
}
37
if (moorDirecion == 1) {
38
digialWrie(conrolPin1, HIGH);
39
digialWrie(conrolPin2, LOW);
40
}
41
else {
42
digialWrie(conrolPin1, LOW);
43
digialWrie(conrolPin2, HIGH);
44
}
45
if (moorEnabled == 1) {
46
analogWrie(enablePin, moorSpeed);
47
}
48
else {
49
analogWrie(enablePin, 0);
50
}
51
previousDirecionSwichSae = direcionSwichSae;
52 53 }
previousOnOffSwichSae = onOffSwichSae;
110
Project 10 Zoerope
USE IT
Plug your Arduino ino your compuer. Atach he batery o he connecor. When you press he On/Off swich, he moor should sar spinning. I you urn he poeniomeer, i should speed up and slow down. Pressing he On/Off buton anoher ime will sop he moor. Try pressing he direcion buton and veriy he
Once you’ve verified ha he circui
moor spins boh ways. Also, i you urn he knob on he po, you
works as expeced, disconnec he
should see he moor speed up or slow down depending on he
batery and USB rom he circui.
value i is sending.
❶
❷
Secure he CD ono he wooden base. Add a drop o glue o
Use he abs o close he cuou, orming a circle.
make sure i doesn’ spin loose when he moor sars.
111
In order o build your zoerope, you mus ake he pinwheel you used in Projec 9 and he cuou wih he verical slis ha is included in your ki. Once he CD is securely atached o he shaf o he moor, plug everyhing back in. Hold your projec up, so you can look hrough he slis (bu make sure he CD is secured o he moor, and don’ ge oo close o i). You should see he sequence o sill images “move”! I i is going oo as or oo slow, urn he knob o he poeniomeer o adjus he speed o he animaion. Try pressing he direcion swich o see wha he animaion looks like when played backwards. The zoerope and images provided in he ki are only your saring poin: ry experimening wih your own animaions, using he cuou as a reerence. To do his, sar wih a basic image. Ideniy one fixed poin in i, and make small changes o he res in each rame. Try o gradually reurn o he original image so ha you can play he animaion in a coninuous loop.
❶
❶
Inser he our abs ino he base o he zoerope.
Inser he srip o paper wih he images inside he zoerope.
112
Project 10 Zoerope
Zoeropes work because o a phenomena called “persisence o vision”, someimes abbreviaed o POV. POV describes he illusion o moion ha is creaed when our eyes observe sill images wih minor variaions in rapid succession. I you search online or “POV display”, you’ll find many projecs made by people ha leverage his effec, ofen wih LEDs and an Arduino.
Make a base o suppor he moor. A small cardboard box wih a hole cu in i could work as a base, leaving your hands ree o play wih he swiches and knob. This will make i easier o show off your work o everyone. Wih a litle work, you can ge your zoerope working in low ligh siuaions as well. Hook up an LED and resisor o one o your ree digial oupu pins. Also add a second poeniomeer, and connec i o an analog inpu. Posiion he ligh so i shines on he images. Using he analog inpu o ime he flashes o he LED, ry and ime i so he ligh flashes when he sli is in ron o your eyes. This could ake some fiddling wih he knobs, bu he resuling effec is really specacular!
11
R O T S I S E R
H C T I W S
INGREDIENTS
M H O L I K 0 1
R O T S I S E R M H O 0 2 2
R E T E M O I T N E T O P
N E E R C S D C L
115
CRYSTAL BALL CREATE A CRYSTAL BALL TO TELL YOUR FUTURE
Discover: LCD displays, switch/case statements, random()
Time: 1 HOUR
Builds on projecs: 1, 2, 3
Level:
Crysal balls can help “predic” he uure. You ask a quesion o he all-knowing ball, and urn i over o reveal an answer. The answers will be predeermined, bu you can wrie in anyhing you like. You’ll use your Arduino o choose rom a oal o 8 responses. The il swich in your ki will help replicae he moion o shaking he ball or answers. The LCD can be used o display alphanumeric characers. The one in your ki has 16 columns and 2 rows, or a oal o 32 characers. There are a large number o connecions on he board. These pins are used or power and communicaion, so i knows wha o wrie on screen, bu you won’ need o connec all o hem. See Fig. 1 or he pins you need o connec.
6 5 4 3 2 1 1 1 1 1 1 1 1
9
8
7
- + 7 6 5 4 3 2 1 D D D D D D D D D D E E L L
The pins on he LCD screen ha are used in he projec and labels. Fig. 1
6
5
4
3
2
1
E W S c s / R V c s R V V
116
Project 11 Crysal Ball
BUILD THE CIRCUIT
+
-
+
-
+
-
+
-
Fig. 2
Fig. 3
In his schemaic he LCD pins arrangemen does no mach he physical order depiced in Fig. 2. In a schemaic, he pins are rearranged by logical grouping o make he schemaic as clear as possible. This is a lile conusing o newcomers unil you ge used o i.
117
The circui is no overly complex, bu here are a lo o wires. Pay aenion when wiring everyhing up o make sure i’s correc.
❶
Connec power and ground o one side o your breadboard.
❷
Place he il swich on he breadboard and atach one lead o 5V. Atach he oher side o ground hrough a 10-kilohm resisor, and o your Arduino’s pin 6. You’re wiring his as a digial inpu, jus as you’ve done in several oher projecs.
❸
The regiser selec ( RS) pin conrols where he characers will appear on screen. The read/wrie pin ( R/W) pus he screen in read or wrie mode. You’ll be using he wrie mode in his projec. The enable ( EN) ells he LCD ha i will be receiving a command. The daa pins ( D0-D7) are used o send characer daa o he screen. You’ll only be using 4 o hese ( D4-D7). Finally, here’s a connecion or adjusing he conras o he display. You’ll use a poeniomeer o conrol his.
❹
The LiquidCrysal library ha comes wih he Arduino sofware handles all he wriing o hese pins, and simplifies he process o wriing sofware o display characers. The wo ouside pins o he LCD ( Vss and LED-) need o be conneced o ground. Also, connec he R/W pin o ground. This places he screen in wrie mode. The LCD power supply ( Vcc) should connec direcly o 5V. The LED+ pin on he screen connecs o power hrough a 220-ohm resisor.
❺
Connec: Arduino Digial pin 2 o LCD D7, Arduino Digial pin 3 o LCD D6, Arduino Digial pin 4 o LCD D5, Arduino Digial pin 5 o LCD D4. These are he daa pins ha ell he screen wha characer o display.
❻
Connec EN on he screen o pin 11 on your Arduino. RS on he LCD connecs o pin 12. This pin enables wriing o he LCD.
❼
Place he poeniomeer on he breadboard, connecing one end pin o power and he oher o ground. The cener pin should connec o V� on he LCD. This will allow you o change he conras o he screen.
118
Project 11 Crysal Ball
Se up he LiquidCrysal
Firs, you’ll need o impor he LiquidCrysal library.
library
Nex, you’ll iniialize he library, somewha similar o he way you did wih he Servo library, elling i wha pins i will be using o communicae. Now ha you’ve se up he library, i’s ime o creae some variables and consans. Creae a consan o hold he pin o he swich pin, a variable or he curren sae o he swich, a variable or he previous sae o he swich, and one more o choose which reply he screen will show.
Prin your irs line
Se up he swich pin as an inpu wih pinMode() in your
seup(). Sar he LCD library, and ell i how large he screen is.
Move he cursor
Now i’s ime o wrie a small inroducory screen welcoming you o he 8-ball. The prin() uncion wries o he LCD screen. You’re going o wrie he words “Ask he” on he op line o he screen. The cursor is auomaically a he beginning o he op line. In order o wrie o he nex line, you’ll have o ell he screen where o move he cursor. The coordinaes o he firs column on he second line are 0,1 (recall ha compuers are zero indexed. 0,0 is he firs column o he firs row). Use he uncion lcd.
seCursor() o move he cursor o he proper place, and ell i o wrie “Crysal ball!”. Now, when you sar he program, i will say “Ask he Crysal ball!” on your screen. In he loop(), you’re going o check he swich firs, and pu he value in he swichSae variable.
Choose a random anwser
Use an i() saemen o deermine i he swich is in a differen posiion han i was previously. I i is differen han i was beore, and i is currenly LOW, hen i’s ime o choose a random reply. The random() uncion reurns a number based on he argumen you provide i. To sar, you’ll have a oal number o 8 differen responses or he ball. Whenever he saemen random(8) is called, i will give a number beween 0-7. Sore ha number in your reply variable.
119
1 #include 2 LiquidCrysal lcd(12, 11, 5, 4, 3, 2);
3 cons in swichPin = 6; 4 in swichSae = 0; 5 in prevSwichSae = 0; 6 in reply;
7 void seup() {
LCD library reference
8
lcd.begin(16, 2);
arduino.cc/lcdlibrary
9
pinMode(swichPin,INPUT);
10 lcd.prin(“Ask he”);
11 lcd.seCursor(0, 1); 12 lcd.prin(“Crysal Ball!”); 13 }
14 void loop() { 15
swichSae = digialRead(swichPin);
16
if (swichSae != prevSwichSae) {
17 18
if (swichSae == LOW) { reply = random(8);
Random reference
arduino.cc/random
120
Project 11 Crysal Ball
Clear he screen wih he uncion lcd.clear(). This also moves he cursor back o locaion 0,0; he firs column in he firs row o he LCD. Prin ou he line “ The ball says:” and move he cursor or he oupu.
Predic he uure
The swich() saemen execues differen pieces o code depending on he value you give i. Each o hese differen pieces o code is called a case. swich() checks he value o he variable reply; whaever value reply holds will deermine wha named case saemen is execued. Inside he case saemens, he code will be he same, bu he messages will be differen. For example, in case 0 he code says lcd.prin (“Yes”). Afer he lcd.prin() uncion, here’s anoher command: break. I ells he Arduino where he end o he case is. When i his break, i skips o he end o he swich saemen. You’ll be creaing a oal o 8 case saemens o sar ou. Four o he responses will be posiive, 2 will be negaive, and he final 2 will ask you o ry again.
The las hing o do in your loop() is o assign swichSae’s value o he variable prevSwichSae. This enables you o rack changes in he swich he nex ime he loop runs.
121
19
lcd.clear();
20
lcd.seCursor(0, 0);
21
lcd.prin(“The ball says:”);
22
lcd.seCursor(0, 1);
23
swich(reply){
24
case 0:
25
lcd.prin(“Yes”);
26
break;
27
case 1:
28
lcd.prin(“Mos likely”);
29
break;
30
case 2:
31
lcd.prin(“Cerainly”);
32
break;
33
case 3:
34
lcd.prin(“Oulook good”);
35
break;
36
case 4:
37
lcd.prin(“Unsure”);
38
break;
39
case 5:
40
lcd.prin(“Ask again”);
41
break;
42
case 6:
43
lcd.prin(“Doubful”);
44
break;
45
case 7:
46
lcd.prin(“No”);
47
break;
48
}
49
}
50
}
51
prevSwichSae = swichSae;
52 }
Switch Case reference
arduino.cc/swichcase
122
Project 11 Crysal Ball
USE IT
To use he magic ball, power he Arduino. Check he screen o make sure i says “Ask he Crysal ball!” I you can’ see he characers, ry urning he poeniomeer. I will adjus he conras o he screen. Ask a quesion o your crysal ball, and ry iling he swich upside down and back again. You should ge an answer o your quesion. I he answer doesn’ sui you, ask again.
Try adding your own sayings o he prin() saemens, bu be mindul o he ac ha here are only 16 characers o use per line. You can also ry adding more responses. Make sure when you add addiional swich cases, you adjus he number o opions ha will randomly populae he reply variable.
LCDs work by changing he elecrical properies o a liquid sandwiched beween polarized glass. The glass only allows cerain kinds o ligh o pass hrough. When he liquid beween he glass is charged, i sars o orm ino a semi-solid sae. This new sae runs in a differen direcion han he polarized glass, blocking ligh rom passing hrough, hus creaing he characers you see on he screen.
The uncions covered here or changing he LCD screen’s ex are airly simple. Once you have a handle on how i works, look a some o he oher uncions he library has. Try geting ex o scroll, or coninually updae. To find ou more abou how he LiquidCrysal library works, visi: arduino.cc/lcd
An LCD display enables you o show ex on a screen, using he LiquidCrysal library. Wih a swich...case saemens conrol he flow o programs by comparing a variable o specified values.
12
R O T S I S E R M H O H C T I W S
D E L
O L I K 0 1
R O T S I S E R M H O 0 2 2
R O T S I S E R M H O G E M 1
R O T I C A P A C
R O T O M
F u 0 0 1
O V R E S
MALE HEADER PIN (3 pins) O Z E I P
INGREDIENTS
125
KNOCK LOCK MAKE YOUR OWN SECRET LOCKING MECHANISM TO KEEP UNWANTED GUESTS OUT OF YOUR SPACE!
Discover: input with a piezo, writing your own functions
Time: 1 HOUR
Builds on projecs: 1, 2, 3, 4, 5
Level:
The piezo you used or playing back sounds in he heremin and keyboard pro jecs can also be used as an inpu device. When plugged ino 5V, he sensor can deec vibraions ha can be read by he Arduino’s analog inpus. You’ll need o plug in a high value resisor (like 1-megohm) as he reerence o ground or his o work well. When he piezo is pressed fla agains a solid surace ha can vibrae, like a wooden able op, your Arduino can sense how inense a knock is. Using his inormaion you can check o see i a number o knocks all in an accepable range. In code you can rack he number o knocks and see i hey mach your setings. A swich will le you lock he moor in place. Some LEDs will give you saus: a red LED will indicae he box is locked, a green LED will indicae he box is unlocked, and a yellow LED les you know i a valid knock has been received. You’ll also be wriing your own uncion ha will le you know i a knock is oo loud or oo sof. Wriing your own uncion helps save ime programming by reusing code insead o wriing i ou many imes. Funcions can ake argumens and reurn values. In his case, you’ll give a uncion he volume o he knock. I i is in he righ range, you’ll incremen a variable. I’s possible o build he circui by isel, bu i’s much more un i you use his as a ool o lock somehing. I you have a wooden or a cardboard box you can cu holes ino, use he servo moor o open and close a lach, keeping people rom geting a your suff.
126
Project 12 Knock Lock
BUILD THE CIRCUIT
Fig. 1
Fig. 2
+
-
+
-
+
-
+
-
127
There are a lo o connecions on he board, be sure o keep rack o how hings are wired up.
❶
Connec power and ground o boh sides o he breadboard. Place he pushbuton on he breadboard and connec one end o 5V. On he oher side o he swich, connec o ground hrough a 10-kilohm resisor. Connec his juncion o digial pin 2 on he Arduino.
❷
Atach he wires rom he piezo o he breadboard. Atach one wire o power. I your piezo has a red wire or one marked wih a “+”, ha is he one o connec o power. I your piezo doesn’ indicae polariy, hen you can hook i up eiher way. Wire he oher end o he piezo o Analog Pin 0 on your Arduino. Place a 1-megohm resisor beween he ground and he oher wire. Lower resisor values will make he piezo less sensiive o vibraions.
❸
Wire up he LEDs, connecing he cahodes (shor leg) o ground, and placing a 220-ohm resisor in series wih he anodes. Through heir respecive resisors, connec he yellow LED o Arduino digial pin 3, he green LED o digial pin 4, and he red LED o digial pin 5.
❹
Inser he male headers ino he emale socke on he servo moor (see Fig.3). Connec he red wire o power, and he black wire o ground. Place a 100uF elecrolyic capacior across power and ground o smooh ou any irregulariies in volage, making sure you have he capacior’s polariy correc. Connec he servo’s daa wire o pin 9 on your Arduino.
Your servo moor comes wi h emale connecors, so you’ll need o add header pins o connec i o he breadboard. Fig. 3
128
Project 12 Knock Lock
THE CODE
Servo library
Jus as in he earlier Mood Cue Projec, you’ll need o impor he
Servo library and creae an insance o use he moor.
Useul consans
Creae consans o name your inpus and oupus.
Variables o hold swich and
Creae variables o hold he values rom your swich and piezo.
piezo values Knock resholds
Se up some consans o use as hresholds or he knock maximum and minimum levels.
Variables or lock sae and
The locked variable will le you know i he lock is enganged or
number o knocks
no. A boolean is a daa ype ha can only be rue (1) or alse (0). You should sar wih he mechanism unlocked. The las global variable will hold he number o valid knocks you have received.
Seing he direcion o he
In your seup(), atach he servo o pin 9.
digial pins and iniializing
Se he LED pins as oupus and he swich pins as inpus.
servo objec and serial por
Unlock
Iniialize serial communicaion wih he compuer so you can monior he knock volume, wha he curren sae o he lock is, and how many more knocks you have o go. Turn on he green LED, move he servo o he unlocked posiion, and prin he curren saus o he serial monior indicaing he circui is in he unlocked posiion.
Checking he swich
In he loop(), you’ll firs check o see i he box is locked or no. This will deermine wha happens in he res o he program. I i is locked, read he swich value.
129
1 #include 2 Servo myServo;
3 cons in piezo = A0; 4 cons in swichPin = 2; 5 cons in yellowLed = 3; 6 cons in greenLed = 4; 7 cons in redLed = 5;
8 in knockVal; 9 in swichVal;
10 cons in quieKnock = 10; 11 cons in loudKnock = 100;
12 boolean locked = false; 13 in numberOfKnocks = 0;
14 void seup(){ 15
myServo.atach(9);
16
pinMode(yellowLed, OUTPUT);
17
pinMode(redLed, OUTPUT);
18
pinMode(greenLed, OUTPUT);
19
pinMode(swichPin, INPUT);
20
Serial.begin(9600);
21
digialWrie(greenLed, HIGH);
22 myServo.wrie(0); 23
Serial.prinln(“The box is unlocked!”);
24 }
25 void loop(){ 26 27
if(locked == false){ swichVal = digialRead(swichPin);
130
Project 12 Knock Lock
Lock I he swich is closed (you’re pressing i), change he locked variable o rue, indicaing he lock is engaged. Turn he green LED off, and he red LED on. I you don’ have he serial monior on, his is helpul visual eedback o le you know he saus o he lock. Move he servo ino he lock posiion, and prin ou a message o he serial monior indicaing he box is now locked. Add a delay so he lock has pleny o ime o move ino place.
Checking he knock sensor
I he locked variable is rue, and he lock is engaged, read he value o he vibraion o he piezo and sore i in knockVal.
Couning only valid knocks
The nex saemen checks o see i you have ewer han hree valid knocks, and here is some vibraion on he sensor. I hese are boh rue, check o see i his curren knock is valid or no and incremen he numberOKnocks variable. This is where you’ll call your cusom uncion checkForKnocks(). You’ll wrie he uncion once you’re finished wih he loop(), bu you already know you’re going o be asking i i his is a valid knock, so pass he knockVal along as an argumen. Afer checking your uncion, prin ou he number o knock sill needed.
Unlock
Check o see i you have hree or more valid knocks. I his is rue, change he locked variable o alse, and move he servo o he unlocked posiion. Wai or a ew milliseconds o le i sar moving, and change he saus o he green and red LEDs. Prin ou a saus message o he serial monior, indicaing he box is unlocked.
Close up he else saemen and he loop() wih a pair o curly brackes.
Deining a uncion o check
Now i’s ime o wrie he uncion checkForKnock(). When
knock validiy
you’re wriing uncions o your own, you need o indicae i i is going o reurn a value or no. I i is no going o reurn a value, you declare i as ype void, similar o he loop() and seup() uncions. I i is going o reurn a value, you mus declare wha kind ( in, long,
floa, ec.). In his case, you’re checking o see i a knock is valid (rue) or no (alse). Declare he uncion as ype boolean.
131
28
if(swichVal == HIGH){
29
locked = rue;
30
digialWrie(greenLed,LOW);
31
digialWrie(redLed,HIGH);
32
myServo.wrie(90);
33
Serial.prinln(“The box is locked!”);
34
delay (1000);
35
}
36
}
37
if(locked == rue){
38
knockVal = analogRead(piezo);
39
if(numberOfKnocks < 3 && knockVal > 0){
40
if(checkForKnock(knockVal) == rue){
41
numberOfKnocks++;
42
}
43
Serial.prin(3-numberOfKnocks);
44
Serial.prinln(“ more knocks o go”);
45
}
46
if(numberOfKnocks >= 3){
47
locked = false;
48
myServo.wrie(0);
49
delay(20);
50
digialWrie(greenLed,HIGH);
51
digialWrie(redLed,LOW);
52
Serial.prinln(“The box is unlocked!”);
53 54
} }
55 }
56 boolean checkForKnock(in value){
132
Project 12 Knock Lock
This paricular uncion will be checking a number (your variable
knockVal) o see i i is valid or no. To pass his variable along o he uncion, you creae a named parameer when you declare he uncion.
Check validiy o knock
In your uncion, whenever you reer o value i will use whaever number i receives as an argumen in he main program. A his poin value will be se o whaever knockVal is. Check o see i value is greaer han your quie knock, and less han your loud knock.
Indicaing knock is valid
I he value alls beween hose wo values i’s a valid knock. Blink he yellow LED once and prin he value o he knock o he serial monior.
Funcion reurns rue
To le he main program know wha he oucome o he comparison is, you use he command reurn. You use he
reurn command, which also erminaes he uncion: once i execues, you reurn o he main program.
Indicaing invalid knock;
I value is eiher oo quie or oo loud, prin i ou o he serial
uncion reurns alse
monior and reurn alse.
Close up your uncion wih one more bracke .
USE IT
When you irs plug in he circui o your Arduino, open he serial monior. You should see he green LED urn on, and he servo will move o he unlocked posiion. The serial monior should prin ou “The box is unlocked!”. You’ll probably hear he piezo make a small “click” when i irs ges power. Try knocking so and hard o see wha sor o inensiy knock riggers your uncion. You’ll know i’s working when he yel-
133
57
if(value > quieKnock && value < loudKnock){
58
digialWrie(yellowLed, HIGH);
59
delay(50);
60
digialWrie(yellowLed, LOW);
61
Serial.prin(“Valid knock of value “);
62
Serial.prinln(value);
63
reurn rue;
64
}
65
else {
66
Serial.prin(“Bad knock value “);
67
Serial.prinln(value);
68
reurn false;
69
}
70 }
low LED lashes and he serial monior ells you you have a valid knock wih is value. I will also le you know he number o knocks you have o go beore unlocking he box. Once you’ve reached he righ number o knocks, he red ligh will urn o, he green ligh will urn on, he servo will move 90 degrees, and he serial monior will le you know he lock is disengaged.
134
Project 12 Knock Lock
The values or your ideal knock may vary rom he ones in he example. This depends on a number o differen variables, like he ype o surace he sensor is atached o and how surdily i is fixed on here. Using he serial monior and he AnalogInSerialOu example in he Arduino IDE, find an appropriae knock value or your seup. You can find a deailed explanaion o ha example here:
arduino.cc/analogoserial I you move he projec ino a box, you’ll need o make holes or he LEDs and he swich. You’ll also need o make a lach or he servo moor o spin ino. I will probably also be helpul o have a hole o run your USB cable hrough o find ou how sensiive your new environmen is o knocks. You may need o rearrange your breadboard and Arduino, or solder he LEDs and swich o make hem accessible o he exerior o your enclosure. Soldering is a process o joining wo or more meal componens ogeher wih an adhesive ha is meled beween he join. I you’ve never soldered beore, ask someone who has experience o help you ou, or ry pracicing on some scrap wire beore atemping wih anoher device in his projec. When you solder somehing, i’s mean o be a permanen connecion, so be sure i’s somehing ha’s ok o hack. See arduino.cc/soldering or a good explanaion o how o solder.
❶ Cu 2 holes in your box: one on he side, and a second hrough he cover lap. Place he servo in he box so ha he arm can move in and ou o he holes when closed.
135
Wriing your own uncions no only allows you o conrol he flow o your code more easily, i also helps keep i readable as your projecs become larger and larger. Over ime, as you wrie more code, you may find you have a large number o uncions you can re-use in differen projecs, making he process quicker and unique o your syle o programming. This example simply couns he righ number o knocks, no mater how long i akes. You can sar o make a more complex example by creaing a imer wih millis(). Use he imer o ideniy i he knocks happen in a specific period o ime. Look back a he Digial Hourglass Projec or an example o how a imer works. You aren’ limied o simply finding knocks in a specific range. You can look or complex paterns o knocks based on he amoun o vibraion and iming ogeher. There are a number o examples online ha alk abou how o do his, search or “Arduino knock lock” o discover more examples o his ype o projec.
Piezo elemens can be used as inpus when wired up as volage dividers wih a high value resisor. Designing a uncion is an easy way o wrie code ha can be reused or specific asks.
❷ Secure he servo in place wih some ape, again making sure he arm can easily roae hrough he slo you made.
13
R O T S I S E R M H O D E L
INGREDIENTS
0 2 2
R O T S I S E R M H O G E M 1
L I O F L A T E M
137
TOUCHY�FEELY LAMP YOU WILL CREATE A LAMP THAT TURNS A LIGHT ON AND OFF WHEN YOU TOUCH A PIECE OF CONDUCTIVE MATERIAL
Discover: installing third party libraries, creating a touch sensor
Time: 45 MINUTES
Builds on projecs: 1, 2, 5
Level:
You’ll be using he CapaciiveSensor library by Paul Badger or his projec. This library allows you o measure he capaciance o your body. Capaciance is a measure o how much elecrical charge somehing can sore. The library checks wo pins on your Arduino (one is a sender, he oher a receiver), and measures he ime i akes or hem o have he same sae. These pins will be conneced o a meal objec like aluminum oil. As you ge closer o he objec, your body will absorb some o he charge, causing i o ake longer or he wo pins o be he same.
Preparing he library
The mos recen version o he CapaciiveSensor library is here:
arduino.cc/capaciive . Download he file o your compuer and unzip i. Open your Arduino skech older (i will be in your “Documens” older by deaul). In he older, creae a new direcory named “libraries”. Place he CapaciiveSensor older you unzipped in his older and resar he Arduino sofware. Click he File>Examples menu in he Arduino sofware, and you’ll see a new enry or “CapaciiveSensor”. The library you added included an example projec. Open he CapaciiveSensorSkech example and compile i. I you don’ ge any errors, you’ll know you insalled i correcly.
For more inormaion on libraries: arduino.cc/en/Reference/Libraries
138
Project 13 Touchy-feely Lamp
BUILD THE CIRCUIT
Fig. 1
Fig. 2
139
❶
Connec an LED o pin 12, and connec he cahode o ground
❷
Connec digial pins 2 and 4 o your breadboard. Connec he
hrough a 220-ohm resisor as shown.
wo pins wih a 1-megahom resisor. In he same row as pin 2, inser a long wire (8-10cm a leas) ha exends away rom he breadboard, no conneced o anyhing on he oher end. This will become your ouch sensor.
There’s no need to supply 5V t o your breadboard in this project. Digit al pin 4 supplies the current to the sensor.
Jus like wih oher LED projecs, diffusing he ligh will make his much more aracive. Ping pong balls, litle lampshades rom paper or plasic, whaever you have handy will work. You can hide he sensor behind somehing solid and i will sill work. Capaciance can be measured hrough non-conducive maerials like wood and plasic. Increasing he surace area o he sensor wih a larger conducive surace will make i more sensive; ry connecing aluminum oil, or copper mesh o your wire. You could make a base or he lamp ou o cardboard, hin wood, or cloh, and line he inner surace wih oil atached o your sensor wire. The whole base o he lamp would hen ac as a ouch sensor. Updae he hreshold variable in he code when you make hese changes o ensure ha you’re sill geting a reliable resul.
140
Project 13 Touchy-feely Lamp
THE CODE
Impor he CapaciiveSensor
A he beginning o your program, include he CapaciiveSensor
library
library. You include i he same way you would a naive Arduino library like he Servo library in he earlier projecs. Creae a named insance o he library. When you use his library, you ell he insance wha pins i will be using o send and receive inormaion. In his case, pin 4 sends o he conducive sensor maerial hrough he resisor, and pin 2 is he sense pin.
Se up he hreshold
Se up a variable or he sensing hreshold a which he lamp will urn on. You’ll change his number afer you es he sensor’s uncionaliy. Then define he pin your LED will be on. In he seup() uncion, open a Serial connecion a 9600 bps. You’ll use his o see he values he sensor reads. Also, make your ledPin an OUTPUT.
Sensing ouch
In he loop() uncion, creae a variable o ype long o hold he sensor’s value. The library reurns he sensor value using a command called CapaciiveSensor() ha akes an argumen ideniying he number o samples you wan o read. I you read only a ew samples, i’s possible you’ll see a lo o variaion in he sensor. I you ake oo many samples, you could inroduce a lag as i reads he sensor muliple imes. 30 samples is a good saring value. Prin he sensor value o he serial monior.
Lamp conrol
Wih an i()...else saemen, check o see i he sensor value is higher han he hreshold. I i is, urn he LED on. I i is no, urn i off.
Then add a small delay() beore ending he loop().
141
1 #include 2 CapaciiveSensor capSensor = CapaciiveSensor(4,2);
3 in hreshold = 1000; 4 cons in ledPin = 12;
5 void seup() { 6
Serial.begin(9600);
7
pinMode(ledPin, OUTPUT);
8 }
9 void loop() { 10
long sensorValue = capSensor.capaciiveSensor(30);
11
Serial.prinln(sensorValue);
12
if(sensorValue > hreshold) {
13
digialWrie(ledPin, HIGH);
14
}
15
else {
16
digialWrie(ledPin, LOW);
17
}
18
delay(10);
19 }
142
Project 13 Touchy-feely Lamp
USE IT
Afer programming he Arduino, you’ll wan o find ou wha he sensor values are when i’s ouched. Open he serial monior and noe he value coming rom he sensor when you’re no ouching i. Press genly on he bare wire you have exposed rom your breadboard. The number should increase. Try pressing more firmly and see i i changes. Once you have an idea o he range o values you’re geting rom he sensor, go back o he skech and change he hreshold variable o a number ha is greaer han he sensor’s value when i is no ouched, bu less han is value when pressed. Upload he skech wih he new value. The ligh should come on reliably when you ouch he wire, and urn off when i’s lef alone. I you aren’ geting he ligh o urn on, ry lowering he hreshold a litle more.
You probably noiced ha he values rom he sensor changed depending on how much o your finger was ouching he conducor. Can you use his o ge oher ineracions wih he LED? Wha abou muliple sensors or ading he ligh brigher and darker? I you place a differen value resisor beween pins 2 and 4 i will change he sensiiviy. Is his useul or your inerace?
Third pary libraries like Paul Badger’s CapaciiveSensor are useul ools or expanding he capabiliies o he Arduino. Once insalled, hey behave similarly o libraries ha are bundled wih he core sofware.
14
R E T E M O I T N E T O P
INGREDIENTS
145
TWEAK THE ARDUINO LOGO USING SERIAL COMMUNICATION, YOU’LL USE YOUR ARDUINO TO CONTROL A PROGRAM ON YOUR COMPUTER
Discover: serial communication with a computer program, Processing
Time: 45 MINUTES
Builds on projecs: 1, 2, 3
Level:
You’ve done a lo o cool suff wih he physical world, now i’s ime o conrol your compuer wih your Arduino. When you program your Arduino, you’re opening a connecion beween he compuer and he microconroller. You can use his connecion o send daa back and orh o oher applicaions. The Arduino has a chip ha convers he compuer’s USB-based communicaion o he serial communicaion he Arduino uses. Serial communicaion means ha he wo compuers, your Arduino and PC, are exchanging bis o inormaion serially, or one afer anoher in ime. When communicaing serially, compuers need o agree on he speed a which hey alk o one anoher. You’ve probably noiced when using he serial monior here’s a number a he botom righ corner o he window. Tha number, 9600 bis per second, or baud, is he same as he value you’ve declared using Serial.
begin(). Tha’s he speed a which he Arduino and compuer exchange daa. A bi is he smalles amoun o inormaion a compuer can undersand. You’ve used he serial monior o look a values rom he analog inpus; you’ll use a similar mehod o ge values ino a program you’re going o wrie in a programming environmen called Processing. Processing is based on Java, and Arduino’s programming environmen is based on Processing’s. They look prety similar, so you should eel righ a home here. Beore geting sared wih he projec, download he laes version o Processing rom processing.org. I may be helpul o look a he “Geting sared” and “Overview” uorials a processing.org/learning. These will help you o amiliarize yoursel wih Processing beore you sar wriing sofware o communicae wih your Arduino.
146
Project 14 Tweak he Arduino Logo
The mos efficien way o send daa beween he Arduino and Processing is by using he Serial.wrie() uncion in Arduino. I’s similar o he Serial.
prin() uncion you’ve been using in ha i sends inormaion o an atached compuer, bu insead o sending human readable inormaion like numbers and leters, i sends values beween 0-255 as raw byes. This limis he values ha he Arduino can send, bu allows or quick ransmission o inormaion. On boh your compuer and Arduino, here’s somehing called he serial buffer which holds ono inormaion unil i is read by a program. You’ll be sending byes rom he Arduino o Processing’s serial buffer. Processing will hen read he byes ou o he buffer. As he program reads inormaion rom he buffer, i clears space or more. When using serial communicaion beween devices and programs, i’s imporan ha boh sides no only know how as hey will be communicaing, bu also wha hey should be expecing. When you mee someone, you probably expec a “Hello!”; i insead hey say somehing like “The ca is uzzy”, chances are you will be caugh off guard. Wih sofware, you will need o ge boh sides o agree on wha is sen and received.
Fig. 1
147
BUILD THE CIRCUIT
Fig. 2
❶
Connec power and ground o your breadboard.
❷
Connec each end o your poeniomeer o power and ground. Connec he middle leg o analogIn pin 0.
Fig. 3
148
Project 14 Tweak he Arduino Logo
THE ARDUINO CODE
Open a serial connecion
Firs, program your Arduino. In seup(), you’ll sar serial communicaion, jus as you did earlier when looking a he values rom an atached sensor. The Processing program you wrie will have he same serial baud rae as your Arduino.
Send he sensor value
In he loop(), you’re going o use he Serial.wrie() command o send inormaion over he serial connecion.
Serial.wrie() can only send a value beween 0 and 255. To make sure you’re sending values ha fi wihin ha range, divide he analog reading by 4.
Le he ADC sabilize
Afer sending he bye, wai or one millisecond o le he ADC setle down. Upload he program o he Arduino hen se i aside while you wrie your Processing skech.
THE PROCESSING CODE
Impor he se up he serial
The Processing language is similar o Arduino, bu here are
objec
enough differences ha you should look a some o heir uorials and he “Geting Sared” guide menioned beore o amiliarize yoursel wih he language. Open a new Processing skech. Processing, unlike he Arduino, doesn’ know abou serial pors wihou including an exernal library. Impor he serial library. You need o creae an insance o he serial objec, jus like you’ve done in Arduino wih he Servo library. You’ll use his uniquely named objec whenever you wan o use he serial connecion.
Creae an objec or he
To use images in Processing, you need o creae an objec ha
image
will hold he image and give i a name.
149
1 void seup() { 2
Serial.begin(9600);
3 }
4 void loop() { 5
6
Serial.wrie(analogRead(A0)/4);
delay(1);
7 }
1 impor processing.serial.*; 2 Serial myPor;
3 PImage logo;
SAVE AND CLOSE THE ARDUINO IDE NOW, LET’S START PROCESSING.
150
Project 14 Tweak he Arduino Logo
Variable o s ore he
Creae a variable ha will hold he background hue o he Arduino
background color
logo. The logo is a .png file, and i has buil-in ransparency, so i’s possible o see he background color change. Processing has a seup() uncion, jus like Arduino. Here’s where you’ll open he serial connecion and give he program a couple o parameers ha will be used while i runs.
Seing he color mode
You can change he way Processing works wih color inormaion. Typically, i works wih colors in a Red Green Blue (RGB) ashion. This is similar o he color mixing you did in Projec 4, when you used values beween 0 and 255 o change he color o an RGB LED. In his program, you’re going o use a color mode called HSB, which sands or Hue, Sauraion, and Brighness. You’ll change he hue when you urn he poeniomeer.
colorMode() akes wo argumens: he ype o mode, and he maximum value i can expec.
Loading he image
To load he Arduino image ino he skech, read i ino he logo objec you creaed earlier. When you supply he URL o an image, Processing will download i when you run he program. Wih he size() uncion, you ell Processing how large he display window will be. I you use logo.widh and logo.
heigh as he argumens, he skech will auomaically scale o he size o he image you’re using.
Prining available serial
Processing has he abiliy o prin ou saus messages using he
pors
prinln() command. I you use his in conjuncion wih he Serial.lis() uncion, you’ll ge a lis o all he serial pors your compuer has when he program firs sars. You’ll use his once you’re finished programming o see wha por your Arduino is on.
Creaing he serial objec
You need o ell Processing inormaion abou he serial connecion. To populae your named serial objec myPor wih he necessary inormaion, he program needs o know i is a new insance o he serial objec. The parameers i expecs are which applicaion i will be speaking o, which serial por i will communicae over, and a wha speed.
151
4 in bgcolor = 0;
5 void seup() {
6
colorMode(HSB, 255);
7
logo = loadImage(“htp://arduino.cc/logo.png”);
8
size(logo.widh, logo.heigh);
9
prinln(“Available serial pors:”);
10
prinln(Serial.lis());
11
myPor = new Serial(his, Serial.lis()[0], 9600);
12 }
152
Project 14 Tweak he Arduino Logo
The atribue his ells Processing you’re going o use he serial connecion in his specific applicaion. The Serial.lis()
[0] argumen specifies which serial por you’re using. Serial. lis() conains an array o all he atached serial devices. The argumen 9600 should look amiliar, i defines he speed a which he program will communicae. The draw() uncion is analogous o Arduino’s loop() in ha i happens over and over again orever. This is where hings are drawn o he program’s window.
Reading Arduino daa rom
Check i here is inormaion rom he Arduino. The myPor.
he serial por
available() command will ell you i here is somehing in he serial buffer. I here are byes here, read he value ino he
bgcolor variable and prin i o he debug window. Seing he image
The uncion background() ses he color o he window. I
background and displaying
akes hree argumens. The firs argumen is he hue, he nex
he image
is brighness, and he las is sauraion. Use he variable bgcolor as he hue value, and se he brighness and sauraion o he maximum value, 255. You’ll draw he logo wih he command image(). You need o ell image() wha o draw, and wha coordinaes o sar drawing i in he window. 0,0 is he op lef, so sar here.
USE IT
Connec your Arduino and open he serial monior. Turn he po on your breadboard. You should see a number o characers as you wis he knob. The serial monior expecs ASCII characers, no raw byes. ASCII is inormaion encoded o represen ex in compuers. Wha you see in he window is he serial monior rying o inerpre he byes as ASCII. When you use Serial.prinln(), you send inormaion ormated or he serial monior. When you use Serial.
wrie(), like in his applicaion you are running now, you’re sending raw inormaion. Programs like Processing can undersand hese raw byes.
153
13 void draw() {
14
if (myPor.available() > 0) {
15
bgcolor = myPor.read();
16
prinln(bgcolor);
17
}
18
background(bgcolor, 255, 255);
19 image(logo, 0, 0); 20 }
154
Project 14 Tweak he Arduino Logo
Close he serial monior. Run he Processing skech by pressing he arrow buon in he Processing IDE. Look a he Processing oupu window. You should see a lis similar o he igure below.
This is a lis o all he serial pors on your compuer. I you’re using OSX, look or a sring ha says somehing like “/dev/ y.usbmodem411”, i will mos likely be he irs elemen in he lis. On Linux, i may appear as “/dev/yUSB0”, or similar. For Windows, i will appear as a COM por, he same one you would use when programming he board. The number in ron o i is he Serial.lis()[] array index. Change he number in your Processing skech o mach he correc por on your compuer. Resar he Processing skech. When he program sars running, urn he poeniomeer aached o he Arduino. You should see he color behind he Arduino logo change as you urn he poeniomeer. You should also see values prining ou in he Processing window. Those numbers correspond o he raw byes you are sending rom he Arduino.
155
Once you have wised and urned o your hear’s desire, ry replacing he po wih an analog sensor. Find somehing you find ineresing o conrol he color. Wha does he ineracion eel like? I’s probably differen han using a mouse or keyboard, does i eel naural o you?
When using serial communicaion, only one applicaion can alk o he Arduino a a ime. So i you’re running a Processing skech ha is conneced o your Arduino, you won’ be able o upload a new Arduino skech or use he serial monior unil you’ve closed he acive applicaion.
Wih Processing and oher programming environmens, you can conrol media on your compuer in some remarkable and novel ways. I you’re excied abou he possibiliies o conrolling conen on your compuer, ake some ime o experimen wih Processing. There are several serial communicaion examples in boh he Processing and Arduino IDEs ha will help you explore urher.
Serial communicaion enables he Arduino o alk wih programs on a compuer. Processing is an open source programming environmen ha he Arduino IDE is based upon. I’s possible o conrol a Processing skech wih he Arduino via serial communicaion.
15
R E L P U O C O T P O
INGREDIENTS
R O T S I S E R M H O 0 2 2
157
HACKING BUTTONS GET CONTROL OF OTHER COMPONENTS AROUND YOU. USING SOME ADDITIONAL CIRCUITRY, YOU CAN “PRESS” BUTTONS WITH YOUR ARDUINO
Discover: optocoupler, connecting with other components
Time: 45 MINUTES
Builds on projecs: 1, 2, 9
Level:
Warning: You’re no longer a beginner i you’re doing his projec. You’ll be opening up an elecronic device and modiying i. You’ll void your device’s warrany, and i you’re no careul, you migh damage he device. Make sure you’re amiliar wih all he elecronics conceps in he earlier projecs beore you atemp his one. We recommend you use inexpensive iems you don’ mind damaging or your firs ew projecs, unil you develop experience and confidence. While he Arduino can conrol a lo o hings, someimes i’s easier o use ools ha are creaed or specific purposes. Perhaps you wan o conrol a elevision or a music player, or drive a remoe conrol car. Mos elecronic devices have a conrol panel wih butons, and many o hose butons can be hacked so ha you can “press” hem wih an Arduino. Conrolling recorded sound is a good example. I you waned o record and play back recorded sound, i would ake a lo o effor o ge he Arduino o do ha. I’s much easier o ge a small device ha records and plays back sound, and replace is butons wih oupus conrolled by your Arduino.
Opocouplers are inegraed circuis ha allow you o conrol one circui rom a differen one wihou any elecrical connecion beween he wo. Inside an opocoupler is an LED and a ligh deecor. When he LED in he opocoupler is urned on by your Arduino, he ligh deecor closes a swich inernally. The swich is conneced o wo o he oupu pins (4 and 5) o he opocoupler. When he inernal swich is closed, he wo oupu pins are conneced. When he swich is open, hey’re no conneced. This way, i’s possible o close swiches on oher devices wihou connecing hem o your Arduino.
158
Project 15 Hacking Butons
In his example, he diagrams are or conrolling a digial recording module ha allows you o record and playback 20 seconds o sound, bu he basic premise holds or any device ha has a swich you can access. While i’s possible o use his example wihou soldering any wires, i cerainly makes hings easier. For more inormaion on soldering, see p. 134.
BUILD THE CIRCUIT
Fig. 1
Fig. 2
159
❶
Connec ground o your breadboard hrough he Arduino.
❷
Place he opocoupler on your breadboard so ha i sraddles
❸
Connec pin 1 on he opocoupler o Arduino pin 2 in series wih
he cener o he board (see circui diagram).
a 220-ohm resisor (remember, you’re powering an LED inside, you don’ wan o burn i ou). Connec pin 2 o he opocoupler o ground.
❹
On he main board o he sound module here are a number o elecrical componens, including a playback buton. To conrol he swich, you’re going o have o remove he buon. Flip he circui board over and find he abs ha hold he buton in place. Genly bend he abs back and remove he buon rom he board.
❺
Under he buton are wo small meal plaes. This patern is ypical o many elecronic devices wih pushbutons. The wo “orks” o his patern are he wo sides o he swich. A small meal disc inside he pushbuton connecs hese wo orks when you press he buton.
❻
When he orks are conneced, he swich is closed on he circui board. You will be closing he swich wih he opocoupler. This mehod, closing a swich wih an opocoupler, works only i one o he wo sides o he pushbuton’s swich is conneced o ground on your device. I you’re no sure, ake a mulimeer and measure he volage beween one o he orks and he ground on your device. You need o do his wih he device urned on, so be careul no o ouch anywhere else on he board. Once you know which ork is ground, disconnec he power o your device.
❼
Nex, connec one wire o each o he small meal plaes. I you are soldering hese wires, be careul o no join he wo sides o he swich ogeher. I you are no soldering and using ape, make sure your connecion is secure, or he swich won’ close. Make sure neiher wire connecs o he oher ork, or your swich will be closed all he ime.
❽
Atach he wo wires o pins 4 and 5 o he opocoupler. Connec he side o he swich ha is grounded o pin 4 o he opocoupler. Connec he oher ork o pin 5 o he opocoupler.
160
Project 15 Hacking Butons
THE CODE
Mos o he un wih his projec is in he circui and he
Name a consan
opocoupler. The code is similar o he firs projec you made wih he Arduino. You’re going o play he sound once every 20 seconds by urning pin 2 HIGH. Creae a consan or he opocoupler conrol pin.
Conigure he pin direcion
In seup(), se he opocoupler pin ino an oupu.
Pull he pin high and low
The loop() urns opoPin HIGH or a ew milliseconds, long enough or he opocoupler o close he swich on he device. Then he opoPin becomes LOW.
Wai or a lile while
Wai or 21 seconds or he whole message o play back beore saring he loop() again.
USE IT
Aach he baery o he sound recorder. Press and hold he record buon on he device. While you’re holding he buon, you can record audio ino he microphone. Use your voice, he ca, or he pos and pans in he kichen o make some noise (bu be careul wih he ca). Once you’ve saisacorily recorded a sound, power your Arduino wih he USB cable. Your recording should sar o play. I you recorded or he ull 20 seconds, he sound should sar again jus a ew momens aer i ends.
Try experimening wih differen sounds and duraions o oggling he playback wih he delay() in your program. I you rigger he swich while a sound is playing, i will sop. How can you ake advanage o his o creae unique sequences o sounds?
161
1 cons in opoPin = 2;
2 void seup(){ 3
pinMode(opoPin, OUTPUT);
4 }
5 void loop(){ 6
digialWrie(opoPin, HIGH);
7
delay(15);
8
digialWrie(opoPin, LOW);
9
delay(21000);
10 }
Inegraed circuis are in virually every elecronic device. The large 28 pin chip on your Arduino is an IC ha houses he brains o he board. There are oher ICs ha suppor his one wih communicaion and power. The opocoupler and main chip on he Arduino are Dual In-line Package (DIP) chips. These DIP chips are he kind ha mos hobbyiss use because hey easily fi in a breadboard and don’ have o be permanenly soldered o be used. The projec example only played sound back a a regular inerval. How could you incorporae he inpus rom earlier projecs o rigger hese sounds? Wha oher batery powered hings do you have around he house ha need an Arduino o conrol hem? This echnique o conrolling an elecronic device wih an opocoupler by connecing o he wo sides o a swich can be used in many oher devices. Wha oher devices do you wan o conrol?
Opocouplers can conrol devices ha are on a differen circui. The wo circuis are elecrically separaed rom each oher inside he componen.
A/Z Acceleromeer -
Direc curren -
Period -
Acuaor -
Drain (ransisor) -
Phoocell -
Alernaing curren -
Dual In-line Package (DIP) -
Phooresisor -
Amperage (amps or amperes) -
Duy cycle -
Phooransisor -
Analog -
Elecriciy -
Polarized -
Analog-o-Digial Converer
Floa -
Power supply -
(ADC) -
Funcion -
Processing -
Anode -
Gae -
Pseudocode -
Argumen -
Global variable -
Pulse Widh Modulaion
Array -
Ground -
(PWM) -
Back-volage -
IDE -
Resisance -
Baud -
Index -
Sensor -
Binary -
Inducion -
Serial buffer -
Bi -
Insance -
Serial communicaion -
Boolean -
Insulaor -
Serial monior -
Bye -
In -
Series -
Calibraion -
Inegraed Circui (IC)-
Shor circui -
Capaciance -
Library -
Skech -
Cahode -
Load -
Soldering -
Circui -
Local variable -
Source (ransisor) -
Common cahode LED -
Long -
Square wave -
Conducor -
Microconroller -
Swich -
Consan -
Millisecond -
Transducer -
Curren -
Objec -
Transisor -
Daashee -
Ohm -
Unsigned -
Daaype -
Ohm’s Law -
USB -
Debugging -
Opocoupler -
Variable -
Decoupling capaciors -
Parallel -
Volage -
Digial -
Parameer -
Volage divider -
GLOSSARY
163
GLOSSARY THERE ARE A NUMBER OF NEW TERMS YOU’VE LEARNED IN THESE PROJECTS. WE’VE COLLECTED THEM ALL HERE FOR REFERENCE
A Acceleromeer - A sensor ha measures ac-
Analog-o-Digial Converer (ADC) - A circui
celeraion. Someimes, hey are used o deec
ha convers an analog volage ino a digial
orienaion, or il.
number represening ha volage. This circui is buil-in o he microconroller, and is con-
Acuaor - A ype o componen ha changes
neced o he analog inpu pins A0-A5. Con-
elecrical energy ino moion. Moors are a ype
vering an analog volage ino a digial number
o acuaor.
akes a iny bi o ime, so we always ollow he analogRead() wih a shor delay().
Alernaing curren - A ype o curren where elecriciy changes is direcion periodically.
Anode - The posiive end o a capacior or diode
This is he sor o elecriciy ha comes ou o
(remember ha an LED is a ype o diode).
a wall socke.
Argumen - A ype o daa supplied o a unc Amperage (amps or amperes) - The amoun o
ion as an inpu. For example, or digialRead()
elecrical charge flowing pas a specific poin
o know wha pin o check, i akes an argu-
in your circui. Describes he curren as i flows
men in he orm o a pin number.
hrough a conducor, like a wire.
Array - In programming, his is a group o vari Analog - Somehing ha can coninuously vary
ables ha are idenified by one name, and ac-
over ime.
cessed by an index number.
164
Glossary
B Back-volage - Volage ha pushes back agains he curren ha creaed i. I can be creaed by moors spinning down. This can damage circuis, which is why diodes are ofen used in conjuncion wih moors. Baud - Shorhand or “bis per second”, signiying he speed a which compuers are communicaing wih each oher. Binary - A sysem wih only wo saes, like rue/alse or off/on. Bi - The smalles piece o inormaion a compuer can send or receive. I has wo saes, 0 and 1. Boolean - A daaype ha indicaes i somehing is rue or alse.
Cahode - The end o a capacior or diode ha ypically connecs o ground. Circui - A circular pah rom a power supply, hrough a load, and hen back again o he oher end o he power supply. Curren flows in a circui only i i is closed, ha is, i he ougoing and reurn pah are boh uninerruped, or closed. I eiher pah is inerruped, or open, hen curren will no flow hrough he circui. Common cahode LED - Types o LEDs ha have muliple colors in one fixure, wih one cahode and muliple anodes. Conducor - Somehing ha enables elecriciy o flow, like a wire. Consan - A named idenifier ha canno change is value in a program. Curren - The flow o elecrical charge hrough a closed circui. Measured in amps.
Bye - 8 bis o inormaion. A bye can hold a number beween 0 and 255.
C Calibraion - The process o making adjusmens o cerain numbers or componens o ge he bes resuls rom a circui or program. In Arduino projecs, his is ofen used when sensors in he real world may give differen values in differen circumsances, or insance he amoun o ligh on a phooresisor. Calibraion can be auomaic, as in Projec 6, or manual, as in Projec 3. Capaciance - The abiliy o somehing o hold an elecrical charge. This charge can be measured wih he Capaciive Sensor library, as seen in Projec 13.
D Daashee - A documen writen by engineers or oher engineers ha describes he design and uncionaliy o elecrical componens. Typical inormaion in a daashee includes he maximum volage and curren a componen requires, as well as an explanaion o he uncionaliy o he pins. Daaype - A classificaion sysem ha deermines wha values a paricular consan, variable, or array will hold. In, floa, long and boolean are all ypes ha can be used in Arduino. Debugging - The process o going hrough a circui or code, and finding errors (also reerred as “bugs”), unil he expeced behavior is achieved.
165
Decoupling capaciors - Capaciors ha are used o regulae spikes and dips in volage, o-
G
en placed close o a sensor or acuaor. Gae - The pin on a ransisor ha is conneced Digial - A sysem o discree values. As Arduino
o he Arduino. When he gae is urned on,
is a ype o digial device, i only knows o wo
by applying 5V, i closes he juncion beween
discree saes, off and on, nohing in beween.
drain and source, compleing he circui i is conneced o.
Direc curren - A ype o curren which always flows in he same direcion. All he projecs in
Global variable - A named variable ha can be
his ki use direc curren.
accessed anywhere inside your program. I is declared beore he seup() uncion.
Drain (ransisor) - The pin ha connecs o he higher curren/volage load o be conrolled.
Ground - The poin o a circui where here is 0 poenial elecrical energy. Wihou a ground,
Dual In-line Package (DIP) - A ype o packaging
elecriciy will no have a place o flow in a
or inegraed circuis ha allows he compo-
circui.
nens o be easily insered ino a breadboard. Duy cycle - A raio indicaing he amoun o ime over a cerain period ha a componen
I
is urned on. When using a PWM value o 127 (ou o a oal o 256), you’re creaing a 50%
IDE - Sands or “Inegraed Developmen En-
duy cycle.
vironmen”. The Arduino IDE is he place where you wrie sofware o upload o he Arduino. I conains all he uncions he Arduino can un-
E
dersand. Oher programming environmens, like Processing, have heir own IDE.
Elecriciy - A ype o energy generaed by
Index - The number supplied o an array ha
elecric charges. You can use elecronic com-
indicaes which elemen you’re reerring o.
ponens o change elecriciy o oher orms o
Compuers are zero-indexed, which means
energy, like ligh and hea.
hey sar couning a 0 insead o 1. To access he hird elemen in an array named ones, or example, you would wrie ones[2].
F
Inducion - The process o using elecrical energy o creae a magneic field. This is used in
Floa - A daaype ha can be expressed as a
moors o spin hem around.
racion. This enails he use o decimal poins or floaing poin numbers.
Insance - A copy o a sofware objec. You’re using insances o he Servo library in Projecs 5
Funcion - A block o code ha execues a spe-
and 12, in each case, you’re creaing a named in-
cific ask repeaedly.
sance o he Servo library o use in he projec.
166
Glossary
Insulaor - Somehing ha prevens elecriciy
is a small compuer ha you will program o lis-
rom flowing. Conducive maerials like wires
en or, process, and display inormaion.
are ofen covered in insulaors like rubber. Millisecond - 1/1,000h o a second. The Arduino In - A daaype ha holds a whole number be-
goes hrough is programs so as, when call-
ween −32,768 and 32,767.
ing delay() and oher ime based uncions, i’s done in milliseconds.
Inegraed Circui (IC) - A circui ha has been creaed on a iny piece o silicon and embedded in plasic (or epoxy). Pins, or legs, proruding rom he body allow you o inerac wih he
O
circui inside. Very ofen we can make good use o an IC knowing only wha o connec o he
Objec - An insance o a library. When using he
pins wihou having o undersand how i unc-
Servo library, were you o creae an insance
ions inernally.
named myServo, myServo would be he objec. Ohm - Uni o measuremen o resisance. Rep-
L
resened by he omega symbol (Ω). Ohm’s Law - A mahemaical equaion ha
Library - A piece o code ha expands he unc-
demonsraes he relaionship beween resis-
ionaliy o a program. In he case o Arduino li-
ance, curren and volage. Usually saed as V
braries, hey eiher enable communicaion wih
(volage) = I (curren) x R (resisance).
a paricular piece o hardware, or are used or manipulaing daa.
Opocoupler - Also known as an opo-isolaor, phoo-coupler, phoo-isolaor, phoo-swich,
Load - A device ha urns elecrical energy ino
and opo-swich. An LED is combined in a
somehing else, such as ligh, hea, or sound.
sealed case wih a phooransisor. The LED is posiioned o illuminae he phooransisor, so
Local variable - A ype o variable ha is used
ha when he LED is urned on, he phooran-
or a shor amoun o ime, hen orgoten. A
sisor will conduc. Used o provide a high de-
variable declared inside he seup() o a pro-
gree o isolaion as here is no elecrical con-
gram would be local: afer he seup() finished
necion common o he inpu and he oupu.
running, he Arduino would orge ha he variable ever exised. Long - A daaype ha can hold a very large
P
number, rom −2,147,483,648 o 2,147,483,647. Parallel - Componens conneced across he same wo poins in a circui are in parallel. Par-
M Microconroller - The brains o he Arduino, his
allel componens always have he same volage drop across hem. Parameer - When declaring a uncion, a
167
named parameer serves as he bridge beween
Pseudocode - A bridge beween wriing in a
he local variables in he uncion, and he argu-
compuer programming language and using
mens i receives when he uncion is called.
naural speech. When creaing pseudocode, i’s helpul o wrie in shor declaraive saemens.
Period - A specific span o ime in which somehing happens. When he period changes,
Pulse Widh Modulaion (PWM) - A way o sim-
you’re adjusing he requency a which some-
ulae an analog oupu when using a digial de-
hing will occur.
vice, PWM involves urning a pin on and off a a very rapid rae.The raio o ON ime o OFF ime
Phoocell - A device or convering ligh energy
deermines he simulaed analog resul.
o elecrical energy. Phooresisor - A resisive device whose resisance varies according o how much ligh alls
R
on i. Resisance - A measure o how efficienly a Phooransisor - A ransisor which is con-
maerial will conduc elecriciy. In paricular,
rolled by ligh raher han by curren.
resisance can be calculaed by Ohm’s Law as: R = V/I.
Polarized - The leads o polarized componens (e.g. LEDs or capaciors) have differen uncions, and hus mus be conneced he righ way. Polarized componens conneced he
S
wrong way migh no work, migh be damaged, or migh damage oher pars o your circui.
Sensor - A componen ha measures one orm
Non-polarized componens (e.g. resisors) can
o energy (like ligh or hea or mechanical en-
be conneced eiher way.
ergy) and convers i o elecrical energy, which he Arduino can undersand.
Power supply - A source o energy, usually a baery, ransormer, or even he USB por o your
Serial buffer - A place in your compuer’s and
compuer. Comes in many varieies such as
microconroller’s memory where inormaion
regulaed or unregulaed, AC or DC. Usually he
received in serial communicaion is sored unil
volage is specified, along wih he maximum
i is read by a program.
curren he supply can deliver beore ailing. Serial communicaion - The means by which Processing - A programming environmen
he Arduino communicaes wih compuers
based on he Java language. Used as a ool o
and oher devices. I involves sending one bi o
inroduce people o he conceps o program-
inormaion a a ime in a sequenial order. The
ming, and in producion environmens.
Arduino has a USB-o-serial converer onboard,
The Arduino IDE is writen in Processing, and so
which enables i o alk wih devices ha don’
will look very amiliar. In addiion, Processing
have a dedicaed serial por.
and Arduino share a similar philosophy and moive, o creaing ree open source ools allowing
Serial monior - A ool buil in o he Arduino
non-echnical people o work wih hardware
IDE allowing sending and receiving serial daa
and sofware.
o and rom a conneced Arduino. See he
168
Glossary
Serial() se o uncions.
device which can ac as eiher an amplifier or a swich. A conrol volage or curren beween
Series - Componens are in series when curren
wo leads conrols a (usually) higher volage or
flows rom he firs ino he nex. The curren
curren beween a differen pair o leads. Com-
flowing hrough boh is he same, and he vol-
mon ypes o ransisors include he Bipolar
age drops across each componen.
Juncion Transisor (BJT) and he Meal Oxide Semiconducor Field Effec Transisor (MOS-
Shor circui - A shor circui beween power
FET). Ofen used o allow a small curren rom
and ground will make your circui sop work-
an Arduino (limied o 40 mA) o conrol sub-
ing and hus should be avoided. In some cases
sanially larger currens, such as hose needed
his migh damage your power supply or pars
by moors, relays, or incandescen lamps. De-
o your circui, and rare cases migh sar a fire.
pending on how hey are consruced, ransisors are eiher N-channel or P-channel, which
Skech - The erm given o programs writen in
deermines how hey should be conneced.
he Arduino IDE. Soldering - The process o making an elecrical connecion by meling solder over elecrical
U
componens or wires ha are o be conneced. This provides a solid connecion beween com-
Unsigned - A erm used o describe some daa-
ponens.
ypes, indicaing ha hey canno be a negaive number. I’s helpul o have an unsigned num-
Source (ransisor) - The pin on a ransisor ha
ber i you only need o coun in one direcion.
connecs o ground. When he gae receives
For insance, when keeping rack o ime wih
power, he source and drain are conneced,
millis(), i’s advisable o use he unsigned long
compleing he circui ha is being conrolled.
daaype.
Square wave - A ype o waveorm ha is iden-
USB - Sands or Universal Serial Bus. I’s a ge-
ified by having only wo saes, on and off.
neric por ha is sandard on mos compuers
When used o generae ones, hey can sound
oday. Wih a USB cable, i’s possible o program
“buzzy”.
and power an Arduino over a USB connecion.
Swich - A componen ha can open or close an elecrical circui. There are many differen kinds o swiches; he ones in he ki are momenary meaning, hey only close he circui while being pressed.
V Variable - A place in your compuer’s or mi-
T
croconroller’s memory or soring inormaion needed in a program. Variables sore values which are likely o change as your pro-
Transducer - Somehing ha changes one orm
gram runs. A variable’s ype depends on he
o energy ino anoher.
ype o inormaion you wan o sore, and he maximum size o he inormaion; or
Transisor - A 3 erminal (usually) elecronic
example, a bye can sore up o 256 dier-
169
en values, bu an in can sore up 65,536 dieren values. Variables can be local o a paricular block o code, or global o an enire program. (see Global variable, Local variable). Volage - A measure o poenial energy, ha a charge migh be pushed wih i provided a closed circui. Volage divider - A ype o circui ha provides an oupu ha is a racion o is inpu volage. You are building a volage divider when you combine a phooresisor wih a fixed resisor o provide an analog inpu. A poeniomeer is anoher example o a volage divider.
170
Further Reading
FURTHER READING
Geting Sared wih Arduino by Massimo Banzi [O’Reilly Media / Make, 2011]. The definiive inroducion o Arduino.
Geting Sared wih Processing by Casey Reas and Ben Fry [O’Reilly Media / Make, 2010]. This shor guide o he Processing programming environmen ells you more abou how o program graphics, sounds, and mulimedia on your compuer.
Making Things Talk, 2nd Ediion by Tom Igoe [O’Reilly Media / Make, 2011]. Writen or more experienced Arduino users, his book gives you many echniques or communicaing beween Arduino microconrollers and oher devices on he inerne, and beyond.
Learning Processing: A Beginner’s Guide o Programming Images, Animaion, and Ineracion by Daniel Shiffman [Morgan Kauman, 2009]. An in-deph inroducion o programming using Processing, or beginners o all ages.
Geting Sared wih RFID by Tom Igoe [O’Reilly Media / Make, 2012]. A shor inroducion o using Radio Frequency Idenificaion wih Arduino and Processing.
171
The Arduino Cookbook, 2nd Ediion by Michael Margolis [O’Reilly Media / Make, 2011]. This
book has a lo o grea recipes or how o use Arduino in more advanced ways.
Making Things Move: DIY Mechanisms or Invenors, Hobbyiss, and Ariss by Dusyn Robers [McGraw-Hill, 2010]. A grea resource
on building movable mechanisms o inerace wih your projecs.
Make: Elecronics, by Charles Plat [O’Reilly Media / Make, 2009]. Cleverly writen inroducion o elecronics suiable or jus abou anyone. No Arduinos were used in he making o his book, bu i’s a valuable ex o undersand elecronics beter.
iOS Sensor Apps wih Arduino, by Alasdair Allan [O’Reilly Media / Make, 2011]. Wih his concise guide, you’ll learn how o connec an exernal sensor o an iOS device and have hem alk o each oher hrough Arduino. You’ll also build an iOS applicaion ha will parse he sensor values i receives and plo he resuling measuremens, all in real-ime.