I am working on a project where the keypad should provide inputs and all the characters should be converted into Integer values and my code is as follows
#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;
}
}
everything is fine the prob comes when I am pressing the del key it is deleting elements sometimes from the beginning of the output. Output is
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
How can I resolve this?
'DEL'
and 'BACK'
are not valid characters.
You could chose different characters or you could define them as constants for readability's sake:
const char DEL = 0x7F; // ASCII code for delete
const char BACK = 0x08; // ASCII code for backspace
And then use them as DEL
and BACK
(without single quotes):
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 == '.') {
...
}