用戶按下紅色圓頂按鈕(不是2狀態的按鈕),因此它必須在所述第一壓切換「 0「 - >」1「&再次按下」1「 - >」0「時。
因此,按下按鈕時,串行監視器將每100毫秒從「0」中打印「1」。行爲表示buttonState從低電平切換到高電平
此外,LED條紋也連接到arduino。因此,當串行監視器中的按鈕狀態顯示爲高電平時,LED狀態將在延遲10秒後切換到高電平,並在切換到低電平狀態之前保持高電平狀態10秒。
最後,buttonState在延遲(25s)之後應該從HIGH切換到LOW,而無需用戶按下按鈕。
問題:
在這一點上,用戶必須按下紅色圓頂按鈕LOW & HIGH狀態之間切換。因此,當按鈕初始狀態爲低電平時,串行監視器顯示「0」,按下時按鈕將切換爲高電平,在串行監視器中顯示「1」,再次按下按鈕時,按鈕將從從高到低,串行監視器顯示「0」。
因此,我想要求幫助如何讓按鈕狀態從高切換到低,而無需用戶按下按鈕。
因此, correctBehaviour:
初始狀態:「0」表示在串行監控,並且當用戶按下按鈕buttonstate示出的「1」中的串行監控和後25S的計數,按鈕狀態將切換到低,而無需用戶再次按下按鈕。
代碼:
const int buttonPin = 2; //the number of the pushbutton pin
const int Relay = 4; //the number of the LED relay pin
uint8_t stateLED = LOW;
uint8_t btnCnt = 1;
int buttonState = 0; //variable for reading the pushbutton status
int buttonLastState = 0;
int outputState = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// Check if there is a change from LOW to HIGH
if (buttonLastState == LOW && buttonState == HIGH)
{
outputState = !outputState; // Change outputState
}
buttonLastState = buttonState; //Set the button's last state
// Print the output
if (outputState)
{
switch (btnCnt++) {
case 100:
stateLED = LOW;
digitalWrite(Relay, HIGH); // after 10s turn on
break;
case 200:
digitalWrite(Relay, LOW); // after 20s turn off
break;
case 202: // small loop at the end, to do not repeat the LED cycle
btnCnt--;
break;
}
Serial.println("1");
}else{
Serial.println("0");
if (btnCnt > 0) {
// disable all:
stateLED = LOW;
digitalWrite(Relay, LOW);
}
btnCnt = 0;
}
delay(100);
}
你是什麼意思「,但沒有這樣做正確使用,如果平均(毫秒() - lastpressed> 20000){...「,我使用延遲(100)是檢查每個按鈕,但按。對不起,我沒有真正明白你的意思 – Luke
閱讀,鍛鍊並瞭解BlinkWithoutDelay示例https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay。這不僅僅是閃爍,而是關於每個非阻塞等待。 – datafiddler