取自前面帖子中的按键检测:
直接上代码:
- //逻辑量的四种状态:低,上升,高,下降
- enum edgeSta {low, trg, high, pop};
- //宏名:edge。 返回值:逻辑量状态。输入参数:bool值 用途:检测逻辑量的边沿。
- #define edge(ReadData) ({\
- static bool Trg = false;\
- static bool Cont = false;\
- static bool Pop = false;\
- Trg = ReadData & (ReadData ^ Cont); \
- Pop = Cont != ReadData & !Trg; \
- Cont = ReadData; \
- enum edgeSta sta = low;\
- if (Cont) {\
- sta = high;\
- } else {\
- sta = low;\
- }\
- if (Trg) {\
- sta = trg;\
- }\
- if (Pop) {\
- sta = pop;\
- }\
- sta;\
- })
-
- //宏名:timer。返回值:bool 时间到返回真。参数:enable使能,startTime第一次执行时间,delayTime执行间隔时间,doSomeThing任意表达式到时间执行的任务。
- #define timer(enable,startTime,delayTime,doSomeThing) ({\
- static unsigned long timsta = millis();\
- static unsigned long tim = startTime;\
- bool ret = false;\
- if(!enable){timsta = millis();tim = startTime;}else{\
- if (millis() - timsta>= tim){\
- doSomeThing;\
- ret = true;\
- timsta = millis(); \
- tim = delayTime;\
- }\
- }\
- ret;\
- })
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- pinMode(8, INPUT_PULLUP);
- }
- //检测8号端口按键的状态
- void fun1() {
- enum edgeSta a = edge(!digitalRead(8));
- switch (a)
- {
- case low:
- //Serial.println("low");
- break;
- case trg:
- Serial.println("trg");
- break;
- case high:
- //Serial.println("high");
- break;
- default:
- Serial.println("pop");
- }
- }
- void loop() {
- // put your main code here, to run repeatedly:
- //联合使用定时器和边沿检测处理按键状态。
- timer(true, 0, 20, fun1());
- }
复制代码
|