4996浏览
查看: 4996|回复: 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;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail