【发布时间】:2016-08-25 08:56:17
【问题描述】:
功能:
用户按下红色圆顶按钮(不是 2 状态按钮),因此它必须在第一次按下“0”->“1”和再次按下“1”->“0”时切换。
因此,当按下时,串行监视器将每 100 毫秒从“0”打印“1”。该行为表示 buttonState 从 LOW 切换到 HIGH
此外,一个 LED 灯条也连接到 arduino。因此,当按钮状态在串行监视器中显示为高电平时,LED 状态将在延迟 10 秒后切换为高电平,并在切换为低电平状态之前保持高电平状态 10 秒。
最后,buttonState 应该在延迟(25 秒)后从 HIGH 切换到 LOW,而无需用户实际按下按钮。
问题:
此时,用户必须按下红色圆顶按钮才能在 LOW 和 HIGH 状态之间切换。因此,当按钮初始状态为 LOW 时,它在串行监视器中显示“0”,当按下时,按钮将切换到 HIGH,在串行监视器中显示“1”,当再次按下按钮时,它将从HIGH 到 LOW,在串行监视器中显示“0”。
因此,我想就如何允许按钮状态从高切换到低而无需用户按下按钮寻求帮助。
因此, 正确的行为:
初始状态:串行监视器中显示“0”,当用户按下按钮时,串行监视器中的按钮状态显示“1”,经过 25 秒计数后,按钮状态将切换到低电平,无需用户再次按下按钮。
代码:
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);
}
【问题讨论】:
标签: arduino arduino-uno arduino-ide