bionic arduino class

Post on 18-Nov-2014

3.278 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

All the *.PDE archives code are in this URL shared:http://www.4shared.com/file/196000558/ca6624de/bionicarduino-sketches.html

TRANSCRIPT

Bionic Arduino

Introduction to Microcontrollers with Arduino

Class 1

11 Nov 2007 - machineproject - Tod E. Kurt

Class Info• Thumbdrive is being passed around, with:

• PDF version of these notes

• Arduino software for Mac OS X & Windows

• Source code (“sketches”) used in class

• Copy files off, then pass thumbdrive around

• Sunday classes: 3 hours

• two ~1.5 hour chunks, w/ 15 min. break in middle

• Tuesday classes: ~2.5 hours

• with some review at the beginning

What’s for Today

• Introduction to Arduino

• Setting up your Arduino Environment

• Your first Arduino sketch

• Basic digital & analog output control

• Basic digital sensor inputs

• Making LEDs glow and blink on command

• How to read buttons & switches

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 2 comes next weekA 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• 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

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

Setup and “light & sound”

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 pieceof hardware

A programmingenvironment

A community& philosophy

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

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

USB

“Stamp”-sized

Bluetooth

LilyPad(for clothing)

DIY

many different variations to suite your needs

Boarduino Kit

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

2.7”

2”

resetbutton

powerLED

digital input/output “pins”

analog input “pins”

test LEDon “pin” 13

TX/RXLEDs ATmega168

USB interface

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

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)

The Steps

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

Use “Extract All...”

On Windows, right-click

• Find the “drivers” directory inside

Plug in Arduino boardquick blink

from test LED

Power LED should stay on

Mac Driver Install

• v2_1_6 for PPC Macs

• v2_2_6 for Intel Macs

Double-click on .dmg Installer

Windows Driver Install

Selecting Location & Type

usually highest-numbered port

pick “Diecimila”

Selecting Location & Type

pick “Diecimila”

starts with tty.usbserial-

Arduino Software

compile(verify)

statusarea

upload to board

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!

blink blink

compile

upload

sketch runs

TX/RX flash

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

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

Status Messages

Uploading worked

Wrong serial port selected

Wrong board selected

Size depends oncomplexity of your sketch

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

compile upload runedit 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

• Running

• loop() – run repeatedly, after setup()

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

Making Circuits

heart pumps, blood flows voltage pushes, current flows

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

Example: LED flashlight

wiring diagram schematic wiring it up

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

current flow

9V

+

LED

resistor500 ohm(green,brown,brown)

(flat part)

500

All LED circuits are essentially this: power source, current limiter, LEDFlat part of LED goes to negative, like bar in schematicThe higher the resistance, the dimmer the LED; the lower, the brighterYou don’t have to wire this up, but the following circuits are just the same

The Circuit for LED Blink

LED

resistor220 ohm(red,red,brown)

flat part

wiring diagram

Arduinoboard

gnd

pin 13

gnd

resistor

LED

schematic

“hello world” of microcontrollers

Arduino Diecimila board has this circuit built-inTo 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

LED

resistor

On LEDs, polarity matters.Shorter lead is “negative” side, goes to ground

Polarity doesn’t matter on resistors

Flat edge here for neg. side

Varying LED Brightness

wiring diagramschematic wired up

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

To turn LED to half-bright, use analogWrite(9,128)

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

resistor220 ohm(red,red,brown)

fla

t p

artArduino

board

gnd

pin 9

gnd

resistor

LED

where “value” ranges between 0 and 255.

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

Arduinoboard

gnd

pin 9

gnd

resistor

LED

Going from schematic to physical circuit.

Solderless Breadboards

notconnected

All connected, a “bus”

numbers & letter labels

just for reference groups of 5

connected

Insert wires into holes to make a connection.*Much* easier, quicker than solderingBut, they wear out, are kind of expensive ($5 for this one, at that was a bargain)

Useful ToolsWire cutters

Needle-nosepliers

Wire stripper

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 Wireswire stripperpliers & cutter

~1/4”

About 1/4” for the stripped parts. And as long as you need for your circuit.

Using Solderless Breadboards

Using needle nose pliers can helppush wires & components into holes

Grab wire or lead toward end and push into hole

All Wired Up

plugged into “ground” bus

Alternate Way

1. rubber band

Or, adding a breadboard to Arduino for 1¢

2. power & gnd wires3. plug into “bus” terminals

4. jumper overto other side

now circuit has power & groundThis 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” SketchLoad “File/Sketchbook/Examples/Analog/Fading”

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

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

note

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

knife switch toggle switch(SPST) (SPDT)

Switches make or break a connection

Many sensors are variations on switches

Fundamentally, they’re all like the simple knife switchSingle pole = only one circuit is being controlledDouble pole = two circuits are being controlled at onceSingle throw = only one path for circuitDouble throw = two potential paths for circuit

Many Kinds of Switches

magnetic tilt leverhexidecimalTilt 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?

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 HIGHNot pressed is LOW

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

Wiring it up

Let’s plug it into pin 2You 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

Now you control the blinking

Load “Sketchbook/Examples/Digital/Button”

(How would you change it to blink the external LED you wired up?)Press to turn off, release to turn on.Notice it blinks the LED on-board the Arduino.Change the code to make it blink the pin 9 LED.

Using Switches to Make Decisions

• Often you’ll want to choose between actions, based on how a switch-like sensor

• E.g. “If person is detected, fire super soaker”

• E.g. “If flower pot soil is dry, turn on sprinklers”

• Define actions, choose them from sensor inputs

• Let’s try that with the actions we currently know

FadeOrBlinkLoad “FadeOrBlink” sketch from the handout

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

the button

Schematic is same as for “Fading” sketch

Battery Power

• 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

plug into

Vin & Gnd

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

Battery Power

• Plugging into the sockets is kind of fiddly

• Better to plug into the power jack

• Works great, but requires a little soldering

set to EXT

Center of jack is

positive

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

Tod E. Kurt

tod@todbot.com

END Class 1

http://todbot.com/blog/bionicarduino/

Feel free to email me if you have any questions.

Resourceshttp://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.

blink blink

compile

upload

sketch runs

TX/RX flashLoad “File/Sketchbook/Examples/Digital/Blink”

Recap: Blinky LEDMake sure things still work

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

wire up pin 9 LED too

Arduinoboard

gnd

pin 9

gnd

resistor

LED

schematic

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“CandleLight”

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 InputTo computers, analog is chunky

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

Analog Input

• Many states, not just two (HIGH/LOW)

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

• Common computer resolutions:

• 8-bit = 256 values

• 16-bit = 65,536 values

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

Analog Input

• Arduino (ATmega168) has six ADC inputs

• (ADC = Analog to Digital Converter)

• Reads voltage between 0 to 5 volts

• Resolution is 10-bit (1024 values)

• In other words, 5/1024 = 4.8 mV smallest voltage change you can measure

Analog InputSure sure, but how to make a varying voltage?

With a potentiometer. Or just pot.

+5V–measure–

gnd–

50k

The pot you have

pots also look like this

PotentiometersMoving the knob is like moving

where the arrow taps the voltage on the resistor

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

If you take apart a pot, there’s a little wiper just like in the schematic symbol.But I might have the directions reversed (clockwise vs. anti-clockwise).

What good are pots?

• Anytime you need a ranged input

• (we’re used to knobs)

• Measure rotational position

• steering wheel, robotic joint, etc.

• But more importantly for us, potentiometers are a good example of a resistive sensor

There are many kinds of resistive sensors

Arduino Analog Input

Two “legs” plug into +5V & Gnd(red + & blue -) buses

Middle “post” plugs into a row (row 7 here)

Run a wire from that row to Analog In 2

Plug pot directly into breadboard

Why are we using Analog In 2? Because it’s in the middle. There’s no reason, any of the 6 analog inputs would work the same.

Pot & LED Circuit

In schematics, inputs are usually on the left, outputs on the rightAlso, more positive voltages are on the top, more negative on the bottom

Arduinoboard

gnd

pin 2

+5V

+5V

gnd

50kpotentiometer

pin 9

LED

resistor220 (red-red-brown)

gnd

This is what your board should have on it now

Varying Brightness by Hand“PotDimmer”

Turn the knob to change LED brightness

process the input data

input

output

Most all embedded systems have a

input→process→output loop

Sketch available in handout

Two Ways toHook up LEDs

Arduinoboard

gnd

pin 9

gnd

resistor

LED

Arduinoboard

gnd

pin 9

resistor

LED

+5V+5V

To turn ON: digitalWrite(9,HIGH)

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

To turn ON: digitalWrite(9,LOW)

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

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.

RGB LEDsNormal LED

RGB LED

cathode –anode +

red cathode –

green cathode –

anode +blue cathode –

anode +

cathode –

anode +

bluered green

actually 3 LEDs in one package

RGB LED, aka “tri-color LED”Common-anode RGB LEDs are much more available than common-cathode.This is why we’re changing around the logic.

Color Mixing

Arduinoboard

pin 11

gnd

pin 10

pin 9220 (red,red,brown)

redgreen blue

+5V

common anode

RGB LED

With RGB you can make any color

(except black)

With just 3 LEDs you can make any* color

Mixing light is the additive color model(paint is subtractive color, and can give you brown)

*besides the additive/substractive color 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

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

Arduinoboard

pin 11

gnd

pin 10

pin 9220 (red,red,brown)

redgreen blue

+5V

common anode

RGB LED

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

Arduinoboard

pin 11

gnd

pin 10

pin 9220 (red,red,brown)

redgreen blue

+5V

common anode

RGB LED

pin 2

+5V

gnd

50kpot

Pot-controlled RGB

“RGBPotMixer”

Use the pot from before to control

the color mix

The code turns the single ranged input value into “sectors” where

each sector is a color

Also see “RGBPotMixer2” for a variation.How would you change it to adjust brightness?

Sensing the Dark• Pots are example of a voltage divider

• Voltage divider splits a voltage in two

• Same as two resistors, but you can vary them

Sensing the Dark: Photocells

• aka. photoresistor, light-dependent resistor

• A variable resistor

• Brighter light == lower resistance

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

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

Photocell Circuit

pin A2

gnd

brown-black-orange

Try it with RGBPotMixer from before

Looks a lot like the pot circuit, 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

thermistor(temperature)

flex sensor(bend, deflection)

photocell(light)

force sensors(pressure)

also air pressure and others

+5V

sensor

resistor

to analog input

circuit is the samefor all these

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

Communicatingwith Others

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

• Talking to other devices uses the “Serial” commands

• Serial.begin() – prepare to use serial

• Serial.print() – send data to computer

• Serial.read() – read data from computer

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

Watch the TX/RX LEDS

• TX – sending to PC

• RX – receiving from PC

• Used when programming or communicating

Arduino Says “Hi”“SerialHelloWorld”

Sends “Hello world!” to your computer

Click on “Serial Monitor” button to

see output

Watch TX LED compared to pin 13 LED

This sketch is located in the handout, but it’s pretty short.Use on-board pin 13 LED, no need to wire anything up.

Telling Arduino What To Do“SerialReadBasic”

You type “H”, LED blinks

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

Serial.available() tells you if data present to read

This sketch is in the handoutAlways 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

• 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

is just serial communications

Serial Communications• “Serial” because data is broken down into bits, each

sent one after the other down a single wire.

• The single ASCII character ‘B’ is sent as:

‘B’ = 0 1 0 0 0 0 1 0 = L H L L L L H L

=LOW

HIGH

• Toggle a pin to send data, just like blinking an LED

• You could implement sending serial data with digitalWrite() and delay()

• A single data wire needed to send data. One other to receive.

Note, a single data wire. You still need a ground wire.

Arduino & USB-to-serial

USB to serial

Arduino

microcontroller

Arduino board is really two circuits

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

Arduino MiniArduino Mini separates the two circuits

Arduino Mini Arduino Mini USB adapter

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

Arduino to ComputerArduino boardLaptop

USB to serialArduino

microcontroller

USB to serial

driver

Arduino

programmer

Processing

sketch

Java program

RX

TX

-OR-

-OR-

-OR-

...

USBTX

RXchip

USB is totally optional for ArduinoBut 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:

Controlling the Computer

In Arduino: read sensor, send data as byte

In Processing: read the byte, do something with it

You write one program on Arduino, one on the computer

But writing Processing programs is for later

• Receiving program on the computer can be in any language that knows about serial ports

• C/C++, Perl, PHP, Java, Max/MSP, Python, Visual Basic, etc.

• Pick your favorite one, write some code for Arduino to control

Controlling the Computer

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

Controlling Arduino, Again“SerialReadBlink”

Most control issues are data conversion issues

Type a number 1-9 and LED blinks that

many times

Converts typed ASCII value into usable number

This sketch is also in the handout

Serial-controlled RGB“SerialRGBLED”

Send color commands to Arduino

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

g50

Sketch parses what you type, changes LEDs

This sketch is in the handout.Color command is two parts: colorCode and colorValuecolorCode 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

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

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

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

Arduinoboard

pin 7

gnd

+

piezobuzzer

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 QuieterEasiest way: add a resistor

(brown,

black,

orange)

Arduinoboard

pin 7

gnd

+

piezobuzzer

10k

Arduinoboard

pin 7

gnd

+

piezobuzzer

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

Leon Theremin

No touching needed!

We’ll use light in lieu of RF

As heard on Star Trek, Beach Boys, horror movies, Mars Attacks!, and bad New Age songs.Works sorta like those touch switches, but no touching here.That is, your body becomes a variable capacitor.

Light Theremin

“Theremin”

Move hand over photocell to change pitch

Play with val processing & cycles count to alter sensitivity, pitch and timbre

Okay so maybe it sounds more like a bad video game than a spooky movieThe glitchy sound is cause because of the time it takes to read the sensorThere are ways around such stuff, but requires more complex programming using timers & interruptsThe sound can get annoying quick

Other Serial Devices

to Wi-Fi to Ethernet to graphic LCDto 8-servo controller

Lantronix Wi-Port and Lantronix Xport http://lantronix.com/Seetron Serial Graphic display and Mini SSC http://www.seetron.com/slcds.htm http://www.seetron.com/ssc.htm

Serial Examples

to Roomba

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

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

Ambient Orb doesn’t connect to computer though. Uses the pager network.Ambient Devices: http://www.ambientdevices.com/

Tod E. Kurt

tod@todbot.com

END Class 2

http://todbot.com/blog/bionicarduino/

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.

blink blink

compile

upload

sketch runs

TX/RX flashLoad “File/Sketchbook/Examples/Digital/Blink”

Recap: Blinky LEDMake sure things still work

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

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

• Several 500 ohm resistors (green-brown-brown)

• Couple of popsicle sticks

• Colorful pipe cleaners

“motors & motion”

DC Motors

come in all shapes and sizes

You probably have 3-4 on you right now

(cell vibrate, laptop fan, laptop dvd drive)

the two motorsin 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

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

A dizzying array of parameters specify a motor

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

MDC motorbattery

polarity determines which way it rotates

To drive them, apply a voltageThe higher the voltage, the faster the spinning

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

M

DC motor

LED

Just as voltage causes rotation...

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

Transistors

TIP120

TIP120

base

collector emitter

base

collector

emitter

Act like switches

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

schematic symbol

electricity flicks the switch instead of your finger

collector

emitter

base

how it kind of works

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

M

DC motor

transistorresistor

battery

+ switch

M

DC motor

transistorresistor

+ switch

+

+

+

big powersource

transistors switch big signals with little signals

little motor big motor

switching a different power source

Need a “Kickback” Diode

M

DC motor

transistorresistor

battery

+ switch

diode

schematic symbol

line

since motors can act like generators,need to prevent them from generating “kickback” into the circuit

diode

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

Arduinoboard

gnd

pin 9

+5V

+5V

M

DC motor

TIP120500

1N4001

(green-brown-brown)

Can control speed of motor with analogWrite() just like controlling brightness of LED

start with the tiny motorb c e

b c

e

motor

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 Circuittransistor turned around to make wiring easier

white diode line into +5V motor across diode

Arduinoboard

gnd

pin 9

+5V

+5V

M

DC motor

TIP120500

1N4001

(green-brown-brown)

e bc

b c

e

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?

Controlling a Bigger Motor

Arduinoboard

gnd

pin 9

+5V

+5V

M

DC motor

TIP120500

1N4001

(green-brown-brown)

+9V battery

Same circuit as before, different voltage source

Motor will spin faster for a given analogWrite() value

9V battery

motor w/ tape propellor

desk ding from motor getting loose

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

tape propellerpipe cleaner squigglerpopsicle stick beater

I’m terrible at mechanical engineering. If anyone has good ways of mounting things to motors, let me know. :-)

Wiring Up Bigger Motor

Don’t just add 9V to +5v bus!Move the diode from +5 to another rowAdd 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*

Arduinoboard

pin 7

gnd

1k

TIP120

1N4004

+5V

to load

5V relay

Just on/off, and a relay needs a diode too

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

Super bright LED light

Arduinoboard

gnd

pin 9

+12V+5V

TIP1201k

red LEDs

120

Relay switcher

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

Full brightness control with PWM

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

• 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

piezo input schematic

Arduinoboard

analog pin 2

gnd

+

piezobuzzer

1M

(brown,

black,

green)

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 SensorArduinoboard

analog pin 2

gnd

+

piezobuzzer

1M

(brown,

black,

green)

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?

volts

time

piezo output voltage

whack!

threshold

t

• 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

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 SensorsCan mount the element on anything

(under rugs, floor mat, door, your body, etc.)

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

You can get bare piezo buzzers (not in a black plastic enclosure) that you can mount on whatever you want.

Could make a MIDI Trigger

Uses piezos & buttons to send MIDI messages

Can trigger drum sounds or arbitrary sound samples

MIDIoutput

buttons

piezos

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

Or Trigger Actuators

Arduinoboard

analog pin 2

gnd

+

piezobuzzer

1M

(brown,

black,

green)

pin 9

+5V

M

DC motor

TIP120500

1N4001

(green,

brown,

brown)

If you still have your motor wired up

“PiezoMotorPulse”

Take a Break

Getting the Board Set Up

Wire up the potentiometer like from last week

Arduinoboard

gnd

pin 2

+5V

+5V

gnd

50kpot

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

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

• setup() – set up sketch, like size, framerate

• draw() – like loop(), called repeatedly

• Other functions can exist when using libraries

Processing & Arduino

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

serial communications

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 Serialcommon Processing serial use

be sure to set to the same as “Serial Port” in Arduino GUI

1.

2.

3.

4.

four steps1. load library2. set portname3. open port4. read/write port

All you need to do talk to Arduino in Processing.The import statement says you want to do serial stuff.The “new Serial” creates a serial port object within ProcessingThen 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

You can have 6 knobs totalbecause there are 6 Analog In pins

(BYTEs are easier to parse in Processing than other formats)

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

Processing + Arduino“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

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

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.

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 LibrariesUnzip, drop into “libraries” folder

drag

unzip open

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

Processing to Arduino“http_rgb_led”

Fetch a web page,get a color value from it, send the color to

Arduino with RGB LED

real quick

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

Tod E. Kurt

tod@todbot.com

END Class 3

http://todbot.com/blog/bionicarduino/

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

blink blink

compile

upload

sketch runs

TX/RX flashLoad “File/Sketchbook/Examples/Digital/Blink”

Recap: Blinky LEDMake sure things still work

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

0 volts

5 volts

50% 50% 50% 50% 50%

2.5 Volts

0 volts

5 volts

20% 80%

1.0 Volts

50%

20% 80% 20% 80%

0 volts

5 volts

75% 25%

3.75 Volts

75% 25% 75% 25%

output_voltage = (on_time / off_time) * max_voltage

Output voltage is averaged from on vs. off time

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)

width

period

height

You experienced a few applications of PWM already.

Servomotors

• Can be positioned from 0-180º

• Internal feedback circuitry & gearing takes care of the hard stuff

• Easy three-wire PWM 5V interface

(usually)

More specifically, these are R/C hobby servos used by remote control enthusiastsIn 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

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

9g

weight: 9gspeed: .12s/60deg @ 6V

torque: 22oz/1.5kg @ 6Vvoltage: 4.6~6V

size: 21x11x28 mm

http://rctoys.com/http://hobbypeople.net/

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 Control

180º Power (+5V)Ground (0V)

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 ArduinoFirst, 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 control wire to digital pin 7

Plug powerwires in

Moving a Servo

Move the servo acrossits range of motion

“ServoSimple”

Uses delayMicroseconds() for pulse width

Uses delay() for pulse frequency

Sketch is in the handoutCreated a custom function to handle making servo pulsesNew 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

Takes the last servo example and adds our

standard serial input to it.

Drive the servo by pressing

number keys

“ServoSerialSimple”

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-A3000Xv0demo% stty -f $PORT 9600 raw -parenb -parodd cs8 -hupcl -cstopb clocal demo% printf "1" > $PORT # rotate servo left demo% printf "5" > $PORT # go to middledemo% 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

• Servo isn’t given periodic pulses to keep it at position

• You need to run two different “tasks”:

• one to read the serial port

• one to drive the servo

If a servo is not being constantly told what to do, it goes slack and doesn’t lift/push/pull

Better Serial Servo

Works just like ServoSerialSimple

(but better)

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

Update the servo when needed, not just when called at the right time

“ServoSerialBetter”

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”

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

The concept inside updateServo() is useful anytime you need to do multiple “things

at once” in an Arduino sketch:

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 longThis is called “cooperative multitasking”, and it’s how OSs in the 80s worked.

Arduino 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

why all the software, doesn’t Arduino have PWM?

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

Separate wires for transmit & receive

Asynchronous communication

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

Synchronous communication

Synchronous – with clockData represented by setting

HIGH/LOW when “clock” changes

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

Device A Device B

TX

RX

RX

TX

Device A Device B

clockdata A->Bdata B->A

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”

Masterdevice

Peripheral device 1

Peripheral device 2

Peripheral device N

• • •

dataSDA

clockSCK

Synchronous serial bus with shared a data line

• 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

a little network for your gadgets

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 thatAnd if your microcontroller doesn’t have I2C hardware built-in, you can fake it by hand in software (for master devices anyway)

Many I2C devices

touch sensor compass

fm transmitter

non-volatile memory

LCD displaytemperature & humidity sensor

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

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

Obligatory BlinkM PromoI2C Smart LED

Does all the hard PWM & waveform generation for youYou 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/Nunchukand: http://www.windmeadow.com/node/42and: 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

horizontal tilt right tilt left

Nunchuck Accelerometer

XZ

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

• 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

SDA

SCK

Arduino “Wire” libraryWriting Data

Start sending

Join I2C bus(as master)

Send data

Load Wire library

Stop sending

And what the various commands do are documented in the instructions / datasheet for a particular device.

Arduino “Wire” libraryReading Data

Request data from device

Join I2C bus(as master)

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 NunchuckWe could hack off the connector

and use the wires directly

But instead let’s use this little adapter board

Wii Nunchuck Adapter

SCK GND

+V SDAn/c

n/c

Nunchuck Pinout

(looking into Nunchuck connector)

Adapter Pinout

+V SCK

SDAGND

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

Wiring it Up

GND SDA+5V SCK

SDA (pin 4)

SCK (pin5)

Pluggin’ in the ‘chuck

Trying the Nunchuck“NunchuckPrint”

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

XZ

Y

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

Adding a Servo

Move the servo by moving your arm

“NunchuckServo”

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 multi-axis robot arm

• Make a “servo recorder” to records your arm movements to servo positions and plays them back

• Great for holiday animatronics

Going Further

• I2C devices

• Try out some other devices

• Just string them on the same two wires used for the Nunchuck

• Cooperative Multitasking

• Try making a theremin with nunchuck & piezo

• See if previous examples can be made more responsive

Going Further

• Nunchuck

• It’s a freespace motion sensor. Control anything like you’re waving a magic wand!

• What about the joystick? We didn’t even get a chance to play with that

• Alternative input device to your computer: control Processing, etc.

SummaryYou’ve learned many different physical building blocks

LEDs

switches/buttonsresistive sensors

motors

piezos

servos

XZ

Y

accelerometers

SummaryAnd you’ve learned many software building blocks

pulse width modulation

serial communication

digital I/O

analog I/O

data driven code

frequency modulation

multiple tasks

I2C

Summary

Hope you had fun and continue playing with Arduino

Feel free to contact me to chat about this stuff

Tod E. Kurt

tod@todbot.com

END Class 4

http://todbot.com/blog/bionicarduino/

Feel free to email me if you have any questions.

top related