Buttons are a common input device and are available in many types.
At the simplest level, a button is simply two wires that are connected or disconnected when the button is pushed.
On our kit, the buttons are connected to ground. When the button is pressed, the input to the Arduino pin is LOW. We did not connect pullup resistors to the button input -- instead we use pullup resistors that are in the microcontroller by setting the INPUT_PULLUP pin mode.
You can start with File > Examples > 02. Digital > Button, make these changes to the sketch,
or you can copy/paste the code in the next section:
Look at the Arduino Kit you have for this workshop.
Identify the pin numbers where the buttons are connected.
Select one of the buttons to use for this exercise.
From the previous exercise Hello World - Blink an LED , remember the pin for one of the LEDs.
Then, change these statements in the sketch to use the pins for your selected button and LED:
const int buttonPin = 9; // the number of the pushbutton pin
const int ledPin = 16; // the number of the LED pin
Also, change:
pinMode(buttonPin, INPUT);
to
pinMode(buttonPin, INPUT_PULLUP); // Our Kit does not have a resistor connected to the button
Or:
File > New
Delete all the code
Copy/paste this sketch, which is based on File > Examples > 02. Digital > Button
/*
Button
based on
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 9; // the number of the pushbutton pin
const int ledPin = 16; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is LOW:
if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Tools > Processor: ATMega32U5 (5V, 16Mhz)
Important! Be sure to select the 5V Processor!
(We are using 5 volt Pro Micros, not the 3.3 volt version.)
Otherwise, when you upload a sketch, you will "brick" the Pro Micro.
Compile and Upload your sketch.
Does it work?
Change it to do something else with the buttons and LEDs.
Reverse the function of the button -- press turns off the LED.
Add the other two buttons and LEDs to the sketch.
Use for ( ) to blink the LED 5 times when the button is pressed. Something like:
for (i=0; i<4; i++) {
// LED on
delay(1000); // wait one second
// LED off
}
Your ideas?