如何检测Arduino中按下按钮的时间?

Raf*_*kel 3 c atmega arduino

标题说明了一切.如何检测Arduino中按下/释放按钮的时间长度,然后打印一些自定义输出?

注意:

有人在我面前问了这个问题,我回答.然而,在我发送答案之前,这个人删除了他自己的问题.我只是重新问了所以我可以发布已经写好的答案(希望它可以帮助其他人).

Raf*_*kel 12

Arduino只能检测按钮的状态(按下或未按下).因此,您可以使用基于此示例的计时器变量,然后您可以保存按下/释放按钮的时间.

代码看起来应该是这样的:

const int buttonPin = 2;  

int buttonState = 0;     // current state of the button
int lastButtonState = 0; // previous state of the button
int startPressed = 0;    // the time button was pressed
int endPressed = 0;      // the time button was released
int timeHold = 0;        // the time button was hold
int timeReleased = 0;    // the time button was released

void setup() {
  pinMode(buttonPin, INPUT); // initialize the button pin as a input
  Serial.begin(9600);        // initialize serial communication
}

void loop() {
  buttonState = digitalRead(buttonPin); // read the button input

  if (buttonState != lastButtonState) { // button state changed
     updateState();
  }

  lastButtonState = buttonState;        // save state for next loop
}

void updateState() {
  // the button was just pressed
  if (buttonState == HIGH) {
      startPressed = millis();
      timeReleased = startPressed - endPressed;

      if (timeReleased >= 500 && timeReleased < 1000) {
          Serial.println("Button was idle for half a second");
      }

      if (timeReleased >= 1000) {
          Serial.println("Button was idle for one second or more"); 
      }

  // the button was just released
  } else {
      endPressed = millis();
      timeHold = endPressed - startPressed;

      if (timeHold >= 500 && timeHold < 1000) {
          Serial.println("Button was hold for half a second"); 
      }

      if (timeHold >= 1000) {
          Serial.println("Button was hold for one second or more"); 
      }

  }
}
Run Code Online (Sandbox Code Playgroud)