我是 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 上的电路设计,您可以在线查看。
请帮我解决这个问题,这对我来说将是一个很大的帮助。