极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 10907|回复: 3

想把4*4键盘上输入的字符转化成字符串,请大神帮忙看下程序哪里出问题了

[复制链接]
发表于 2015-8-3 16:28:40 | 显示全部楼层 |阅读模式
本帖最后由 凯风自北来 于 2015-8-4 18:51 编辑

输入2#之后串口显示是这样的,请问程序哪里出了问题

  1. #include <Keypad.h>
  2. char customKey;
  3. const byte ROWS = 4; //four rows
  4. const byte COLS = 4; //four columns
  5. char hexaKeys[ROWS][COLS] = {
  6.   {'1','2','3','A'},
  7.   {'4','5','6','B'},
  8.   {'7','8','9','C'},
  9.   {'*','0','#','D'}
  10. };
  11. byte rowPins[ROWS] = {9, 8, 7, 6};
  12. byte colPins[COLS] = {5, 4, 3, 2};
  13. Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

  14. void setup() {
  15.     Serial.begin(9600);
  16. }
  17. void loop()
  18. {
  19.   customKey = customKeypad.getKey();
  20.   String res="";
  21.   while( customKey !='#')
  22.   { customKey = customKeypad.getKey();
  23.     res += char(customKey);delay(2);
  24.   }
  25.   Serial.print(res);
  26. }
复制代码

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x
回复

使用道具 举报

发表于 2015-8-4 08:46:48 | 显示全部楼层
while(customKey !='#')
这儿有问题,也就是说,只要你没输入‘#’,就会一直在while循环里面,res会一直变大,又由于你什么都没输入,所以res字符串中才会有这么多空字符。
一般键盘的程序都是当有按键按下后才记录字符。


String res="";
void loop()
{
  customKey = customKeypad.getKey();
  if(customKey=='#')
  {
    Serial.print(res);
  }
  else if(customKey!=' ')
  {
    res += char(customKey);
    delay(2);
  }
}
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-8-4 09:51:49 | 显示全部楼层
164335413 发表于 2015-8-4 08:46
while(customKey !='#')
这儿有问题,也就是说,只要你没输入‘#’,就会一直在while循环里面,res会一直变 ...

我刚刚试了下,没有输入和空格' '不等效
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-8-4 09:53:55 | 显示全部楼层
164335413 发表于 2015-8-4 08:46
while(customKey !='#')
这儿有问题,也就是说,只要你没输入‘#’,就会一直在while循环里面,res会一直变 ...

这样是正确的
  1. String res="";
  2. void loop()
  3. {
  4.   customKey = customKeypad.getKey();
  5.   if(customKey=='#')
  6.   {
  7.     Serial.print(res);
  8.   }
  9.   else if(customKey!=NO_KEY)
  10.   {
  11.     res += char(customKey);
  12.     delay(100);
  13.   }
  14. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-8 14:39 , Processed in 0.070426 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表