The system has 1 button and 3 LEDs. Each time the button is pressed, a new LED state/blinking pattern is initiated, and after the third press the cycle continues. Apparently, my code works for the first button press. After the button was pressed the second time, nothing seemed to happen. I can't for the life of me find where the problem is.
const int light1 = 11;
const int light2 = 12;
const int light3 = 13;
const int buttonpin = 2; //
int currentstate = 0; //current state of button
int previousstate = 0; //previous state of button
int buttoncounter = 0;
const int interval1 = 500;
const int interval2 = 200;
const int interval3 = 300;
unsigned long startpoint = 0;
void setup() {
pinMode(light1, OUTPUT);
pinMode(light2, OUTPUT);
pinMode(light3, OUTPUT);
pinMode(buttonpin, INPUT);
Serial.begin(9600);
}
void loop(){
currentstate = digitalRead(buttonpin); //store input value in "currentstate"
delay(10); //debounce
int val2 = digitalRead(buttonpin); //debounce
if (currentstate == val2){ //debounce
//compare currentstate to previoustate
if (currentstate != previousstate) {
buttoncounter++;
Serial.print("Current state: "); //this will print the current state
Serial.println(buttoncounter);
}
}
previousstate = currentstate;
if (buttoncounter == 0){ //state 0
digitalWrite(light1, LOW);
digitalWrite(light2, LOW);
digitalWrite(light3, LOW);
}
else if (buttoncounter == 1){ //state 1
digitalWrite(light1, HIGH);
digitalWrite(light2, LOW);
digitalWrite(light3, LOW);
}
else if (buttoncounter == 2){
digitalWrite(light1, LOW); //state 2
startpoint = millis(); //set startpoint = the current time in ms
if (millis() - startpoint >= interval1){ //at 0.5 s
digitalWrite(light1, HIGH);
digitalWrite(light2, HIGH);
digitalWrite(light3, HIGH);
startpoint = millis();
if (millis() - startpoint >= interval1){ //at 1.0 s
digitalWrite(light1, LOW);
digitalWrite(light2, LOW);
startpoint = millis();
if (millis() - startpoint >= interval2){ //at 1.2 s
digitalWrite(light1, HIGH);
digitalWrite(light2, HIGH);
digitalWrite(light3, LOW);
startpoint = millis();
if (millis() - startpoint >= interval3){ //at 1.5 s
digitalWrite(light1, LOW);
digitalWrite(light3, LOW);
startpoint = millis();
if (millis() - startpoint >= interval3){ //at 1.8 s
digitalWrite(light1, HIGH);
digitalWrite(light3, HIGH);
startpoint = millis();
if (millis() - startpoint >= interval2){ //at 2 s
digitalWrite(light1, LOW);
digitalWrite(light2, LOW);
digitalWrite(light3, LOW);
}
}
}
}
}
}
}
else if (buttoncounter >= 3){ //if button is pressed more than two times
buttoncounter = 0; //buttoncounter is reset to 0 to repeat the cycle
}
}