Arduino Buttons Notes 2up
Arduino Buttons Notes 2up
Button Input:
On/off state change
Living with the Lab
Gerald Recktenwald
Portland State University
[email protected]
1
10/25/12
2
10/25/12
1 and 3
1 and 4
2 and 3
1 and 3
1 and 4
2 and 3
3
10/25/12
• Normally open
❖ electrical contact is made when button is pressed
• Normally closed
❖ electrical contact is broken when button is pressed
• Internal spring returns button to its un-pressed state
4
10/25/12
1. Build the circuit: same one is used for all examples
a. Test with LED on/off
b. LED is only controlled by the button, not by Arduino code
2. Create a wait to start button
a. Simplest button implementation
b. Execution is blocked while waiting for a button click
3. Use an interrupt handler
a. Most sophisticated: Don t block execution while waiting for
button input
b. Most sophisticated: Requires good understanding of coding
c. Requires de-bouncing
d. Not too hard to use as a black box
5
10/25/12
Technical Note
5V 5V
Pull-up
LED
10 kΩ
resistor:
Push-button
330 Ω switch
Digital
input pin Pull-down
resistor:
330 Ω Digital
Push-button input pin
switch 10 kΩ
6
10/25/12
7
10/25/12
!
Serial.begin(9600);! while loop continues
while ( !start_click ) {! as long as start_click
start_click = digitalRead( button_pin );! is FALSE
Serial.println("Waiting for button press");!
}!
}!
!
void loop() {! Same loop() function as
int button;! in the preceding sketch
!
button = digitalRead( button_pin );!
if ( button == HIGH ) {!
Serial.println("on");!
} else {!
Serial.println("off");!
}!
}!
8
10/25/12
9
10/25/12
10
10/25/12
Other references
Ladyada tutorial
❖ Excellent and detailed
❖ http://www.ladyada.net/learn/arduino/lesson5.html
Arduino reference
❖ Minimal explanation
‣ http://www.arduino.cc/en/Tutorial/Button
❖ Using interrupts
‣ http://www.uchobby.com/index.php/2007/11/24/arduino-interrupts/
‣ http://www.arduino.cc/en/Reference/AttachInterrupt
11