arduino - 使用瞬时按钮的双稳态单按钮切换,保持时不连续切换
问题描述
按住按钮时如何停止连续状态更改?
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 语句集成到循环中,也许还有 SWITCH(case) 语句。
基本上我需要能够通过单次按下来切换输出引脚,我还希望 - 在未来 - 能够通过使用 FOR 和 SWITCH(案例)在一起。那是一个不同的职位。除非您也可以推测出解决该问题的方法。
解决方案
最简单的方法是添加一个保存按钮状态的变量。
当您按下按钮时,该变量设置为 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));
}
推荐阅读
- asp.net - 如何在 plesk 服务器上托管 asp.net webform 动态网站?
- angular - Angular 8,agm api,./node_modules/@agm/core/fesm5/agm-core.js 4538:34-52 中的警告
- python - 替换一行字符串中的一个字符
- tensorflow - 如何微调 tensorflow 对象检测 api 模型?
- node.js - 我正在尝试将存储桶 Grid FS 中的 _id 获取到另一个 mongo 文档
- swift - 具有本地依赖的本地 swift 包
- angular - Angular Material Drag and drop - 拖动一个元素并在放置时将其转换为另一个元素
- php - 将 *.txt 文件中的数据插入 assoc 数组
- javascript - 如何更改 Select2 箭头图标?
- microcontroller - 哪个程序负责从闪存加载到 RAM 并在微控制器裸机中运行程序?