Sunteți pe pagina 1din 119

Introduction to Arduino and Electronics

Class 1/4

7 April 2013 - John Duksta


Giving Credit

This courseware is a mashup of my own


content,Tod E. Kurt’s Bionic Arduino course,
taught at Machine Project in LA, Lutz Hamel’s
Intro to Arduino course taught at AS220 Labs
in Providence and the Adafruit Arduino
Tutorials by Simon Monk.
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
• Class will run 3 - 4 hours each session
• some review at the beginning of each class
What’s for Today
• Introduction to Arduino
• Setting up your Arduino Environment
• Your first Arduino sketch
• Basic digital input and output
• Basic digital sensor inputs
• Making LEDs glow and blink on command
• How to read buttons & switches
ARDX Kit Contents
• Arduino Uno board • 2 Pushbuttons
• Solderless breadboard • 10K Potentiometer
• Acrylic Mount • Photo Resistor
• USB cable • Temperature Sensor
• Jumper wires • 5V Relay
• 9V Battery clip • 2 Transistors
• 1 RGB LED • Resistors
• 10 Red LEDs • 560 Ohm x25 (green, blue,
• 10 Green LEDs brown)
• 1 Blue LED • 2.2k Ohm x3 (red, red, red)
• DC Motor • 10k Ohm x3 (brown, black,
orange)
• Mini Servo
• 2 Diodes
• 74HC595 Shift Register
• Piezo Element
Extra Bits for Fun

• Wii Nunchuck Adapter


• H-Bridge Chip
• Nokia 5110 LCD Display
A Word on Safety
• Electronics can hurt you
• There may be lead in some of the parts
• Wash up afterwards
• You can hurt electronics
• Static-sensitive: don’t shuffle your feet &
touch
• Wires only bend so much
What is Arduino?
The word “Arduino” can mean 3 things

A physical piece A programming A community


of hardware environment & philosophy
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 ATmega328 microcontroller chip


• chip was designed to be used with C language
Arduino Uno R3 Overview
test LED
on pin 13 digital input/output “pins”
reset power
button LED

USB

2”
TX/RX
LEDs ATmega328

power pins
2.7” analog input pins
Arduino Capabilities
• 32 KB of Flash program memory

• 2 KB of RAM

• 16 MHz Clock (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
Arduino Hardware Variety
LilyPad
DIY
(for clothing)
USB

Boarduino Kit

“Stamp”-sized

Bluetooth
many different variations to suite your needs
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
• Integrated Development
Environment

• View/write/edit sketches

• Then you compile and


program them onto the
hardware
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-1.0.4-window.zip” for Windows
• “arduino-1.0.4-macosx.zip” for Mac OS X
• Unzip the zip file. Double-click on Mac
On Windows, right-click
Use “Extract All...”

• Find the “drivers” directory inside


Plug in Arduino board
quick blink
from test LED

Power LED should stay on


Windows Driver Install
Selecting Location & Type

usually highest-
numbered port

pick “Arduino
Uno”
Selecting Location & Type

starts with
tty.usbserial-

pick “Arduino
Uno”
Arduino Software

compile upload to board


(verify)

status
area
Load Blink Example
• File → Examples → 01.Basics → Blink
Save a copy

• The examples are read-only


• File → Save As...
• MyBlink
Compile and Upload
• Write your sketch

• Press Compile button


(to check for errors) compile

• Press Upload button to program


Arduino board with your sketch
upload

TX/RX flash

l i n k
b k
l i n
b sketch runs
Status Messages
Size depends on
complexity of your sketch

Uploading worked

Wrong serial port selected

Wrong board selected

nerdy cryptic error messages


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!
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 later
• Arduino has up to 13 digital outputs, and
you easily can add more with helper chips
Lots of Built-in Examples

And more here:


http://www.arduino.cc/en/Tutorial/HomePage
Comments
• Makes your code readable
• Notes for yourself
• Single line -
// Don’t change this variable
• Multiline -
/* this is awesome
I can leave notes for myself
*/
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Variables

• Variables hold data for you


• Numbers
• Letters
• Strings
Data types
• Usual C data types are available
• int – integer (-3, 0, 1, 3234, etc)
• float – a floating point number (4.21)
• char – a character (“a”, “b”, “Z”, “?”)
• array – a collection of a variable type
• string – an array of char
• Arduino Datatypes
• boolean – true or false
• String – the String Object (note the capital S)
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Constants
• Like variables, but they don’t change
• Convention is to use ALLCAPS
• Built-in constants
• HIGH, LOW (pin status)
• INPUT, OUTPUT, INPUT_PULLUP (pin
config)
• true, false (breaks the ALLCAPS
convention)
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Arduino Functions
• Language is standard C/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.
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Sketch structure

• Declare variables at top


• Initialize
• setup() – run once at beginning, set pins
• Running
• loop() – run repeatedly, after setup()
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Sketch structure

• Declare variables at top


• Initialize
• setup() – run once at beginning, set pins
• Running
• loop() – run repeatedly, after setup()
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Sketch structure

• Declare variables at top


• Initialize
• setup() – run once at beginning, set pins
• Running
• loop() – run repeatedly, after setup()
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 13 has an LED connected on most Arduino boards.


// give it a name:
int led = 13;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
Blink Faster
• Change the delay parameter from 1000 to 500

• Compile and Upload


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

All connected,
a “bus”
not
connected
Useful Tools
Wire stripper Wire cutters

Needle-nose
pliers
Making Jumper Wires
pliers & cutter wire stripper

~1/4”
Using Solderless
Breadboards
Using needle nose pliers can help
push wires & components into holes
Making Circuits

heart pumps, blood flows voltage pushes, current flows


Example: LED flashlight
current flow

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

LED

(flat part)

wiring diagram schematic wiring it up

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


Basic Electronics Flash Light

Voltage Load
Source

Our Blink Circuit


Basic Electronics
• The dreaded short circuit:

• this is a circuit with a load equal to


Current = ∞ zero

• this allows “infinite” current to flow


from the positive terminal of the
Voltage voltage source to the negative
Load = 0 terminal
Source
• it will break stuff!

• Always check your circuits carefully


before applying power

• Never connect an Arduino output pin


directly to ground, always use a load
resistor
Basic Electronics
Some Electronic Symbols

Image source: Engineer's Mini Notebook, Mims III, Master Publishining, 2007.
LEDs & Resistors

On LEDs, polarity matters.


Shorter lead is negative (cathode) side, goes to ground

LED
Flat edge here for neg. side

resistor
Resistors have no polarity
Current Limiting
Resistors

• Too much current can burn out an LED


• Adding a resistor restricts current flow
• 220Ω to 1kΩ are usually fine
• http://ledcalc.com/
The Circuit for LED Blink
“hello world” of microcontrollers

wiring diagram schematic


Arduino board has this circuit built-in
To turn on LED use digitalWrite(13,HIGH)
PWM Signals
• Pulse Width Modulated (PWM) Signals
• μCs cannot generate analog output, but we
can fake it by creating digital signals with
different “duty cycles” - signals with different
pulse widths.
• To the analog world the different duty cycles
create different effective voltages
• analogWrite(pin, value)
PWM Signals
Effective Duty Cycle
Voltage

Effective Duty Cycle


Voltage

Effective Duty Cycle


Voltage
Varying LED Brightness
Same circuit as Blink circuit but pin 9 instead of pin 13

schematic wiring diagram


The PWM pins work with the “analogWrite(pin,value)” command
where “value” ranges between 0 and 255.
To turn LED to half-bright, use analogWrite(9,128)
All Wired Up
plugged into “ground” bus
LED “Fading” Sketch
Load “File/Examples/Analog/Fading”

note

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


Reduce “delay()” values to make it go faster
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
For loops
• A type of iterative control
• Generally used to do the same thing over a
range of values
for(int i = 0; i <= 100; i += 1)
{
// Do something with i
}
/*
Fading

This example shows how to fade an LED using the analogWrite() function.

*/

int ledPin = 9; // LED connected to digital pin 9

void setup() {
// nothing happens in setup
}

void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 255 to 0):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 255 to 0):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 255 to 0):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 255 to 0):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 255 to 0):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
Aside: LED Light Tubes

Snug-fit straws on
the end of your
LEDs to make
them glow more
visibly
Random Behavior
“CandleLight”

Uses simple
pseudo random
number generator
to mimic flame

Use random(min,max)
to pick a number between
min & max.
/*
* CandleLight
* -----------
*
* Use random numbers to emulate a flickering candle with a PWM'd LED
*
*/

int ledPin = 9; // select the pin for the LED


int val = 0; // variable that holds the current LED brightness
int delayval = 0; // variable that holds the current delay time

void setup() {
randomSeed(0); // initialize the random number generator
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
}

void loop() {
val = random(100,255); // pick a random number between 100 and 255
analogWrite(ledPin, val); // set the LED brightness

delayval = random(50,150); // pick a random number between 30 and 100


delay(delayval); // delay that many milliseconds
}
RGB Leds
• Red, Green and Blue LEDs in one package
• Use PWM to get any color
RGB Color Mixing
int redPin = 11;
int greenPin = 10;
Load RGB_Led sketch int bluePin = 9;

from the handouts void setup()


{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

void loop()
{
setColor(255, 0, 0); // red
delay(1000);
setColor(0, 255, 0); // green
delay(1000);
setColor(0, 0, 255); // blue
delay(1000);
setColor(255, 255, 0); // yellow
delay(1000);
setColor(80, 0, 80); // purple
delay(1000);
setColor(0, 255, 255); // aqua
delay(1000);
}

Note the use of a user void setColor(int red, int green, int blue)
{
defined function analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Return Type Parameters
Name

void setColor(int red, int green, int blue)


{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

• parameter variables are only valid within the


function
• once function exits, all variables go away
RGB Breadboard Layout
Using Web Colors
• Colors on the web are specified as
hexidecimal RGB values
#FF0000 = Red
#00FF00 = Green
#0000FF = Blue

setColor(0x4B, 0x0, 0x82); // indigo

• Note that we prepend 0x to a number to


specify that it’s in hexidecimal
Take a Break
595 Shift Register
• Serial to Parallel Converter
• Control 8 LEDs with 3 signal pins
• Can be daisy chained
• Handy and cheap (33¢ each)
595 Schematic
int latchPin = 5;
int clockPin = 6;
int dataPin = 4; Variable
byte leds = 0;
Declarations
void setup()
{ Setup Function
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}

void loop()
{
Loop Function
leds = 0;
updateShiftRegister();
delay(500);
for (int i = 0; i < 8; i++)
{
bitSet(leds, i);
updateShiftRegister();
delay(500);
}
}
User Defined
void updateShiftRegister()
{ Function
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
int latchPin = 5;
int clockPin = 6;
int dataPin = 4;

byte leds = 0;

void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop()
{
leds = 0;
updateShiftRegister();
delay(500);
for (int i = 0; i < 8; i++)
{
bitSet(leds, i);
updateShiftRegister();
delay(500);
}
}
bitSet
Sets (writes a 1 to) a bit of a numeric variable
bitSet(x,n)
x - the variable being acted upon
n - the bit to set, starting at 0 for the LSB

http://arduino.cc/en/Reference/BitSet
void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
shiftOut
Shifts out a byte of data one bit at a time
shiftOut(dataPin, clockPin, bitOrder, value)
dataPin - the pin on which to output each bit (int)
clockPin - the pin to toggle once the dataPin has
been set to the correct value (int)
bitOrder: either MSBFIRST or LSBFIRST
value: the data to shift out. (byte)
http://arduino.cc/en/Reference/ShiftOut
The Serial Monitor

• Communicate between Arduino and your


computer
• Great for debugging
• Also handy if you want to transfer data and/
or control signals between your computer
and the Arduino
The Serial Monitor
Serial Monitor Code

• Open SerialMonitor595 sketch


• Variable declarations and updateShiftRegister
haven’t changed
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
updateShiftRegister();
Serial.begin(9600);
while (! Serial); // Wait until Serial is ready - Leonardo
Serial.println("Enter LED Number 0 to 7 or 'x' to clear");
}
Serial
Serial.begin(speed) - initialize the serial port
Serial.print() - print text
Serial.println() - print text with a CR
Serial.available() - is there input available?
Serial.read() - read a byte from the serial port
Serial.write() - write bytes to the serial port
http://arduino.cc/en/Reference/Serial
void loop()
{
if (Serial.available())
{
char ch = Serial.read();
if (ch >= '0' && ch <= '7')
{
int led = ch - '0';
bitSet(leds, led);
updateShiftRegister();
Serial.print("Turned on LED ");
Serial.println(led);
}
if (ch == 'x')
{
leds = 0;
updateShiftRegister();
Serial.println("Cleared");
}
}
}
If/Else
• Test conditions and do different things
• Can be:
• if {}
• if {} else {}
• if {} else if {} else {}
• Can have as many “else if” clauses as you
want
http://arduino.cc/en/Reference/Else
if (pinFiveInput < 500)
{
// do Thing A
}
if (pinFiveInput < 500)
{
// do Thing A
}
else
{
// do Thing B
}
if (pinFiveInput < 500)
{
// do Thing A
}
else if (pinFiveInput >= 1000)
{
// do Thing B
}
else
{
// do Thing C
}
Comparison Operators
• == (equal to)
• != (not equal to)
• < (less than)
• > (greater than)
• <= (less than or equal to)
• >= (greater than or equal to)
http://arduino.cc/en/Reference/HomePage
Sensors & Inputs
Many sensors are variations on switches
Switches make or break a connection

knife switch toggle switch


(SPST) (SPDT)
Many Kinds of Switches

magnetic hexidecimal tilt lever


Homemade Switches
“Trick Penny”
Penny on a surface.
When the penny is lifted, alarms go off
Homemade Switches
“Trick Penny”
Homemade Switches
“Smart Wind Chimes”
When the wind blows hard enough,
you’re sent email
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

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 down”
the input to ground (0
volts)
• Pressing switch “pushes”
input to 5 volts
• Press is HIGH
Not pressed is LOW
Internal Pullup

• ATmega chips have built-in pullup resistors


• Don’t need to use an external pull up/down
resistor
• Because it’s a pull up, the logic is backwards
• HIGH is default, LOW is when the button is
pressed
Load “DigitalInputLab” Sketch
int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
if (digitalRead(buttonApin) == LOW)
{
digitalWrite(ledPin, HIGH);
}
if (digitalRead(buttonBpin) == LOW)
{
digitalWrite(ledPin, LOW);
}
}
Using digitalRead()
• In setup():
pinMode(myPin,INPUT_PULLUP) makes
a pin an input with the pullup resistor enabled
• 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)


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
/*
FadeOrBlink
Schematic is same as for */
“Fading” sketch int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;
int blinkMode = false;

void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
Combines “Blink” & “Fading” }

sketches into one, selected by void loop()


the button {
// Test button states
if (digitalRead(buttonApin) == LOW)
{
blinkMode = true;
}
if (digitalRead(buttonBpin) == LOW)
{
blinkMode = false;
}

// Now blink if blinkMode is true or fade if it's false


if (blinkMode == true)
{
digitalWrite(ledPin, LOW); // turn LED OFF
Things to do for next
class

• Design a concept for an interactive object


for inspiration check out:
http://www.arduino.cc/playground/Projects/
ArduinoUsers
• individual or group projects
END Class 1

http://duksta.org/electronics/blr-arduino

John Duksta
ducksauz@hellyeah.com
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

S-ar putea să vă placă și