【发布时间】:2016-12-31 18:34:32
【问题描述】:
功能:
用户按下红色圆顶按钮 Red Dome Button,假设该按钮状态为高电平,在串行监视器上,它应该每 100ms 打印“1”,延迟 5s 后:LED 灯将处于 HIGH 状态,大约会亮 10 秒,之后 LED 灯会切换到 LOW 状态,这意味着 LED 灯会熄灭。
因此流程:
正确的行为:
初始状态-> 串口监视器显示“0” 当用户按下按钮 -> 串行监视器每 100 毫秒显示“1”,延迟 10 秒后,LED 状态将为高。
在延迟 10 秒后,LED 状态将为低电平,串行监视器显示仍为“1”秒,每 100 毫秒表示红色圆顶按钮的按钮状态仍为高电平
问题:
当前行为: 初始状态-> 串口监视器显示“0” 当用户按下按钮时 -> 串口监视器显示单个“1”,而不是连续显示“1”,但延迟 10 秒后,LED 状态将为高。
在延迟 10 秒后,LED 状态将变为低电平。此时,LED 不应再次变为 HIGH,但在延迟 10s 后,LED 状态会在 10s 后变为 HIGH 和 LOW。然后它变成一个循环。 串行监视器显示仍为“1”,表示红色圆顶按钮的按钮状态仍为 HIGH
因此,如何启用,一旦按下按钮,它将显示连续的“1”并延迟 10 秒,LED 将处于 HIGH 状态,再延迟 10 秒,LED 状态将是低的。即使按钮状态处于高电平,LED 仍将保持低电平状态
代码:
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 5s turn on
break;
case 200:
digitalWrite(Relay, LOW); // after 10s turn off
break;
case 102: // small loop at the end, to do not repeat the 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