So I was experimenting with what I could do with pushbuttons and I wanted to create a program that oscillates an LED the first time you press the button and then stops the second time you press it, but then you can press it again to restart the cycle, etc. I coded this up and when I press the button, it gets caught in a loop with the else if (buttonPressed == 1) statement and the LED just keeps blinking regardless of the amount of times you press the button after. I've been messing around with different tricks and back ways to get the Arduino to do the same function but I can't seem to get it. Anybody have any suggestions on how to revise this program's logic into getting it to do what I need? Here is what I have at the moment:
const int LED = 13;
const int BUTTON = 7;
int val = 0; //used to keep track of whether button state is HIGH or LOW
int buttonPressed = 0; //used to keep track of times button is pressed
void setup() {
pinMode(LED, OUTPUT); //LED pin 13
pinMode(BUTTON, INPUT); //BUTTON pin 7
}
void loop() {
val = digitalRead(BUTTON); //val is either HIGH or LOW
if (val == HIGH) {
buttonPressed++; //if val is HIGH, buttonPressed + 1
}
if (buttonPressed == 0) {
digitalWrite(LED, LOW); //if button is pressed 0 times, LED is off
}
else if (buttonPressed == 1) {
digitalWrite(LED, HIGH); //if button is pressed once, LED blinks
delay(100);
digitalWrite(LED, LOW);
delay(100);
}
else {
buttonPressed = 0; //if button is pressed more than once, button is reset to 0 presses and therefore LED is shut off
}
}