When I enter second digit it replaces first one and starts from there

Video: https://streamable.com/18b3xv
Code:

#include <Keypad.h>
#include <Servo.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);
int position = 0;
char password[5] = "1234";
char input[5];
bool canType = true;

const byte rows = 4;
const byte cols = 4;

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

byte rowPins[rows] = { 9, 8, 7, 6 };
byte colPins[cols] = { 5, 4, 3, 2 };

Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.clear();
  lcd.backlight();
}

void loop() {
  char key = customKeypad.getKey();

  if (key && position < 4 && canType) {
    lcd.print(key);
    lcd.setCursor(position, 0);
    input[position] = key;
    Serial.println(position);
    position++;
  }

  //Checking
  if(position == 4){
    canType = false;
    delay(1000);
    lcd.clear();
    position = 0;
    if(strcmp(input, password) == 0){
      lcd.print("CORRECT");
    }    
    else{
      lcd.print("WRONG");
    }
    delay(2000);
    lcd.clear();
    canType = true;
  }
}
1 Like

Thanks for using code tags.

Please produce a normal post according to the forum guidelines. A video is not sufficient.

You have not even asked a question.

not sure i see a problem with the code, but it is unnecessarily complicated

consider

  • simply process the input once 4 values are read within the code that reads the input rather than have separate flags (i.e. "canType") and tests for "position"
#include <Keypad.h>
#include <Servo.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd (0x27, 16, 2);
int position = 0;
char password[5] = "1234";
char input[5];

const byte rows = 4;
const byte cols = 4;

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

byte rowPins[rows] = { 9, 8, 7, 6 };
byte colPins[cols] = { 5, 4, 3, 2 };

Keypad customKeypad = Keypad (makeKeymap (keys), rowPins, colPins, rows, cols);

void setup () {
    Serial.begin (9600);
    lcd.init ();
    lcd.clear ();
    lcd.backlight ();
}

void loop () {
    char key = customKeypad.getKey ();

    if (key) {
        input [position] = key;

        lcd.setCursor (position, 0);
        lcd.print (input [position]);

        //Checking
        if (++position == 4)  {
            position = 0;

            lcd.clear ();
            if (strcmp (input, password) == 0)
                lcd.print ("CORRECT");
            else
                lcd.print ("WRONG");

            delay (2000);
            lcd.clear ();
        }
    }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.