Hello,
I am trying to make a simple sketch that does the following: When you push a push-button once, it prints "Led1" on the serial monitor; when you push the same button a second time, it prints "Led2" on the serial monitor, etc. The code is based off the State-Change example.
Here is the code:
//Constants
const int buttonPin = 2; // the pin that the pushbutton is attached to
// Variables
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin
pinMode(buttonPin, INPUT);
// initialize serial
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
{
if(buttonPushCounter == 1)
{
Serial.print("Led1");
if(buttonPushCounter == 2)
{
Serial.print("Led2");
if(buttonPushCounter == 3)
{
Serial.print("Led3");
}
else {
}
}
lastButtonState = buttonState;}
}
}}
}
It works fine for the first push (it indicated Led1 when the button has been pushed once), but it stops working after that. When I push it a second or a third time, the serial monitor doesn't indicate Led2 or Led3...
Does anybody know what the problem is? If so, how can I fix it?