Arduino - Button - Long Press Short Press Arduino - 按钮 - 长按短按
Arduino - Button - Long Press Short Press
We will learn: 我们将学习:
- How to detect the button’s short press
如何检测按钮的短按 - How to detect the button’s long press
如何检测按钮的长按 - How to detect both the button’s long press and short press
如何检测按钮的长按和短按 - Long press and short press with debouncing
长按和短按带去弹跳
In the first three parts, we learn how to detect in principle.
在前三部分中,我们学习了如何原则上进行检测。
In the last part, we learn how to detect in practical use by applying the debounce. See why do we need to debounce for button. Without debouncing, we may detect wrong the button short press.
在最后一部分中,我们将学习如何通过应用去抖动来检测实际使用中的检测。看看为什么我们需要为按钮去抖动。如果不去抖动,我们可能会检测到错误的按钮短按。
Hardware Required 所需硬件
1 | × | Arduino UNO or Genuino UNO Arduino UNO 或 Genuino UNO | |
---|---|---|---|
1 | × | USB 2.0 cable type A/B USB 2.0 电缆 A/B 型 | |
1 | × | Push Button 按钮 | |
1 | × | (Optional) Panel-mount Push Button (可选)面板安装按钮 | |
1 | × | Breadboard 面包板 | |
1 | × | Jumper Wires 跳线 | |
1 | × | (Optional) 9V Power Adapter for Arduino (可选)用于Arduino的9V电源适配器 | |
1 | × | (Recommended) Screw Terminal Block Shield for Arduino Uno (推荐)用于Arduino Uno的螺钉接线端子屏蔽层 | |
1 | × | (Optional) Transparent Acrylic Enclosure For Arduino Uno (可选)Arduino Uno透明亚克力外壳 |
About Button 关于按钮
If you do not know about button (pinout, how it works, how to program …), learn about them in the following tutorials:
如果您不了解按钮(引脚排列、工作原理、如何编程等),请在以下教程中了解它们:
- Arduino - Button tutorial
Arduino - 按钮教程
Wiring Diagram 接线图
In this tutorial, we will use the internal pull-up resistor. Therefore, the state of the button is HIGH when normal and LOW when pressed.
在本教程中,我们将使用内部上拉电阻。因此,按钮的状态在正常时为高电平,按下时为低电平。
How To Detect Short Press 如何检测短按
We measure the time duration between the pressed and released events. If the duration is shorter than a defined time, the short press event is detected.
我们测量按下和发布事件之间的持续时间。如果持续时间短于定义的时间,则检测短按事件。
Let’s see step by step:
让我们一步一步地看:
- Define how long the maximum of short press lasts
定义短按的最大持续时间
const int SHORT_PRESS_TIME = 500; // 500 milliseconds
- Detect the button is pressed and save the pressed time
检测按钮是否被按下并保存按下时间
if(lastState == HIGH && currentState == LOW)pressedTime = millis();
- Detect the button is released and save the released time
检测按钮已释放并保存释放时间
if(lastState == LOW && currentState == HIGH)releasedTime = millis();
- Calculate press duration and
计算按压持续时间和
long pressDuration = releasedTime - pressedTime;
- Determine the short press by comparing the press duration with the defined short press time.
通过将按压持续时间与定义的短按压时间进行比较来确定短按。
if( pressDuration < SHORT_PRESS_TIME ) Serial.println("A short press is detected");
Arduino Code for detecting the short press 用于检测短按的Arduino代码
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int SHORT_PRESS_TIME = 500; // 500 milliseconds// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;void setup() {Serial.begin(9600);pinMode(BUTTON_PIN, INPUT_PULLUP);
}void loop() {// read the state of the switch/button:currentState = digitalRead(BUTTON_PIN);if(lastState == HIGH && currentState == LOW) // button is pressedpressedTime = millis();else if(lastState == LOW && currentState == HIGH) { // button is releasedreleasedTime = millis();long pressDuration = releasedTime - pressedTime;if( pressDuration < SHORT_PRESS_TIME )Serial.println("A short press is detected");}// save the the last statelastState = currentState;
}
Quick Steps 快速步骤
- Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Press the button shortly several times.
短按按钮几次。 - See the result on Serial Monitor
在串行监视器上查看结果
※ NOTE THAT: ※ 注意事项:
The Serial Monitor may show several short press detection for one press. This is the normal behavior of the button. This behavior is called the “chattering phenomenon”. The issue will be solved in the last part of this tutorial.
串行监视器可能会显示一次按下的几次短按检测。这是按钮的正常行为。这种行为被称为“颤动现象”。该问题将在本教程的最后一部分解决。
How To Detect Long Press 如何检测长按
There are two use cases for detecting the long press.
检测长按有两个用例。
- The long-press event is detected right after the button is released
释放按钮后立即检测到长按事件 - The long-press event is detected during the time the button is being pressed, even the button is not released yet.
在按下按钮期间检测到长按事件,甚至按钮尚未松开。
In the first use case, We measure the time duration between the pressed and released events. If the duration is longer than a defined time, the long-press event is detected.
在第一个用例中,我们测量按下和发布事件之间的持续时间。如果持续时间超过定义的时间,则检测长按事件。
In the second use case, After the button is pressed, We continuously measure the pressing time and check the long-press event until the button is released. During the time button is being pressed. If the duration is longer than a defined time, the long-press event is detected.
在第二个用例中,按下按钮后,我们连续测量按下时间并检查长按事件,直到释放按钮。在按下时间按钮期间。如果持续时间超过定义的时间,则检测长按事件。
Arduino Code for detecting long press when released Arduino代码,用于在释放时检测长按
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int LONG_PRESS_TIME = 1000; // 1000 milliseconds// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;void setup() {Serial.begin(9600);pinMode(BUTTON_PIN, INPUT_PULLUP);
}void loop() {// read the state of the switch/button:currentState = digitalRead(BUTTON_PIN);if(lastState == HIGH && currentState == LOW) // button is pressedpressedTime = millis();else if(lastState == LOW && currentState == HIGH) { // button is releasedreleasedTime = millis();long pressDuration = releasedTime - pressedTime;if( pressDuration > LONG_PRESS_TIME )Serial.println("A long press is detected");}// save the the last statelastState = currentState;
}
Quick Steps 快速步骤
- Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Press and release the button after one second.
一秒钟后按下并松开按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
The long-press event is only detected right after the button is released
只有在释放按钮后才能检测到长按事件
Arduino Code for detecting long press during pressing 用于在按压过程中检测长按的Arduino代码
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int LONG_PRESS_TIME = 1000; // 1000 milliseconds// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
bool isPressing = false;
bool isLongDetected = false;void setup() {Serial.begin(9600);pinMode(BUTTON_PIN, INPUT_PULLUP);
}void loop() {// read the state of the switch/button:currentState = digitalRead(BUTTON_PIN);if(lastState == HIGH && currentState == LOW) { // button is pressedpressedTime = millis();isPressing = true;isLongDetected = false;} else if(lastState == LOW && currentState == HIGH) { // button is releasedisPressing = false;}if(isPressing == true && isLongDetected == false) {long pressDuration = millis() - pressedTime;if( pressDuration > LONG_PRESS_TIME ) {Serial.println("A long press is detected");isLongDetected = true;}}// save the the last statelastState = currentState;
}
Quick Steps 快速步骤
- Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Press and release the button after several seconds.
几秒钟后按下并松开按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
How To Detect Both Long Press and Short Press 如何检测长按和短按
Short Press and Long Press after released 发布后短按和长按
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int SHORT_PRESS_TIME = 1000; // 1000 milliseconds
const int LONG_PRESS_TIME = 1000; // 1000 milliseconds// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;void setup() {Serial.begin(9600);pinMode(BUTTON_PIN, INPUT_PULLUP);
}void loop() {// read the state of the switch/button:currentState = digitalRead(BUTTON_PIN);if(lastState == HIGH && currentState == LOW) // button is pressedpressedTime = millis();else if(lastState == LOW && currentState == HIGH) { // button is releasedreleasedTime = millis();long pressDuration = releasedTime - pressedTime;if( pressDuration < SHORT_PRESS_TIME )Serial.println("A short press is detected");if( pressDuration > LONG_PRESS_TIME )Serial.println("A long press is detected");}// save the the last statelastState = currentState;
}
Quick Steps 快速步骤
- Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Long and short press the button.
长按和短按按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
※ NOTE THAT: ※ 注意事项:
The Serial Monitor may show several short press detection when long press. This is the normal behavior of the button. This behavior is called the “chattering phenomenon”. The issue will be solved in the last part of this tutorial.
长按时,串行监视器可能会显示几次短按检测。这是按钮的正常行为。这种行为被称为“颤动现象”。该问题将在本教程的最后一部分解决。
Short Press and Long Press During pressing 短按和长按 按压过程中
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int SHORT_PRESS_TIME = 1000; // 1000 milliseconds
const int LONG_PRESS_TIME = 1000; // 1000 milliseconds// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongDetected = false;void setup() {Serial.begin(9600);pinMode(BUTTON_PIN, INPUT_PULLUP);
}void loop() {// read the state of the switch/button:currentState = digitalRead(BUTTON_PIN);if(lastState == HIGH && currentState == LOW) { // button is pressedpressedTime = millis();isPressing = true;isLongDetected = false;} else if(lastState == LOW && currentState == HIGH) { // button is releasedisPressing = false;releasedTime = millis();long pressDuration = releasedTime - pressedTime;if( pressDuration < SHORT_PRESS_TIME )Serial.println("A short press is detected");}if(isPressing == true && isLongDetected == false) {long pressDuration = millis() - pressedTime;if( pressDuration > LONG_PRESS_TIME ) {Serial.println("A long press is detected");isLongDetected = true;}}// save the the last statelastState = currentState;
}
Quick Steps 快速步骤
- Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Long and short press the button.
长按和短按按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
※ NOTE THAT: ※ 注意事项:
The Serial Monitor may show several short press detection when long press. This is the normal behavior of the button. This behavior is called the “chattering phenomenon”. The issue will be solved in the last part of this tutorial.
长按时,串行监视器可能会显示几次短按检测。这是按钮的正常行为。这种行为被称为“颤动现象”。该问题将在本教程的最后一部分解决。
Long Press and Short Press with Debouncing 长按和短按带去弹跳
It is very important to debounce the button in many applications.
在许多应用中,对按钮进行去抖动非常重要。
Debouncing is a little complicated, especially when using multiple buttons. To make it much easier for beginners, we created a library, called ezButton.
去抖动有点复杂,尤其是在使用多个按钮时。为了让初学者更容易,我们创建了一个名为 ezButton 的库。
We will use this library in below codes
我们将在下面的代码中使用这个库
Short Press and Long Press with debouncing after released 短按和长按,释放后去弹跳
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/#include <ezButton.h>const int SHORT_PRESS_TIME = 1000; // 1000 milliseconds
const int LONG_PRESS_TIME = 1000; // 1000 millisecondsezButton button(7); // create ezButton object that attach to pin 7;unsigned long pressedTime = 0;
unsigned long releasedTime = 0;void setup() {Serial.begin(9600);button.setDebounceTime(50); // set debounce time to 50 milliseconds
}void loop() {button.loop(); // MUST call the loop() function firstif(button.isPressed())pressedTime = millis();if(button.isReleased()) {releasedTime = millis(); long pressDuration = releasedTime - pressedTime; if( pressDuration < SHORT_PRESS_TIME )
Serial.println("A short press is detected"); if( pressDuration > LONG_PRESS_TIME )
Serial.println("A long press is detected");}
}
Quick Steps 快速步骤
- Install ezButton library. See How To
安装 ezButton 库。了解操作方法 - Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Long and short press the button.
长按和短按按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
Short Press and Long Press with debouncing During Pressing 短按和长按,按压过程中去弹跳
/** Created by ArduinoGetStarted.com** This example code is in the public domain** Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press*/#include <ezButton.h>const int SHORT_PRESS_TIME = 1000; // 1000 milliseconds
const int LONG_PRESS_TIME = 1000; // 1000 millisecondsezButton button(7); // create ezButton object that attach to pin 7;unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongDetected = false;void setup() {Serial.begin(9600);button.setDebounceTime(50); // set debounce time to 50 milliseconds
}void loop() {button.loop(); // MUST call the loop() function firstif(button.isPressed()){pressedTime = millis();isPressing = true;isLongDetected = false;}if(button.isReleased()) {isPressing = false;releasedTime = millis();long pressDuration = releasedTime - pressedTime;if( pressDuration < SHORT_PRESS_TIME )Serial.println("A short press is detected");}if(isPressing == true && isLongDetected == false) {long pressDuration = millis() - pressedTime;if( pressDuration > LONG_PRESS_TIME ) {Serial.println("A long press is detected");isLongDetected = true;}}
}
Quick Steps 快速步骤
- Install ezButton library. See How To
安装 ezButton 库。了解操作方法 - Upload the above code to Arduino via Arduino IDE
通过Arduino IDE将上述代码上传到Arduino - Long and short press the button.
长按和短按按钮。 - See the result on Serial Monitor
在串行监视器上查看结果
Video Tutorial 视频教程
We are considering to make the video tutorials. If you think the video tutorials are essential, please subscribe to our YouTube channel to give us motivation for making the videos.
我们正在考虑制作视频教程。如果您认为视频教程是必不可少的,请订阅我们的 YouTube 频道,为我们制作视频提供动力。
Why Needs Long Press and Short Press 为什么需要长按和短按
- To save the number of buttons. A single button can keep two or more functionalities. For example, short press for changing operation mode, long press for turn off the device.
保存按钮数量。一个按钮可以保留两个或多个功能。例如,短按可更改操作模式,长按可关闭设备。 - Use of long press to reduce the short press by accident. For example, some kinds of devices use the button for factory reset. If the button is pressed by accident, it is dangerous. To avoid it, the device is implemented to be factory reset only when the button is long-press (e.g over 5 seconds)
使用长按减少意外短按。例如,有些设备使用按钮进行出厂重置。如果意外按下按钮,就会造成危险。为了避免这种情况,设备只有在长按按钮(例如超过 5 秒)时才能进行出厂重置。