c++ - 键盘有一些问题

标签 c++ arduino keypad

我正在做一个项目,键盘应该提供输入,所有字符都应该转换成整数值,我的代码如下

#include <Keypad.h>
#include <string.h>
#define buttonPin 2

int buttonpressed = HIGH;
const byte numRows= 4;
const byte numCols= 4;
char num[20];
int i =0;
char keymap[numRows][numCols]= { 
{'1','2','3','A'}, // A B C for future use
{'4','5','6','B'},
{'7','8','9','C'},
{'.','0','DEL','BACK'} 
};
byte rowPins[numRows] = {7,6,5,4}; //Rows 0 to 3
byte colPins[numCols]= {11,10,9,8}; //Columns 0 to 3

Keypad matrix= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

void setup() 
{
  pinMode(buttonPin,INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  buttonpressed = digitalRead(buttonPin);
  char key = matrix.getKey();
  if(key != NO_KEY && key == 'DEL')
  {
    i=0;
    Serial.println();
  }
  if(key != NO_KEY && key == 'BACK')
  {
    i=i-1;
    Serial.println();
    for(int j=0;j<=i;j++)
    Serial.print(num[j]);
  }
  if (key != NO_KEY  && (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'||key=='.')){
    num[i] = key;
    Serial.print(num[i]);
    i++;
    }

 if(buttonpressed == LOW){
  int length = strlen(num);
  double val = atof(num);
 Serial.println();
 Serial.print("The float number = ");
 Serial.println(val);
 delay(500);
 for(i = 0; i<=length; i++)
 {
  num[i] = '0';
 }
 i=0;
 }
}

一切正常当我按下 del 键时,问题出现了,它有时会从输出的开头删除元素。 输出是

7.77               // pressed BACK
7.7                // pressed BACK
7.77770.           // pressed BACK
777770.            // pressed BACK
777770             // pressed BACK
77777              // pressed DEL
77755888444417.777 // pressed BACK
7755888444417.777  // pressed BACK

我该如何解决?

最佳答案

'DEL''BACK' 不是有效字符。

为了可读性,您可以选择不同的字符或将它们定义为常量:

const char DEL  = 0x7F; // ASCII code for delete
const char BACK = 0x08; // ASCII code for backspace

然后将它们用作 DELBACK(不带单引号):

char keymap[numRows][numCols]= { 
    {'1','2','3','A'}, // A B C for future use
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'.','0',DEL,BACK} 
};
char key = matrix.getKey();
if (key == DEL) {
    ...
}
else if (key == BACK) {
    ...
}
else if (('0' <= key && key <= '9') || key == '.') {
    ...
}

关于c++ - 键盘有一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51083259/

相关文章:

android - 如何从 Android 键盘中为 EditText 排除特殊字符

javascript - 错误 : fs. readFileSync 不是函数

c - ESP8266异常(3)

c++ - 遍历 C 中数组中不存在的变量

c++ - 使用私有(private)参数调用公共(public)函数

c++ - SD.remove() 没有删除 Arduino C++ 上的文件

android - 在 ActionBar 中将数字输入类型设置为 SearchView

带有十进制错误的Xcode数字键盘

c++ - Release模式工作正常但 Debug模式给出未处理的异常 - 使用 Octave DLL

c++ - 如何在C中定义函数指针数组