首页 > 解决方案 > Arduino,去抖电压时间延迟代码中的运行时间代码错误

问题描述

我是 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 上的电路设计,您可以在线查看。

TinkerCad 电路设计

请帮我解决这个问题,这对我来说将是一个很大的帮助。

标签: c++carduinocircuittinkercad

解决方案


您的代码可能在多个位置出现故障:

  • 你没有正确循环 for loop
  • 你的逻辑不起作用
  • 数字阅读不起作用
  • 打印不起作用

首先,删除去抖动检查,看看这是否有效:

//if(millis() > (last_debounce_time + debounce_delay)){

要检查所有其他问题,请在其余 if 之前添加以下内容:

  • 延迟,这样你就不会得到无穷无尽的数据
  • 打印millis、last_debounce_time、debounce_delay和btn_read
  • 结束线

然后运行并按下按钮。输出会让你知道问题出在哪里


推荐阅读