I am trying to input keypad values to an array. The code compiles without any error. When running the code, the code proceeds into the for loop and prints 'm' on the lcd, but doesn't execute "customKey = customKeypad.getKey();" and the below steps and keeps printing 'm' 5 times. I am not able to enter keypad values. Please help.

#include <LiquidCrystal.h>
#include <Keypad.h>

const int rs = A1, en = A0, d4 = A2, d5 = A3, d6 = A4, d7 = A5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, {
    '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } };

byte rowPins[ROWS] = { 13, 12, 11, 10 };
byte colPins[COLS] = { 9, 8, 7, 6 };

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,
    COLS);

//String inputString = "";
char customKey;
char a[5];

void setup() {
  Serial.begin(9600);
  //inputString.reserve(200);
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  if (Serial.read() == '1') {
    lcd.setCursor(0, 0);
    lcd.print("WELCOME !");
    delay(1000);
    lcd.clear();
    lcd.print("Enter UserID :");
    lcd.setCursor(0, 1);
    for (int i = 0; i < 5; i++) {
      lcd.print('m');
      customKey = customKeypad.getKey();
      delay(30);

      if (customKey) {
        lcd.print('*');
        a[i] = customKey;
      }
      if (i == 5) {
        a[i] = '\0';
        break;
      }

      delay(1000);
    }
  }
}

customKeypad.getKey(); doesn't wait for the key press. it returns 0 if no key is pressed.

you should rewrite the sketch to a version where the loop() can loop and key presses are read as they are pressed.

  • Is there no other way ? I am checking Serial.read()=='1' because I need to get '1' serial output from a zigbee connected to the Arduino to proceed to used id. – maheshmt Dec 4 at 10:33
  • You do not have to rewrite the sketch, but you should. It is definitely better to write non-blocking code, because then you can add other functionalities, which seem to happen simultaneously. When you really don't want to, just put the getKey() command inside a while(customKey == 0) statement. It will block the program, until a key is pressed. – chrisl Dec 4 at 14:49
  • the rewrite requires a use of state variable. it can then include the 'idle' state before '1' was received over Serial – kamen Dec 6 at 10:28

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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