我有6個不同的LED連接到引腳2到7和一個按鈕連接到引腳8.我有兩個功能,一個導通和關閉間隔一秒導通和關閉兩個功能和以彩色圖案領先。我試圖在按下按鈕時在這兩種模式之間切換。但它不按我想要的方式工作。我必須按住按鈕,直到全部LED熄滅才能切換模式。按下按鈕後,我希望我的指示燈立即切換模式。按鈕信號檢測不正確
我已經嘗試while循環切換模式,當引腳8(按鈕)高,但我得到相同的結果,我不得不推動,使其工作。
繼承人我的代碼:
//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);
}
首先,根據問題按鈕連接到引腳2並根據代碼 - 到引腳8.哪一個是它?其次,你只需要初始化引腳8一次 - 在每次循環迭代中都不需要它。 – 2015-03-02 20:41:24
對不起,其連接的引腳8。現在我糾正了我的問題 – 2015-03-02 20:42:58