wwwymq 发表于 2016-4-24 23:39:03

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

本帖最后由 wwwymq 于 2016-4-26 00:26 编辑

上次说到可以用宏处理按键消息:http://www.geek-workshop.com/thread-26618-1-1.html
其实稍作改动就能很暴力的处理矩阵按键,直接上代码:
#define readMatrixKey(rowPin,columnPin,onTrigger,onPop) do{\
    pinMode(columnPin,INPUT_PULLUP);\
    pinMode(rowPin,OUTPUT);\
    static bool Trg = false;\
    static bool Cont = false;\
    static bool Pop = false;\
    static unsigned long timdel = millis();\
    if (millis() - timdel >= 20) {\
      bool ReadData = !digitalRead(columnPin);\
      Trg = ReadData & (ReadData ^ Cont); \
      Pop = Cont != ReadData & !Trg; \
      Cont = ReadData; \
      if (Trg) {\
      onTrigger;\
      }\
      if (Pop) {\
      onPop; \
      }\
      timdel = millis(); \
    }\
    pinMode(columnPin,INPUT);\
    pinMode(rowPin,INPUT);\
} while (0)
void setup() {
// put your setup code here, to run once:
for (int i = 2; i < 10; i++)
{
    pinMode(i, INPUT);
}
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
readMatrixKey(2, 6,Serial.println("2,6 PUSH"), Serial.println("2,6 POP"));
readMatrixKey(2, 7,Serial.println("2,7 PUSH"), Serial.println("2,7 POP"));
readMatrixKey(2, 8,Serial.println("2,8 PUSH"), Serial.println("2,8 POP"));
}
2到9pin对应矩阵薄膜按键的8个针
这种按键:

rowPin对应输出针脚
columnPin对应输入针脚
这段程序中我没有像常规的矩阵键盘处理一样扫描矩阵键盘的整体键码,而是单独扫描每个按键,并分别对按键的事件作出相应,这也就是我为什么说处理方式很暴力的原因了,支持多键同时按下。
运行效果

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

wwwymq 发表于 2016-4-25 00:10:26

沙发自己坐

novelcrab 发表于 2016-4-25 16:25:51

确实很暴力,调用也很方便,真心不错,谢谢分享!

novelcrab 发表于 2016-4-25 16:27:21

在坛子里应该多鼓励这种基础性的代码,按键处理是做一个完整的、可以应用于商业的最基本的东西

wwwymq 发表于 2016-4-26 00:25:52

novelcrab 发表于 2016-4-25 16:25 static/image/common/back.gif
确实很暴力,调用也很方便,真心不错,谢谢分享!

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

darkorigin 发表于 2016-4-26 17:43:01

不错呢。。。鼓励

darkorigin 发表于 2016-4-26 17:44:18

novelcrab 发表于 2016-4-25 16:27 static/image/common/back.gif
在坛子里应该多鼓励这种基础性的代码,按键处理是做一个完整的、可以应用于商业的最基本的东西

他这个代码解决的不是有和无的问题
层面更高,
实现了键位冲突的检测。
基础的商业键盘只有基础的检测功能即可,逐键扫描即可
页: [1]
查看完整版本: arduino宏的应用实例2--用宏暴力处理矩阵键盘