6318| 0
|
[求助] 4x4矩阵键盘长按按键控制反应,失败 |
用Arduino连接4x4矩阵键盘,LED灯。写了代码,目的是:长按A键3秒后LED灯闪一下。代码上传成功,但是目前的成功率很迷,有的时候按三秒就正常反应,有的时候不管我按下多少秒灯都不做理会。所以我的代码肯定存在缺陷。希望有人帮忙指点一下,不胜感激! 代码如下: #include <Keypad.h> int LED = 13; const byte ROWS = 4; const byte COLS = 4; char hexaKeys[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {4, 5, 6, 7}; //connect to the row pinouts of the keypad byte colPins[COLS] = {8, 9, 10, 11}; //connect to the column pinouts of the keypad //initialize an instance of class NewKeypad Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); } void loop() { char customKey = customKeypad.getKey(); if (timer()) { digitalWrite(LED, HIGH); delay(2000); digitalWrite(LED, LOW); } } bool timer() { //timer这个函数是我自定义的,前面大部分是示例,错误就在这部分 char customKey = customKeypad.getKey(); int setTime = 3000; //设定所需连续按键时间 int flag = 0; if (customKey == 'A') { flag = 1; long orgTime = millis();//感觉这句不太对,我想用orgTime标记按下A键的初时刻,但是由于A一直按着,orgTime可能会往后变化?? while (millis() - orgTime <= setTime) { if (customKey != 'A')flag = 0; } } if (flag == 1)return true; else return false; } |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed