I have 6 different led connected to pin 2 to 7 and a push button connected to pin 8. I got two functions one turning led on and off with interval of one second and other one turning on and off led in color patterns. I am trying to switch between these two modes when i press push button. But its not working the way i want. I have to hold the push button till the all led are off to switch mode. I want my led to switch mode immediately after i press push button.
I have tried while loop to to switch mode when pin 8(push button) is high but i am getting same results i have to push and hold to make it work.
Heres my code:
//BUTTON STATE
int state = 0;
bool currentState = LOW;
bool lastState = LOW;
void setup() {
// put your setup code here, to run once:
for(int pin = 2;pin <8; pin++){//DECLARE PIN FOR OUTPUT FROM PIN 2 TO 7
pinMode(pin,OUTPUT);
pinMode(8,INPUT);
}
}
bool buttonState(bool last){
bool current = digitalRead(8);
if(last != current){
current = digitalRead(8);
}
return current;
}
void led_dance(int mode){
if(mode == 0 && digitalRead(8) != HIGH){
mode_sequeal();
}
else{
mode_color();
}
}
void mode_sequeal(){//TURN ON LED IN SERIES AND TURN IT OFF IN SERIES
for(int led = 2;led <8; led++){//FOR TURNING LED ON
digitalWrite(led, HIGH);//TURNS LED ON
delay(1000);//DELAY FOR 1 SECONDS
}
for(int led = 2;led <8; led++){//FOR TURNING LED OFF
digitalWrite(led, LOW);
delay(1000);//DELAY FOR 1 SECONDS
}
}
void mode_color(){
digitalWrite(2,HIGH);
digitalWrite(5,HIGH);
delay(500);
digitalWrite(2,LOW);
digitalWrite(5,LOW);
digitalWrite(3,HIGH);
digitalWrite(7,HIGH);
delay(500);
digitalWrite(3,LOW);
digitalWrite(7,LOW);
digitalWrite(4,HIGH);
digitalWrite(6,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(6,LOW);
}
void loop() {
// put your main code here, to run repeatedly:
currentState = buttonState(lastState);
if(lastState == LOW && currentState == HIGH){
state++;
}
lastState = currentState;
if(state == 2){
state = 0;
}
led_dance(state);
}