1
标题自己说。如何检测Arduino中按下/释放按钮的时间,然后打印一些自定义输出?如何检测Arduino中按下按钮的时间?
注:
有人问这个问题,在我面前,我回答。然而,这个人 删除了他自己的问题,然后才能发送答案。我只是重新问它,所以我可以发布已经写好的答案(希望它可以帮助 其他人)。
标题自己说。如何检测Arduino中按下/释放按钮的时间,然后打印一些自定义输出?如何检测Arduino中按下按钮的时间?
注:
有人问这个问题,在我面前,我回答。然而,这个人 删除了他自己的问题,然后才能发送答案。我只是重新问它,所以我可以发布已经写好的答案(希望它可以帮助 其他人)。
Arduino只能检测到按钮的状态(按下或未按下)。因此,您可以使用基于this example的计时器变量,然后您可以保存按钮/按钮释放的时间。
代码应该是这个样子:
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 is hold
int timeReleased = 0; // the time button is released
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// button state changed
if (buttonState != lastButtonState) {
// the button was just pressed
if (buttonState == HIGH) {
startPressed = milis();
timeReleased = startPressed - endPressed;
if (timeReleased >= 500 && timeReleased < 1000) {
Serial.println("Button idle for half a second");
}
if (timeReleased >= 1000) {
Serial.println("Button idle for one second or more");
}
// the button was just released
} else {
endPressed = milis();
timeHold = endPressed - startPressed;
if (timeHold >= 500 && timeHold < 1000) {
Serial.println("Button hold for half a second");
}
if (timeHold >= 1000) {
Serial.println("Button hold for one second or more");
}
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}