开关短按与长按
Sensor_Key库-开关短按与长按示例
所需硬件
电路搭建 将碰撞开关接到Hub的A0/A1引脚。
代码
#include <Microduino_Key.h>
AnalogKey keyAnalog(A0);
void setup() {
Serial.begin(9600);
keyAnalog.begin(INPUT);
}
void loop() {
switch (keyAnalog.readEvent(0, 50)) { //(模拟最小值,模拟最大值)
case SHORT_PRESS:
Serial.println("KEY (analog) SHORT_PRESS"); //短按
break;
case LONG_PRESS:
Serial.println("KEY (analog) LONG_PRESS"); //长按
break;
}
delay(50);
}
#include <Microduino_Key.h>
DigitalKey keyDigital(A0);
void setup() {
Serial.begin(9600);
keyDigital.begin(INPUT_PULLUP);
}
void loop() {
switch (keyDigital.readEvent()) {
case SHORT_PRESS:
Serial.println("KEY (digital) SHORT_PRESS"); //短按
break;
case LONG_PRESS:
Serial.println("KEY (digital) LONG_PRESS"); //长按
break;
}
delay(50);
}
#include <Microduino_Key.h>
VirtualKey keyVirtual;
void setup() {
Serial.begin(9600);
keyVirtual.begin();
pinMode(A0, INPUT_PULLUP);
}
void loop() {
bool val = !digitalRead(A0); //val 可以是任何bool变量
switch (keyVirtual.readEvent(val,1500)) {
case SHORT_PRESS:
Serial.println("KEY (Virtual) SHORT_PRESS"); //短按
break;
case LONG_PRESS:
Serial.println("KEY (Virtual) LONG_PRESS"); //长按
break;
}
delay(50);
}
相关案例
|