It is outputting squares after 4 symbols

Here I am trying to type 4 digits with 4x4 kepyad and display them on LCD(16x2). After I type 4 symbols it should output what I typed. It is outputting what I typed but adding square in the end.
image

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

LiquidCrystal_I2C lcd(0x27, 16, 2);
int position = 0;
int line = 0;
char password[4] = "123D";
char input[4];
int typed = 0;

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);

int pos = 0;

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

void loop() {
  char customKey = customKeypad.getKey();
  
  if (customKey) {
    typed++;
    lcd.setCursor(position, line);
    lcd.print(customKey);
    input[position] = customKey;
    Serial.println(position);
    position++;
  }
  if(typed == 4){
    Serial.println(input);
  }
}

make your input larger

char input[4+1]; // +1 for trailing null char

and add the null char at the end before trying to print

why do you have typed and position?

why do i need null char?

i add 1 to position after displaying and typed before. Typed is for counting how many chars i typed and position is for lcd.

Welcome to the forum

char input[4];

To hold a 4 character string with its zero termination you need an array of chars with 5 elements. As written, the string is not terminated properly

Maybe take a look at Keypad data entry. A beginners guide for some ideas

Because that’s how c-strings work. It tells the print function where to stop reading the bytes in memory

It would also be good to reset the index to not write beyond the bounds of the array

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