Você está na página 1de 219

Bionic Arduino

Introduction to Microcontrollers with Arduino

Class 1

11 Nov 2007 - machineproject - Tod E. Kurt

Bionic Arduino Introduction to Microcontrollers with Arduino Class 1 11 Nov 2007 - machineproject - Tod

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

Bionic?

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 I Contents Class Kit 2 comes next week A little shoebox-sized plastic storage bin

Class Kit 2 comes next week

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

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

USB cable

piezo buzzer

potentiometer with knob

5 orange LEDs (large, clear)

1 RGB LED (diffuse, com. anode)

two push switches

resistors:

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

word “Arduino” can mean 3 things A physical piece of hardware A programming environment A community

A programming environment

word “Arduino” can mean 3 things A physical piece of hardware A programming environment A community

A community & philosophy

word “Arduino” can mean 3 things A physical piece of hardware A programming environment A community

Arduino 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

chip • chip was designed to be used with C language The designer of the AVR
chip • chip was designed to be used with C language The designer of the AVR

The designer of the AVR purposefully arranged its registers and instruction set so that C programs would compile e" ciently on it. This is a big deal, compared to previous microcontrollers where C programs were almost always less e " cient than a hand-coded assembly language variant.

Arduino Hardware Variety

DIY
DIY

LilyPad

(for clothing)

Arduino Hardware Variety DIY LilyPad (for clothing) USB Bluetooth Boarduino Kit “Stamp”-sized many different
Arduino Hardware Variety DIY LilyPad (for clothing) USB Bluetooth Boarduino Kit “Stamp”-sized many different

USB

Arduino Hardware Variety DIY LilyPad (for clothing) USB Bluetooth Boarduino Kit “Stamp”-sized many different

Bluetooth

Boarduino Kit

DIY LilyPad (for clothing) USB Bluetooth Boarduino Kit “Stamp”-sized many different variations to suite your

“Stamp”-sized

(for clothing) USB Bluetooth Boarduino Kit “Stamp”-sized many different variations to suite your needs Openness has

many different variations to suite your needs

Openness has its advantages, many di ! erent 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”

test LED on “pin” 13 digital input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs
test LED on “pin” 13 digital input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs
ATmega168
ATmega168
on “pin” 13 digital input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs button reset

power

LED

13 digital input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs button reset 2.7” analog

2”

USB interface

input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs button reset 2.7” analog input “pins”

TX/RX

LEDs

button reset

input/output “pins” ATmega168 power LED 2” USB interface TX/RX LEDs button reset 2.7” analog input “pins”

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

Arduino Software • Like a text editor • View/write/edit sketches • But then you program them

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

“arduino-0010-win.zip” for Windows

“arduino-0010-mac.zip” for Mac OS X

Unzip the zip file. Double-click on Mac

for Mac OS X • Unzip the zip file. Double-click on Mac On Windows, right-click Use

On Windows, right-click

Use “Extract All

file. Double-click on Mac On Windows, right-click Use “Extract All ” • Find the “drivers” directory

Find the “drivers” directory inside

Plug in Arduino board

from quick test blink LED

Plug in Arduino board from quick test blink LED Power LED should stay on
Plug in Arduino board from quick test blink LED Power LED should stay on

Power LED should stay on

Mac Driver Install

Double-click on .dmg Installer

Mac Driver Install Double-click on .dmg Installer • v2_1_6 for PPC Macs • v2_2_6 for Intel

v2_1_6 for PPC Macs

v2_2_6 for Intel Macs

Windows Driver Install

Windows Driver Install
Windows Driver Install
Windows Driver Install
Windows Driver Install
Windows Driver Install

Selecting Location & Type

Selecting Location & Type usually highest- numbered port pick “Diecimila”
Selecting Location & Type usually highest- numbered port pick “Diecimila”

usually highest- numbered port

pick “Diecimila”

Selecting Location & Type

Selecting Location & Type starts with tty.usbser ial- pick “Diecimila”

starts with tty.usbser ial-

Selecting Location & Type starts with tty.usbser ial- pick “Diecimila”

pick “Diecimila”

Arduino Software

upload to board
upload to board
Arduino Software upload to board c o m p i l e ( ver ify) status

compile ( ver ify)

status

area

Arduino Software upload to board c o m p i l e ( ver ify) status

Using Arduino

Using Arduino compile upload blink blink • Write your sketch • Press Compile button (to check
Using Arduino compile upload blink blink • Write your sketch • Press Compile button (to check

compile

Using Arduino compile upload blink blink • Write your sketch • Press Compile button (to check
Using Arduino compile upload blink blink • Write your sketch • Press Compile button (to check

upload

blink blink
blink blink

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”

sketch runs

Change the “delay()” values to change blink rate

Status Messages

Uploading worked

Size depends on complexity of your sketch

Uploading worked Size depends on complexity of your sketch Wrong serial port selected Wrong board selected

Wrong serial port selected

Size depends on complexity of your sketch Wrong serial port selected Wrong board selected nerdy cryptic
Size depends on complexity of your sketch Wrong serial port selected Wrong board selected nerdy cryptic

Wrong board selected

nerdy cryptic error messages

Troubleshooting

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!
edit
compile
upload
run
done!

Lots of Built-in Examples

Lots of Built-in Examples And more here: http://www.arduino.cc/en/Tutorial/HomePage And all over the Net. Search for

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 co ! ee 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

Making Circuits heart pumps, blood flows voltage pushes, current flows It’s all about the flow of

heart pumps, blood flows

Making Circuits heart pumps, blood flows voltage pushes, current flows It’s all about the flow of

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

Example: LED flashlight current flow + 9V – resistor 500 ohm LED (flat part) (green,brown,brown) wiring

current flow

+ 9V –
+
9V
Example: LED flashlight current flow + 9V – resistor 500 ohm LED (flat part) (green,brown,brown) wiring
resistor 500 ohm LED
resistor
500 ohm
LED

(flat part)

current flow + 9V – resistor 500 ohm LED (flat part) (green,brown,brown) wiring diagram 500 schematic

(green,brown,brown)

wiring diagram

500
500

schematic

part) (green,brown,brown) wiring diagram 500 schematic wiring it up Electricity flows in a loop. Can stop

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

LED Arduino board pin 13 gnd resistor 220 ohm (red,red,brown) flat part
LED
Arduino
board
pin 13
gnd
resistor
220 ohm
(red,red,brown)
flat part

resistor

gnd resistor 220 ohm (red,red,brown) flat part resistor gnd LED wiring diagram schematic Arduino Diecimila board
gnd resistor 220 ohm (red,red,brown) flat part resistor gnd LED wiring diagram schematic Arduino Diecimila board

gnd

LED

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 o ! .

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 LED Flat edge
On LEDs, polarity matters.
Shorter lead is “negative” side, goes to ground
LED
Flat edge here for neg. side
resistor
Polarity doesn’t matter on resistors

Varying LED Brightness

Same circuit as Blink circuit but pin 9 instead of pin 13

Arduino board pin 9 gnd
Arduino
board
pin 9
gnd

resistor

pin 9 instead of pin 13 Arduino board pin 9 gnd resistor LED gnd schematic resistor
pin 9 instead of pin 13 Arduino board pin 9 gnd resistor LED gnd schematic resistor

LED

gnd

schematic

resistor 220 ohm (red,red,brown) flat part
resistor
220 ohm
(red,red,brown)
flat part

wiring diagram

220 ohm (red,red,brown) flat part wiring diagram wired up The PWM pins work with the “

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

resistor

Let’s Wire It Up Arduino board pin 9 gnd resistor LED gnd Going from schematic to
Let’s Wire It Up Arduino board pin 9 gnd resistor LED gnd Going from schematic to

LED

gnd

Let’s Wire It Up Arduino board pin 9 gnd resistor LED gnd Going from schematic to
Let’s Wire It Up Arduino board pin 9 gnd resistor LED gnd Going from schematic to

Going from schematic to physical circuit.

Solderless Breadboards

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

numbers & letter just labels for

reference

groups of 5 connected

All connected, a bus

groups of 5 connected All connected, a “ b u s ” not connected Insert wires

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 cutters Wire stripper Needle-nose pliers
Wire cutters
Wire stripper
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

~1/4”
~1/4”
Making Jumper Wires pliers & cutter wire stripper ~1/4” About 1/4” for the stripped parts. And
Making Jumper Wires pliers & cutter wire stripper ~1/4” About 1/4” for the stripped parts. And
Making Jumper Wires pliers & cutter wire stripper ~1/4” About 1/4” for the stripped parts. And

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

Using needle nose pliers can help push wires & components into holes Grab wire or lead

Grab wire or lead toward end and push into hole

All Wired Up

plugged into “ground” bus
plugged into “ground” bus

Alternate Way

Or, adding a breadboard to Arduino for 1¢

2. power & gnd wires 3. plug into “bus” terminals 1. rubber band now circuit
2. power & gnd wires
3. plug into “bus” terminals
1. rubber band
now circuit has power & ground

4. jumper over to other side

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/

LED “Fading” Sketch

Load “File/Sketchbook/Examples/Analog/Fading”

note

Load “File/Sketchbook/Examples/Analog/Fading” note Press “Upload”. After a second, LED will “throb” on

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

variations on switches Switches make or break a connection knife switch (SPST) toggle switch (SPDT) Fundamentally,

knife switch

(SPST)

Switches make or break a connection knife switch (SPST) toggle switch (SPDT) Fundamentally, they’re all like

toggle switch

(SPDT)

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

Many Kinds of Switches magnetic hexidecimal tilt lever Tilt sensor has a little ball inside you

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” Penny on a surface. When the penny is lifted, alarms go off

Homemade Switches

“Trick Penny”

Homemade Switches “Trick Penny” Surface is conductive metal sheet. Wire soldered to penny. Wire looped or

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

When the wind blows hard enough, you’re sent email Should use stranded wire, not solid. Code

Should use stranded wire, not solid. Code analyzes series of on/o ! /on/o ! 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)

HIGH

LOW

Specifically, a “HIGH” (5 volts) • or a “LOW” (0 volts) HIGH LOW How do you

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)

Resistor “pulls” input to ground (0 volts)

Pressing switch “pushes” input to 5 volts

Press is HIGH Not pressed is LOW

input to 5 volts • Press is HIGH Not pressed is LOW Don’t want “pull-down” to

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

Wiring it up

Wiring it up Let’s plug it into pin 2 You can leave the last project on

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”

Input Sketch Load “Sketchbook/Examples/Digital/Button” Now you control the blinking (How would you change it to

Now you control the blinking

(How would you change it to blink the external LED you wired up?)

Press to turn o ! , 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 know

FadeOrBlink

Load “FadeOrBlink” sketch from the handout

Schematic is same as for “Fading” sketch

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

is same as for “Fading” sketch Combines “Blink” & “Fading” sketches into one, selected by the

Battery Power

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

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

plug into Vin & Gnd set to EXT
plug
into
Vin &
Gnd
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
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.

Resources

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

Bionic Arduino Introduction to Microcontrollers with Arduino Class 2 13 Nov 2007 - machineproject - Tod

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 stu ! , let’s see how far we get.

Recap: Blinky LED

Make sure things still work

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

compile

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

upload

blink blink
blink blink
LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink” TX/RX

Load “File/Sketchbook/Examples/Digital/Blink”

TX/RX flash

sketch runs

Change the “delay()” values to change blink rate

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 schematic gnd wire up pin 9 LED too
Arduino
board
resistor
pin 9
gnd
schematic
gnd
wire up pin 9 LED too
LED

LED

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

on the end of your LEDs to make them glow more visibly I have a box

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

Random Behavior

“CandleLight”

Uses simple pseudo random number generator to mimic flame

Use random(min,max) to pick a number between min & max.

random(min,max) to pick a number between min & max. This sketch is in the handout. Can

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

Analog Input To computers, analog is chunky image from: http://www.engr.colostate.edu/~dga/me307/lectures.html

image from: http://www.engr.colostate.edu/~dga/me307/lectures.html

Analog Input

Many states, not just two (HIGH/LOW)

Number of states (or values, or “bins”) is resolution

Common computer resolutions:

8-bit = 256 values

16-bit = 65,536 values

32-bit = 4,294,967,296 values

Common computer resolutions: • 8-bit = 256 values • 16-bit = 65,536 values • 32-bit =

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.

50k
50k
varying voltage? With a potentiometer . Or just pot . 50k The pot you have +5V–

The pot you have

+5V–

measure–

voltage? With a potentiometer . Or just pot . 50k The pot you have +5V– measure–

gnd–

voltage? With a potentiometer . Or just pot . 50k The pot you have +5V– measure–

pots also look like this

Potentiometers

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

like moving where the arrow taps the voltage on the resistor When a resistor goes across

When a resistor goes across a voltage di ! erence, 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

a row (row 7 here) Run a wire from that row to Analog In 2 Why
a row (row 7 here) Run a wire from that row to Analog In 2 Why

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

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

gnd

50k pin 2 pin 9 potentiometer LED gnd gnd gnd In schematics, inputs are usually on
50k pin 2 pin 9 potentiometer LED gnd gnd gnd In schematics, inputs are usually on

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

Varying Brightness by Hand “PotDimmer” Turn the knob to change LED brightness input process the input

“PotDimmer”

Turn the knob to change LED brightness

input

“PotDimmer” Turn the knob to change LED brightness input process the input data output Most all

process the input data

output

to change LED brightness input process the input data output Most all embedded systems have a
to change LED brightness input process the input data output Most all embedded systems have a

Most all embedded systems have a input processoutput loop

Sketch available in handout

Two Ways to Hook up LEDs

Arduino board pin 9 gnd
Arduino
board
pin 9
gnd

resistor

Two Ways to Hook up LEDs Arduino board pin 9 gnd resistor LED gnd To turn
Two Ways to Hook up LEDs Arduino board pin 9 gnd resistor LED gnd To turn

LED

gnd

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

To set brightness: analogWrite(9,val)

+5V

+5V Arduino LED board resistor pin 9 gnd
+5V
Arduino
LED
board
resistor
pin 9
gnd

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 + cathode –
anode +
cathode –

RGB LED

anode +
anode +

red

blue

green

RGB LEDs

anode + cathode –

RGB LED anode + red blue green RGB LEDs anode + cathode – red cathode –

red cathode – anode + blue cathode – green cathode –

red cathode – anode + blue cathode – green cathode – actually 3 LEDs in one

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

+5V

common anode RGB LED Arduino board pin 11 pin 10 pin 9 220 (red,red,brown) gnd
common anode
RGB LED
Arduino
board
pin 11
pin 10
pin 9
220 (red,red,brown)
gnd
green
blue
red
pin 10 pin 9 220 (red,red,brown) gnd green blue red With RGB you can make any

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 di ! erent, it’s hard to get the mix to be just right for a variety of annoying reasons:

- the physics of LEDs mean that di ! erent color LEDs put out di ! erent amounts of light

- our eyes respond non-linearly across the spectrum, i.e. 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

Laying out RGB LED Circuit +5V common anode RGB LED Arduino board pin 11 pin 10

+5V

common anode RGB LED Arduino board pin 11 pin 10 pin 9 220 (red,red,brown) gnd
common anode
RGB LED
Arduino
board
pin 11
pin 10
pin 9
220 (red,red,brown)
gnd
green
blue
red
pin 10 pin 9 220 (red,red,brown) gnd green blue red slightly bend the longest lead and

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

“RGBMoodLight”

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 stu ! in a minute.

handout. We’ll get to the serial port stu ! in a minute. It just ramps up

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

Pot-controlled RGB +5V common anode RGB LED Arduino +5V board pin 11 pin 10 50k pin
+5V common anode RGB LED Arduino +5V board pin 11 pin 10 50k pin 2
+5V
common anode
RGB LED
Arduino
+5V
board
pin 11
pin 10
50k
pin 2
pin 9
pot
220 (red,red,brown)
gnd
green
blue
red
gnd

Pot-controlled RGB

“RGBPotMixer”

Use the pot from before to control the color mix

The code turns the single ranged input value into “sectors” where each sector is a color

input value into “sectors” where each sector is a color Also see “RGBPotMixer2” for a variation.

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

of a voltage divider • Voltage divider splits a voltage in two • Same as two

Sensing the Dark:

Photocells

aka. photoresistor, light-dependent resistor

A variable resistor

Brighter light == lower resistance

Photocells you have range approx. 0-10k-1M

resistance • Photocells you have range approx. 0-10k-1M schematic symbol Pretty cheap too. Can get a

schematic symbol

Photocells you have range approx. 0-10k-1M schematic symbol Pretty cheap too. Can get a grab bag

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

Photocell Circuit

brown-black-orange
brown-black-orange

gnd

pin A2

Photocell Circuit brown-black-orange gnd pin A2 Try it with RGBPotMixer from before Looks a lot like

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

Diffuser made from piece of plastic scratched with sandpaper Also, can use plastic wrap scrunched up

Also, can use plastic wrap scrunched up to make an interesting di !user.

Resistive sensors

Resistive sensors thermistor (temperature) force sensors (pressure) circuit is the same for all these +5V sensor

thermistor

(temperature)

Resistive sensors thermistor (temperature) force sensors (pressure) circuit is the same for all these +5V sensor

force sensors (pressure)

circuit is the same for all these

force sensors (pressure) circuit is the same for all these +5V sensor to analog input resistor

+5V

sensor

to analog

input

resistor

the same for all these +5V sensor to analog input resistor flex sensor (bend, deflection) photocell

flex sensor (bend, deflection)

to analog input resistor flex sensor (bend, deflection) photocell (light) also air pressure and others Thermistor

photocell

(light)

also air pressure and others

Thermistor image from: http://www.facstaff.bucknell.edu/mastascu/elessonsHTML/Sensors/TempR.html Also see: http://www.ladyada.net/make/midisense/makesensor.html

Communicating with Others

Arduino can use same USB cable for programming and to talk with computers

Talking to other devices uses the “Serial” commands

Serial.begin() – prepare to use serial

Serial.print() – send data to computer

Serial.read() – read data from computer

Can talk to not just computers. Most things more complex than simple sensors/actuators speak serial.

Watch the TX/RX LEDS

TX – sending to PC

RX – receiving from PC

Used when programming or communicating

the TX/RX LEDS • TX – sending to PC • RX – receiving from PC •

Arduino Says “Hi”

“SerialHelloWorld”

Sends “Hello world!” to your computer

Click on “Serial Monitor” button to see output

Watch TX LED compared to pin 13 LED

button to see output Watch TX LED compared to pin 13 LED This sketch is located

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

Telling Arduino What To Do “SerialReadBasic” You type “H”, LED blinks In “Serial Monitor”, type “H”,

“SerialReadBasic”

You type “H”, LED blinks

In “Serial Monitor”, type “H”, press Send

Serial.available() tells

you if data present to read

This sketch is in the handout Always check Serial.available() or if Serial.read() != -1 to determine if 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

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
‘B’ =
0
1
0
0
0
0
1
0
=
L H L L
L L H L
HIGH
=
LOW

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
USB to serial
Arduino
microcontroller

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

Arduino Mini

Arduino Mini separates the two circuits

Arduino Mini Arduino Mini separates the two circuits Arduino Mini USB adapter Arduino Mini aka. “Arduino

Arduino Mini USB adapter

Mini separates the two circuits Arduino Mini USB adapter Arduino Mini aka. “Arduino Stamp” If you

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 TX USB RX Arduino USB to serial driver USB to serial programmer
Laptop
Arduino board
TX
USB
RX
Arduino
USB to serial
driver
USB to serial
programmer
chip
Arduino
RX
TX
microcontroller
-OR-
Processing
sketch
-OR-
Java program
-OR-

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

There are many different variations to suite your needs:

sensor data from Arduino to computer with Serial.print() • 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

on the computer In Arduino: read sensor, send data as byte In Processing: read the byte,

In Processing: read the byte, do something with it

sensor, send data as byte In Processing: read the byte, do something with it But writing

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

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

“SerialReadBlink”

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

typed ASCII value into usable number Most control issues are data conversion issues This sketch is

Serial-controlled RGB

“SerialRGBLED”

Send color commands to Arduino

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

Sketch parses what you type, changes LEDs

g50
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

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

a character string and sticks available serial data into it Pay no attention to the pointer

Pay no attention to the pointer symbol (“*”) Must be careful about calling readSerialString() too often or you’ll read partial strings

Piezoelectrics

Big word – piezein is greek for “squeeze”

Some crystals, when squeezed, make a spark

Turns out the process goes the other way too

Spark a quartz crystal, and it 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

supports the piezo element and has resonant cavity for sound Oscillating voltage alternately squeezes and releases
supports the piezo element and has resonant cavity for sound Oscillating voltage alternately squeezes and releases
supports the piezo element and has resonant cavity for sound Oscillating voltage alternately squeezes and releases

Oscillating voltage alternately squeezes and releases the piezo element. Must apply flucuating voltage, a steady HIGH or LOW won’t work.

diagrams from: http://www.maxim-ic.com/appnotes.cfm/appnote_number/988

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

piezo Only take it out of its case to use it as a sensor another $1.99

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

piezo Arduino buzzer board + pin 7 – gnd
piezo
Arduino
buzzer
board
+
pin 7
gnd
Buzzer piezo Arduino buzzer board + pin 7 – gnd Piezo leads are very thin. The

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

Type multiple letters from “ cdefgabC ” to make melodies This sketch is in the handout,

This sketch is in the handout, Notice the problem with this sketch? Di! erent notes play for di ! erent amounts of time. 50 cycles of low C isn’t the same amount of time as 50 cycles of high B

Making it Quieter

Easiest way: add a resistor

piezo Arduino buzzer board + pin 7 – gnd
piezo
Arduino
buzzer
board
+
pin 7
gnd
a resistor piezo Arduino buzzer board + pin 7 – gnd Arduino board 10k + pin
Arduino board 10k + pin 7 (brown, – black, orange) gnd
Arduino
board
10k
+
pin 7
(brown,
black,
orange)
gnd

piezo

buzzer

Like most things in electronics, if you want less of something, add a resistor. A better value would probably be 1k, but we 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.

button trigger, control playback speed with photocell, etc. Melody definition is sort of like the old

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

field No touching needed! We’ll use light in lieu of RF Leon Theremin As heard on

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

& cycles count to alter sensitivity, pitch and timbre Okay so maybe it sounds more like

Okay so maybe it sounds more like a bad video game than a spooky movie The glitchy sound is cause because of the time it takes to read the sensor There are ways around such stu ! , but requires more complex programming using timers & interrupts The sound can get annoying quick

Other Serial Devices

Other Serial Devices to Wi-Fi to Ethernet t o g r a p h i c

to Wi-Fi

to Ethernet

Other Serial Devices to Wi-Fi to Ethernet t o g r a p h i c

to graphic LCD to 8-servo controller

Lantronix Wi-Port and Lantronix Xport http://lantronix.com/

Seetron Serial Graphic display and Mini SSC

http://www.seetron.com/slcds.htm

http://www.seetron.com/ssc.htm

Serial Examples

Serial Examples You’ve already seen this. :) http://hackingroomba.com / to Roomba

You’ve already seen this. :) http://hackingroomba.com/

to Roomba

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 communications

Many other devices speak serial

Older keyboards & mice speak are serial (good for sensors!)

Interface boards (graphic LCDs, servo drivers, RFID readers, Ethernet,Wi-Fi)

Going Further

RGB LEDS

You can pretty easily replicate the Ambient Orb ($150) functionality

Make a status display for your computer

Computer-controlled accent lighting (a wash of color against the walls)

accent lighting (a wash of color against the walls) Ambient Orb doesn’t connect to computer though.

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

Bionic Arduino Introduction to Microcontrollers with Arduino Class 3 18 Nov 2007 - machineproject - Tod

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

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

compile

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

upload

blink blink
blink blink
LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink” TX/RX

Load “File/Sketchbook/Examples/Digital/Blink”

TX/RX flash

sketch runs

Change the “delay()” values to change blink rate

Class Kit 2 Contents

“motors & motion”

Class Kit 2 Contents “motors & motion”

Class Kit 2 Manifest

Nintendo Wii Nunchuck

Wii Nunchuck Adapter

Large DC motor

Small DC motor

Small servo motor

TIP120 power transistor

1N4001 power diode

“motors & motion”

Several 500 ohm resistors (green-brown-brown)

Couple of popsicle sticks

Colorful pipe cleaners

come in all shapes and sizes

You probably have 3-4 on you right now

(cell vibrate, laptop fan, laptop dvd drive)

DC Motors

the two motors in the kit
the two motors
in the kit

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

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

battery

The higher the voltage, the faster the spinning battery M DC motor polarity determines which way
The higher the voltage, the faster the spinning battery M DC motor polarity determines which way
M
M
The higher the voltage, the faster the spinning battery M DC motor polarity determines which way

DC motor

polarity determines which way it rotates

battery M DC motor polarity determines which way it rotates Try this out real quick. Then

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 Motors as Generators Just as voltage causes rotation LED M DC motor rotation causes voltage
DC Motors as Generators Just as voltage causes rotation LED M DC motor rotation causes voltage

LED

M
M

DC motor

as Generators Just as voltage causes rotation LED M DC motor rotation causes voltage This is

rotation

causes voltage

This is used for “regenerative braking” in electric & hybrid cars

Try it out, but you have to spin really fast to get it to light
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)

These high-e ! ciency 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.

Transistors

Act like switches

electricity flicks the switch instead of your finger

TIP120 base collector emitter
TIP120
base
collector
emitter

base

collector emitter
collector
emitter

TIP120

schematic symbol

base

emitter base collector emitter TIP120 schematic symbol base collector emitter how it kind of works Turning

collector

emitter

how it kind of works

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

The di "erences 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 M resistor transistor switch + battery
DC motor
M
resistor
transistor
switch
+
battery

big motor

+ DC motor M + resistor transistor switch + +
+
DC motor
M
+
resistor
transistor
switch
+
+

big power

source

switching a different power source

transistors switch big signals with little signals

Need a “Kickback” Diode

diode

Need a “Kickback” Diode diode line schematic symbol DC motor M resistor switch diode transistor +
Need a “Kickback” Diode diode line schematic symbol DC motor M resistor switch diode transistor +

line

Need a “Kickback” Diode diode line schematic symbol DC motor M resistor switch diode transistor +
Need a “Kickback” Diode diode line schematic symbol DC motor M resistor switch diode transistor +

schematic symbol

DC motor

a “Kickback” Diode diode line schematic symbol DC motor M resistor switch diode transistor + battery
M resistor switch
M
resistor
switch

diode

transistor

+

symbol DC motor M resistor switch diode transistor + battery since motors can act like generators,

battery

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)

b c e

Controlling a Motor

+5V

+5V DC motor 1N4001 M Arduino board c b pin 9 TIP120 500 e (green-brown-brown)
+5V
DC motor
1N4001
M
Arduino
board
c
b
pin 9
TIP120
500
e
(green-brown-brown)
gnd
board c b pin 9 TIP120 500 e (green-brown-brown) gnd motor start with the tiny motor
motor
motor

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

Wiring up Motor Circuit +5V +5V DC motor 1N4001 M Arduino board b c pin 9
+5V +5V DC motor 1N4001 M Arduino board b c pin 9 TIP120 500 e
+5V
+5V
DC motor
1N4001
M
Arduino
board
b c
pin 9
TIP120
500
e
(green-brown-brown)
gnd
transistor turned around to make wiring easier e c b white diode line into +5V
transistor
turned
around to
make wiring
easier
e
c
b
white diode line into +5V
motor across diode

Sketch

“SerialMotorSpeed”

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?

Monitor to control the speed of the motor How would you change this to control the

Controlling a Bigger Motor

Same circuit as before, different voltage source

+9V battery

+5V

+5V DC motor 1N4001 M Arduino board pin 9 TIP120 500 (green-brown-brown) gnd
+5V
DC motor
1N4001
M
Arduino
board
pin 9
TIP120
500
(green-brown-brown)
gnd

motor w/ tape propellor

desk ding from motor getting loose
desk ding from
motor getting loose

9V

battery

Motor will spin faster for a given analogWrite() value

Actually with both of the motors you have, you can run o " 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

Fun Motor Attachments pipe cleaner squiggler tape propeller popsicle stick beater I’m terrible at mechanical

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

Wiring Up Bigger Motor Don’t just add 9V to +5v bus! Move the diode from +5

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

row Add red 9V wire to that row, Add black 9V wire to Gnd You might

You might find it easier to push the red 9V wire in with the motor wire.

Can Switch Anything*

+12V +5V red LEDs Arduino board 120 pin 9 TIP120 1k gnd Super bright LED
+12V
+5V
red LEDs
Arduino
board
120
pin 9
TIP120
1k
gnd
Super bright LED light
Full brightness control with PWM
+5V 1N4004 5V relay 1k TIP120
+5V
1N4004
5V relay
1k
TIP120
Arduino board pin 7 gnd
Arduino
board
pin 7
gnd

to load

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

The normal piezoelectric effect is generating electricity from squeezing a crystal.

Can get several thousand volts, makes a spark

• Can get several thousand volts, makes a spark • You probably have seen a big

You probably have seen a big example of this already:

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

Arduino piezo board buzzer + analog pin 2 – gnd 1M (brown, black, green)
Arduino
piezo
board
buzzer
+
analog pin 2
gnd
1M
(brown,
black,
green)

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

Arduino board analog pin 2 gnd
Arduino
board
analog pin 2
gnd
Arduino board analog pin 2 gnd piezo buzzer + – 1M (brown, black, green)

piezo

buzzer

+ –
+

1M

(brown,

black,

green)

piezo buzzer + – 1M (brown, black, green) Could also plug it directly into the Arduino,

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

for input to go over threshold, then to drop below threshold Number is “t”, the number

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 threshold time t whack! volts
piezo output voltage
threshold
time
t
whack!
volts

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

on anything (under rugs, floor mat, door, your body, etc.) Here’s one glued to a larger

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
piezos
MIDI
output
buttons

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

Or Trigger Actuators

Or Trigger Actuators “PiezoMotorPulse” +5V DC motor M 500 (green, brown, brown) Arduino board analog pin

“PiezoMotorPulse”

+5V

DC motor M 500 (green, brown, brown)
DC motor
M
500
(green,
brown,
brown)
Arduino board analog pin 2 pin 9 gnd
Arduino
board
analog pin 2
pin 9
gnd

piezo

buzzer

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

1N4001

TIP120

If you still have your motor wired up

Take a Break

Getting the Board Set Up

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

+5V

Arduino +5V board 50k pin 2 pot gnd gnd
Arduino
+5V
board
50k
pin 2
pot
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

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

to devices like Arduino • Think of it as a free Max/MSP And it’s totally open
to devices like Arduino • Think of it as a free Max/MSP And it’s totally open

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

Press “Run” button • You just made a Java applet The Processing application folders are in

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.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. 4.
1.
2.
3.
4.

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 stu " . 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

“PotSend”

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

can have 6 knobs total because there are 6 Analog In pins Meanwhile, back in Arduino,

Meanwhile, back in Arduino, load up this sketch we’ll use with Processing

Processing + Arduino

Processing + Arduino “ArduinoReadCircle” The pot controls the hue of the onscreen circle Arduino is running

“ArduinoReadCircle”

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

“ArduinoBounce”

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

trails Uncomment the “ fill() ” line to get color trails Notice the bug that happens

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

And Another One

“ArduinoPong”

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

and a little more game logic and you have a 2-player game These are all very

These are all very minorly-modified examples of standard Processing sketches.

Triggering Sounds

“ArduinoSounds”

Every time the piezo is knocked a sound plays and a red disc appears onscreen

This sketch needs the “minim” sound library.

onscreen This sketch needs the “minim” sound library. You can add your own sounds (WAV or

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 drag
unzip
open
drag

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

Processing to Arduino

real quick

“http_rgb_led”

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

value from it , send the color to Arduino with RGB LED This is not to

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

Bionic Arduino Introduction to Microcontrollers with Arduino Class 4 20 Nov 2007 - machineproject - Tod

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

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

compile

Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”
Recap: Blinky LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink”

upload

blink blink
blink blink
LED Make sure things still work compile upload blink blink Load “File/Sketchbook/Examples/Digital/Blink” TX/RX

Load “File/Sketchbook/Examples/Digital/Blink”

TX/RX flash

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

PWM

Output voltage is averaged from on vs. off time

output_voltage = (on_time / off_time) * max_voltage

5

0

5

0

5

0

volts

volts

volts

volts

volts

volts

max_voltage 5 0 5 0 5 0 volts volts volts volts volts volts 75% 25% 75%
max_voltage 5 0 5 0 5 0 volts volts volts volts volts volts 75% 25% 75%
75% 25% 75% 25% 75% 25% 50% 50% 50% 50% 50% 50%
75%
25%
75%
25%
75%
25%
50%
50%
50%
50%
50%
50%
75% 25% 75% 25% 75% 25% 50% 50% 50% 50% 50% 50% 20% 80% 20% 80%
75% 25% 75% 25% 75% 25% 50% 50% 50% 50% 50% 50% 20% 80% 20% 80%
75% 25% 75% 25% 75% 25% 50% 50% 50% 50% 50% 50% 20% 80% 20% 80%
75% 25% 75% 25% 75% 25% 50% 50% 50% 50% 50% 50% 20% 80% 20% 80%

20%

80%

20%

80%

20%

80%

3.75 Volts

2.5

Volts

1.0

Volts

PWM

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)

height

You experienced a few applications of PWM already.

width

period
period

Servomotors

Can be positioned

from 0-180º

(usually)

Internal feedback circuitry & gearing takes care of the hard stuff

Easy three-wire PWM 5V interface

of the hard stuff • Easy three-wire PWM 5V interface More specifically, these are R/C hobby

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

motor • All built in, you just feed it a PWM signal With these little blue

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 motion

Can turn rotation into linear movement with clever mechanical levers

Even clothes use servos now: http://www.technologyreview.com/read_article.aspx?id=17639&ch=infotech

Servos

Come in all sizes

from super-tiny

to drive-your-car

But all have the same 3-wire interface

Servos are spec’d by:

weight: 9g speed: .12s/60deg @ 6V torque: 22oz/1.5kg @ 6V voltage: 4.6~6V size: 21x11x28 mm

http://rctoys.com/

http://hobbypeople.net/

9g

157g
157g

Servo Mounts & Linkages

Lots of ways to mount a servo

And turn its rotational motion into other types of motion

mounting bracket: http://www.sierragiant.com/prod28.html

servo And turn its rotational motion into other types of motion mounting bracket: http://www.sierragiant.com/prod28.html
servo And turn its rotational motion into other types of motion mounting bracket: http://www.sierragiant.com/prod28.html

180º

Servo Control

180º Servo Control Ground (0V) Power (+5V) Control (PWM) • PWM freq is 50 Hz (i.e.
180º Servo Control Ground (0V) Power (+5V) Control (PWM) • PWM freq is 50 Hz (i.e.

Ground (0V) Power (+5V) Control (PWM)

180º Servo Control Ground (0V) Power (+5V) Control (PWM) • PWM freq is 50 Hz (i.e.

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

Servo Movement 0 degrees 1000 microsecs 90 degrees 1500 microsecs 180 degrees 2000 microsecs In practice,

1000 microsecs

90 degrees

Servo Movement 0 degrees 1000 microsecs 90 degrees 1500 microsecs 180 degrees 2000 microsecs In practice,

1500 microsecs

180 degrees

degrees 1000 microsecs 90 degrees 1500 microsecs 180 degrees 2000 microsecs In practice, pulse range can

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
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
Plug power
wires in
Plug control wire
to digital pin 7

Moving a Servo

Moving a Servo “ServoSimple” Move the servo across its range of motion Uses delayMicroseconds() for pulse

“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

“ServoSerialSimple”

Drive the servo by pressing number keys

Takes the last servo example and adds our standard serial input to it.

last servo example and adds our standard serial input to it. Sketch is in the handout.

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

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 demo% printf "5" > $PORT demo% printf "9" > $PORT

# rotate servo left # go to middle # 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
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

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

“ServoSerialBetter”

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

the right time Uses “ millis() ” to know what time it is Sketch is in

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 though

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 PWM why all the software, doesn’t Arduino have PWM? • Arduino has built-in 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

PWM circuits of the ATmega8 chip -» no software needed The PWM speed used for analogWrite()

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 RX Device A Device B RX TX
TX
RX
Device A
Device B
RX
TX

asynchronous – no clock Data represented by setting HIGH/LOW at given times

Separate wires for transmit & receive

Each device must have good “rhythm”

Synchronous communication

clock data A->B Device A Device B data B->A
clock
data A->B
Device A
Device B
data B->A

Synchronous – with clock Data represented by setting HIGH/LOW when “clock” changes

A single clock wire & data wire for each direction like before

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 Master device SDA data
SCK
clock
Master
device
SDA
data
Peripheral device 1
Peripheral
device 1
Peripheral device 2
Peripheral
device 2

• • •

Peripheral device N
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

Many I2C devices non-volatile memory touch sensor compass temperature & humidity sensor fm transmitter LCD display

non-volatile memory

touch sensor
touch sensor
Many I2C devices non-volatile memory touch sensor compass temperature & humidity sensor fm transmitter LCD display

compass

Many I2C devices non-volatile memory touch sensor compass temperature & humidity sensor fm transmitter LCD display

temperature & humidity sensor

fm transmitter

compass temperature & humidity sensor fm transmitter LCD display And many others (gyros,keyboards, motors, )

LCD display

And many others

(gyros,keyboards, motors, )

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

Obligatory BlinkM Promo

I2C Smart LED

Obligatory BlinkM Promo I2C Smart LED Does all the hard PWM & waveform generation for you

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

with 8-bit A/D converter • 2 buttons • $20 If you look at the architecture for

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.

Accelerometer?

Measures acceleration (changes in speed)

Like when the car pushes you into the seat

Gravity is acceleration

So, also measures tilt

the seat • Gravity is acceleration • So, also measures tilt h o r i z

horizontal

tilt right tilt left
tilt right
tilt left

Nunchuck Accelerometer

Nunchuck Accelerometer Z X Y Wii Remote & Nunchuck accelerometer axes I’m not sure if I
Nunchuck Accelerometer Z X Y Wii Remote & Nunchuck accelerometer axes I’m not sure if I

Z

X

Nunchuck Accelerometer Z X Y Wii Remote & Nunchuck accelerometer axes I’m not sure if I
Y
Y

Wii Remote & Nunchuck accelerometer axes

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

Wiimote axis image from http://www.wiili.org/index.php/Wiimote

I2C on Arduino

SDA SCK
SDA
SCK

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)

Writing Data Load Wire library Join I2C bus (as master) Start sending Send data Stop sending
Writing Data Load Wire library Join I2C bus (as master) Start sending Send data Stop sending

Start sending

Send data Stop sending

I2C bus (as master) Start sending Send data Stop sending And what the various commands do
I2C bus (as master) Start sending Send data Stop sending And what the various commands do
I2C bus (as master) Start sending Send data Stop sending And what the various commands do
I2C bus (as master) Start sending Send data Stop sending And what the various commands do

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)

“Wire” library Reading Data Join I2C bus (as master) Request data from device Get data What

Request data from device

Data Join I2C bus (as master) Request data from device Get data What kinds of interactions

Get data

Join I2C bus (as master) Request data from device Get data What kinds of interactions you
Join I2C bus (as master) Request data from device Get data What kinds of interactions you

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