如何停止按钮时保持连续的状态变化?
const int btn = 5;
const int ledPin = 3;
int ledValue = LOW;
void setup(){
Serial.begin(9600);
pinMode(btn, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop ()
{
if (digitalRead(btn) == LOW)
delay(100);
{
ledValue = !ledValue;
delay(100);
digitalWrite(ledPin, ledValue);
delay(100);
Serial.println(digitalRead(ledPin));
}
}
当我按住按钮,我收到的连续状态变化。 我想按按钮,接收单状态变化,在保持 - 或意外保持 - 我不希望改变状态。
更多的寻找与触发器的结果边缘检测的效果。
还有更多的发展要在此代码实现,但这是第一阶段。 最后,我将整合FOR语句进入循环,也许开关(情况)语句。
基本上,我需要能够切换输出引脚与单瞬间推,我也想 - 在未来 - 基于特定的输入条件,能够以循环可能的输出状态,通过使用和开关的方式(情况)在一起。 这是一个不同的职位。 除非你可以推测该问题的解决方案,以及。
最简单的方法是添加保存按钮的状态的变量。
当您按下按钮时,该变量设置为true,你想要的代码运行。 虽然该变量是真实的,你写的代码不会被执行的第二次。 当您松开按钮时,变量被设置为false,那么下一个按下按钮将再次执行代码。
码:
bool isPressed = false; // the button is currently not pressed
void loop ()
{
if (digitalRead(btn) == LOW) //button is pressed
{
if (!isPressed) //the button was not pressed on the previous loop (!isPressed means isPressed == FALSE)
{
isPressed = true; //set to true, so this code will not run while button remains pressed
ledValue = !ledValue;
digitalWrite(ledPin, ledValue);
Serial.println(digitalRead(ledPin));
}
}
else
{
isPressed = false;
// the button is not pressed right now,
// so set isPressed to false, so next button press will be handled correctly
}
}
编辑:加入的第二示例
const int btn = 5;
const int ledPin = 3;
int ledValue = LOW;
boolean isPressed = false;
void setup(){
Serial.begin(9600);
pinMode(btn, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop ()
{
if (digitalRead(btn) == LOW && isPressed == false ) //button is pressed AND this is the first digitalRead() that the button is pressed
{
isPressed = true; //set to true, so this code will not run again until button released
doMyCode(); // a call to a separate function that holds your code
} else if (digitalRead(btn) == HIGH)
{
isPressed = false; //button is released, variable reset
}
}
void doMyCode() {
ledValue = !ledValue;
digitalWrite(ledPin, ledValue);
Serial.println(digitalRead(ledPin));
}
文章来源: bistable single push toggle using momentary pushbutton, NO contiguous toggle upon hold