You are on page 1of 219

Bionic Arduino

Introduction to Microcontrollers with Arduino

Class 1

11 Nov 2007 - machineproject - Tod E. Kurt

Class Info
• Thumbdrive is being passed around, with:
• PDF version of these notes
• Arduino software for Mac OS X & Windows
• Source code (“sketches”) used in class
• Copy files off, then pass thumbdrive around
• Sunday classes: 3 hours
• two ~1.5 hour chunks, w/ 15 min. break in middle
• Tuesday classes: ~2.5 hours
• with some review at the beginning
What’s for Today
• Introduction to Arduino
• Setting up your Arduino Environment
• Your first Arduino sketch
• Basic digital & analog output control
• Basic digital sensor inputs
• Making LEDs glow and blink on command
• How to read buttons & switches
Can electronic senses mimic human ones?

Do electronic “muscles” work as well as biological ones? Or


What can electronic senses detect that humans can’t?

How would you augment yourself with these new abilities?

This class is about exploring the various input & output

components used in robots, cell phones, video games, and
automobiles, using the friendly Arduino board.
Your devices are watching and responding to you, know their limitations
so you can defeat them when the machine uprising comes.

At worst, you’ll be able to fashion a convincing disguise from pasting Arduinos on your body.
Class Kit I Contents

Class Kit 2 comes next week

A little shoebox-sized plastic storage bin makes a good holder for your electronics stuff.

Not shown, RGB LED. oops. It showed up late to the photoshoot.

Class Kit 1 Manifest
Setup and “light & sound”

• Arduino Diecimila USB board • 9V battery and connector

• Solderless breadboard • resistors:

• 6 x 220 ohm (red-red-brown)
• USB cable • 2 x10k (brown-black-orange)
• 1 x1M (brown-black-green)
• piezo buzzer
• photocell
• potentiometer with knob
• phototransistor (small,clear)
• 5 orange LEDs (large, clear)
• 4 colors of hookup wire
• 1 RGB LED (diffuse, com. anode)
• rubber bands
• two push switches

There will be a second update kit next week: “motion & motors”
A Word on Safety
• Electronics can hurt you
• Lead in some of the parts
• Wash up afterwards
• You can hurt electronics
• Static-sensitive: don’t shuffle your feet & touch
• Wires only bend so much
What is Arduino?
The word “Arduino” can mean 3 things

A physical piece A programming A community

of hardware environment & philosophy
Philosophy & Community
• Open Source Physical Computing Platform
• “open source hardware”
• open source: free to inspect & modify
• physical computing. er, what? ubiquitous computing, pervasive computing,
ambient intelligence, calm computing, everyware, spimes, blogjects, smart objects...

• Community-built
• Examples wiki (the “playground”) editable by anyone
• Forums with lots of helpful people
Arduino Hardware
• Similar to Basic Stamp (if you know of it)
• but cheaper, faster, & open

• Uses AVR ATmega168 microcontroller chip

• chip was designed to be used with C language

The designer of the AVR purposefully arranged its registers and instruction set so that C programs
would compile efficiently on it. This is a big deal, compared to previous microcontrollers where C
programs were almost always less efficient than a hand-coded assembly language variant.
Arduino Hardware Variety
(for clothing)

Boarduino Kit


many different variations to suite your needs
Openness has its advantages, many different varieties.
Anyone can build an Arduino work-alike in any form-factor they want.
Product images from and
Arduino Capabilities
• 16 kBytes of Flash program memory

• 1 kByte of RAM

• 16 MHz (Apple II: 1 MHz)

• Inputs and Outputs

• 13 digital input/output pins

• 5 analog input pins

• 6 analog output pins*

• Completely stand-alone: doesn’t need a

computer once programmed
* only sorta analog, uses PWM , which we’ll talk about later.

Don’t worry if the above doesn’t make sense, you don’t really need to know it.
Arduino Diecimila Board
test LED digital input/output “pins”
on “pin” 13
USB interface

LEDs ATmega168 reset

2.7” analog input “pins”

Arduino Terminology
“sketch” – a program you write to run on an
Arduino board
“pin” – an input or output connected to something.
e.g. output to an LED, input from a knob.
“digital” – value is either HIGH or LOW.
(aka on/off, one/zero) e.g. switch state
“analog” – value ranges, usually from 0-255.
e.g. LED brightness, motor speed, etc.
Arduino Software
• Like a text editor

• View/write/edit sketches

• But then you program

them into hardware

If you’ve used Processing to write little Java programs, you’ll notice the interface looks familiar.
Arduino takes the editor GUI from Processing and some of its philosophy, but Arduino code and
Processing code are totally unrelated.
Installing Arduino
The Steps
1. Get the Arduino software & unzip it
2. Plug in Arduino board
3. Install the driver
4. Reboot
5. Run the Arduino program
6. Tell Arduino (program) about Arduino (board)
Getting and Unpacking
• On the thumbdrives
• “” for Windows
• “” for Mac OS X
• Unzip the zip file. Double-click on Mac
On Windows, right-click
Use “Extract All...”

• Find the “drivers” directory inside

Plug in Arduino board
quick blink
from test LED

Power LED should stay on

Mac Driver Install
Double-click on .dmg Installer

• v2_1_6 for PPC Macs

• v2_2_6 for Intel Macs
Windows Driver Install
Selecting Location & Type

usually highest-
numbered port

pick “Diecimila”
Selecting Location & Type

starts with

pick “Diecimila”
Arduino Software

compile upload to board


Using Arduino
• Write your sketch

• Press Compile button

(to check for errors) compile

• Press Upload button to program

Arduino board with your sketch

Try it out with the “Blink” sketch!

TX/RX flash
Load “File/Sketchbook/Examples/Digital/Blink” l in k
b k
l i n
b sketch runs
Change the “delay()” values to change blink rate
Status Messages
Size depends on
complexity of your sketch

Uploading worked

Wrong serial port selected

Wrong board selected

nerdy cryptic error messages

• Most common problem is incorrect serial
port setting
• If you ever have any “weird” errors from the
Arduino environment, just try again.
• The red text at the bottom is debugging
output in case there may be a problem
• Status area shows summary of what’s wrong
I made an LED blink,
so what?
• Most actuators are switched on and off with
a digital output
• The digitalWrite() command is the
software portion of being able to control
just about anything
• LEDs are easy, motors come in a bit
• Arduino has up to 13 digital outputs, and
you easily can add more with helper chips
Development Cycle
• Make as many changes as you want
• Not like most web programming: edit ➝ run
• Edit ➝ compile ➝ upload ➝ run
edit compile upload run done!
Lots of Built-in Examples

And more here:

And all over the Net. Search for “Arduino tutorial” or “Arduino notes” or whatever you’re interested
in and “Arduino” and likely you’ll find some neat pages.
Take a Break

Grab a coffee upstairs at Downbeat Cafe.

Arduino “Language”
• Language is standard C (but made easy)

• Lots of useful functions

• pinMode() – set a pin as input or output
• digitalWrite() – set a digital pin high/low
• digitalRead() – read a digital pin’s state
• analogRead() – read an analog pin
• analogWrite() – write an “analog” value
• delay() – wait an amount of time
• millis() – get the current time
• And many others. And libraries add more.
Also: serial library, LCD library, servo examples
Sketch structure

• Declare variables at top

• Initialize
• setup() – run once at beginning, set pins
• Running
• loop() – run repeatedly, after setup()

Pins can be changed in loop() too, but conceptually easier in setup()

Making Circuits

heart pumps, blood flows voltage pushes, current flows

It’s all about the flow of current. Kinda like the flow of liquid.
Some electronics devices hold back current, like a tiny hose. These are “resistors”.
Example: LED flashlight
current flow

9V resistor
– 500 ohm
(green,brown,brown) 500


(flat part)

wiring diagram schematic wiring it up

Electricity flows in a loop. Can stop flow by breaking the loop

All LED circuits are essentially this: power source, current limiter, LED
Flat part of LED goes to negative, like bar in schematic
The higher the resistance, the dimmer the LED; the lower, the brighter
You don’t have to wire this up, but the following circuits are just the same
The Circuit for LED Blink
“hello world” of microcontrollers


flat part

pin 13

resistor gnd
220 ohm

wiring diagram schematic

Arduino Diecimila board has this circuit built-in

To turn on LED use digitalWrite(13,HIGH)
This is a “computer-controlled LED flashlight”.
In schematics signals often flow from top-left to bottom-right.
Common nodes like “gnd” are given their own symbol.
You could wire this circuit up on any digital pin, doesn’t matter which.
Same circuit as last page, but “battery” is pin 13 of Arduino, and you can turn it on and off.

Schematics are pretty easy to learn, not many people use wiring diagrams.
LEDs & Resistors

On LEDs, polarity matters.

Shorter lead is “negative” side, goes to ground

Flat edge here for neg. side

Polarity doesn’t matter on resistors
Varying LED Brightness
Same circuit as Blink circuit but pin 9 instead of pin 13

flat part
pin 9

gnd resistor
220 ohm

schematic wiring diagram wired up

The PWM pins work with the “analogWrite(value)” command

where “value” ranges between 0 and 255.
To turn LED to half-bright, use analogWrite(9,128)
More about PWM later, but it only works on those pins labeled “PWM”.

Very quickly, it works by making and breaking the flow several hundred times a second. So really
it’s flashing, just like blink, but doing it very fast. Our eyes make it look like brighter or dimmer.
We’ll have to build this circuit.
Let’s Wire It Up

pin 9


Going from schematic to physical circuit.

Solderless Breadboards
numbers &
letter labels
just for groups of 5
reference connected

All connected,
a “bus”

Insert wires into holes to make a connection.

*Much* easier, quicker than soldering
But, they wear out, are kind of expensive ($5 for this one, at that was a bargain)
Useful Tools
Wire stripper Wire cutters


Even with solderless breadboards you’ll need to cut and strip wire. Each of these costs around $5
each. If you have to get just one, get the wire stripper.
Making Jumper Wires
pliers & cutter wire stripper


About 1/4” for the stripped parts.

And as long as you need for your circuit.
Using Solderless
Using needle nose pliers can help
push wires & components into holes

Grab wire or lead toward end and push into hole

All Wired Up
plugged into “ground” bus
Alternate Way
Or, adding a breadboard to Arduino for 1¢

2. power & gnd wires

3. plug into “bus” terminals

4. jumper over
to other side

now circuit has power & ground 1. rubber band

This makes it a bit easier to deal with wiring up circuits for two reasons.
First, it secures the breadboard and Arduino together, so wires are less likely to come loose.
Secondly, it gives you lots of power and ground holes, which you usually need a lot of.

Use this setup for the rest of your circuits.

Rubber band trick around Arduino & solderless breadboard shameless stolen from Kimiko Ryokai’s
Tangible User Interface class (INFO290-13):
LED “Fading” Sketch
Load “File/Sketchbook/Examples/Analog/Fading”


Press “Upload”. After a second, LED will “throb” on and off

Reduce “delay()” values to make it go faster

Try other PWM pins (remember: you have to rewire)

Things to Try With “Fading”

• Make it go really fast or really slow

• Fading from half- to full-bright
• Try other PWM pins
• Multiple fading LEDs, at different rates
Sensors & Inputs
Many sensors are variations on switches
Switches make or break a connection

knife switch toggle switch


Fundamentally, they’re all like the simple knife switch

Single pole = only one circuit is being controlled
Double pole = two circuits are being controlled at once
Single throw = only one path for circuit
Double throw = two potential paths for circuit
Many Kinds of Switches

magnetic hexidecimal tilt lever

Tilt sensor has a little ball inside you can hear.
Used to have mercury switches, with real metallic mercury inside. Not so much now tho’.
Magnetic reed switches are cool, but delicate.
The hex switch is actually many switches in one, and outputs 4 signals
Homemade Switches
“Trick Penny”
Penny on a surface.
When the penny is lifted, alarms go off
Homemade Switches
“Trick Penny”

Surface is conductive metal sheet.

Wire soldered to penny.
Wire looped or crimped to metal sheet.
Homemade Switches
“Smart Wind Chimes”
When the wind blows hard enough,
you’re sent email

Should use stranded wire, not solid.

Code analyzes series of on/off/on/off pulses to determine wind.
Digital Input
• Switches make or break a connection
• But Arduino wants to see a voltage
• Specifically, a “HIGH” (5 volts)
• or a “LOW” (0 volts)


How do you go from make/break to HIGH/LOW?

From Switch to HIGH / LOW
• With no connection,
digital inputs “float”
between 0 & 5 volts
• Resistor “pulls” input to
ground (0 volts)
• Pressing switch “pushes”
input to 5 volts
• Press is HIGH
Not pressed is LOW

Don’t want “pull-down” to be too small, or it uses a lot of current

Wiring it up

Let’s plug it into pin 2

You can leave the last project on the board if you want.
Using digitalRead()
• In setup(): pinMode(myPin,INPUT)
makes a pin an input
• In loop(): digitalRead(myPin) gets
switch’s position
• If doing many tests, use a variable to hold the output value of

• e.g. val = digitalRead(myPin)

Enough with the atoms, back to the bits

Digital Input Sketch
Load “Sketchbook/Examples/Digital/Button”

Now you control the blinking

(How would you change it to blink the external LED you wired up?)
Press to turn off, release to turn on.
Notice it blinks the LED on-board the Arduino.
Change the code to make it blink the pin 9 LED.
Using Switches to
Make Decisions
• Often you’ll want to choose between actions,
based on how a switch-like sensor
• E.g. “If person is detected, fire super soaker”
• E.g. “If flower pot soil is dry, turn on sprinklers”

• Define actions, choose them from sensor inputs

• Let’s try that with the actions we currently
Load “FadeOrBlink” sketch from the handout

Schematic is same as for

“Fading” sketch

Combines “Blink” & “Fading”

sketches into one, selected by
the button
Battery Power
Arduino can work totally stand-alone. It’s easy
• First, program
sketch into Arduino plug
• Unplug USB cable Vin &
• Change jumper
from USB to EXT

• Plug in power
set to
• Power LED lights EXT
up. It works!

• Reverse steps to
Battery Power
Center of set to
jack is EXT
• Plugging into the positive
sockets is kind of

• Better to plug into

the power jack

• Works great, but

requires a little
Going Further

• Make your own switches: aluminum foil, pennies,

• Build a Knight Rider / Cylon scanning light
• Build a bike light that only works when you peddle
• Make an Annoy-a-Tron™ (blink-blink-blink, wait.... blink-blink-blink)

Lots of things you can do with just LEDs & switches

END Class 1

Tod E. Kurt

Feel free to email me if you have any questions.

Official homepage. Also check out the Playground & forums
Great Arduino tutorials
Various movies, hacks, tutorials on Arduino
Index of Arduino knowledge
Arduino starter kits, Boarduino Arduino clone, lots of cool kits
Sells Arduino boards and lots of neat sensors & stuff

“Physical Computing”, Dan O’Sullivan & Tom Igoe
“Making Things Talk”, Tom Igoe
“Hacking Roomba”, Tod E. Kurt
obligiatory book plug
Bionic Arduino
Introduction to Microcontrollers with Arduino

Class 2

13 Nov 2007 - machineproject - Tod E. Kurt

What’s for Today
• Random Behavior
• Color mixing
• Analog input with variable resistors
• Potentiometers & photocells
• Basic serial input & output
• Playing sound with piezo buzzers
This is a lot of stuff, let’s see how far we get.
Recap: Blinky LED
Make sure things still work



Load “File/Sketchbook/Examples/Digital/Blink” TX/RX flash

l in k
b k
l i n
b sketch runs
Change the “delay()” values to change blink rate
Known Good
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 shouldn’t need to, do it anyway.
Especially when mysterious problems arise, revert to a known state
Getting the Board Set Up
pin 9

schematic gnd

wire up pin 9 LED too

Questions / Review

Any questions, comments, or problems?

Aside: LED Light Tubes

Snug-fit straws on
the end of your
LEDs to make
them glow more

I have a box of multi-colored straws for whatever color LED you like
Random Behavior

Uses simple
pseudo random
number generator
to mimic flame

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:

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.


The pot you have

pots also look like this

Moving the knob is like moving
where the arrow taps the voltage on the resistor

When a resistor goes across a voltage difference, like +5V to Gnd, the voltage measured at any point
along a resistor’s length is proportional to the distance from one side.

If you take apart a pot, there’s 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

• (we’re 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
Plug pot directly into breadboard

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

Why are we using Analog In 2? Because it’s in the middle. There’s no reason, any of the 6 analog
inputs would work the same.
Pot & LED Circuit
This is what your board should have on it now


+5V board
220 (red-red-brown)
50k pin 2 pin 9
gnd LED



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
Varying Brightness by Hand

Turn the knob to

change LED
brightness input
process the
input data

Most all embedded

systems have a
Sketch available in handout
Two Ways to
Hook up LEDs

Arduino Arduino LED

board board

resistor resistor
pin 9 pin 9
gnd gnd


To turn ON: digitalWrite(9,HIGH) To turn ON: digitalWrite(9,LOW)

To turn OFF: digitalWrite(9,LOW) To turn OFF: digitalWrite(9,HIGH)

To set brightness: analogWrite(9,val) To set brightness: analogWrite(9,255-val)

We’ve been using the one on the left because it makes more sense.
But you’ll 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.
Normal LED
anode +
anode +
cathode –
cathode –

anode +
red cathode –
anode +
blue cathode –
green cathode –
red blue 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 we’re changing around the logic.
Color Mixing
With just 3 LEDs you can make any* color
common anode

pin 11
pin 10
pin 9
220 (red,red,brown)

green blue red With RGB you can
make any color
(except black)

Mixing light is the additive color model

(paint is subtractive color, and can give you brown)
*besides the additive/substractive color different, it’s hard to get the mix to be just right for a
variety of annoying reasons:
- the physics of LEDs mean that different color LEDs put out different amounts of light
- our eyes respond non-linearly across the spectrum, i.e. we’re more sensitive to green than red
- the lenses in most RGB LEDs don’t focus each color to the same spot
Laying out RGB LED Circuit
common anode

pin 11
pin 10
pin 9
220 (red,red,brown)

green blue red

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

Ignore the green wire in the pictures, that’s another circuit.

Keep the pot from last circuit if you can.
RGB Color Fading

Slow color fading

and mixing

Also outputs the current

color values to the serial port

This sketch is located in the handout.

We’ll get to the serial port stuff in a minute.

It just ramps up and down the red,green,& blue color values and writes them with analogWrite()
Pot-controlled RGB

common anode

+5V board
pin 11
pin 10
50k pin 2 pin 9
pot 220 (red,red,brown)

green blue red
Pot-controlled RGB

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:
• 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



Try it with RGBPotMixer from before

Looks a lot like the pot circuit, doesn’t it?

Mood Light

Diffuser made from

piece of plastic
scratched with

Also, can use plastic wrap scrunched up to make an interesting diffuser.

Resistive sensors
circuit is the same
for all these

thermistor to analog
(temperature) resistor


flex sensor
(bend, deflection)

force sensors also air pressure

(pressure) and others
Thermistor image from:
Also see:
with Others
• Arduino can use same USB cable for
programming and to talk with computers
• Talking to other devices uses the “Serial”
• Serial.begin() – prepare to use serial

• Serial.print() – send data to computer

• – 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”

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 it’s pretty short.
Use on-board pin 13 LED, no need to wire anything up.
Telling Arduino What To Do

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 != -1 to determine if there’s 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 it’s actually receiving something.
Arduino Communications
is just serial communications

• Psst, Arduino doesn’t 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

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

• 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
Arduino board is really two circuits

USB to serial


Original Arduino boards were RS-232 serial, not USB.

Arduino Mini
Arduino Mini separates the two circuits

Arduino Mini USB adapter Arduino Mini

aka. “Arduino Stamp”
If you don’t talk with a computer, the USB-to-serial functionality is superfluous.
Arduino to Computer
Laptop Arduino board
Arduino USB to serial
USB to serial
programmer driver chip Arduino



Java program


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 they’re talking via a serial port.
Arduino & USB

• Since Arduino is all about serial

• And not USB,
• Interfacing to things like USB flash drives,
USB hard disks, USB webcams, etc. is not

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:
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
You write one program on Arduino, one on the computer

In Arduino: read sensor, send data as byte

In Processing: read the byte, do something with it

But writing Processing programs is for later

Controlling the Computer
• Receiving program on the computer can be
in any language that knows about serial
• C/C++, Perl, PHP, Java, Max/MSP,
Python, Visual Basic, etc.
• Pick your favorite one, write some code for
Arduino to control

If interested, I can give details on just about every language above.

Controlling Arduino, Again

Type a number 1-9

and LED blinks that
many times

Converts typed ASCII value

into usable number

Most control issues are

data conversion issues

This sketch is also in the handout

Serial-controlled RGB

Send color commands

to Arduino
e.g. “r200”, “g50”, “b0”

Sketch parses what you

type, changes LEDs g50

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
makes reading strings

• Can use it to read all

available serial data from

• 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 you’ll read partial strings

• 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 flexes
• Piezo buzzers use this to make sound
(flex something back and forth, it moves air)

Piezo buzzers don’t 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 flucuating voltage, a steady HIGH or LOW won’t work.

diagrams from:

What’s 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

another $1.99 I won’t be getting back from Radio Shack

Of course, you usually destroy the enclosure to get at the element.
And it’s the enclosure that has the proper support and resonant cavity to make a loud sound
Piezo Buzzer

pin 7


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

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?
Different notes play for different amounts of time.
50 cycles of low C isn’t the same amount of time as 50 cycles of high B
Making it Quieter
Easiest way: add a resistor

Arduino Arduino
board board
+ +
pin 7 pin 7 piezo
(brown, buzzer
– –
gnd gnd

Like most things in electronics, if you want less of something, add a resistor.
A better value would probably be 1k, but we don’t have that on hand.
This may not seem important now, but wait for the next project.
Play a Stored Melody

Plays a melody stored

in the Arduino

Could be battery-powered, play

melody on button trigger, control
playback speed with photocell, etc.

Melody definition 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

The original spooky

sound machine

Works by measuring your

body’s electric field

No touching needed!
We’ll use light in lieu of RF Leon Theremin
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

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 stuff, but requires more complex programming using timers &
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

Seetron Serial Graphic display and Mini SSC
Serial Examples

to Roomba

You’ve already seen this. :)
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 (we’ll
cover that later)
Going Further
• Serial communications
• Not just for computer-to-Arduino
• 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
• 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 doesn’t connect to computer though. Uses the pager network.
Ambient Devices:
END Class 2

Tod E. Kurt

Feel free to email me if you have any questions.

Bionic Arduino
Introduction to Microcontrollers with Arduino

Class 3

18 Nov 2007 - machineproject - Tod E. Kurt

What’s for Today
• About DC motors
• Transistors as switches
• Controlling DC motors
• Introduction to Processing
• Controlling your computer with Arduino
• Piezo buzzers as sensors

In the handout thumbdrives, be sure to copy the Processing zip or dmg file for your OS.
Recap: Blinky LED
Make sure things still work



Load “File/Sketchbook/Examples/Digital/Blink” TX/RX flash

l in k
b k
l i n
b sketch runs
Change the “delay()” values to change blink rate
Class Kit 2 Contents
“motors & motion”
Class Kit 2 Manifest
“motors & motion”

• Nintendo Wii Nunchuck • Several 500 ohm resistors

• Wii Nunchuck Adapter
• Couple of popsicle sticks
• Large DC motor
• Colorful pipe cleaners
• Small DC motor

• Small servo motor

• TIP120 power transistor

• 1N4001 power diode

DC Motors
the two motors
come in all in the kit

shapes and sizes

You probably have

3-4 on you right now
(cell vibrate, laptop fan, laptop dvd drive)

When motors first came out, people thought we’d just have one for the house. The household
motor. Various attachments for vacuuming, meat grinding, ceiling fan were available, and some
houses had intricate mazes of belts and gears routed through the house to supply this rotational
DC Motors
A dizzying array of parameters specify a motor

• direct-drive vs. gearhead – built-in gears or not

• voltage – what voltage it best operates at

• current (efficiency) – how much current it needs to spin

• speed – how fast it spins

• torque – how strong it spins

• oh, and also: size, shaft diameter, shaft length,etc.

The two motors you have are small direct-drive,
high-efficiency motors that work at 5 volts
Gearhead motors are the best.
DC Motors
• When the first start up, they draw a lot more
current, up to 10x more.
• If you “stall” them (make it so they can’t
turn), they also draw a lot of current
• They can operate in either direction, by
switching voltage polarity
• Usually spin very fast: >1000 RPM
• To get slower spinning, need gearing
DC Motors
To drive them, apply a voltage
The higher the voltage, the faster the spinning

M DC motor

polarity determines which way it rotates

Try this out real quick.

Then swap polarity
Don’t let it go to long. These motors will work at 9V for awhile, but aren’t made to continuously run
at that voltage.
DC Motors as Generators
Just as voltage causes rotation...

DC motor

...rotation causes voltage

Try it out, but you have to spin really

This is used for “regenerative fast to get it to light (if LED doesn’t
light, try spinning the other direction)
braking” in electric & hybrid cars

These high-efficiency motors I gave you don’t generate much current (because they don’t use much
current). I have a cheapy motor that lights LEDs better that I can show you.
Act like switches
electricity flicks the switch instead of your finger

120 collector collector

emitter emitter
collector emitter schematic symbol how it kind of works

Turning on the “base” connects the “collector” & “emitter” together

The differences between the pins are very important. The names aren’t that important, but their
functions are. The “base” is the input that you use to open and close the “switch” across the
“collector” and “emitter”. On this type of transistor (called an NPN), you need to make sure the
collector is always more positive than the emitter. Generally you do this by connecting the emitter
to ground.
Switching Motors with
little motor big motor
DC motor +
DC motor
resistor resistor big power
transistor transistor source
+ switch + switch +


switching a different power source

transistors switch big signals with little signals

Need a “Kickback” Diode
DC motor
M diode

line switch


schematic symbol

since motors can act like generators,

need to prevent them from generating “kickback” into the circuit
Once a motor starts spinning, its inertia keeps it spinning, this turns it into a generator and thus
can generate a “kickback” voltage. The kickback diode routes that voltage harmlessly back into the
motor so it can’t damage the rest of the circuit.

Kickback is also called “back EMF” (EMF == electromotive force == voltage)

Controlling a Motor
+5V motor
DC motor
Arduino M
pin 9 b
500 e

start with the tiny motor


Can control speed of motor with analogWrite()

just like controlling brightness of LED
Why 500 ohms? Because I have a lot of 500 ohm resistors. Typically you see 1k ohms. Anything 1k
or below will work. The lower the value, the more current you’re “wasting” to turn on the transistor.
Wiring up Motor Circuit
around to
make wiring

e c b

DC motor
Arduino M

b c
pin 9 TIP120
500 e
gnd white diode line into +5V
motor across diode

Type a number 0-9

in Serial Monitor to
control the speed of
the motor

How would you change this

to control the motor speed
with the potentiometer?
Controlling a Bigger Motor
Same circuit as before, different voltage source

+5V battery


DC motor
Arduino M

pin 9 TIP120

motor w/ tape
desk ding from
motor getting loose

Motor will spin faster for a given analogWrite() value

Actually with both of the motors you have, you can run off the Arduino power supply. But many
motors cannot because they either draw too much current or they need a voltage higher than 5
Fun Motor Attachments

pipe cleaner squiggler tape propeller

popsicle stick beater
I’m terrible at mechanical engineering. If anyone has good ways of mounting things to motors, let
me know. :-)
Wiring Up Bigger Motor

Don’t just add 9V to +5v bus!

Move the diode from +5 to another row
Add red 9V wire to that row,
Add black 9V wire to Gnd
You might find it easier to push the red 9V wire in with the motor wire.
Can Switch Anything*

Arduino red LEDs

pin 9 TIP120
gnd Super bright LED light
Full brightness control with PWM


1N4004 5V relay
pin 7 toload
to load: light bulb, car ignition, washing machine, etc.
Relay switcher
Just on/off, and a relay needs a diode too

*Anything up to about 1 amp. Need a bigger transistor or a relay after that

Piezo Buzzer as Sensor
• Piezo buzzers exhibit the reverse piezoelectric
• The normal piezoelectric effect is generating
electricity from squeezing a crystal.
• Can get several thousand volts, makes a spark
• You probably have seen a big example of this
fireplace lighter

I have a demo piezo igniter from one of these lighters. It’s fun to shock yourself.
Puts out several thousand volts. (ionization voltage of air =~ 30kV/cm)
Piezo Knock Sensor
• To read a piezo you can
just hook it into an
analog input, but:

You need to drain off piezo

any voltage with a +

analog pin 2

resistor, or it just builds –


up (brown,

• The protection diodes

inside the AVR chip
protect against the high piezo input schematic

Note polarity of piezo still matters.

If you’re doing this for real, you’d probably want to add an external protection diode, called a “zener
diode”. It acts invisible until the voltage gets over its designed value (like 5 volts in this case), then
it acts like a short circuit.
Wiring up Piezo Sensor
piezo board

analog pin 2
– gnd

Could also plug it directly into the Arduino, might be easier because of those thin little wires on the
Piezo Knock

Whack the piezo to

print out a number
based on force of

Waits for input to go over threshold,

then to drop below threshold

Number is “t”, the number of times it looped waiting for the value to drop below THRESHOLD.
Notice how it doesn’t work quite right.
How Does that Work?
• When a piezo is struck, it “rings” like a bell
• But instead of sound, it outputs voltage
• The sketch measures time above a certain
voltage, hoping to catch largest ring

piezo output voltage



Depending on how fast you can watch the input, this technique works either really well or not that
well. There are much faster ways of watching inputs that loops with analogRead()
But for now it works okay
Custom Piezo Sensors
Can mount the element on anything
(under rugs, floor mat, door, your body, etc.)

Here’s one glued to a larger brass disc for a drum trigger

You can get bare piezo buzzers (not in a black plastic enclosure) that you can mount on whatever
you want.
Could make a MIDI Trigger
Uses piezos & buttons
to send MIDI messages

Can trigger drum sounds

or arbitrary sound samples


I used this during Halloween a few years ago to trigger scary sounds.
Or Trigger Actuators

Arduino DC motor
piezo board M

analog pin 2 pin 9 TIP120
– 500
gnd (green,
(brown, brown)

If you still have your

motor wired up
Take a Break
Getting the Board Set Up

+5V board

50k pin 2


Wire up the potentiometer like

from last week

And if you wire up an LED to pin 9, you can try out the “PotDimmer” sketch again to make sure
things are wired up right.
• Processing makes Java programming
as fun & easy as Arduino makes AVR

• Started as a tool to make generative


• Is also often used to interface to

devices like Arduino

• Think of it as a free Max/MSP

And it’s totally open source like Arduino.

Processing GUI and Arduino GUI are from the same code, which is why it looks & acts similar.
Using Processing

• First, “install”
• Load up
“Examples » Topics
» Motion »

• Press “Run” button

• You just made a

Java applet

The Processing application folders are in the handout, no installation is needed.

Also try Examples » Topics » Motion » Collision. It’s a lot of fun.
Notice how “Run” launches a new window containing the sketch.
The black area at the bottom is a status window, just like in Arduino.
About Processing

• Processing sketches have very similar structure

to Arduino sketches
• setup() – set up sketch, like size, framerate
• draw() – like loop(), called repeatedly
• Other functions can exist when using libraries
Processing & Arduino
serial communications

• Processing and Arduino both talk to “serial”

devices like the Arduino board
• Only one program per serial port
• So turn off Arduino’s Serial Monitor when connecting
via Processing and vice-versa.

• Processing has a “Serial” library to talk to

Arduino. E.g.:
port = new Serial(..,“my_port_name”,19200), port.write(), port.available(), etc.
serialEvent() { }

The built-in serial library adds a new function you can use to your sketch: serialEvent()
The serialEvent() function will get called whenever serial data is available.
Or you can poll with port.available().
Processing Serial
common Processing serial use

four steps be sure to set

1. load library to the same as
2. set portname 2. “Serial Port” in
3. open port Arduino GUI
4. read/write port


All you need to do talk to Arduino in Processing.

The import statement says you want to do serial stuff.
The “new Serial” creates a serial port object within Processing
Then you can that object (or used the passed in one) to read from in the “serialEvent()” function
Arduino Talking to Processing

Read knob,
send it’s value

Note: doesn’t send the value as

ASCII text, but as a binary byte
(BYTEs are easier to parse in Processing
than other formats)

You can have 6 knobs total

because there are 6 Analog In pins
Meanwhile, back in Arduino, load up this sketch we’ll use with Processing
Processing + Arduino

The pot controls

the hue of the
onscreen circle

Arduino is running “PotSend”,

repeatedly sending a number from
0-255 indicating knob position

This sketch is in the handout, under “processing_sketches”.

Another One

Every time a byte is

received via the serial
port, it alters the size
of the ball to match.

Comment out the “background(102)”

line to get trails
Uncomment the “fill()” line to get
color trails

Notice the bug that happens when you change the size near a border.
And Another One

The basics of a pong game.

The pot controls paddle

Add another pot and a

little more game logic and
you have a 2-player game
These are all very minorly-modified examples of standard Processing sketches.
Triggering Sounds

Every time the

piezo is knocked...
a sound plays and
a red disc appears

This sketch needs the

“minim” sound library.

You can add your own sounds (WAV or MP3)

Hook a piezo up to your front door, and plug your computer into your stereo.
Every time someone knocks on your door, a sound is played: a custom doorbell!

The zipfile for the “minim” library is in the handout, called “”.
Unzip it and place the “minim” folder in the “Processing 0133/libraries” folder.
Adding Processing Libraries
Unzip, drop into “libraries” folder
unzip open


Same for Windows and Mac OS X. Mac OS X shown.

Processing to Arduino
real quick

Fetch a web page,

get a color value from
it, send the color to
Arduino with RGB LED

This is not to build, just quickly cover. It’s not in the handout, but,
full details at:
Going Further

• DC motors
• Get some gearhead motors for serious
torque or slower RPM
• Use Lego, Erector, Meccano to build
mechanical linkages for motors
• Oh and you can now build a robot
Going Further
• Transistor switches
• Anytime you need to switch a signal more
powerful than what Arduino can use
• These transistors switch up to 1 amp of DC
voltage. For AC household currents, use
transistor to switch a relay
• Can control just about anything in your house
Going Further
• Processing & Serial communications
• Processing can talk to the Net. It’s an
Internet-to-Arduino gateway
• It can also talk to many computer
peripherals, like video cameras
• Maybe: Arduino controls the motors,
laptop controls the cameras of your robot
END Class 3

Tod E. Kurt

Feel free to email me if you have any questions.

Bionic Arduino
Introduction to Microcontrollers with Arduino

Class 4

20 Nov 2007 - machineproject - Tod E. Kurt

What’s for Today
• About PWM
• Controlling Servos
• About the I2C bus
• Using I2C on Arduino
• About Accelerometers
• Nintendo Wii Nunchuck as Input Device
Recap: Blinky LED
Make sure things still work



Load “File/Sketchbook/Examples/Digital/Blink” TX/RX flash

l in k
b k
l i n
b sketch runs
Change the “delay()” values to change blink rate
Pulse Width Modulation
• More commonly called “PWM”
• Computers can’t output analog voltages
• Only digital voltages (0 volts or 5 volts)
• But you can fake it
• if you average a digital signal flipping
between two voltages.
• For example...
Output voltage is averaged from on vs. off time
output_voltage = (on_time / off_time) * max_voltage

5 volts
3.75 Volts
0 volts
75% 25% 75% 25% 75% 25%

5 volts
2.5 Volts
0 volts
50% 50% 50% 50% 50% 50%

5 volts

0 volts 1.0 Volts

20% 80% 20% 80% 20% 80%
• Used everywhere
• Lamp dimmers, motor
speed control, power
supplies, noise making

• Three characteristics of
PWM signals
• Pulse width range (min/max)
• Pulse period
(= 1/pulses per second)

• Voltage levels
(0-5V, for instance)

You experienced a few applications of PWM already.

• Can be positioned
from 0-180º (usually)
• Internal feedback
circuitry & gearing
takes care of the
hard stuff
• Easy three-wire
PWM 5V interface

More specifically, these are R/C hobby servos used by remote control enthusiasts
In general, “servomotor” is a motor with an inherent feedback mechanism that allows you to send
position commands to it without requiring you to do the position reading.
Servos are Awesome
• DC motor
• High-torque gearing
• Potentiometer to
read position
• Feedback circuitry to
read pot and control
• All built in, you just
feed it a PWM signal

With these little blue ones you have, you can see inside a bit at the internals of the servo.
Servos, good for what?

• Roboticists, movie effects people, and

puppeteers use them extensively
• Any time you need controlled, repeatable
• Can turn rotation into linear movement
with clever mechanical levers

Even clothes use servos now:

• Come in all sizes
• from super-tiny 9g
• to drive-your-car
• But all have the same
3-wire interface
• Servos are spec’d by:
weight: 9g 157g
speed: .12s/60deg @ 6V
torque: 22oz/1.5kg @ 6V
voltage: 4.6~6V
size: 21x11x28 mm
Servo Mounts & Linkages

Lots of ways to mount a servo

And turn its rotational motion

into other types of motion

mounting bracket:

Servo Control
Ground (0V)
180º Power (+5V)
Control (PWM)

• PWM freq is 50 Hz (i.e. every 20 millisecs)

• Pulse width ranges from 1 to 2 millisecs
• 1 millisec = full anti-clockwise position
• 2 millisec = full clockwise position
Servo Movement
0 degrees 90 degrees 180 degrees

1000 microsecs 1500 microsecs 2000 microsecs

In practice, pulse range can range from 500 to 2500 microsecs

(and go ahead and add a wire marker to your servo like the above)
Put the red “arm” on your servo. Needs a philips screwdriver.
Many commercial servo drivers have a calibration setting to deal with servo variability
Servo and Arduino
First, add some jumper wires to the servo connector


PWM control

I recommend matching the color coding of the wires as closely as possible

Servo and Arduino

Plug power
wires in

Plug control wire

to digital pin 7
Moving a Servo

Move the servo across

its range of motion

Uses delayMicroseconds() for pulse width

Uses delay() for pulse frequency

Sketch is in the handout

Created a custom function to handle making servo pulses
New function “delayMicroseconds()”. Like “delay()”, but µsec instead of millisec.
(and actually, just delaying 20 millisec is kinda wrong. should be: 20 - (pulsewidth/1000)
(1000 microseconds = 1 millisecond, and 1000 milliseconds = 1 second)
Serial-controlled Servo

Drive the servo

by pressing
number keys

Takes the last servo

example and adds our
standard serial input to it.

Sketch is in the handout.

Why that for loop? Because it takes time for the servo to get to a position and it has no memory.
Aside: Controlling Arduino
• Any program on the computer, not just the
Arduino software, can control the Arduino
• On Unixes like Mac OS X & Linux, even the
command-line can do it:
demo% export PORT=/dev/tty.usbserial-A3000Xv0
demo% stty -f $PORT 9600 raw -parenb -parodd cs8 -hupcl -cstopb clocal
demo% printf "1" > $PORT # rotate servo left
demo% printf "5" > $PORT # go to middle
demo% printf "9" > $PORT # rotate servo right

Unix is rad.
Robo Cat Toy Idea

Tape on a pipe cleaner, and using random

behavior similar to the “Candlelight”
sketch, make a randomly moving cat toy
Be sure to securely mount the servo before doing trial runs. Cats are good at taking apart prototype
Servo Timing Problems
• Two problems with the last sketch
• When servoPulse() function runs,
nothing else can happen
• Servo isn’t given periodic pulses to keep it
at position
• You need to run two different “tasks”:
• one to read the serial port
• one to drive the servo
If a servo is not being constantly told what to do, it goes slack and doesn’t lift/push/pull
Better Serial Servo
Works just like
(but better)

Update the servo when

needed, not just when
called at the right time

Uses “millis()” to
know what time it is

Sketch is in the handout.

Trades memory use (the extra variables), for more useful logic.
Can call updateServo() as often as you want, servo is only moved when needed.
Multiple Servos

• The updateServo() technique can be

extended to many servos
• Only limit really is number of digital output
pins you have
• It starts getting tricky after about 8 servos
Multiple “Tasks”
The concept inside updateServo() is
useful anytime you need to do multiple “things
at once” in an Arduino sketch:

• Define your task

• Break it up into multiple time-based chunks (“task slices”)

• Put those task slices in a function

• Use millis() to determine when a slice should run

• Call the functions from loop()

Inside your task slices, avoid using delay(), for loops, and other code structures that would cause
the code to stay inside a task for too long
This is called “cooperative multitasking”, and it’s how OSs in the 80s worked.
Arduino PWM
why all the software, doesn’t Arduino have PWM?

• Arduino has built-in PWM

• On pins 9,10,11
• Use analogWrite(pin,value)
• It operates at a high, fixed frequency
(thus not usable for servos)
• But great for LEDs and motors
• Uses built-in PWM circuits of the
ATmega8 chip -» no software needed
The PWM speed used for analogWrite() is set to 450Hz or 30 kHz currently. I forget which, but it’s
not something changeable without understanding more about how AVRs work.
So when programming AVRs in C outside of Arduino, PWM speed can be set to just about any value.
Take a Break
Serial Communication
Asynchronous communication Synchronous communication

TX RX clock
data A->B
Device A Device B Device A Device B
data B->A

asynchronous – no clock Synchronous – with clock

Data represented by setting Data represented by setting
HIGH/LOW at given times HIGH/LOW when “clock” changes

A single clock wire & data wire for

Separate wires for transmit & receive
each direction like before

Each device must have good “rhythm” Neither needs good rhythm, but one is the conductor

Is one better than the other? It depends on your application. Async is good if there are only two
devices and they’re both pre-configured to agree on the speed (like your Arduino sketches)

Synchronous is generally better for faster speeds (because you don’t need an accurate clock, just
the ability to watch the clock wire).
I2C, aka “Two-wire”
Synchronous serial bus with shared a data line
a little network for your gadgets

SCK clock
SDA data

Peripheral Peripheral Peripheral

device 1 device 2 device N

• Up to 127 devices on one bus

• Up to 1Mbps data rate
• Really simple protocol (compared to USB,Ethernet,etc)
• Most microcontrollers have it built-in
The shared data line means the devices have to agree on when they should “talk” on it. Like how on
CBs you say “over” and “over & out” to indicate you’re finished so the other person talk.

See “Introduction to I2C”:

“I2C” stands for “Inter-Integrated Circuit”, but no one calls it that
And if your microcontroller doesn’t have I2C hardware built-in, you can fake it by hand in software
(for master devices anyway)
Many I2C devices

touch sensor compass

fm transmitter

And many others

(gyros,keyboards, motors,...)
temperature &
LCD display humidity sensor
Images from,except LCD from
Obligatory BlinkM Promo
I2C Smart LED

Does all the hard PWM & waveform generation for you
You should be able to buy these from in a month or so.
Nintendo Wii Nunchuck
• Standard I2C interface

• 3-axis accelerometer with

10-bit accuracy

• 2-axis analog joystick with

8-bit A/D converter

• 2 buttons

• $20

If you look at the architecture for the Nintendo Wii and its peripherals, you see an almost un-Nintendo adherence
to standards. The Wii controllers are the most obvioius examples of this. The Wii controller bus is standard I2C.
The Wii remote speaks Bluetooth HID to the Wii (or your Mac or PC)

Because it uses standard I2C, it’s easy to make the Nunchuck work with Arduino, Basic Stamp or most other


And then there’s the Wii Remote, besides Bluetooth HID, it also has accelerometers, buttons, speaker, memory, and
is I2C master.
• Measures acceleration
(changes in speed)

• Like when the car

pushes you into the seat

• Gravity is acceleration

• So, also measures tilt

horizontal tilt right tilt left

Nunchuck Accelerometer

Wii Remote & Nunchuck

accelerometer axes
I’m not sure if I have the Nunchuck one right.

Wiimote axis image from

I2C on Arduino

• I2C built-in on Arduino’s

ATmega168 chip

• Use “Wire” library to access it

• Analog In 4 is SDA signal

• Analog In 5 is SCK signal


Arduino “Wire” library
Writing Data
Load Wire library
Join I2C bus
(as master)

Start sending
Send data
Stop sending

And what the various commands do are documented in the instructions / datasheet for a particular
Arduino “Wire” library
Reading Data

Join I2C bus

(as master)

Request data from device

Get data

What kinds of interactions you can have depends on

the device you’re talking to
Most devices have several “commands”

And what the various commands do are documented in the instructions / datasheet for a particular
Wiring up the Nunchuck
We could hack off the connector
and use the wires directly

But instead let’s use this

little adapter board
Wii Nunchuck Adapter
Nunchuck Pinout Adapter Pinout

n/c +V SCK

(looking into Nunchuck connector)

Note there *are* labels on the adapter, but they’re wrong. So you’ll have to trust the diagrams
Wiring it Up
SCK (pin5)
SDA (pin 4)

Pluggin’ in the ‘chuck
Trying the Nunchuck

Read the Nunchuck

every 1/10th of a second
& print out all the data:
- joystick position (x,y)
- accelerometer (x,y,z)
- buttons Z,C Z

Uses the beginnings of an Arduino library I’m writing.

Adding a Servo

Move the servo by

moving your arm

You’re a cyborg!

Also press the Z button to

flash the pin 13 LED

Utilizes the task slicing mentioned before

Nunchuck Servo
Twist the

and the servo

matches your
Segway Emulator

Same basic code as NunchuckServo.

For details see:
Going Further
• Servos
• Hook several together to create a multi-
axis robot arm
• Make a “servo recorder” to records your
arm movements to servo positions and
plays them back
• Great for holiday animatronics
Going Further
• I2C devices
• Try out some other devices
• Just string them on the same two wires used
for the Nunchuck
• Cooperative Multitasking
• Try making a theremin with nunchuck & piezo
• See if previous examples can be made more
Going Further
• Nunchuck
• It’s a freespace motion sensor. Control
anything like you’re waving a magic wand!
• What about the joystick? We didn’t even
get a chance to play with that
• Alternative input device to your
computer: control Processing, etc.
You’ve learned many different physical building blocks

resistive sensors


motors accelerometers servos

And you’ve learned many software building blocks

pulse width communication
analog I/O

data driven digital I/O

multiple tasks

Hope you had fun and continue playing with Arduino

Feel free to contact me to chat about this stuff

END Class 4

Tod E. Kurt

Feel free to email me if you have any questions.