c++ - 尝试在按下时消除此按钮的抖动
问题描述
所以我有一个T-Beam。我正在尝试在按下按钮时实现 D-bounce,这样当按下按钮时,无论多长时间都会有去抖动。目前我让它工作,所以当按下按钮时,它会打印,但由于按钮的噪音,它会打印数百次。我已经放入了去抖代码,但是它没有按预期工作,我不知道为什么。
请查看下面的代码,因为我正在努力实现它。
#include <LoRa.h>
#define SS 18 // GPIO18 −− CS
#define RST 14 // GPIO14 −− RESET
#define DI0 26 // GPIO26 −− I n t e r r u p t Request
#define BAND 868E6 // 868MHz −− UK/European Radio
const int buttonPin = 38;
int buttonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 200;
void setup() {
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
// i n i t i a l i z e S e r i a l Monitor
Serial.begin(115200);
}
int counter = 0;
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
( (millis() - lastDebounceTime) > debounceDelay);
}
else {
Serial.println("HELLO!");
lastDebounceTime = millis();
}
解决方案
您的代码似乎包含一个已执行但从未使用结果的语句。我说的是行话( (millis() - lastDebounceTime) > debounceDelay)
。我稍微更改了您的代码以实现正确的去抖动:
bool buttonState = LOW, previousState = HIGH, buttonPressed = false;
void loop()
{
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH)
{
if(previousState == LOW)
{
lastDebounceTime = millis();
}
else if(millis() - lastDebounceTime > debounceDelay && !buttonPressed)
{
// this will be executed once after debouncing
Serial.println("HELLO!");
buttonPressed = true;
}
}
else
{
buttonPressed = false;
}
previousState = buttonState;
}
推荐阅读
- google-apps-script - 无法在自己的 Google 表格中运行自己的脚本 - 出现“应用未验证”
- search - 为什么在 DNN 中添加业务控制器类命名空间会使模块消失?
- javascript - Vue - 在动态加载的组件上将组件传递给路由器视图
- css - 使用引导程序 4.0 将一行与中心对齐
- android - 如何在复合视图中删除 ConstraintLayout 的默认边距?
- python-3.x - 计算由 matplotlib.pyplot.fill(...) 填充的区域
- apache-kafka - 将记录从 oracle db 流式传输到 kafka 的方法是什么
- excel - 使用 VBA 创建一个没有空列和行的 CSV 文件
- c++ - 如何在像素图中填充源外部的颜色
- flutter - 时间戳到 LocalDateTime 的转换