functionality:
用户按下红色圆顶按钮红色圆顶按钮,它应该是信号,buttonState是高的,在串行显示器,它应该打印"1“在每100毫秒后,延迟5s:发光二极管将处于高状态,将点燃约10s,然后,LED灯将切换到低状态,意味着LED灯将关闭。
因此,流动:
正确行为:
初始状态->串行监视器显示“0”当用户按下按钮->串行监视器显示“1”在每100毫秒,在延迟10秒后,发光二极管的状态将很高。
在延迟10s后,LED的状态将降低,串行监视器显示仍然是“1”,每100 is显示一次,以表示红色圆顶按钮的按钮状态仍然很高。
发行:
当前行为:初始状态->串行监视器显示“0”当用户按下按钮->串行监视器显示单个"1“,而不是连续显示”1“,但延迟10秒后,->状态将很高。
在延迟10s后,LED的状态将是低的。在这一点上,LED不应该再高,但是,在延迟10s后,LED状态变得高和低后,10s。然后它变成了一个循环。串行显示器仍然处于"1“的位置,以表示红色圆顶按钮的按钮状态仍然很高。
因此,如何使按钮一旦按下,显示连续的"1“和延迟10s,LED就会处于高的状态,再延迟10s,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);
}发布于 2016-08-24 18:30:00
当您有delay(10000)和delay(2000);时,您期望的是什么?如果你等得太久,应该每100毫秒打印一次?
您的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);
}https://stackoverflow.com/questions/39126444
复制相似问题