你好,如果你想要实现长按短按的功能,可以使用以下代码。
int buttonState = 0;
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
// put your setup code here, to run once:
pinMode(2, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
int reading = digitalRead(2);
if (reading != buttonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
// the button state is LOW, which means it's being pressed
// do something here
}
else {
// the button state is HIGH, which means it's not being pressed
// do something here
}
}
}
}
这段代码使用了一个变量 buttonState
来存储按键的当前状态(按下或未按下),并使用变量 lastDebounceTime
来记录按键状态最后一次改变的时间。每次执行循环时,都会读取按键的状态,并与存储在 buttonState
中的值进行比较。如果不同,则将 lastDebounceTime
重置为当前时间。接下来,程序会检查是否已经过了一段时间(在这里设置为 50 毫秒),如果是,则认为按键的状态已经稳定,可以执行相应的操作。
希望这能帮到你。