我正在一个项目中,其中键盘应该提供输入,并且所有字符都应转换为Integer值,并且我的代码如下
#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
我该如何解决?
答案 0 :(得分:1)
'DEL'
和'BACK'
是无效字符。
出于可读性考虑,您可以选择其他字符,也可以将它们定义为常量:
const char DEL = 0x7F; // ASCII code for delete
const char BACK = 0x08; // ASCII code for backspace
然后将它们用作DEL
和BACK
(不带单引号):
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 == '.') {
...
}