Light-Based Theremin Project Guide
Light-Based Theremin Project Guide
06
PIEZO
PHOTORESISTOR
10 KILOHM RESISTOR
71
LIGHT
THEREMIN
TIME TO MAKE SOME NOISE! USING A PHOTORESISTOR
AND A PIEZO ELEMENT, YOU’RE GOING TO MAKE A
LIGHTttBASED THEREMIN
PERIOD
PWM 50: analogWrite(50)
Notice how the signal is low most of the time,
5
but the frequency is the same as PWM 200.
0
PERIOD
PWM 200: analogWrite(200)
Notice how the voltage is high most of the
5
time, but the frequency is the same as PWM 50.
0
PERIOD
TONE 440: tone(9,440)
The duty cycle is 50% (on half the time, off half
5
the time), but the frequency changes.
0
PERIOD
TONE 880: tone(9,880)
Same duty cycle as Tone 440; but twice the
5
frequency.
Fig. 1 10 MILLISECONDS
72 Project 06
Light Theremin
A piezo is a small element that vibrates when it receives electricity. When it moves,
it displaces air around it, creating sound waves.
BUILD THE
CIRCUIT
+ - + -
Fig. 2 + - + -
73
Fig. 3
Traditional theremins can control the frequency and the volume of sound. In this
example, You’ll be able to control the frequency only. While you can’t control the
volume through the Arduino, it is possible to change the voltage level that gets
to the speaker manually. What happens if you put a potentiometer in series with
pin 8 and the piezo? What about another photoresistor?
❹ Take your piezo, and connect one end to ground, and the other
to digital pin 8 on the Arduino.
THE CODE
Create variables for Create a variable to hold the analogRead() value from the
calibrating the sensor photoresistor. Next, create variables for the high and low values.
You’re going to set the initial value in the sensorLow variable to
1023, and set the value of the sensorHigh variable to 0. When
you first run the program, you’ll compare these numbers to the
sensor’s readings to find the real maximum and minimum values.
Name a constant for your Create a constant named ledPin. You’ll use this as an indicator
calibration indicator that your sensor has finished calibrating. For this project, use the
on-board LED connected to pin 13.
Set digital pin direction and In the setup(), change the pinMode() of ledPin to OUTPUT,
turn it high and turn the light on.
Use a while() loop for The next steps will calibrate the sensor’s maximum and minimum
calibration values. You’ll use a while() statement to run a loop for 5
seconds. while() loops run until a certain condition is met. In
this case you’re going to use the millis() function to check
the current time. millis() reports how long the Arduino has
been running since it was last powered on or reset.
Compare sensor values for In the loop, you’ll read the value of the sensor; if the value is less
calibration than sensorLow (initially 1023), you’ll update that variable. If
it is greater than sensorHigh (initially 0), that gets updated.
Indicate calibration has When 5 seconds have passed, the while() loop will end. Turn offi
finished the LED attached to pin 13. You’ll use the sensor high and low
values just recorded to scale the frequency in the main part of
your program.
75
1 int sensorValue;
2 int sensorLow = 1023;
3 int sensorHigh = 0;
5 void setup() {
6 pinMode(ledPin, OUTPUT);
7 digitalWrite(ledPin, HIGH);
9 sensorValue = analogRead(A0);
10 if (sensorValue > sensorHigh) {
11 sensorHigh = sensorValue;
12 }
13 if (sensorValue < sensorLow) {
14 sensorLow = sensorValue;
15 }
16 }
17 digitalWrite(ledPin, LOW);
18 }
76 Project 06
Light Theremin
Read and store the sensor In the loop(), read the value on A0 and store it in sensorValue.
value
Map the sensor value to a Create a variable named pitch. The value of pitch is going
frequency to be mapped from sensorValue. Use sensorLow and
sensorHigh as the bounds for the incoming values. For starting
values for output, try 50 to 4000. These numbers set the range
of frequencies the Arduino will generate.
Play the frequency Next, call the tone() function to play a sound. It takes three
arguments : what pin to play the sound on (in this case pin 8),
what frequency to play (determined by the pitch variable), and
how long to play the note (try 20 milliseconds to start).
USE IT When you first power the Arduino on, there is a 5 second win-
dow for you to calibrate the sensor. To do this, move your
hand up and down over the photoresistor, changing the
amount of light that reaches it. The closer you replicate the
motions you expect to use while playing the instrument, the
better the calibration will be.
19 void loop() {
20 sensorValue = analogRead(A0);
21 int pitch =
map(sensorValue,sensorLow,sensorHigh, 50, 4000);
22 tone(8,pitch,20);
23 delay(10);
24 }
The range in the map() function that determines the pitch is pretty wide, try
changing the frequencies to find ones that are the right fit for your musical style.
The tone() function operates very much like the PWM in analogWrite() but with
one significant diffierence. In analogWrite() the frequency is fixed; you change the
ratio of the pulses in that period of time to vary the duty cycle. With tone() you’re
still sending pulses, but changing the frequency of them. tone() always pulses at a
50% duty cycle (half the time the pin is high, the other half the time it is low).
INGREDIENTS
07
PIEZO
10 KILOHM RESISTOR
1 MEGOHM RESISTOR
KEYBOARD
INSTRUMENT
WITH FEW RESISTORS AND BUTTONS YOU ARE GOING TO
BUILD A SMALL MUSICAL KEYBOARD
This is a way to read a number of switches using the analog input. It’s a helpful
technique if you find yourself short on digital inputs. You’ll hook up a number of
switches that are connected in parallel to analog in 0. Most of these will connect
to power through a resistor. When you press each button, a diffierent voltage level
will pass to the input pin. If you press two buttons at the same time, you’ll get a
unique input based on the relationship between the two resistors in parallel.
BUILD THE
CIRCUIT
+ - + -
+ - + -
Fig. 3
81
Think about an enclosure for the keyboard. While old analog synthesizers had
wires poking out all over the place, your keyboard is sleek and digital. Prepare a
small piece of cardboard that can be cut out to accommodate your buttons. Label
the keys, so you know what notes are triggered by each key.
❶ ❹
Draw and cut a piece of paper with holes for the four Position the paper over the buttons and piezo.
buttons and piezo. Decorate it to look like a piano keyboard. Enjoy your creation!
82 Project 07
Keyboard Instrument
THE CODE
The array In this program, you’ll need to keep a list of frequencies you want
to play when you press each of your buttons. You can start out
with the frequencies for middle C, D, E and F (262Hz, 294Hz,
330Hz, and 349Hz). To do this, you’ll need a new kind of variable
called an array.
An array is a way to store diffierent values that are related to
each other, like the frequencies in a musical scale, using only
one name. They are a convenient tool for you to quickly and
eftciently access information. To declare an array, start as you
would with a variable, but follow the name with a pair of square
brackets: []. Affer the equals sign, you’ll place your elements in
curly brackets.
To read or change the elements of the array, you reference the
individual element using the array name and then the index of
the item you want to address. The index refers to the order in
which the items appear when the array is created. The first item
in the array is item 0, the second is item 1, and so forth.
Create an array of Set up an array of four notes using the frequencies listed above.
frequencies Make this array a global variable by declaring it before the
setup().
Begin serial communication In your setup(), start serial communication with the computer.
Read the analog value and In the loop(), declare a local variable to hold the value
send it to the serial monitor read on pin A0. Because each switch has a diffierent resistor
value connecting it to power, each will have a diffierent value
associated with it. To see the values, add the line Serial.
println(keyVal) to send to the computer.
Use an if()...else statement to Using an if()...else statement, you can assign each value to a
determine what note to play diffierent tone. The values included in the example program are
ballpark figures for these resistor sizes. As all resistors have some
tolerance for error, these may not work exactly for you. Use the
information from the serial monitor to adjust as necessary.
83
int buttons[6];
// set up an array with 6 integers
int buttons[0] = 2;
// give the first element of the array the value 2
2 void setup() {
3 [Link](9600);
4 }
5 void loop() {
6 int keyVal = analogRead(A0);
7 [Link](keyVal);
8 if(keyVal == 1023){
9 tone(8, notes[0]);
10 }
84 Project 07
Keyboard Instrument
Play the notes that correspond Affer each if() statement, call the tone() function. The
to the analog value program references the array to determine what frequency
to play. If the value of A0 matches one of your if statements,
you can tell the Arduino to play a tone. It’s possible your circuit
is a little “noisy” and the values may fluctuate a little bit while
pressing a switch. To accommodate for this variation, it’s a good
idea to have a small range of values to check against. If you use
the comparison “&&”, you can check multiple statements to see
if they are true.
If you press the first button, notes[0] will play. If you press the
second, notes[1] will play, and if you press the third, notes[2] will
play. This is when arrays become really handy.
Stop playing the tone when Only one frequency can play on a pin at any given time, so if
nothing is pressed you’re pressing multiple keys, you’ll only hear one sound.
Press multiple buttons at the same time, and see what sort of
values you get in the serial monitor. Use these new values to
trigger even more sounds. Experiment with diffierent frequencies
to expand your musical output. You can find frequencies of
musical notes on this page: [Link]/frequencies
If you replace the switches and resistor ladder with analog sensors, can you use the
additional information they give you to create a more dynamic instrument? You
could use the value to change the duration of a note or, like in the Theremin Project,
create a sliding scale of sounds.
85
20 else{
21 noTone(8);
22 }
23 }
The tone() function is fun for generating sounds, but it does have a few limi-
tations. It can only create square waves, not smooth sine waves or triangles.
Square waves don’t look much like waves at all. As you saw in Fig. 1 in Project 6,
it’s a series of on and offi pulses.
As you start your band, keep some things in mind : only one tone can play at a time
and tone() will interfere with analogWrite() on pins 3 and 11.
INGREDIENTS
08
LED
10 KILOHM RESISTOR
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 BUILTttIN TIMER
The millis() function helps to solve these problems. It keeps track of the time
your Arduino has been running in milliseconds. You used it previously in Project 6
when you created a timer for calibration.
So far you’ve been declaring variables as int. An int (integer) is a 16-bit number,
it holds values between -32,768 and 32,767. Those may be some large numbers,
but if the Arduino is counting 1000 times a second with millis(), you’d run out
of space in less than a minute. The long datatype holds a 32-bit number (between
-2,147,483,648 and 2,147,483,647). Since you can’t run time backwards to get
negative numbers, the variable to store millis() time is called an unsigned
long. When a datatype is called unsigned, it is only positive. This allows you to
count even higher. An unsigned long can count up to 4,294,967,295. That’s
enough space for milis() to store time for almost 50 days. By comparing the
current millis() to a specific value, you can see if a certain amount of time has
passed.
When you turn your hourglass over, a tilt switch will change its state, and that will
set offi another cycle of LEDs turning on.
The tilt switch works just like a regular switch in that it is an on/offi sensor. You’ll
use it here as a digital input. What makes tilt switches unique is that they detect
orientation. Typically they have a small cavity inside the housing that has a metal
88 Project 08
Digital Hourglass
ball. When tilted in the proper way, the ball rolls to one side of the cavity and
connects the two leads that are in your breadboard, closing the switch.
With six LEDs, your hourglass will run for an hour, just as its name implies.
BUILD THE
CIRCUIT
+ - + -
+ - + -
Fig. 1
Fig. 2
89
❹ Connect the anode (longer leg) of six LEDs to digital pins 2-7.
Connect the LEDs to ground through 220-ohm resistors.
❷ Connect one lead of the tilt switch to 5V. Connect the other to
a 10-kilohm resistor to ground. Connect the junction where they
meet to digital pin 8.
You don’t need to have your Arduino tethered to the computer for this to work.
Try building a stand with some cardboard or styrofoam and power the Arduino
with a battery to make a portable version. You can create a cover with some nu-
meric indicators alongside the lights.
Tilt switches are great, inexpensive tools for determining the orientation of some-
thing. Accelerometers are another type of tilt sensor, but they give out much more
information. They are also significantly more expensive. If you’re just looking to see if
something is up or down, a tilt sensor works great.
90 Project 08
Digital Hourglass
THE CODE
Declare a named constant You’re going to need a number of global variables in your
program to get this all working. To start, create a constant named
switchPin. This will be the name of the pin your tilt switch is on.
Create a variable to hold the Create a variable of type unsigned long, This will hold the time
time an LED was last changed.
Name variables for the inputs Create a variable for the switch state, and another to hold the
and outputs previous switch state. You’ll use these two to compare the
switch’s position from one loop to the next.
Create a variable named led. This will be used to count which LED
is the next one to be turned on. Start out with pin 2.
Declare a variable describing The last variable you’re creating is going to be the interval
the interval between events between each LED turning on. This will be be a long datatype.
In 10 minutes (the time between each LED turning on) 600,000
milliseconds pass. If you want the delay between lights to be
longer or shorter, this is the number you change.
Set the direction of your In your setup(), you need to declare the LED pins 2-7 as
digital pins outputs. A for() loop declares all six as OUTPUT with just 3 lines
of code. You also need to declare switchPin as an INPUT.
Check the time since the When the loop() starts, you’re going to get the amount of time
program started running the Arduino has been running with millis() and store it in a
local variable named currentTime.
Evaluate the amount of Using an if() statement, you’ll check to see if enough time has
time that has passed since passed to turn on an LED. Subtract the currentTime from the
the previous loop() previousTime and check to see if it is greater than the interval
variable. If 600,000 milliseconds have passed (10 minutes), you’ll
set the variable previousTime to the value of currentTime.
91
3 int switchState = 0;
4 int prevSwitchState = 0;
5 int led = 2;
7 void setup() {
8 for(int x = 2;x<8;x++){
9 pinMode(x, OUTPUT);
10 }
11 pinMode(switchPin, INPUT);
12 }
13 void loop(){
14 unsigned long currentTime = millis();
Turn on an LED, prepare for previousTime indicates the last time an LED was turned on.
the next one Once you’ve set previousTime, turn on the LED, and increment
the led variable. The next time you pass the time interval, the
next LED will light up.
Check to see if all lights Add one more if statement in the program to check if the LED on
are on pin 7 is turned on. Don’t do anything with this yet. You’ll decide
what happens at the end of the hour later.
Read the value of the switch Now that you’ve checked the time, you’ll want to see if the
switch has changed its state. Read the switch value into the
switchState variable.
Reset the variables to their With an if() statement, check to see if the switch is in a diffierent
defaults if necessary position than it was previously. The != evaluation checks to see
if switchState does not equal prevSwitchState. If they
are diffierent, turn the LEDs offi, return the led variable to the first
pin, and reset the timer for the LEDs by setting previousTime
to currentTime.
Set the current state to the At the end of the loop(), save the switch state in
previous state prevSwitchState , so you can compare it to the value you
get for switchState in the next loop().
17 digitalWrite(led, HIGH);
18 led++;
19 if(led == 7){
20 }
21 }
22 switchState = digitalRead(switchPin);
23 if(switchState != prevSwitchState){
24 for(int x = 2;x<8;x++){
25 digitalWrite(x, LOW);
26 }
27 led = 2;
28 previousTime = currentTime;
29 }
30 prevSwitchState = switchState;
31 }
When the clock reaches one hour and all six lights are on, they just stay on. Can
you think of a way to get your attention when the hour is up? Sound or flashing
the lights are both good indicators. The led variable can be checked to see if all
the lights are on, that’s a good place to check for grabbing someone’s attention.
Unlike an hourglass filled with sand, the lights go either up or down depending
on the orientation of the switch. Can you figure out how you can use the switch-
State variable to indicate what direction the lights should go?
DIODE 1N4007
MOTOR
SWITCH
9v
battery
BATTERY BATTERY SNAP
95
MOTORIZED
PINWHEEL
GET THE ARDUINO TO SPIN A COLORFUL PINWHEEL
USING A MOTOR
Controlling motors with an Arduino is more complicated than just controlling LEDs
for a couple of reasons. First, motors require more current than the Arduino’s out-
put pins can supply, and second, motors can generate their own current through
a process called induction, which can damage your circuit if you don’t plan for it.
However, motors make it possible to move physical things, making your projects
much more exciting. They’re worth the complications!
Moving things takes a lot of energy. Motors typically require more current than
the Arduino can provide. Some motors require a higher voltage as well. To start
moving, and when it has a heavy load attached, a motor will draw as much cur-
rent as it can. The Arduino can only provide 40 milliamps (mA) from its digital pins,
much less than what most motors require to work.
Transistors are components that allow you to control high current and high voltage
power sources from the low current output of the Arduino. There are many diffier-
ent kinds, but they work on the same principle. You can think of transistors as digital
switches. When you provide voltage to one of the transistor’s pins, called the gate, it
closes the circuit between the other two pins, called the source and drain. This way,
you can turn a higher current/voltage motor on and offi with your Arduino.
The reverse is also true: a motor can generate electricity when the shaff is spun
around. Try attaching an LED to the two leads of your motor, then spin the shaff
with your hand. If nothing happens, spin the shaff the other way. The LED should
light up. You’ve just made a tiny generator out of your motor.
When you stop supplying energy to a motor, it will continue to spin, because it
has inertia. When it’s spinning, it will generate a voltage in the opposite direction
than the current you gave it. You saw this effiect when you made your motor light
up an LED. This reverse voltage, sometimes called back-voltage, can damage your
transistor. For this reason, you should put a diode in parallel with the motor, so
that the back voltage passes through the diode. The diode will only allow electric-
ity to flow in one direction, protecting the rest of the circuit.
BUILD THE
CIRCUIT
Fig. 1
Fig. 2
97
LEDs are diodes too, in case you were wondering why their leads were also called
anodes and cathodes. There are many kinds of diodes, but they all share one trait.
They allow current to flow from anode to cathode, but not the reverse.
98 Project 09
Motorized Pinwheel
THE CODE
Name your constants and The code is remarkably similar to the code you first used for
variables turning on an LED. First of all, set up some constants for the
switch and motor pins and a variable named switchState to
hold the value of the switch.
Declare the pins’ direction In your setup(), declare the pinMode() of the motor (OUTPUT)
and switch (INPUT) pins.
Read the input, pull the Your loop() is straightforward. Check the state of the switch-
output high if pressed Pin with digitalRead().
Motors have an optimal operating voltage. They will work on as little as 50% of the
rated voltage and as much as 50% over that number. If you vary the voltage, you
can change the speed at which the motor rotates. Don’t vary it too much, though,
or you will burn out your motor.
4 void setup() {
5 pinMode(motorPin, OUTPUT);
6 pinMode(switchPin, INPUT);
7 }
8 void loop(){
9 switchState = digitalRead(switchPin);
10 if (switchState == HIGH) {
11 digitalWrite(motorPin, HIGH);
12 }
13 else {
14 digitalWrite(motorPin, LOW);
15 }
16 }
Transistors are solid state devices, they have no moving parts. Because of this, you
can switch them on and offi very quickly. Try hooking up a potentiometer to an
analog input and use that to PWM the pin that controls the transistor. What do you
think will happen to the motor’s speed if you vary the voltage it’s getting? Using
your patterns on your spinner, can you get diffierent visual effiects?
100 Project 09
Motorized Pinwheel
❶
Snap part C into part B, and then gently press part D on to
them.
❷
Place the paper disk on the CD and secure it using the flaps
on the back.
101
With the motor spinning as fast as it does, you can probably make a pretty large
spinner. Be careful that it doesn’t fly offi and poke someone in the eye. Experiment
with diffierent patterns on the outside to create visual effiects.
❹
Gently press the motor shaft into the hole in the back of
part B.
❸
Attach the CD to the cross formed by parts B and D. Use a
drop of glue to keep the CD from coming off.
INGREDIENTS
POTENTIOMETER 10
H-BRIDGE
10 KILOHM RESISTOR
MOTOR
SWITCH
9v
battery
BATTERY BATTERY SNAP
103
ZOETROPE
CREATE MOVING IMAGES IN FORWARD AND REVERSE WITH
YOUR ARDUINO WHEN YOU CONNECT A MOTOR TO AN
HttBRIDGE AND SOME STILL IMAGES
Discover: H-bridges
Before the internet, television, even before movies, some of the first moving images
were created with a tool called a zoetrope. Zoetropes create the illusion of motion
from a group of still images that have small changes in them. They are typically
cylinders with slits cut in the side. When the cylinder spins and you look through
the slits, your eyes perceive the still images on the other side of the wall to be ani-
mated. The slits help keep the images from becoming a big blur, and the speed at
which the images appear provide cause the images to appear to move. Originally,
these novelties were spun by hand, or with a cranking mechanism.
In this project, you’ll build your own zoetrope that animates a carnivorous plant.
You’ll power the motion with a motor. To make this system even more advanced,
you’ll add a switch that lets you control direction, another to turn it offi and on,
and a potentiometer to control the speed.
In the Motorized Pinwheel Project you got a motor to spin in one direction. If you
were to take power and ground on the motor and flip their orientation, the motor
would spin in the opposite direction. It’s not very practical to do that everytime
you want to spin something in a diffierent direction, so you’ll be using a compo-
nent called an H-bridge to reverse the polarity of the motor.
H-bridges are a type of component known as integrated circuits (IC). ICs are
components that hold large circuits in a tiny package. These can help simplify
more complex circuits by placing them in an easily replaceable component. For
example, the H-bridge you’re using in this example has a number of transistors
built in. To build the circuit inside the H-bridge you would probably need another
breadboard.
104 Project 10
Zoetrope
1 16 With an IC, you can access the circuits through the pins that
2 15 come out the sides. Diffierent ICs have diffierent numbers of pins,
3 14
4 13 and not all of them are used in every circuit. It’s sometimes con-
5 12 venient to refer to the pins by number instead of function. When
6 11
looking at an IC, the part with a dimple is referred to as the top .
7 10
8 9 You can identify pin numbers by counting from the top-leff in a
Fig. 1 “U” direction like in Fig. 1.
BUILD THE
CIRCUIT
+ - + -
9V
Fig. 2 + - + -
Fig. 3
105
❻ The H-bridge get its power from pin 16, plug that into 5V. Pins 4
and 5 both go to ground.
THE CODE
Name your constants Create constants for the output and input pins.
Create variables for remem- Use variables to hold the values from your inputs. You’ll be doing
bering program state state change detection for both switches, comparing the state
from one loop to the next, similar to the Hourglass Project. So,
in addition to storing the current state, you’ll need to record the
previous state of each switch.
Create variables for motor motorDirection keeps track of which direction the motor is
control spinning, and motorPower keeps track of whether the motor is
spinning or not.
Declare the digital pins as In setup(), set the direction of each input and output pin.
inputs and outputs
Turn the motor off Turn the enable pin LOW to start, so the motor isn’t spinning right
away.
Read sensor information In your loop(), read the state of the On/Offi switch and store it
in the onOftSwitchState variable.
107
7 int onOffSwitchState = 0;
8 int previousOnOffSwitchState = 0;
9 int directionSwitchState = 0;
10 int previousDirectionSwitchState = 0;
11 int motorEnabled = 0;
12 int motorSpeed = 0;
13 int motorDirection = 1;
14 void setup(){
15 pinMode(directionSwitchPin, INPUT);
16 pinMode(onOffSwitchStateSwitchPin, INPUT);
17 pinMode(controlPin1, OUTPUT);
18 pinMode(controlPin2, OUTPUT);
19 pinMode(enablePin, OUTPUT);
20 digitalWrite(enablePin, LOW);
21 }
22 void loop(){
23 onOffSwitchState =
digitalRead(onOffSwitchStateSwitchPin);
24 delay(1);
25 directionSwitchState =
digitalRead(directionSwitchPin);
26 motorSpeed = analogRead(potPin)/4;
108 Project 10
Zoetrope
Check if on/off sensor has If there is a diffierence between the current switch state and the
changed previous, and the switch is currently HIGH, set the motorPower
variable to 1. If it is LOW, set the variable to 0.
Read the values of the direction switch and potentiometer. Store
the values in their respective variables.
Check to see if the direction Check to see if the direction switch is currently in a diffierent
has changed position than it was [Link] it is diffierent, change the motor
direction variable. There are only 2 ways for the motor to spin,
so you’ll want to alternate the variable between two states. One
way to accomplish this is byΩ using the inversion operator like so:
motorDirection =!motorDirection.
Change the pins to turn The motorDirection variable determines which direction the
the motor in the proper motor is turning. To set the direction, you set the control pins
direction setting one HIGH and the other LOW. When motorDirection
changes, reverse the states of the control pins.
PWM the motor if it is If the motorEnabled variable is 1, set the speed of the motor using
enabled analogWrite() to PWM the enable pin. If motorEnabled is
0, then turn the motor offi by setting the analogWrite value
to 0.
Save the current states for Before exiting the loop(), save the current state of the switches
the next loop() as the previous state for the next run through the program.
109
27 if(onOffSwitchState != previousOnOffSwitchState){
28 if(onOffSwitchState == HIGH){
29 motorEnabled = !motorEnabled;
30 }
31 }
32 if (directionSwitchState !=
previousDirectionSwitchState) {
33 if (directionSwitchState == HIGH) {
34 motorDirection = !motorDirection;
35 }
36 }
37 if (motorDirection == 1) {
38 digitalWrite(controlPin1, HIGH);
39 digitalWrite(controlPin2, LOW);
40 }
41 else {
42 digitalWrite(controlPin1, LOW);
43 digitalWrite(controlPin2, HIGH);
44 }
45 if (motorEnabled == 1) {
46 analogWrite(enablePin, motorSpeed);
47 }
48 else {
49 analogWrite(enablePin, 0);
50 }
51 previousDirectionSwitchState =
directionSwitchState;
52 previousOnOffSwitchState = onOffSwitchState;
53 }
110 Project 10
Zoetrope
USE IT Plug your Arduino into your computer. Attach the battery to the
connector. When you press the On/Offi switch, the motor should
start spinning. If you turn the potentiometer, it should speed up
and slow down. Pressing the On/Offi button another time will
stop the motor. Try pressing the direction button and verify the
Once you’ve verified that the circuit motor spins both ways. Also, if you turn the knob on the pot, you
works as expected, disconnect the should see the motor speed up or slow down depending on the
ba❺ery and USB from the circuit. value it is sending.
❶ ❹
Secure the CD onto the wooden base. Add a drop of glue to Use the tabs to close the cutout, forming a circle.
make sure it doesn’t spin loose when the motor starts.
111
In order to build your zoetrope, you must take the pinwheel you used in Project 9
and the cutout with the vertical slits that is included in your kit. Once the CD is se-
curely attached to the shaff of the motor, plug everything back in. Hold your project
up, so you can look through the slits (but make sure the CD is secured to the motor,
and don’t get too close to it). You should see the sequence of still images “move”!
If it is going too fast or too slow, turn the knob of the potentiometer to adjust the
speed of the animation.
Try pressing the direction switch to see what the animation looks like when played
backwards. The zoetrope and images provided in the kit are only your starting point:
try experimenting with your own animations, using the cutout as a reference.
To do this, start with a basic image. Identify one fixed point in it, and make small
changes to the rest in each frame. Try to gradually return to the original image so
that you can play the animation in a continuous loop.
❶ ❶
Insert the four tabs into the base of the zoetrope. Insert the strip of paper with the images inside the
zoetrope.
112 Project 10
Zoetrope
Make a base to support the motor. A small cardboard box with a hole cut in it could
work as a base, leaving your hands free to play with the switches and knob. This will
make it easier to show offi your work to everyone.
With a little work, you can get your zoetrope working in low light situations as well.
Hook up an LED and resistor to one of your free digital output pins. Also add a sec-
ond potentiometer, and connect it to an analog input. Position the light so it shines
on the images. Using the analog input to time the flashes of the LED, try and time it
so the light flashes when the slit is in front of your eyes. This could take some fiddling
with the knobs, but the resulting effiect is really spectacular!
SWITCH
INGREDIENTS
11
10 KILOHM RESISTOR
POTENTIOMETER
LCD SCREEN
115
CRYSTAL
BALL
CREATE A CRYSTAL BALL TO TELL YOUR FUTURE
Crystal balls can help “predict” the future. You ask a question to the all-knowing
ball, and turn it over to reveal an answer. The answers will be predetermined, but
you can write in anything you like. You’ll use your Arduino to choose from a total
of 8 responses. The tilt switch in your kit will help replicate the motion of shaking
the ball for answers.
The LCD can be used to display alphanumeric characters. The one in your kit has
16 columns and 2 rows, for a total of 32 characters. There are a large number of
connections on the board. These pins are used for power and communication,
so it knows what to write on screen, but you won’t need to connect all of them.
See Fig. 1 for the pins you need to connect.
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
LED-
LED+
D7
D6
D5
D4
D3
D2
D1
D0
E
R/W
RS
V0
Vcc
Vss
BUILD THE
CIRCUIT
+ - + -
+ - + -
Fig. 2
Fig. 3
In this schematic the LCD pins arrangement does not match the physical order depicted in Fig. 2.
In a schematic, the pins are rearranged by logical grouping to make the schematic as clear as pos-
sible. This is a little confusing to newcomers until you get used to it.
117
The circuit is not overly complex, but there are a lot of wires.
Pay attention when wiring everything up to make sure it’s
correct.
❹ Place the tilt switch on the breadboard and attach one lead to
5V. Attach the other side to ground through a 10-kilohm resis-
tor, and to your Arduino’s pin 6. You’re wiring this as a digital
input, just as you’ve done in several other projects.
❷ The register select (RS) pin controls where the characters will
appear on screen. The read/write pin (R/W) puts the screen
in read or write mode. You’ll be using the write mode in this
project. The enable (EN) tells the LCD that it will be receiving
a command. The data pins (D0-D7) are used to send charac-
ter data to the screen. You’ll only be using 4 of these (D4-D7).
Finally, there’s a connection for adjusting the contrast of the
display. You’ll use a potentiometer to control this.
Set up the LiquidCrystal First, you’ll need to import the LiquidCrystal library.
library Next, you’ll initialize the library, somewhat similar to the way you
did with the Servo library, telling it what pins it will be using to
communicate.
Now that you’ve set up the library, it’s time to create some
variables and constants. Create a constant to hold the pin of
the switch pin, a variable for the current state of the switch, a
variable for the previous state of the switch, and one more to
choose which reply the screen will show.
Print your first line Set up the switch pin as an input with pinMode() in your
setup(). Start the LCD library, and tell it how large the screen is.
Move the cursor Now it’s time to write a small introductory screen welcoming you
to the 8-ball. The print() function writes to the LCD screen.
You’re going to write the words “Ask the” on the top line of the
screen. The cursor is automatically at the beginning of the top line.
In order to write to the next line, you’ll have to tell the screen
where to move the cursor. The coordinates of the first column on
the second line are 0,1 (recall that computers are zero indexed.
0,0 is the first column of the first row). Use the function lcd.
setCursor() to move the cursor to the proper place, and tell
it to write “Crystal ball!”.
Now, when you start the program, it will say “Ask the Crystal ball!”
on your screen.
In the loop(), you’re going to check the switch first, and put the
value in the switchState variable.
Choose a random anwser Use an if() statement to determine if the switch is in a diffierent
position than it was previously. If it is diffierent than it was before,
and it is currently LOW, then it’s time to choose a random reply.
The random() function returns a number based on the
argument you provide it. To start, you’ll have a total number
of 8 diffierent responses for the ball. Whenever the statement
random(8) is called, it will give a number between 0-7. Store that
number in your reply variable.
119
1 #include <LiquidCrystal.h>
2 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
10 [Link](“Ask the”);
11 [Link](0, 1);
12 [Link](“Crystal Ball!”);
13 }
14 void loop() {
15 switchState = digitalRead(switchPin);
Predict the future The switch() statement executes diffierent pieces of code
depending on the value you give it. Each of these diffierent pieces
of code is called a case. switch() checks the value of the
variable reply; whatever value reply holds will determine what
named case statement is executed.
Inside the case statements, the code will be the same, but the
messages will be diffierent. For example, in case 0 the code
says [Link] (“Yes”). Affer the [Link]() function,
there’s another command: break. It tells the Arduino where the
end of the case is. When it hits break, it skips to the end of the
switch statement. You’ll be creating a total of 8 case statements
to start out. Four of the responses will be positive, 2 will be
negative, and the final 2 will ask you to try again.
19 [Link]();
20 [Link](0, 0);
21 [Link](“The ball says:”);
22 [Link](0, 1);
51 prevSwitchState = switchState;
52 }
122 Project 11
Crystal Ball
USE IT To use the magic ball, power the Arduino. Check the screen to
make sure it says “Ask the Crystal ball!” If you can’t see the char-
acters, try turning the potentiometer. It will adjust the contrast
of the screen.
Ask a question of your crystal ball, and try tilting the switch up-
side down and back again. You should get an answer to your
question. If the answer doesn’t suit you, ask again.
Try adding your own sayings to the print() statements, but be mindful of the
fact that there are only 16 characters to use per line. You can also try adding more
responses. Make sure when you add additional switch cases, you adjust the number
of options that will randomly populate the reply variable.
The functions covered here for changing the LCD screen’s text are fairly simple.
Once you have a handle on how it works, look at some of the other functions the
library has. Try getting text to scroll, or continually update. To find out more about
how the LiquidCrystal library works, visit: [Link]/lcd
INGREDIENTS
LED
12
10 KILO OHM RESISTOR
1 MEGOHM RESISTOR
100uF CAPACITOR
KNOCK
LOCK
MAKE YOUR OWN SECRET LOCKING MECHANISM TO KEEP
UNWANTED GUESTS OUT OF YOUR SPACE!
The piezo you used for playing back sounds in the theremin and keyboard pro-
jects can also be used as an input device. When plugged into 5V, the sensor can
detect vibrations that can be read by the Arduino’s analog inputs. You’ll need to
plug in a high value resistor (like 1-megohm) as the reference to ground for this
to work well.
When the piezo is pressed flat against a solid surface that can vibrate, like a wood-
en table top, your Arduino can sense how intense a knock is. Using this informa-
tion you can check to see if a number of knocks fall in an acceptable range. In code
you can track the number of knocks and see if they match your settings.
A switch will let you lock the motor in place. Some LEDs will give you status: a red
LED will indicate the box is locked, a green LED will indicate the box is unlocked,
and a yellow LED lets you know if a valid knock has been received.
You’ll also be writing your own function that will let you know if a knock is too loud
or too soff. Writing your own function helps save time programming by reusing
code instead of writing it out many times. Functions can take arguments and
return values. In this case, you’ll give a function the volume of the knock. If it is in
the right range, you’ll increment a variable.
It’s possible to build the circuit by itself, but it’s much more fun if you use this as
a tool to lock something. If you have a wooden or a cardboard box you can cut
holes into, use the servo motor to open and close a latch, keeping people from
getting at your stuffi.
126 Project 12
Knock Lock
BUILD THE
CIRCUIT
+ - + -
+ - + -
Fig. 1
Fig. 2
127
❹ Attach the wires from the piezo to the breadboard. Attach one
wire to power. If your piezo has a red wire or one marked with
a “+”, that is the one to connect to power. If your piezo doesn’t
indicate polarity, then you can hook it up either way. Wire
the other end of the piezo to Analog Pin 0 on your Arduino.
Place a 1-megohm resistor between the ground and the other
wire. Lower resistor values will make the piezo less sensitive to
vibrations.
❸ Insert the male headers into the female socket on the servo
motor (see Fig.3). Connect the red wire to power, and the black
wire to ground. Place a 100uF electrolytic capacitor across
power and ground to smooth out any irregularities in voltage,
making sure you have the capacitor’s polarity correct. Connect
the servo’s data wire to pin 9 on your Arduino.
THE CODE
Just as in the earlier Mood Cue Project, you’ll need to import the
Servo library
Servo library and create an instance to use the motor.
Variables to hold switch and Create variables to hold the values from your switch and piezo.
piezo values
Knock tresholds Set up some constants to use as thresholds for the knock
maximum and minimum levels.
Variables for lock state and The locked variable will let you know if the lock is enganged or
number of knocks not. A boolean is a data type that can only be true (1) or false
(0). You should start with the mechanism unlocked.
The last global variable will hold the number of valid knocks you
have received.
Setting the direction of the In your setup(), attach the servo to pin 9.
digital pins and initializing Set the LED pins as outputs and the switch pins as inputs.
servo object and serial port
Checking the switch In the loop(), you’ll first check to see if the box is locked or not.
This will determine what happens in the rest of the program. If it
is locked, read the switch value.
129
1 #include <Servo.h>
2 Servo myServo;
8 int knockVal;
9 int switchVal;
14 void setup(){
15 [Link](9);
16 pinMode(yellowLed, OUTPUT);
17 pinMode(redLed, OUTPUT);
18 pinMode(greenLed, OUTPUT);
19 pinMode(switchPin, INPUT);
20 [Link](9600);
21 digitalWrite(greenLed, HIGH);
22 [Link](0);
23 [Link](“The box is unlocked!”);
24 }
25 void loop(){
26 if(locked == false){
27 switchVal = digitalRead(switchPin);
130 Project 12
Knock Lock
Lock
If the switch is closed (you’re pressing it), change the locked
variable to true, indicating the lock is engaged. Turn the green
LED offi, and the red LED on. If you don’t have the serial monitor
on, this is helpful visual feedback to let you know the status of
the lock. Move the servo into the lock position, and print out a
message to the serial monitor indicating the box is now locked.
Add a delay so the lock has plenty of time to move into place.
Checking the knock sensor If the locked variable is true, and the lock is engaged, read the
value of the vibration of the piezo and store it in knockVal.
Counting only valid knocks The next statement checks to see if you have fewer than three
valid knocks, and there is some vibration on the sensor. If these
are both true, check to see if this current knock is valid or not and
increment the numberOfKnocks variable. This is where you’ll
call your custom function checkForKnocks(). You’ll write the
function once you’re finished with the loop(), but you already
know you’re going to be asking it if this is a valid knock, so pass
the knockVal along as an argument. Affer checking your function,
print out the number of knock still needed.
Unlock Check to see if you have three or more valid knocks. If this is
true, change the locked variable to false, and move the servo to
the unlocked position. Wait for a few milliseconds to let it start
moving, and change the status of the green and red LEDs. Print
out a status message to the serial monitor, indicating the box is
unlocked.
Defining a function to check Now it’s time to write the function checkForKnock(). When
knock validity you’re writing functions of your own, you need to indicate if it is going
to return a value or not. If it is not going to return a value, you declare
it as type void, similar to the loop() and setup() functions. If it
is going to return a value, you must declare what kind (int, long,
float, etc.). In this case, you’re checking to see if a knock is valid
(true) or not (false). Declare the function as type boolean.
131
28 if(switchVal == HIGH){
29 locked = true;
30 digitalWrite(greenLed,LOW);
31 digitalWrite(redLed,HIGH);
32 [Link](90);
33 [Link](“The box is locked!”);
34 delay (1000);
35 }
36 }
37 if(locked == true){
38 knockVal = analogRead(piezo);
Check validity of knock In your function, whenever you refer to value it will use whatever
number it receives as an argument in the main program. At this
point value will be set to whatever knockVal is.
Check to see if value is greater than your quiet knock, and less
than your loud knock.
Indicating knock is valid If the value falls between those two values it’s a valid knock. Blink
the yellow LED once and print the value of the knock to the serial
monitor.
Function returns true To let the main program know what the outcome of the
comparison is, you use the command return. You use the
return command, which also terminates the function: once it
executes, you return to the main program.
Indicating invalid knock; If value is either too quiet or too loud, print it out to the serial
function returns false monitor and return false.
USE IT When you first plug in the circuit to your Arduino, open the
serial monitor. You should see the green LED turn on, and the
servo will move to the unlocked position.
Try knocking soft and hard to see what sort of intensity knock
triggers your function. You’ll know it’s working when the yel-
133
58 digitalWrite(yellowLed, HIGH);
59 delay(50);
60 digitalWrite(yellowLed, LOW);
61 [Link](“Valid knock of value “);
62 [Link](value);
63 return true;
64 }
65 else {
66 [Link](“Bad knock value “);
67 [Link](value);
68 return false;
69 }
70 }
low LED flashes and the serial monitor tells you you have a
valid knock with its value. It will also let you know the number
of knocks you have to go before unlocking the box.
Once you’ve reached the right number of knocks, the red light
will turn off, the green light will turn on, the servo will move
90 degrees, and the serial monitor will let you know the lock
is disengaged.
134 Project 12
Knock Lock
The values for your ideal knock may vary from the ones in the example. This de-
pends on a number of diffierent variables, like the type of surface the sensor is
attached to and how sturdily it is fixed on there. Using the serial monitor and the
AnalogInSerialOut example in the Arduino IDE, find an appropriate knock value for
your setup. You can find a detailed explanation of that example here:
[Link]/analogtoserial
If you move the project into a box, you’ll need to make holes for the LEDs and
the switch. You’ll also need to make a latch for the servo motor to spin into. It will
probably also be helpful to have a hole to run your USB cable through to find out
how sensitive your new environment is to knocks.
You may need to rearrange your breadboard and Arduino, or solder the LEDs and
switch to make them accessible to the exterior of your enclosure. Soldering is a
process of joining two or more metal components together with an adhesive that
is melted between the joint. If you’ve never soldered before, ask someone who has
experience to help you out, or try practicing on some scrap wire before attempting
with another device in this project. When you solder something, it’s meant to be a
permanent connection, so be sure it’s something that’s ok to hack.
See [Link]/soldering for a good explanation of how to solder.
❶
Cut 2 holes in your box: one on the side, and a second
through the cover flap. Place the servo in the box so that
the arm can move in and out of the holes when closed.
135
Writing your own functions not only allows you to control the flow of your code more
easily, it also helps keep it readable as your projects become larger and larger. Over
time, as you write more code, you may find you have a large number of functions you
can re-use in diffierent projects, making the process quicker and unique to your style
of programming.
This example simply counts the right number of knocks, no matter how long it takes.
You can start to make a more complex example by creating a timer with millis().
Use the timer to identify if the knocks happen in a specific period of time. Look back
at the Digital Hourglass Project for an example of how a timer works. You aren’t lim-
ited to simply finding knocks in a specific range. You can look for complex patterns of
knocks based on the amount of vibration and timing together. There are a number
of examples online that talk about how to do this, search for “Arduino knock lock” to
discover more examples of this type of project.
❹
Secure the servo in place with some tape, again making sure
the arm can easily rotate through the slot you made.
LED
INGREDIENTS
220 OHM RESISTOR
13
1 MEGOHM RESISTOR
METAL FOIL
137
TOUCHY-FEELY
LAMP
YOU WILL CREATE A LAMP THAT TURNS A LIGHT ON AND
OFF WHEN YOU TOUCH A PIECE OF CONDUCTIVE MATERIAL
You’ll be using the CapacitiveSensor library by Paul Badger for this project. This
library allows you to measure the capacitance of your body.
Preparing the library The most recent version of the CapacitiveSensor library is here:
[Link]/capacitive. Download the file to your computer
and unzip it. Open your Arduino sketch folder (it will be in your
“Documents” folder by default). In the folder, create a new di-
rectory named “libraries”. Place the CapacitiveSensor folder you
unzipped in this folder and restart the Arduino soffware.
Click the File>Examples menu in the Arduino soffware, and you’ll
see a new entry for “CapacitiveSensor”. The library you added
included an example project. Open the CapacitiveSensorSketch
example and compile it. If you don’t get any errors, you’ll know
you installed it correctly.
BUILD THE
CIRCUIT
Fig. 1
Fig. 2
139
Just like with other LED projects, diffiusing the light will make this much more at-
tractive. Ping pong balls, little lampshades from paper or plastic, whatever you have
handy will work.
You can hide the sensor behind something solid and it will still work. Capacitance
can be measured through non-conductive materials like wood and plastic. Increas-
ing the surface area of the sensor with a larger conductive surface will make it more
sensitve; try connecting aluminum foil, or copper mesh to your wire. You could
make a base for the lamp out of cardboard, thin wood, or cloth, and line the inner
surface with foil attached to your sensor wire. The whole base of the lamp would
then act as a touch sensor. Update the threshold variable in the code when you
make these changes to ensure that you’re still getting a reliable result.
140 Project 13
Touchy-feely Lamp
THE CODE
Import the CapacitiveSensor At the beginning of your program, include the CapacitiveSensor
library library. You include it the same way you would a native Arduino
library like the Servo library in the earlier projects.
Create a named instance of the library. When you use this library,
you tell the instance what pins it will be using to send and receive
information. In this case, pin 4 sends to the conductive sensor
material through the resistor, and pin 2 is the sense pin.
Set up the threshold Set up a variable for the sensing threshold at which the lamp
will turn on. You’ll change this number affer you test the sensor’s
functionality.
Then define the pin your LED will be on.
Sensing touch In the loop() function, create a variable of type long to hold the
sensor’s value. The library returns the sensor value using a com-
mand called CapacitiveSensor() that takes an argument
identifying the number of samples you want to read. If you read
only a few samples, it’s possible you’ll see a lot of variation in the
sensor. If you take too many samples, you could introduce a lag
as it reads the sensor multiple times. 30 samples is a good start-
ing value. Print the sensor value to the serial monitor.
1 #include <CapacitiveSensor.h>
2 CapacitiveSensor capSensor = CapacitiveSensor(4,2);
5 void setup() {
6 [Link](9600);
7 pinMode(ledPin, OUTPUT);
8 }
9 void loop() {
10 long sensorValue = [Link](30);
11 [Link](sensorValue);
18 delay(10);
19 }
142 Project 13
Touchy-feely Lamp
USE IT Affer programming the Arduino, you’ll want to find out what
the sensor values are when it’s touched. Open the serial moni-
tor and note the value coming from the sensor when you’re not
touching it. Press gently on the bare wire you have exposed from
your breadboard. The number should increase. Try pressing more
firmly and see if it changes.
Once you have an idea of the range of values you’re getting from
the sensor, go back to the sketch and change the threshold vari-
able to a number that is greater than the sensor’s value when
it is not touched, but less than its value when pressed. Upload
the sketch with the new value. The light should come on reliably
when you touch the wire, and turn offi when it’s leff alone. If you
aren’t getting the light to turn on, try lowering the threshold a
little more.
You probably noticed that the values from the sensor changed depending on how
much of your finger was touching the conductor. Can you use this to get other
interactions with the LED? What about multiple sensors for fading the light brighter
and darker? If you place a diffierent value resistor between pins 2 and 4 it will change
the sensitivity. Is this useful for your interface?
INGREDIENTS
145
TWEAK THE
ARDUINO LOGO
USING SERIAL COMMUNICATION, YOU’LL USE YOUR
ARDUINO TO CONTROL A PROGRAM ON YOUR COMPUTER
You’ve done a lot of cool stutt with the physical world, now it’s time to control
your computer with your Arduino. When you program your Arduino, you’re
opening a connection between the computer and the microcontroller. You can
use this connection to send data back and forth to other applications.
The Arduino has a chip that converts the computer’s USB-based communication
to the serial communication the Arduino uses. Serial communication means that
the two computers, your Arduino and PC, are exchanging bits of information
serially, or one affer another in time.
When communicating serially, computers need to agree on the speed at which
they talk to one another. You’ve probably noticed when using the serial monitor
there’s a number at the bottom right corner of the window. That number, 9600
bits per second, or baud, is the same as the value you’ve declared using Serial.
begin(). That’s the speed at which the Arduino and computer exchange data.
A bit is the smallest amount of information a computer can understand.
You’ve used the serial monitor to look at values from the analog inputs; you’ll
use a similar method to get values into a program you’re going to write in a
programming environment called Processing. Processing is based on Java, and
Arduino’s programming environment is based on Processing’s. They look pretty
similar, so you should feel right at home there.
Before getting started with the project, download the latest version of Processing
from [Link]. It may be helpful to look at the “Getting started” and
“Overview” tutorials at [Link]/learning. These will help you to familiarize
yourself with Processing before you start writing soffware to communicate with
your Arduino.
146 Project 14
Tweak the Arduino Logo
The most eftcient way to send data between the Arduino and Processing is by
using the [Link]() function in Arduino. It’s similar to the Serial.
print() function you’ve been using in that it sends information to an attached
computer, but instead of sending human readable information like numbers and
letters, it sends values between 0-255 as raw bytes. This limits the values that the
Arduino can send, but allows for quick transmission of information.
On both your computer and Arduino, there’s something called the serial buffier
which holds onto information until it is read by a program. You’ll be sending bytes
from the Arduino to Processing’s serial buffier. Processing will then read the bytes
out of the buffier. As the program reads information from the buffier, it clears space
for more.
When using serial communication between devices and programs, it’s important
that both sides not only know how fast they will be communicating, but also
what they should be expecting. When you meet someone, you probably expect a
“Hello!”; if instead they say something like “The cat is fuzzy”, chances are you will be
caught offi guard. With soffware, you will need to get both sides to agree on what
is sent and received.
Fig. 1
147
BUILD THE
CIRCUIT
Fig. 2
Fig. 3
148 Project 14
Tweak the Arduino Logo
THE ARDUINO
CODE
Open a serial connection First, program your Arduino. In setup(), you’ll start serial
communication, just as you did earlier when looking at the values
from an attached sensor. The Processing program you write will
have the same serial baud rate as your Arduino.
Send the sensor value In the loop(), you’re going to use the [Link]()
command to send information over the serial connection.
[Link]() can only send a value between 0 and 255. To
make sure you’re sending values that fit within that range, divide
the analog reading by 4.
Let the ADC stabilize Affer sending the byte, wait for one millisecond to let the ADC
settle down. Upload the program to the Arduino then set it aside
while you write your Processing sketch.
THE PROCESSING
CODE
Import the set up the serial The Processing language is similar to Arduino, but there are
object enough diffierences that you should look at some of their
tutorials and the “Getting Started” guide mentioned before to
familiarize yourself with the language.
Open a new Processing sketch. Processing, unlike the Arduino,
doesn’t know about serial ports without including an external
library. Import the serial library.
You need to create an instance of the serial object, just like you’ve
done in Arduino with the Servo library. You’ll use this uniquely
named object whenever you want to use the serial connection.
Create an object for the To use images in Processing, you need to create an object that
image will hold the image and give it a name.
149
1 void setup() {
2 [Link](9600);
3 }
4 void loop() {
5 [Link](analogRead(A0)/4);
1 import [Link].*;
2 Serial myPort;
3 PImage logo;
150 Project 14
Tweak the Arduino Logo
Variable to store the Create a variable that will hold the background hue of the Arduino
background color logo. The logo is a .png file, and it has built-in transparency, so it’s
possible to see the background color change.
Setting the color mode You can change the way Processing works with color information.
Typically, it works with colors in a Red Green Blue (RGB) fashion.
This is similar to the color mixing you did in Project 4, when you
used values between 0 and 255 to change the color of an RGB
LED. In this program, you’re going to use a color mode called
HSB, which stands for Hue, Saturation, and Brightness. You’ll
change the hue when you turn the potentiometer.
Loading the image To load the Arduino image into the sketch, read it into the logo
object you created earlier. When you supply the URL of an image,
Processing will download it when you run the program.
With the size() function, you tell Processing how large the
display window will be. If you use [Link] and logo.
height as the arguments, the sketch will automatically scale to
the size of the image you’re using.
Printing available serial Processing has the ability to print out status messages using the
ports println() command. If you use this in conjunction with the
[Link]() function, you’ll get a list of all the serial ports
your computer has when the program first starts. You’ll use this once
you’re finished programming to see what port your Arduino is on.
Creating the serial object You need to tell Processing information about the serial
connection. To populate your named serial object myPort with
the necessary information, the program needs to know it is a
new instance of the serial object. The parameters it expects are
which application it will be speaking to, which serial port it will
communicate over, and at what speed.
151
4 int bgcolor = 0;
5 void setup() {
6 colorMode(HSB, 255);
7 logo = loadImage(“[Link]
8 size([Link], [Link]);
11 myPort =
new Serial(this, [Link]()[0], 9600);
12 }
152 Project 14
Tweak the Arduino Logo
The attribute this tells Processing you’re going to use the serial
connection in this specific application. The [Link]()
[0] argument specifies which serial port you’re using. Serial.
list() contains an array of all the attached serial devices. The
argument 9600 should look familiar, it defines the speed at
which the program will communicate.
Reading Arduino data from Check if there is information from the Arduino. The myPort.
the serial port available() command will tell you if there is something in
the serial buffier. If there are bytes there, read the value into the
bgcolor variable and print it to the debug window.
Setting the image The function background() sets the color of the window. It
background and displaying takes three arguments. The first argument is the hue, the next
the image is brightness, and the last is saturation. Use the variable bgcolor
as the hue value, and set the brightness and saturation to the
maximum value, 255.
You’ll draw the logo with the command image(). You need
to tell image() what to draw, and what coordinates to start
drawing it in the window. 0,0 is the top leff, so start there.
Connect your Arduino and open the serial monitor. Turn the
USE IT
pot on your breadboard. You should see a number of charac-
ters as you twist the knob. The serial monitor expects ASCII
characters, not raw bytes. ASCII is information encoded to
represent text in computers. What you see in the window is
the serial monitor trying to interpret the bytes as ASCII.
13 void draw() {
14 if ([Link]() > 0) {
15 bgcolor = [Link]();
16 println(bgcolor);
17 }
Once you have twisted and turned to your heart’s desire, try replacing the pot
with an analog sensor. Find something you find interesting to control the color.
What does the interaction feel like? It’s probably diffierent than using a mouse or
keyboard, does it feel natural to you?
When using serial communication, only one application can talk to the Arduino at a
time. So if you’re running a Processing sketch that is connected to your Arduino, you
won’t be able to upload a new Arduino sketch or use the serial monitor until you’ve
closed the active application.
With Processing and other programming environments, you can control media on
your computer in some remarkable and novel ways. If you’re excited about the pos-
sibilities of controlling content on your computer, take some time to experiment
with Processing. There are several serial communication examples in both the Pro-
cessing and Arduino IDEs that will help you explore further.
INGREDIENTS
220 OHM RESISTOR
15
157
HACKING
BUTTONS
GET CONTROL OF OTHER COMPONENTS AROUND YOU.
USING SOME ADDITIONAL CIRCUITRY, YOU CAN “PRESS”
BUTTONS WITH YOUR ARDUINO
Warning: You’re no longer a beginner if you’re doing this project. You’ll be opening
up an electronic device and modifying it. You’ll void your device’s warranty, and if
you’re not careful, you might damage the device. Make sure you’re familiar with
all the electronics concepts in the earlier projects before you affempt this one. We
recommend you use inexpensive items you don’t mind damaging for your first few
projects, until you develop experience and confidence.
While the Arduino can control a lot of things, sometimes it’s easier to use tools
that are created for specific purposes. Perhaps you want to control a television
or a music player, or drive a remote control car. Most electronic devices have a
control panel with buttons, and many of those buttons can be hacked so that
you can “press” them with an Arduino. Controlling recorded sound is a good
example. If you wanted to record and play back recorded sound, it would take
a lot of effiort to get the Arduino to do that. It’s much easier to get a small
device that records and plays back sound, and replace its buttons with outputs
controlled by your Arduino.
Optocouplers are integrated circuits that allow you to control one circuit from
a diffierent one without any electrical connection between the two. Inside an
optocoupler is an LED and a light detector. When the LED in the optocoupler
is turned on by your Arduino, the light detector closes a switch internally. The
switch is connected to two of the output pins (4 and 5) of the optocoupler.
When the internal switch is closed, the two output pins are connected. When the
switch is open, they’re not connected. This way, it’s possible to close switches on
other devices without connecting them to your Arduino.
158 Project 15
Hacking Buttons
In this example, the diagrams are for controlling a digital recording module that allows you to
record and playback 20 seconds of sound, but the basic premise holds for any device that has
a switch you can access. While it’s possible to use this example without soldering any wires, it
certainly makes things easier. For more information on soldering, see p. 134.
BUILD THE
CIRCUIT
Fig. 1
Fig. 2
159
❺ Under the button are two small metal plates. This pattern is
typical of many electronic devices with pushbuttons. The two
“forks” of this pattern are the two sides of the switch. A small
metal disc inside the pushbutton connects these two forks
when you press the button.
❻ When the forks are connected, the switch is closed on the circuit
board. You will be closing the switch with the optocoupler.
This method, closing a switch with an optocoupler, works only if
one of the two sides of the pushbutton’s switch is connected to
ground on your device. If you’re not sure, take a multimeter and
measure the voltage between one of the forks and the ground
on your device. You need to do this with the device turned on, so
be careful not to touch anywhere else on the board.
Once you know which fork is ground, disconnect the power to
your device.
❼ Next, connect one wire to each of the small metal plates. If you
are soldering these wires, be careful to not join the two sides
of the switch together. If you are not soldering and using tape,
make sure your connection is secure, or the switch won’t close.
Make sure neither wire connects to the other fork, or your switch
will be closed all the time.
THE CODE
Name a constant Most of the fun with this project is in the circuit and the
optocoupler. The code is similar to the first project you made
with the Arduino. You’re going to play the sound once every 20
seconds by turning pin 2 HIGH.
Create a constant for the optocoupler control pin.
Configure the pin direction In setup(), set the optocoupler pin into an output.
Pull the pin high and low The loop() turns optoPin HIGH for a few milliseconds, long
enough for the optocoupler to close the switch on the device.
Then the optoPin becomes LOW.
Wait for a little while Wait for 21 seconds for the whole message to play back before
starting the loop() again.
Attach the battery to the sound recorder. Press and hold the
USE IT
record button on the device. While you’re holding the button,
you can record audio into the microphone. Use your voice, the
cat, or the pots and pans in the kitchen to make some noise
(but be careful with the cat).
Try experimenting with diffierent sounds and durations of toggling the playback
with the delay() in your program.
If you trigger the switch while a sound is playing, it will stop. How can you take
advantage of this to create unique sequences of sounds?
161
2 void setup(){
3 pinMode(optoPin, OUTPUT);
4 }
5 void loop(){
6 digitalWrite(optoPin, HIGH);
7 delay(15);
8 digitalWrite(optoPin, LOW);
9 delay(21000);
10 }
Integrated circuits are in virtually every electronic device. The large 28 pin chip on
your Arduino is an IC that houses the brains of the board. There are other ICs that
support this one with communication and power. The optocoupler and main chip on
the Arduino are Dual In-line Package (DIP) chips. These DIP chips are the kind that
most hobbyists use because they easily fit in a breadboard and don’t have to be per-
manently soldered to be used.
The project example only played sound back at a regular interval. How could you
incorporate the inputs from earlier projects to trigger these sounds? What other
battery powered things do you have around the house that need an Arduino to con-
trol them? This technique of controlling an electronic device with an optocoupler by
connecting to the two sides of a switch can be used in many other devices. What
other devices do you want to control?
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
Accelerometer - A sensor that measures ac- Analog-to-Digital Converter (ADC) - A circuit
celeration. Sometimes, they are used to detect that converts an analog voltage into a digital
orientation, or tilt. number representing that voltage. This circuit
is built-in to the microcontroller, and is con-
Actuator - A type of component that changes nected to the analog input pins A0-A5. Con-
electrical energy into motion. Motors are a type verting an analog voltage into a digital number
of actuator. takes a tiny bit of time, so we always follow the
analogRead() with a short delay().
Alternating current - A type of current where
electricity changes its direction periodically. Anode - The positive end of a capacitor or diode
This is the sort of electricity that comes out of (remember that an LED is a type of diode).
a wall socket.
Argument - A type of data supplied to a func-
Amperage (amps or amperes) - The amount of tion as an input. For example, for digitalRead()
electrical charge flowing past a specific point to know what pin to check, it takes an argu-
in your circuit. Describes the current as it flows ment in the form of a pin number.
through a conductor, like a wire.
Array - In programming, this is a group of vari-
Analog - Something that can continuously vary ables that are identified by one name, and ac-
over time. cessed by an index number.
164 Glossary
B
Cathode - The end of a capacitor or diode that
typically connects to ground.
D
C Datasheet - A document written by engineers
for other engineers that describes the design
and functionality of electrical components.
Calibration - The process of making adjustments
Typical information in a datasheet includes the
to certain numbers or components to get the
maximum voltage and current a component
best results from a circuit or program. In Arduino
requires, as well as an explanation of the func-
projects, this is offen used when sensors in the
tionality of the pins.
real world may give diffierent values in diffierent
circumstances, for instance the amount of light
Datatype - A classification system that deter-
on a photoresistor. Calibration can be automatic,
mines what values a particular constant, varia-
as in Project 6, or manual, as in Project 3.
ble, or array will hold. Int, float, long and boolean
are all types that can be used in Arduino.
Capacitance - The ability of something to
hold an electrical charge. This charge can be
Debugging - The process of going through a cir-
measured with the Capacitive Sensor library,
cuit or code, and finding errors (also referred as
as seen in Project 13.
“bugs”), until the expected behavior is achieved.
165
G
Decoupling capacitors - Capacitors that are
used to regulate spikes and dips in voltage, of-
ten placed close to a sensor or actuator.
Gate - The pin on a transistor that is connected
Digital - A system of discrete values. As Arduino to the Arduino. When the gate is turned on,
is a type of digital device, it only knows of two by applying 5V, it closes the junction between
discrete states, offi and on, nothing in between. drain and source, completing the circuit it is
connected to.
Direct current - A type of current which always
flows in the same direction. All the projects in Global variable - A named variable that can be
this kit use direct current. accessed anywhere inside your program. It is
declared before the setup() function.
Drain (transistor) - The pin that connects to the
higher current/voltage load to be controlled. Ground - The point of a circuit where there is 0
potential electrical energy. Without a ground,
Dual In-line Package (DIP) - A type of packaging electricity will not have a place to flow in a
for integrated circuits that allows the compo- circuit.
nents to be easily inserted into a breadboard.
I
Duty cycle - A ratio indicating the amount of
time over a certain period that a component
is turned on. When using a PWM value of 127
(out of a total of 256), you’re creating a 50% IDE - Stands for “Integrated Development En-
duty cycle. vironment”. The Arduino IDE is the place where
you write soffware to upload to the Arduino. It
contains all the functions the Arduino can un-
Electricity - A type of energy generated by Index - The number supplied to an array that
electric charges. You can use electronic com- indicates which element you’re referring to.
ponents to change electricity to other forms of Computers are zero-indexed, which means
energy, like light and heat. they start counting at 0 instead of 1. To access
the third element in an array named tones, for
example, you would write tones[2].
Insulator - Something that prevents electricity is a small computer that you will program to lis-
from flowing. Conductive materials like wires ten for, process, and display information.
are offen covered in insulators like rubber.
Millisecond - 1/1,000th of a second. The Arduino
Int - A datatype that holds a whole number be- goes through its programs so fast, when call-
tween 32,768 and 32,767. ing delay() and other time based functions, it’s
done in milliseconds.
Integrated Circuit (IC) - A circuit that has been
created on a tiny piece of silicon and embedded
in plastic (or epoxy). Pins, or legs, protruding
from the body allow you to interact with the
circuit inside. Very offen we can make good use
O
of an IC knowing only what to connect to the Object - An instance of a library. When using the
pins without having to understand how it func- Servo library, were you to create an instance
tions internally. named myServo, myServo would be the object.
Microcontroller - The brains of the Arduino, this Parameter - When declaring a function, a
167
named parameter serves as the bridge between Pseudocode - A bridge between writing in a
the local variables in the function, and the argu- computer programming language and using
ments it receives when the function is called. natural speech. When creating pseudocode, it’s
helpful to write in short declarative statements.
Period - A specific span of time in which some-
thing happens. When the period changes, Pulse Width Modulation (PWM) - A way to sim-
you’re adjusting the frequency at which some- ulate an analog output when using a digital de-
thing will occur. vice, PWM involves turning a pin on and offi at a
very rapid [Link] ratio of ON time to OFF time
Photocell - A device for converting light energy determines the simulated analog result.
to electrical energy.
Square wave - A type of waveform that is iden- USB - Stands for Universal Serial Bus. It’s a ge-
tified by having only two states, on and offi. neric port that is standard on most computers
When used to generate tones, they can sound today. With a USB cable, it’s possible to program
“buzzy”. and power an Arduino over a USB connection.
FURTHER
READING