arduino宏的应用实例2--用宏暴力处理矩阵键盘 (转)

2016-05-011.6万
AI 快速预览详细 收起
本文介绍了使用宏定义处理矩阵键盘的方法。通过单独扫描每个按键并分别响应事件,实现了多键同时按下的功能。这种方法简化了键盘扫描的过程,提高了代码的可读性和效率。示例代码中使用了静态变量和时间标志来处理按键事件。
上次说到可以用宏处理按键消息,其实稍作改动就能很暴力的处理矩阵按键,直接上代码:
  1. #define readMatrixKey(rowPin,columnPin,onTrigger,onPop) do{\
  2.     pinMode(columnPin,INPUT_PULLUP);\
  3.     pinMode(rowPin,OUTPUT);\
  4.     static bool Trg = false;\
  5.     static bool Cont = false;\
  6.     static bool Pop = false;\
  7.     static unsigned long timdel = millis();\
  8.     if (millis() - timdel >= 20) {\
  9.       bool ReadData = !digitalRead(columnPin);\
  10.       Trg = ReadData & (ReadData ^ Cont); \
  11.       Pop = Cont != ReadData & !Trg; \
  12.       Cont = ReadData; \
  13.       if (Trg) {\
  14.         onTrigger;\
  15.       }\
  16.       if (Pop) {\
  17.         onPop; \
  18.       }\
  19.       timdel = millis(); \
  20.     }\
  21.     pinMode(columnPin,INPUT);\
  22.     pinMode(rowPin,INPUT);\
  23.   } while (0)
  24. void setup() {
  25.   // put your setup code here, to run once:
  26.   for (int i = 2; i < 10; i++)
  27.   {
  28.     pinMode(i, INPUT);
  29.   }
  30.   Serial.begin(9600);
  31. }
  32. void loop() {
  33.   // put your main code here, to run repeatedly:
  34.   readMatrixKey(2, 6,  Serial.println("2,6 PUSH"), Serial.println("2,6 POP"));
  35.   readMatrixKey(2, 7,  Serial.println("2,7 PUSH"), Serial.println("2,7 POP"));
  36.   readMatrixKey(2, 8,  Serial.println("2,8 PUSH"), Serial.println("2,8 POP"));
  37. }
复制代码
2到9pin对应矩阵薄膜按键的8个针
这种按键arduino宏的应用实例2--用宏暴力处理矩阵键盘 (转)图1rowPin对应输出针脚
columnPin对应输入针脚
这段程序中我没有像常规的矩阵键盘处理一样扫描矩阵键盘的整体键码,而是单独扫描每个按键,并分别对按键的事件作出相应,这也就是我为什么说处理方式很暴力的原因了,支持多键同时按下。
运行效果arduino宏的应用实例2--用宏暴力处理矩阵键盘 (转)图2


修正一个BUG时间标志的类型应该是static unsigned long ,而不是static int,否则定时在30多秒后失效。

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(1)
dsweiliang
dsweiliang
学习学习
- 没有更多了 -