4x4矩阵键盘长按按键控制反应,失败

2018-07-151.4万
AI 快速预览详细 收起
本文讨论了使用Arduino连接4x4矩阵键盘和LED灯的项目,目标是实现长按A键3秒后LED灯闪烁。代码上传成功但成功率不稳定。文章详细分析了代码中的缺陷,特别是定时器函数中的初始时刻记录逻辑。通过修正这一部分,可以提高按键响应的稳定性。
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;
}

创作许可协议

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

评论(0)
- 没有更多了 -