我想只用一个按钮来更换 LED。第一次单击按钮 - 红色 LED 亮起,第二次 - 红色熄灭,绿色亮起,第三次 - 绿色熄灭,黄色亮起,第四次 - 再次以红色开始...
首先,我尝试一键打开红色,然后关闭...
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;
}
}
}
这样可行。然后我尝试添加另外两个 LED ..
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;
}
}
}
那是行不通的。有人知道如何实现这一点吗?