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 所需硬件
About Button 关于按钮
If you do not know about button (pinout, how it works, how to program …), learn about them in the following tutorials:
如果您不了解按钮(引脚排列、工作原理、如何编程等),请在以下教程中了解它们:
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