You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino薄膜键盘数学答题项目故障求助:无法获取键盘输入

Arduino薄膜开关模块无法获取输入的问题修复

问题根源分析

你的代码存在几个关键问题导致无法正常获取键盘输入:

  • 键盘映射数组中使用了**数字字面量(如1、2)**而非字符字面量(如'1'、'2'),getKey()返回的是字符类型,数字2和字符'2'的ASCII码值不同,导致判断永远不匹配。
  • loop()中每次执行都会立刻打印提问,然后仅调用一次getKey()就进入10秒延迟,没有等待用户按键输入的逻辑,程序会跳过输入环节直接进入后续判断。
  • 未处理getKey()返回NO_KEY(无按键按下)的情况,导致空值进入判断逻辑。

修正后的代码

#include <Keypad.h>

// 修正:使用字符字面量定义按键映射
char pad[4][4] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[4] = {9,8,7,6};
byte colPins[4] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(pad), rowPins, colPins, 4, 4);

void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  digitalWrite(10, LOW);
}

void loop() {
  Serial.println("1+1等于多少?");
  
  // 循环等待直到有按键按下
  char answer = NO_KEY;
  while (answer == NO_KEY) {
    answer = customKeypad.getKey();
  }
  
  Serial.print("你输入的答案是:");
  Serial.println(answer);

  // 判断答案是否正确
  if (answer == '2') {
    digitalWrite(10, HIGH);
    delay(30000); // 点亮30秒
    digitalWrite(10, LOW);
    delay(1000);
  } else {
    // 简化闪烁逻辑,循环3次
    for (int i = 0; i < 3; i++) {
      digitalWrite(10, HIGH);
      delay(1000);
      digitalWrite(10, LOW);
      delay(1000);
    }
  }
}

关键修改说明

  • 将按键映射数组中的数字改为字符类型,确保和getKey()返回值类型匹配。
  • 添加循环等待逻辑,直到检测到有效按键输入才继续执行。
  • 简化错误状态下的LED闪烁代码,使用for循环减少冗余。
  • 修正串口提示为中文,符合需求描述。

内容的提问来源于stack exchange,提问作者tomer fleischer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 09:24:23