0

I have a 4*4 keypad and I want to use it to enter a number. I will then use this number as a delay to a LED or a motor to run for the specified time. This is my sample code:

#include<Keypad.h>
#include<LiquidCrystal.h>
const byte numRows = 4; //number of rows on keypad
const byte numCols = 4; //number of columns on keypad


char keymap[numRows][numCols]= 
{
{'1', '2', '3', 'A'}, 
{'4', '5', '6', 'B'}, 
{'7', '8', '9', 'C'},
{'X', '0', 'Y', 'D'}
};

char value[4]="";
int index = 0;

byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

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

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
lcd.begin(20,4);

lcd.print("       WELCOME      ");
delay(100);
}

void loop() {
char keypress = key.getKey();
while (keypress != NO_KEY){  
  if (keypress == 'X'){
      lcd.clear();
      for(int j=0;j<=4;j++){
        value[j]=0;
      }
      index=0;
      }
   else if (keypress == 'Y'){
      int amt = atoi(value);
      digitalWrite(13, HIGH);
      delay(amt);
      } 
   else   
      value[index]=keypress;
      index++;
    }  
}

How do I read the value returned by the keypad as an integer? (When I press 3 I want to read 3 not "3").

3
  • Hello and welcome! What is your actual question?
    – Ghanima
    May 3 '17 at 20:08
  • from this code i should be able to get the input from the keypad and pass the value to delay the led May 3 '17 at 20:15
  • Am I missing something, any reason you can't initialize keymap to contain 3 rather than '3'? It's an array of 8 bit values, why not set it to be the numbers you want rather than text characters?
    – Andrew
    May 4 '17 at 15:51
2

You can easily read by this line of code

value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3

1
  • 1
    I would write '0' rather than 48. The two are equivalent, but the former makes it clearer that you are subtracting the code point of the digit zero. Jan 1 '18 at 16:35
1

Your problem is that you have your keypress matching inside a while loop. That means it will, once matched once, continue matching over and over again as infinitum. You need to replace your while with an if so it only runs once for each keypress.

Not the answer you're looking for? Browse other questions tagged or ask your own question.