键盘有一些问题

Keypad having some issues

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

#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 == '.') {
    ...
}