功能性:
在按下红色圆顶按钮(不是2状态按钮)之前,串行监视器将打印一个列表" 0" s,当按下红色圆顶按钮时,按钮状态将从LOW切换为高,因此在串行监视器上将打印一个" 1" s列表。
但是,当按钮处于HIGH状态时,串行监视器打印" 1" s和用户将无法将按钮状态从HIGH切换到LOW。因此,按钮只能在一段时间(25秒)后自动从HIGH切换到LOW。
因此, 正确行为 :
初始状态print => 00000000000000(当用户按下红色圆顶按钮=> buttonstate将LOW更改为HIGH时)111111111111111111(当用户按下按钮时,没有任何反应)111111111111111111(25秒延迟后,buttonState将切换为HIGH到LOW)0000000000000
问题:
此时,用户可以在LOW到HIGH和HIGH到LOW之间切换。意思是,flow => 00..000(用户按下按钮,切换到高电平)111 ... 111(用户按下按钮,切换到高电平为低电平)0000 ...
我不确定如何启用按钮仅从LOW切换到HIGH但禁用按钮从HIGH切换到LOW。
当用户按下按钮时,它可以改变按钮状态,从" 0"到" 1"但是当它处于" 1"。
时无法改变按钮状态因此,我想请求一些允许以下正确行为的帮助。
由于
代码:
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 250:
digitalWrite(Relay, LOW); // after 20s turn off
//Toggle ButtonState to LOW from HIGH without user pressing the button
digitalWrite(buttonPin, LOW);
break;
case 252: // 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);
}
答案 0 :(得分:0)
您需要设置outputState并让它设置,直到它在25秒后重置。如果仍按下按钮,则它将循环显示251。
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;
bool outputState = false;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
}
void loop() {
outputState |= digitalRead(buttonPin); // if pushButton is high, set outputState (low does nothing)
// Print the output
if (outputState)
{
switch (btnCnt++) {
case 100:
stateLED = LOW;
digitalWrite(Relay, HIGH); // after 10s turn on
break;
case 250:
digitalWrite(Relay, LOW); // after 20s turn off
//Toggle ButtonState to LOW from HIGH without user pressing the button
outputState = false; // reset state to low
break;
case 251: // loop (it might happen, if previous step sets outputState=false but button is still pressed -> no action)
--btnCnt;
outputState = false;
break;
}
Serial.println("1");
}else{
Serial.println("0");
if (btnCnt > 0) {
// disable all:
stateLED = LOW;
digitalWrite(Relay, LOW);
}
btnCnt = 0;
}
delay(100);
}