i wanted to change LEDs with only one button. First click on the Button - Red Led turns on, Second - Red turns off and green turns on, third - Green turns off and yellow turns on, fourth - starts again with Red...
First i tried to turn on Red with one click and then turn off...
int red = 8;
int button = 13;
int buttonstate = 0;
bool redOn = false;
void setup(){
pinMode(red,OUTPUT);
pinMode(button,INPUT);
}
void loop(){
buttonstate = digitalRead(button);
if (buttonstate == 1){
if (redOn == false){
digitalWrite(red,HIGH);
redOn = true;
}
else{
digitalWrite(red,LOW);
redOn = false;
}
}
}
That works. Then I tried to add the other two LEDs..
int red = 8;
int yellow = 3;
int green = 6;
int button = 13;
int buttonstate = 0;
bool redOn = false;
bool yellowOn = false;
bool greenOn = false;
void setup(){
pinMode(red,OUTPUT);
pinMode(yellow,OUTPUT);
pinMode(green,OUTPUT);
pinMode(button,INPUT);
}
void loop(){
buttonstate = digitalRead(button);
if (buttonstate == 1){
if (redOn == false){
digitalWrite(red,HIGH);
redOn = true;
}
else if (redOn == true && greenOn == false && yellowOn == false) {
digitalWrite(red,LOW);
redOn = false;
digitalWrite(green,HIGH);
greenOn = true;
}
else if (redOn == false && greenOn == true && yellowOn == false) {
digitalWrite(green,LOW);
greenOn = false;
digitalWrite(yellow,HIGH);
yellowOn = true;
}
else if (redOn == false && greenOn == false && yellowOn == true) {
digitalWrite(yellow,LOW);
yellowOn = false;
}
else{
redOn = false;
greenOn = false;
yellowOn = false;
}
}
}
That doesn't work. Has someone an idea how to realize this?
You should at first detect if the button changed before running into the light switching stuff:
From your code I'm not fully sure how the desired LED lighting pattern should look like, though, so skipping this part (until you provide a precise description).Edit according to your comment:
There are several ways to achieve this blink pattern; with your boolean variables you could do like this (only considering the booleans, signals need to be set accordingly):
Above code would leave a dark phase after yellow being on; if you don't want one, you can simply have:
Another variant is having a counter: