功能
用户按下红色圆顶按钮红色圆顶按钮,假设发出buttonState为HIGH的信号,并且在串行监视器上,它应该是打印" 1"每隔100ms,延迟5s后:LED灯将处于HIGH状态,亮起约10s后,LED灯将切换到LOW状态,这意味着LED灯将熄灭。
因此流程:
正确行为:
初始状态 - >串行监视器显示" 0" s 当用户按下按钮时 - >串行监视器每隔100ms显示一次" 1"在延迟10秒后,LED状态将为高电平。
并且在延迟10秒后LED状态将为低电平,串行监视器显示仍然每隔100毫秒显示红色圆顶按钮的按钮状态仍为高电平< / p>
问题:
当前行为: 初始状态 - &gt;串行监视器显示&#34; 0&#34; s 当用户按下按钮时 - &gt;串行监视器显示单个&#34; 1&#34;并且没有显示连续的&#34; 1&#34; s,但在延迟10秒后,LED状态将为高。
在延迟10秒后,LED状态将为低电平。此时,LED不应再次为高电平,但是,在延迟10秒后,LED状态在10秒后变为高电平和低电平。然后它变成一个循环。 串行监视器显示仍处于&#34; 1&#34;发出信号表示红色圆顶按钮的按钮状态仍处于高位
因此,如何启用按钮一旦按下,它将显示连续的&#34; 1&#34;如果延迟10秒,LED将处于高电平状态,再延迟10秒,LED状态将为低电平。此后,即使按钮状态为HIGH
,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);
}
答案 0 :(得分:0)
当您有delay(10000)
然后delay(2000);
时,您的期望是什么?如果你等了这么长时间它应该每100毫秒打印一次“1”?
您的outputState会在按钮更改时更改,但您可以直接使用按钮状态跳过该部分 - 它完全相同。
我可以想象类似的东西(未经测试,这只是概念):
const int buttonPin = 2;
const int Relay = 4;
uint8_t stateLED = LOW;
uint8_t btnCnt = 1;
void loop() {
if (digitalRead(buttonPin) == HIGH) {
switch (btnCnt++) {
case 0: case 1:
stateLED = HIGH; // no idea, why is that in original code, but whatever
break;
case 50:
stateLED = LOW;
digitalWrite(Relay, HIGH); // after 5s turn on
break;
case 100:
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 {
if (btnCnt > 0) {
Serial.println("0");
// disable all:
stateLED = LOW;
digitalWrite(Relay, LOW);
}
btnCnt = 0;
}
delay(100);
}
void setup() {
Serial.begin(57600);
pinMode(buttonPin, INPUT);
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
}