【发布时间】:2020-08-17 20:46:33
【问题描述】:
我是 Ansh Goel,我正在向 Udemy 学习 Arduino。我是这个领域的初学者。我正在为按钮去抖动创建一个代码来解决反弹电压的问题。但是代码中有错误。没有编译时错误,但它是运行时错误。
我还尝试使用 Serial.print() 检查代码以找到错误所在,然后我发现错误出现在第二个嵌套 if 条件中。 为了方便起见,我还提到了代码中的错误。那里我也无法将 Serial.print("A") 函数获取到串行监视器。
我的主要动机是运行代码,以便在按下按钮时使用一些延迟来停止电压反弹。
从第 41 行开始
这是我用来消除按钮抖动的代码
const int btn_pin = 2;
const int debounce_delay = 50; //ms
// We need to remember the previous button state between loops
int btn_prev = HIGH;
int btn_state = HIGH;
unsigned long last_debounce_time = 0;
// Counter
int counter = 0;
void setup() {
Serial.begin(9600);
// Set up pins
pinMode(btn_pin, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop() {
int btn_read;
// Read current button state
btn_read = digitalRead(btn_pin);
//Remember when the button change state
// If the button was previously HIGH and now LOW, it's been pressed
if ( (btn_prev == HIGH) && (btn_read == LOW )) {
//Store the time it took to take the action for button press
last_debounce_time = millis();
}
//Wait before changing the state of the button
// IN THIS CONDITION THERE IS ERROR SOMEWHERE I AM NOT GETTING IT
if(millis() > (last_debounce_time + debounce_delay)){
if(btn_read != btn_state) {
Serial.println("A");
// Then store the button change value to the global variable
btn_state = btn_read;
if(btn_state == LOW) {
// Increment and print counter
counter++;
Serial.println(counter);
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
}
}
// Remember the previous button state for the next loop iteration
btn_prev = btn_state;
}
出于测试目的,这是 TinkerCad 上的电路设计,您可以在线查看。
请帮我解决问题,这对我来说将是一个很大的帮助。
【问题讨论】:
-
最后应该将 btn_prev 设置为 btn_state 还是应该在那里使用 btn_read?考虑一下这些变量中的每一个代表什么,并以两种方式引导您自己完成代码。
标签: c++ c arduino circuit tinkercad