P. 1
Bionic Arduino Class

Bionic Arduino Class

|Views: 3,380|Likes:
Published by MC. Rene Solis R.
All the *.PDE archives code are in this URL shared:
All the *.PDE archives code are in this URL shared:

More info:

Published by: MC. Rene Solis R. on Jan 13, 2010
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





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 two ~1.5 hour chunks, w/ 15 min. break in middle with some review at the beginning

• •

Sunday classes: 3 hours Tuesday classes: ~2.5 hours

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 better? 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 Solderless breadboard USB cable piezo buzzer potentiometer with knob 5 orange LEDs (large, clear) 1 RGB LED (diffuse, com. anode) two push switches

• • • • • •

9V battery and connector

• • •

6 x 220 ohm (red-red-brown) 2 x10k (brown-black-orange) 1 x1M (brown-black-green)

photocell phototransistor (small,clear) 4 colors of hookup wire rubber bands

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 of hardware A programming environment A community & philosophy

Arduino Philosophy & Community
• Open Source Physical Computing Platform
• • • • •
ambient intelligence, calm computing, everyware, spimes, blogjects, smart objects...

“open source hardware” open source: free to inspect & modify physical computing. er, what? ubiquitous computing, pervasive computing,

• 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) • Uses AVR ATmega168 microcontroller chip

chip was designed to be used with C language

but cheaper, faster, & open

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 Sparkfun.com and Adafruit.com

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 on “pin” 13

digital input/output “pins”
power LED

USB interface


reset button


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)

• On the thumbdrives • “arduino-0010-win.zip” for Windows • “arduino-0010-mac.zip” for Mac OS X • Unzip the zip file. Double-click on Mac
Use “Extract All...”

Getting and Unpacking

On Windows, right-click

• 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 highestnumbered port

pick “Diecimila”

Selecting Location & Type
starts with tty.usbserial-

pick “Diecimila”

Arduino Software
compile (verify) upload to board

status area

Using Arduino
• • •
Write your sketch Press Compile button (to check for errors) 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”
Change the “delay()” values to change blink rate

link sketch runs b

link b

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: http://www.arduino.cc/en/Tutorial/HomePage
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 loop() – run repeatedly, after setup() Running

• •

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



(flat part)

wiring diagram


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

Arduino board resistor pin 13 gnd LED

resistor 220 ohm


wiring diagram


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
Arduino board resistor pin 9 gnd LED
flat part


resistor 220 ohm


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
Arduino board resistor pin 9 gnd LED


Going from schematic to physical circuit.

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

All connected, a “bus”

not connected

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

Needle-nose pliers

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 Breadboards
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

Or, adding a breadboard to Arduino for 1¢

Alternate Way

3. plug into “bus” terminals 4. jumper over to other side

2. power & gnd wires

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): http://courses.ischool.berkeley.edu/i290-13/f07/

now circuit has power & ground

1. rubber band

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
(SPST) 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

toggle switch

Many Kinds of Switches





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 (LOW & HIGH) ground (0 volts) input to 5 volts
Press is HIGH Not pressed is LOW

• Resistor “pulls” input to • Pressing switch “pushes”

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 digitalRead(). 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

• Define actions, choose them from sensor inputs • Let’s try that with the actions we currently

• •

E.g. “If person is detected, fire super soaker” E.g. “If flower pot soil is dry, turn on sprinklers”

Load “FadeOrBlink” sketch from the handout
Schematic is same as for “Fading” sketch


Combines “Blink” & “Fading” sketches into one, selected by the button

Arduino can work totally stand-alone. It’s easy

Battery Power
plug into Vin & Gnd

• • • • • •

First, program sketch into Arduino Unplug USB cable Change jumper from USB to EXT Plug in power (7-12VDC) Power LED lights up. It works! Reverse steps to reprogram

set to EXT

Battery Power
• • •
Plugging into the sockets is kind of fiddly Better to plug into the power jack Works great, but requires a little soldering Center of jack is positive set to EXT

Going Further
• • • •
Make your own switches: aluminum foil, pennies, etc. 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.

http://arduino.cc/ Official homepage. Also check out the Playground & forums http://ladyada.net/learn/arduino/ Great Arduino tutorials http://todbot.com/blog/category/arduino/ Various movies, hacks, tutorials on Arduino http://freeduino.org/ Index of Arduino knowledge http://adafruit.com/ Arduino starter kits, Boarduino Arduino clone, lots of cool kits http://sparkfun.com/ Sells Arduino boards and lots of neat sensors & stuff Books: “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 • 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 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

link sketch runs b
Change the “delay()” values to change blink rate

link b

Known Good Configuration
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
Arduino board resistor pin 9 gnd LED



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 visibly

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.
+5V– measure– gnd–
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 • 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

(we’re used to knobs)

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.

This is what your board should have on it now

Pot & LED Circuit
+5V Arduino board resistor 220 (red-red-brown)

+5V 50k potentiometer

pin 2 gnd

pin 9 LED

gnd gnd

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 output

Most all embedded systems have a input→process→output loop
Sketch available in handout

Two Ways to Hook up LEDs
+5V Arduino board resistor pin 9 gnd LED gnd pin 9 resistor +5V Arduino board LED


To turn ON: digitalWrite(9,HIGH) To turn OFF: digitalWrite(9,LOW) To set brightness: analogWrite(9,val)

To turn ON: digitalWrite(9,LOW) To turn OFF: digitalWrite(9,HIGH) 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 –



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 RGB LED

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





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 RGB LED

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





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() from http://www.arduino.cc/en/Tutorial/DimmingLEDs

Pot-controlled RGB

common anode RGB LED

+5V 50k pot

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

pin 2 gnd





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

• aka. photoresistor, light-dependent resistor • A variable resistor • Brighter light == lower resistance • Photocells you have range approx. 0-10k-1M

Sensing the Dark: Photocells

schematic symbol
Pretty cheap too. Can get a grab bag of 100 misc from Jameco for $20

Photocell Circuit

pin A2

gnd 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 sandpaper

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

Resistive sensors
circuit is the same for all these
+5V sensor to analog input resistor

thermistor (temperature)

photocell (light) flex sensor (bend, deflection) force sensors (pressure)
Thermistor image from: http://www.facstaff.bucknell.edu/mastascu/elessonsHTML/Sensors/TempR.html Also see: http://www.ladyada.net/make/midisense/makesensor.html

also air pressure and others

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”

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 Serial.read() != -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 Arduino microcontroller

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

Arduino board

Arduino programmer

USB to serial driver

USB to serial



Arduino microcontroller

Processing sketch

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 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() your needs:

• There are many different variations to suite

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 ports Python, Visual Basic, etc.

• C/C++, Perl, PHP, Java, Max/MSP, • 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


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 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 use this to • Piezo buzzersback and forth, make sound (flex something 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 sensor

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
Arduino board pin 7 piezo buzzer + – gnd

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? 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
piezo buzzer pin 7 + – gnd

Arduino board

Arduino board pin 7

(brown, black, orange)

+ –

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 don’t 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 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
“ooo-weee-ooooo” 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
“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 & 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

Serial Examples

to Roomba
You’ve 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 cover that later)

• Can also be used as input devices (we’ll

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
• RGB LEDS • You can pretty easily
your computer replicate the Ambient Orb ($150) functionality

• Make a status display for • 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: http://www.ambientdevices.com/

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

link sketch runs b
Change the “delay()” values to change blink rate

link b

Class Kit 2 Contents
“motors & motion”

Class Kit 2 Manifest
“motors & motion”

• • • • • • •

Nintendo Wii Nunchuck Wii Nunchuck Adapter Large DC motor Small DC motor Small servo motor TIP120 power transistor 1N4001 power diode

• • •

Several 500 ohm resistors (green-brown-brown) Couple of popsicle sticks Colorful pipe cleaners

DC Motors
come in all shapes and sizes
the two motors in the kit

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 power.

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 Characteristics
• 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 switching voltage polarity

• They can operate in either direction, by • 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



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 fast to get it to light (if LED doesn’t light, try spinning the other direction)

This is used for “regenerative 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



collector base emitter



base 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 Transistors
little motor
DC motor

big motor
DC motor +

resistor + battery switch transistor + switch resistor

+ transistor + big power source

switching a different power source

transistors switch big signals with little signals

Need a “Kickback” Diode
DC motor



+ battery

resistor switch transistor

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 +5V DC motor Arduino board pin 9 500


b c 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
transistor turned around to make wiring easier
e c b

+5V +5V DC motor Arduino board pin 9 500




c e


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
+9V battery +5V
+5V DC motor Arduino board pin 9 500



9V battery



motor w/ tape propellor

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 volts.

Fun Motor Attachments

pipe cleaner squiggler

popsicle stick beater

tape propeller

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*
+12V +5V red LEDs 120 TIP120 1k gnd Arduino board pin 9

Super bright LED light
Full brightness control with PWM
+5V 1N4004 5V relay

Arduino board 1k pin 7 TIP120 gnd

to load light bulb, car ignition, washing machine, etc. to load:

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 any voltage with a resistor, or it just builds up The protection diodes inside the AVR chip protect against the high voltage
piezo buzzer + – 1M
(brown, black, green)

Arduino board

analog pin 2 gnd

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 buzzer + – 1M
(brown, black, green)

Arduino 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.

Piezo Knock
“PiezoKnock” Whack the piezo to print out a number based on force of whack
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
volts piezo output voltage threshold

time whack! t

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
(under rugs, floor mat, door, your body, etc.)

Can mount the element on anything

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
piezos MIDI output buttons
I used this during Halloween a few years ago to trigger scary sounds.

Or Trigger Actuators

piezo buzzer + – 1M
(brown, black, green)

Arduino board

DC motor

pin 9 500
(green, brown, brown)


analog pin 2 gnd


If you still have your motor wired up

Take a Break

Getting the Board Set Up
+5V Arduino board +5V 50k pot pin 2 gnd gnd

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 programming Started as a tool to make generative art 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” Processing Load up
“Examples » Topics » Motion » Bounce” 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

• Other functions can exist when using libraries

• setup() – set up sketch, like size, framerate • draw() – like loop(), called repeatedly

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.read(), 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 1. load library 2. set portname 3. open port 4. read/write port 1. 2. 3.
be sure to set to the same as “Serial Port” in Arduino GUI


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 position

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 onscreen
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 “minim-1.1-lib.zip”. 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: http://todbot.com/blog/2006/10/23/diy-ambient-orb-with-arduino-update/

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

link sketch runs b
Change the “delay()” values to change blink rate

link b

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 20% 80% 20% 80% 20% 80%

1.0 Volts

• 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 • Easy three-wire

circuitry & gearing takes care of the hard stuff 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 motor 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 motion

• 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 • to drive-your-car • But all have the same
3-wire interface
weight: speed: torque: voltage: size:
http://rctoys.com/ http://hobbypeople.net/


• Servos are spec’d by:
9g .12s/60deg @ 6V 22oz/1.5kg @ 6V 4.6~6V 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) 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

Gnd Power 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
“ServoSimple” 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 board command-line can do it:

• On Unixes like Mac OS X & Linux, even the
demo% demo% demo% demo% demo% export PORT=/dev/tty.usbserial-A3000Xv0 stty -f $PORT 9600 raw -parenb -parodd cs8 -hupcl -cstopb clocal printf "1" > $PORT # rotate servo left printf "5" > $PORT # go to middle 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 electronics.

Servo Timing Problems
• Two problems with the last sketch • When servoPulse() function runs,
nothing else can happen at position

• Servo isn’t given periodic pulses to keep it • 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
ServoSerialSimple (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 pins you have though

• Only limit really is number of digital output • 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
TX Device A RX TX RX Device B Device A

Synchronous communication
clock data A->B data B->A

Device B

asynchronous – no clock Data represented by setting HIGH/LOW at given times
Separate wires for transmit & receive

Synchronous – with clock Data represented by setting HIGH/LOW when “clock” changes
A single clock wire & data wire for 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

clock data

Master device

Peripheral device 1

Peripheral device 2


Peripheral 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”: http://www.embedded.com/story/OEG20010718S0073 “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
non-volatile memory

touch sensor


fm transmitter And many others
(gyros,keyboards, motors,...)

LCD display
Images from Sparkfun.com,except LCD from matrixorbital.com

temperature & humidity sensor

Obligatory BlinkM Promo
I2C Smart LED

Does all the hard PWM & waveform generation for you
You should be able to buy these from Sparkfun.com 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 microcontrollers. See: http://www.wiili.org/index.php/Wiimote/Extension_Controllers/Nunchuk and: http://www.windmeadow.com/node/42 and: http://todbot.com/blog/2007/10/25/boarduino-wii-nunchuck-servo/ 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


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 device.

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 device.

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 SDA



(looking into Nunchuck connector)

Note there *are* labels on the adapter, but they’re wrong. So you’ll have to trust the diagrams above

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
“NunchuckServo” 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 nunchuck

and the servo matches your movement

Segway Emulator

Same basic code as NunchuckServo. For details see: http://todbot.com/blog/2007/10/25/boarduino-wii-nunchuck-servo/

Going Further
• Servos • Hook several together to create a multiaxis 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
get a chance to play with that anything like you’re waving a magic wand!

• What about the joystick? We didn’t even • Alternative input device to your
computer: control Processing, etc.

You’ve learned many different physical building blocks

switches/buttons LEDs

resistive sensors

piezos motors accelerometers servos

And you’ve learned many software building blocks serial communication analog I/O data driven code digital I/O multiple tasks frequency modulation I2C pulse width modulation

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.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->