Bionic Arduino
Introduction to Microcontrollers with Arduino
Class 2
13 Nov 2007 - machineproject - Tod E. Kurt
Whats for Today
Random Behavior
RGB LEDs
Color mixing
Analog input with variable resistors
Potentiometers & photocells
Basic serial input & output
Playing sound with piezo buzzers
This is a lot of stu!, lets see how far we get.
b
l
i
n
k
b
l
i
n
k
compile
upload
sketch runs
TX/RX ash Load File/Sketchbook/Examples/Digital/Blink
Recap: Blinky LED
Make sure things still work
Change the delay() values to change blink rate
Known Good
Conguration
Rule #1 of experimenting:
Before trying anything new,
Get back to a known working state
So spend a few minutes & get Blink working again
Get your entire edit->compile->upload->run working
Even if it becomes so second nature to you that you feel you shouldnt need to, do it anyway.
Especially when mysterious problems arise, revert to a known state
Getting the Board Set Up
wire up pin 9 LED too
Arduino
board
gnd
pin 9
gnd
resistor
LED
schematic
Questions / Review
Any questions, comments, or problems?
Aside: LED Light Tubes
Snug-t straws on
the end of your
LEDs to make
them glow more
visibly
I have a box of multi-colored straws for whatever color LED you like
Random Behavior
CandleLight
Uses simple
pseudo random
number generator
to mimic ame
Use random(min,max)
to pick a number between
min & max.
This sketch is in the handout.
Can also use random numbers to make random decisions.
Note: not truly random, but good enough for most purposes.
Analog Input
To computers, analog is chunky
image from: http://www.engr.colostate.edu/~dga/me307/lectures.html
Analog Input
Many states, not just two (HIGH/LOW)
Number of states (or values, or bins) is resolution
Common computer resolutions:
8-bit = 256 values
16-bit = 65,536 values
32-bit = 4,294,967,296 values
Analog Input
Arduino (ATmega168) has six ADC inputs
(ADC = Analog to Digital Converter)
Reads voltage between 0 to 5 volts
Resolution is 10-bit (1024 values)
In other words, 5/1024 = 4.8 mV smallest
voltage change you can measure
Analog Input
Sure sure, but how to make a varying voltage?
With a potentiometer. Or just pot.
+5V
measure
gnd
50k
The pot you have
pots also look like this
Potentiometers
Moving the knob is like moving
where the arrow taps the voltage on the resistor
When a resistor goes across a voltage di!erence, like +5V to Gnd, the voltage measured at any point
along a resistors length is proportional to the distance from one side.
If you take apart a pot, theres a little wiper just like in the schematic symbol.
But I might have the directions reversed (clockwise vs. anti-clockwise).
What good are pots?
Anytime you need a ranged input
(were used to knobs)
Measure rotational position
steering wheel, robotic joint, etc.
But more importantly for us, potentiometers
are a good example of a resistive sensor
There are many kinds of resistive sensors
Arduino Analog Input
Two legs plug into +5V & Gnd
(red + & blue -) buses
Middle post plugs into a row
(row 7 here)
Run a wire from that row to
Analog In 2
Plug pot directly into breadboard
Why are we using Analog In 2? Because its in the middle. Theres no reason, any of the 6 analog
inputs would work the same.
Pot & LED Circuit
In schematics, inputs are usually on the left, outputs on the right
Also, more positive voltages are on the top, more negative on the bottom
Arduino
board
gnd
pin 2
+5V
+5V
gnd
50k
potentiometer
pin 9
LED
resistor
220 (red-red-brown)
gnd
This is what your board should have on it now
Varying Brightness by Hand
PotDimmer
Turn the knob to
change LED
brightness
process the
input data
input
output
Most all embedded
systems have a
input"process"output
loop
Sketch available in handout
Two Ways to
Hook up LEDs
Arduino
board
gnd
pin 9
gnd
resistor
LED
Arduino
board
gnd
pin 9
resistor
LED
+5V
+5V
To turn ON: digitalWrite(9,HIGH)
To turn OFF: digitalWrite(9,LOW) To turn OFF: digitalWrite(9,HIGH)
To turn ON: digitalWrite(9,LOW)
To set brightness: analogWrite(9,val) To set brightness: analogWrite(9,255-val)
Weve been using the one on the left because it makes more sense.
But youll see the method on the right as well.
The reason for this is that some circuits can switch to Gnd better than they can switch to +5V.
RGB LEDs
Normal LED
RGB LED
cathode
anode +
red cathode
green cathode
anode +
blue cathode
anode +
cathode
anode +
blue red green
actually 3 LEDs in one package
RGB LED, aka tri-color LED
Common-anode RGB LEDs are much more available than common-cathode.
This is why were changing around the logic.
Color Mixing
Arduino
board
pin 11
gnd
pin 10
pin 9
220 (red,red,brown)
red green blue
+5V
common anode
RGB LED
With RGB you can
make any color
(except black)
With just 3 LEDs you can make any* color
Mixing light is the additive color model
(paint is subtractive color, and can give you brown)
*besides the additive/substractive color di!erent, its hard to get the mix to be just right for a
variety of annoying reasons:
- the physics of LEDs mean that di!erent color LEDs put out di!erent amounts of light
- our eyes respond non-linearly across the spectrum, i.e. were more sensitive to green than red
- the lenses in most RGB LEDs dont focus each color to the same spot
Laying out RGB LED Circuit
slightly bend the longest lead and plug it into the +5v (red) bus
plug remaining leads into rows (12,14,&16 here)
connect 220 (red-red-brown) resistors across middle to matching rows
run wires from resistors to pins 9,10,11 of Arduino, can color-code if you want
Arduino
board
pin 11
gnd
pin 10
pin 9
220 (red,red,brown)
red green blue
+5V
common anode
RGB LED
Ignore the green wire in the pictures, thats another circuit.
Keep the pot from last circuit if you can.
RGB Color Fading
RGBMoodLight
Slow color fading
and mixing
Also outputs the current
color values to the serial port
This sketch is located in the handout.
Well get to the serial port stu! in a minute.
It just ramps up and down the red,green,& blue color values and writes them with analogWrite()
from http://www.arduino.cc/en/Tutorial/DimmingLEDs
Pot-controlled RGB
Arduino
board
pin 11
gnd
pin 10
pin 9
220 (red,red,brown)
red green blue
+5V
common anode
RGB LED
pin 2
+5V
gnd
50k
pot
Pot-controlled RGB
RGBPotMixer
Use the pot from
before to control
the color mix
The code turns the single ranged
input value into sectors where
each sector is a color
Also see RGBPotMixer2 for a variation.
How would you change it to adjust brightness?
Sensing the Dark
Pots are example of a voltage divider
Voltage divider splits a voltage in two
Same as two resistors, but you can vary them
Sensing the Dark:
Photocells
aka. photoresistor, light-dependent resistor
A variable resistor
Brighter light == lower resistance
Photocells you have range approx. 0-10k-1M
schematic symbol
Pretty cheap too. Can get a grab bag of 100 misc from Jameco for $20
Photocell Circuit
pin A2
gnd
brown-black-orange
Try it with RGBPotMixer from before
Looks a lot like the pot circuit, doesnt it?
Mood Light
Diffuser made from
piece of plastic
scratched with
sandpaper
Also, can use plastic wrap scrunched up to make an interesting di!user.
Resistive sensors
thermistor
(temperature)
ex sensor
(bend, deection)
photocell
(light)
force sensors
(pressure)
also air pressure
and others
+5V
sensor
resistor
to analog
input
circuit is the same
for all these
Thermistor image from: http://www.facstaff.bucknell.edu/mastascu/elessonsHTML/Sensors/TempR.html
Also see: http://www.ladyada.net/make/midisense/makesensor.html
Communicating
with Others
Arduino can use same USB cable for
programming and to talk with computers
Talking to other devices uses the Serial
commands
Serial.begin() prepare to use serial
Serial.print() send data to computer
Serial.read() read data from computer
Can talk to not just computers.
Most things more complex than simple sensors/actuators speak serial.
Watch the TX/RX LEDS
TX sending to PC
RX receiving from PC
Used when programming
or communicating
Arduino Says Hi
SerialHelloWorld
Sends Hello world!
to your computer
Click on Serial
Monitor button to
see output
Watch TX LED compared
to pin 13 LED
This sketch is located in the handout, but its pretty short.
Use on-board pin 13 LED, no need to wire anything up.
Telling Arduino What To Do
SerialReadBasic
You type H, LED blinks
In Serial Monitor,
type H, press Send
Serial.available() tells
you if data present to read
This sketch is in the handout
Always check Serial.available() or if Serial.read() != -1 to determine if theres actual data to read.
Can modify it to print hello world after it receives something, but before it checks for H.
This way you can verify its actually receiving something.
Arduino Communications
Psst, Arduino doesnt really do USB
It really is serial, like old RS-232 serial
All microcontrollers can do serial
Not many can do USB
Serial is easy, USB is hard
serial terminal from the olde days
is just serial communications
Serial Communications
Serial because data is broken down into bits, each
sent one after the other down a single wire.
The single ASCII character B is sent as:
B = 0 1 0 0 0 0 1 0
= L H L L L L H L
=
LOW
HIGH
Toggle a pin to send data, just like blinking an LED
You could implement sending serial data with digitalWrite()
and delay()
A single data wire needed to send data. One other to receive.
Note, a single data wire. You still need a ground wire.
Arduino & USB-to-serial
USB to serial
Arduino
microcontroller
Arduino board is really two circuits
Original Arduino boards were RS-232 serial, not USB.
Arduino Mini
Arduino Mini separates the two circuits
Arduino Mini Arduino Mini USB adapter
aka. Arduino Stamp
If you dont talk with a computer, the USB-to-serial functionality is superuous.
Arduino to Computer
Arduino board Laptop
USB to serial
Arduino
microcontroller
USB to serial
driver
Arduino
programmer
Processing
sketch
Java program
RX
TX
-OR-
-OR-
-OR-
...
USB TX
RX
chip
USB is totally optional for Arduino
But it makes things easier
Original Arduino boards were RS-232 serial, not USB.
All programs that talk to Arduino (even the Arduino IDE) think that theyre talking via a serial port.
Arduino & USB
Since Arduino is all about serial
And not USB,
Interfacing to things like USB ash drives,
USB hard disks, USB webcams, etc. is not
possible
Also, USB is a host/peripheral protocol. Being a USB host means needing a lot of processing
power and software, not something for a tiny 8kB microcontroller.
It can be a peripheral. In fact, there is an open project called AVR-USB that allows AVR chips like
used in Arduino to be proper USB peripherals. See: http://www.obdev.at/products/avrusb/
Controlling the Computer
Can send sensor data from Arduino to
computer with Serial.print()
There are many different variations to suite
your needs:
Controlling the Computer
In Arduino: read sensor, send data as byte
In Processing: read the byte, do something with it
You write one program on Arduino, one on the computer
But writing Processing programs is for later
Receiving program on the computer can be
in any language that knows about serial
ports
C/C++, Perl, PHP, Java, Max/MSP,
Python, Visual Basic, etc.
Pick your favorite one, write some code for
Arduino to control
Controlling the Computer
If interested, I can give details on just about every language above.
Controlling Arduino, Again
SerialReadBlink
Most control issues are
data conversion issues
Type a number 1-9
and LED blinks that
many times
Converts typed ASCII value
into usable number
This sketch is also in the handout
Serial-controlled RGB
SerialRGBLED
Send color commands
to Arduino
e.g. r200, g50, b0
g50
Sketch parses what you
type, changes LEDs
This sketch is in the handout.
Color command is two parts: colorCode and colorValue
colorCode is a character, r, g, or b.
colorValue is a number between 0-255.
Sketch shows rudimentary character string processing in Arduino.
This is still one of the hardest tasks, unfortunately.
Reading Serial Strings
The function
Serial.available()
makes reading strings
easier
Can use it to read all
available serial data from
computer
The readSerialString()
function at right takes a
character string and sticks
available serial data into it
Pay no attention to the pointer symbol (*)
Must be careful about calling readSerialString() too often or youll read partial strings
Piezoelectrics
Big word piezein is greek for squeeze
Some crystals, when squeezed, make a spark
Turns out the process goes the other way too
Spark a quartz crystal, and it exes
Piezo buzzers use this to make sound
(ex something back and forth, it moves air)
Piezo buzzers dont have quartz crystals, but instead a kind of ceramic that also exhibits
piezoelectric properties.
I pronounce it pie-zoh. Or sometimes pee-ay-zoh.
Piezo Buzzers
Two wires, red & black.
Polarity matters: black=ground
Apply an oscillating voltage to
make a noise
The buzzer case supports the
piezo element and has
resonant cavity for sound
Oscillating voltage alternately squeezes and releases the piezo element.
Must apply ucuating voltage, a steady HIGH or LOW wont work.
diagrams from: http://www.maxim-ic.com/appnotes.cfm/appnote_number/988
Whats in a Piezo Buzzer?
You can get at the piezo
element pretty easily.
Be careful not to crack
the white disc that is
the actual piezo
Only take it out of its
case to use it as a
sensor
another $1.99 I wont be getting back from Radio Shack
Of course, you usually destroy the enclosure to get at the element.
And its the enclosure that has the proper support and resonant cavity to make a loud sound
Piezo Buzzer
Arduino
board
pin 7
gnd
+
piezo
buzzer
Piezo leads are very thin. The breadboard holes grab them better than the header sockets, which is
why the jumper leads are used.
Or you can jam a jumper wire in the holes to hold in the piezo leads.
Play a Melody
SoundSerial
Play the piezo beeper
with the Serial Monitor
Type multiple letters
from cdefgabC to
make melodies
This sketch is in the handout,
Notice the problem with this sketch?
Di!erent notes play for di!erent amounts of time.
50 cycles of low C isnt the same amount of time as 50 cycles of high B
Making it Quieter
Easiest way: add a resistor
(brown,
black,
orange)
Arduino
board
pin 7
gnd
+
piezo
buzzer
10k
Arduino
board
pin 7
gnd
+
piezo
buzzer
Like most things in electronics, if you want less of something, add a resistor.
A better value would probably be 1k, but we dont have that on hand.
This may not seem important now, but wait for the next project.
Play a Stored Melody
PlayMelody
Plays a melody stored
in the Arduino
Could be battery-powered, play
melody on button trigger, control
playback speed with photocell, etc.
Melody denition is sort of like the old cell ringtone style
Melody playing logic is a little hard to follow, since it is timing critical.
Make a Theremin
ooo-weee-ooooo
The original spooky
sound machine
Works by measuring your
bodys electric eld
Leon Theremin
No touching needed!
Well use light in lieu of RF
As heard on Star Trek, Beach Boys, horror movies, Mars Attacks!, and bad New Age songs.
Works sorta like those touch switches, but no touching here.
That is, your body becomes a variable capacitor.
Light Theremin
Theremin
Move hand over
photocell to
change pitch
Play with val processing & cycles count
to alter sensitivity, pitch and timbre
Okay so maybe it sounds more like a bad video game than a spooky movie
The glitchy sound is cause because of the time it takes to read the sensor
There are ways around such stu!, but requires more complex programming using timers &
interrupts
The sound can get annoying quick
Other Serial Devices
to Wi-Fi to Ethernet
to graphic LCD
to 8-servo controller
Lantronix Wi-Port and Lantronix Xport http://lantronix.com/
Seetron Serial Graphic display and Mini SSC http://www.seetron.com/slcds.htm http://www.seetron.com/ssc.htm
Serial Examples
to Roomba
Youve already seen this. :)
http://hackingroomba.com/
Going Further
Piezo buzzers
Can hook up multiple buzzers for
polyphonic sound
Can play waves other than just square
waves using PWM techniques
Can also be used as input devices (well
cover that later)
Going Further
Serial communications
Not just for computer-to-Arduino
communications
Many other devices speak serial
Older keyboards & mice speak are serial
(good for sensors!)
Interface boards (graphic LCDs, servo
drivers, RFID readers, Ethernet, Wi-Fi)
Going Further
RGB LEDS
You can pretty easily
replicate the Ambient Orb
($150) functionality
Make a status display for
your computer
Computer-controlled accent
lighting (a wash of color
against the walls)
Ambient Orb doesnt connect to computer though. Uses the pager network.
Ambient Devices: http://www.ambientdevices.com/
Tod E. Kurt
[email protected]
END Class 2
http://todbot.com/blog/bionicarduino/
Feel free to email me if you have any questions.