A pretty useful techinque you'll want to add to your collection of sketch-knowledge is how to keep track of button presses. Try this sketch:
/*
* Counting presses
*/
int switchPin = 2; // switch is connected to pin 2
int val; // variable for reading the pin status
int buttonState; // variable to hold the button state
int buttonPresses = 0; // how many times the button has been pressed
void setup() {
pinMode(switchPin, INPUT); // Set the switch pin as input
Serial.begin(9600); // Set up serial communication at 9600bps
buttonState = digitalRead(switchPin); // read the initial state
}
void loop(){
val = digitalRead(switchPin); // read input value and store it in val
if (val != buttonState) { // the button state has changed!
if (val == LOW) { // check if the button is pressed
buttonPresses++; // increment the buttonPresses variable
Serial.print("Button has been pressed ");
Serial.print(buttonPresses);
Serial.println(" times");
}
}
buttonState = val; // save the new state in our variable
}
|
Notice, we've added the ++ operator. Simply, the statement "buttonPresses++" increments (adds 1 to) the buttonPresses variable. This is a shortcut for "buttonPresses = buttonPresses + 1". We first saw this in the For Lesson from Unit 4.
Additional Tasks: - Modify this sketch so that it increments the variable when you let go of the button rather than press it.
- Change this sketch so that it counts down rather than up. When you get to zero you should reset the variable so you can start over.
- Attach 5 LEDs to your Arduino. At the beginning of the program they should all be turned on. Each time I push the button, one should go out.
|