开关状态与动作
Sensor_Key库-开关状态与动作示例
所需硬件
电路搭建 将碰撞开关接到Hub的A0/A1引脚。
代码
#include <Microduino_Key.h>
AnalogKey keyAnalog(A0);
void setup() {
Serial.begin(9600);
keyAnalog.begin(INPUT);
}
void loop() {
switch (keyAnalog.readVal(0, 50)) { //(模拟最小值,模拟最大值)
case KEY_RELEASED:
Serial.println("KEY (analog) RELEASED---1"); //按键释放状态
break;
case KEY_PRESSED:
Serial.println("KEY (analog) PRESSED-------2"); //按键按下状态
break;
case KEY_PRESSING:
Serial.println("KEY (analog) PRESSING--------3"); //按键按下动作
break;
case KEY_RELEASING:
Serial.println("KEY (analog) RELEASING---------4"); //按键释放动作
break;
}
delay(100);
}
#include <Microduino_Key.h>
DigitalKey keyDigital(A0);
void setup() {
Serial.begin(9600);
keyDigital.begin(INPUT_PULLUP);
}
void loop() {
switch (keyDigital.readVal()) {
case KEY_RELEASED:
Serial.println("KEY (digital) RELEASED---1"); //按键释放状态
break;
case KEY_PRESSED:
Serial.println("KEY (digital) PRESSED-------2"); //按键按下状态
break;
case KEY_PRESSING:
Serial.println("KEY (digital) PRESSING--------3"); //按键按下动作
break;
case KEY_RELEASING:
Serial.println("KEY (digital) RELEASING---------4"); //按键释放动作
break;
}
delay(100);
}
#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.readVal(val)) {
case KEY_RELEASED:
Serial.println("KEY (digital) RELEASED---1"); //按键释放状态
break;
case KEY_PRESSED:
Serial.println("KEY (digital) PRESSED-------2"); //按键按下状态
break;
case KEY_PRESSING:
Serial.println("KEY (digital) PRESSING--------3"); //按键按下动作
break;
case KEY_RELEASING:
Serial.println("KEY (digital) RELEASING---------4"); //按键释放动作
break;
}
delay(100);
}
相关案例
|