Date post: | 22-Feb-2018 |
Category: |
Documents |
Upload: | truongdiep |
View: | 238 times |
Download: | 7 times |
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
• Solderless breadboard
• Acrylic Mount
• USB cable
• Jumper wires
• 9V Battery clip
• 1 RGB LED
• 10 Red LEDs
• 10 Green LEDs
• 1 Blue LED
• DC Motor
• Mini Servo
• 74HC595 Shift Register
• Piezo Element
• 2 Pushbuttons
• 10K Potentiometer
• Photo Resistor
• Temperature Sensor
• 5V Relay
• 2 Transistors
• Resistors
• 560 Ohm x25 (green, blue, brown)
• 2.2k Ohm x3 (red, red, red)
• 10k Ohm x3 (brown, black, orange)
• 2 Diodes
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 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 ATmega328 microcontroller chip
• chip was designed to be used with C language
2.7”
2”
resetbutton
powerLED
digital input/output “pins”
analog input pins
test LEDon pin 13
TX/RXLEDs ATmega328
USB
Arduino Uno R3 Overview
power 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
USB
“Stamp”-sized
Bluetooth
LilyPad(for clothing)
DIY
many different variations to suite your needs
Boarduino Kit
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
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-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
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
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(verify)
statusarea
upload to board
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)
• Press Upload button to program Arduino board with your sketch
blink blink
compile
upload
sketch runs
TX/RX flash
Status Messages
Uploading worked
Wrong serial port selected
Wrong board selected
Size depends oncomplexity of your sketch
nerdy cryptic error messages
Development Cycle
• Make as many changes as you want
• Not like most web programming: edit ➝ run
• Edit ➝ compile ➝ upload ➝ run
compile upload runedit 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
notconnected
All connected, a “bus”
numbers & letter labels
just for reference groups of 5
connected
Useful ToolsWire cutters
Needle-nosepliers
Wire stripper
Making Jumper Wireswire stripperpliers & cutter
~1/4”
Using Solderless Breadboards
Using needle nose pliers can helppush wires & components into holes
Making Circuits
heart pumps, blood flows voltage pushes, current flows
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
Basic ElectronicsFlash Light
Our Blink Circuit
LoadVoltageSource
Basic Electronics• The dreaded short circuit:
• this is a circuit with a load equal to zero
• this allows “infinite” current to flow from the positive terminal of the voltage source to the negative terminal
• 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
Load = 0VoltageSource
Current = ∞
Basic Electronics
Image source: Engineer's Mini Notebook, Mims III, Master Publishining, 2007.
Some Electronic Symbols
LEDs & Resistors
LED
resistor
On LEDs, polarity matters.Shorter lead is negative (cathode) side, goes to ground
Resistors have no polarity
Flat edge here for neg. side
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
wiring diagram schematic
“hello world” of microcontrollers
Arduino board has this circuit built-inTo 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
Duty CycleEffectiveVoltage
EffectiveVoltage
EffectiveVoltage
Duty Cycle
Duty Cycle
Varying LED Brightness
wiring diagramschematicThe PWM pins work with the “analogWrite(pin,value)” command
To turn LED to half-bright, use analogWrite(9,128)
Same circuit as Blink circuit but pin 9 instead of pin 13
where “value” ranges between 0 and 255.
All Wired Upplugged into “ground” bus
LED “Fading” SketchLoad “File/Examples/Analog/Fading”
Press “Upload”. After a second, LED will “throb” on and off
Reduce “delay()” values to make it go faster
note
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 LEDint val = 0; // variable that holds the current LED brightnessint 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;int bluePin = 9;
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);}
void setColor(int red, int green, int blue){ analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue); }
Load RGB_Led sketch from the handouts
Note the use of a user defined function
void setColor(int red, int green, int blue){ analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue); }
Return TypeName
Parameters
• 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;
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); }}
void updateShiftRegister(){ digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, leds); digitalWrite(latchPin, HIGH);}
Variable Declarations
Setup Function
Loop Function
User Defined Function
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);}
shiftOutShifts 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
knife switch toggle switch(SPST) (SPDT)
Switches make or break a connection
Many sensors are variations on switches
Many Kinds of Switches
magnetic tilt leverhexidecimal
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)
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 down” the input to ground (0 volts)
• Pressing switch “pushes” input to 5 volts
• Press is HIGHNot 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
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); }}
Load “DigitalInputLab” Sketch
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
FadeOrBlinkLoad “FadeOrBlink” sketch from the handout
Combines “Blink” & “Fading” sketches into one, selected by
the button
Schematic is same as for “Fading” sketch
/*FadeOrBlink*/
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); }
void loop() { // 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 delay(50); digitalWrite(ledPin, HIGH); // turn LED ON delay(50); } else { for(int fadeval = 0 ; fadeval <= 255; fadeval+=5) { // fade in (from min to max) analogWrite(ledPin, fadeval); // sets the value (range from 0-255) delay(10); } for(int fadeval = 255; fadeval >=0; fadeval-=5) { // fade out (from max to min) analogWrite(ledPin, fadeval); delay(10); } } }
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
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