Skip to content
Free Delivery on Orders Above Rs 999/- Pan-India
Cash on Delivery Available for Orders above Rs.500/- and Upto Rs 3000/-
SAVE more when you BUY more. Upto 30% Off on BULK PURCHASE
GST Invoices for Your Business
Dedicated Technical Support Team
Safely Delivering Genuine Products PAN INDIA
Delivering to
Select Location ▾
Delivering to Select Location
▾

4x4 Arduino Keypad: Pinout, Code & Password Lock Project

4x4 Arduino Keypad: Pinout, Code & Password Lock Project
-
Written By - Robocraze -
๐Ÿ“… Updated on 25 Nov 2026
โœจ Summarize with AI
โœ… Prompt copied

Summary

A 4x4 Arduino keypad uses 8 pins, 4 rows and 4 columns, and the Keypad library scans them to detect each press. In this guide, we cover the pinout, wiring and test code, then build a password door lock with an SG90 servo, I2C LCD, EEPROM-saved password and 30-second lockout.

A 4x4 Arduino keypad has 8 pins: 4 for rows and 4 for columns. Each of its 16 keys sits where one row crosses one column. Arduino pulls one line LOW at a time and reads the others. The Keypad library runs this scan for you and returns the key that was pressed.

In this guide, we explain how the matrix works, which pin goes where, and how to read keys with the Keypad library. Then we build a password door lock with an SG90 servo and a 16x2 I2C LCD. The lock saves its password in EEPROM and blocks entry for 30 seconds after 3 wrong tries.

How a Matrix Keypad Works

A matrix keypad saves pins by wiring keys in a grid instead of giving each key its own wire. Sixteen separate buttons would need 16 Arduino pins. A 4x4 matrix needs only 8.

Inside the keypad, four row lines run across and four column lines run down. Each key is a small switch at one crossing. When you press 5, it connects Row 2 to Column 2. Nothing else changes.

4x4 keypad matrix ยท key 5 sits on Row 2 and Column 2

The Keypad library finds the connection by scanning:

  1. It sets every row pin as an input with the internal pull-up turned on, so each row reads HIGH.

  2. It drives Column 1 LOW and reads all four rows.

  3. If a row reads LOW, the key at that row and Column 1 is pressed.

  4. It sets Column 1 back to HIGH and repeats for Columns 2, 3 and 4.

One full scan takes a few microseconds, so the library can check the keypad hundreds of times a second. It also debounces each key (10 ms by default), so one press gives one character.

The pull-up idea is the same one used for single buttons. We cover it in our guide on how to wire a push button to Arduino with pull-up resistors.

4x4 Keypad Pinout

Hold the keypad face up with the ribbon or header at the bottom. On most 4x4 membrane keypads, the 8 pins read left to right as R1 to R4, then C1 to C4.

Keypad pin

Line

Keys on this line

Arduino UNO pin

1

Row 1 (R1)

1, 2, 3, A

D9

2

Row 2 (R2)

4, 5, 6, B

D8

3

Row 3 (R3)

7, 8, 9, C

D7

4

Row 4 (R4)

*, 0, #, D

D6

5

Column 1 (C1)

1, 4, 7, *

D5

6

Column 2 (C2)

2, 5, 8, 0

D4

7

Column 3 (C3)

3, 6, 9, #

D3

8

Column 4 (C4)

A, B, C, D

D2

ย 

Important: the keypad has no VCC or GND pin. It is only switches, so all 8 wires go to digital pins.

Not every keypad uses this order. Some hard-key PCB modules print labels on the board, and some start with the columns. If the order is unclear, set a multimeter to continuity, hold down 1, and find the two pins that beep. Those two pins are R1 and C1.

Membrane vs hard (PCB) keypad

Feature

4x4 membrane keypad

4x4 matrix keypad module

Keys

Flat, soft-touch membrane

Tactile push buttons on a PCB

Size

79 x 69 x 1 mm

42 x 39 x 11 mm

Mounting

Adhesive back, sticks to a panel

Header pins, fits a breadboard or PCB

Connector

8-pin, 2.54 mm pitch

8 pins, 2.54 mm pitch

Best for

Door panels, enclosures, finished builds

Prototyping, clear click feedback

ย 

Both use the same 4x4 matrix, so the wiring and code in this guide work with either one.

Wiring and Code With the Keypad Library

4x4 Matrix Keypad 16 tactile keys, 8 pins at 2.54 mm pitch, plugs straight into a breadboard. Works with Arduino, ESP32 and 8051 boards. Buy the 4x4 Matrix Keypad ยท See all keypads and joysticks

Step 1: Wire the keypad

Connect the 8 keypad pins to Arduino D9 through D2, in order. Keypad pin 1 goes to D9 and keypad pin 8 goes to D2, as in the pinout table above. Use male-to-male jumpers for a hard keypad or male-to-female jumpers for a membrane keypad.

This leaves D0 and D1 free for Serial, D10 free for the servo, and A4/A5 free for the I2C LCD. Need a refresher on the board? See our Arduino UNO pin diagram guide.

Step 2: Install the Keypad library

  1. Open the Arduino IDE and go to Sketch > Include Library > Manage Libraries.

  2. Search for Keypad.

  3. Install Keypad by Mark Stanley, Alexander Brevig.

Step 3: Upload the test sketch

Before adding the LCD and servo, we test the keypad on its own. This sketch prints each key press to the Serial Monitor.


#include 

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};  // R1, R2, R3, R4
byte colPins[COLS] = {5, 4, 3, 2};  // C1, C2, C3, C4

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
  Serial.begin(9600);
  Serial.println("Press any key...");
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    Serial.print("Key pressed: ");
    Serial.println(key);
  }
}

How the code works

  • keys[ROWS][COLS] is the keymap. It tells the library which character sits at each row and column.

  • rowPins and colPins list the Arduino pins in R1 to R4 and C1 to C4 order.

  • keypad.getKey() scans once and returns the pressed key, or 0 (NO_KEY) if nothing is pressed. It does not wait, so the rest of your loop keeps running.

Open the Serial Monitor at 9600 baud and press a few keys. You should see Key pressed: 5 when you press 5. If the wrong character appears, jump to the troubleshooting section.

Project: Password Door Lock With Servo and I2C LCD

Now we turn the keypad into a working Arduino password lock. The LCD shows * for each digit, the servo arm acts as the bolt, and the password stays saved even after a power cut.

Parts list

Part

Qty

What it does

Arduino UNO

1

Runs the lock sketch

4x4 Matrix Keypad or 4x4 Membrane Keypad

1

Password entry

16x2 LCD with I2C module

1

Shows prompts and masked input

SG90 servo motor

1

Moves the latch: 0ยฐ locked, 90ยฐ open

Breadboard and jumper wires

1 set

Connections

USB cable or 5V 2A adapter

1

Power

ย 

Find more keypad options in the joysticks and keypads collection.

Wiring

The keypad stays on D9 to D2, as in the test sketch. We add the LCD and servo on the pins below.

Module

Module pin

Arduino UNO pin

I2C LCD

GND

GND

I2C LCD

VCC

5V

I2C LCD

SDA

A4

I2C LCD

SCL

A5

SG90 servo

Brown (GND)

GND

SG90 servo

Red (VCC)

5V

SG90 servo

Orange (signal)

D10


Password door lock wiring ยท Arduino UNO, 4x4 keypad, I2C LCD, SG90

USB power is fine for testing. For a real door latch, power the servo from a separate 5V supply and join its GND to the Arduino GND. The SG90 servo guide covers its current draw and angles.

Libraries

Install these from the Library Manager, along with Keypad:

  • LiquidCrystal I2C by Frank de Brabander

  • Servo and EEPROM come built into the Arduino IDE.

Full sketch



  /*
  Password Door Lock: 4x4 Keypad + I2C LCD + SG90 Servo
  Board: Arduino UNO
  Libraries: Keypad (Mark Stanley, Alexander Brevig), LiquidCrystal_I2C (Frank de Brabander), Servo, EEPROM

  Keys:
    0-9  type the password (shown as *)
    #    submit
    *    clear what you typed
    A    change password (only while the door is unlocked)
    D    lock the door again
*/

#include 
#include 
#include 
#include 
#include 

// ---------- Keypad ----------
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};   // R1, R2, R3, R4
byte colPins[COLS] = {5, 4, 3, 2};   // C1, C2, C3, C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// ---------- LCD and servo ----------
LiquidCrystal_I2C lcd(0x27, 16, 2);  // try 0x3F if the screen stays blank
Servo lockServo;
const byte SERVO_PIN      = 10;
const byte LOCKED_ANGLE   = 0;
const byte UNLOCKED_ANGLE = 90;

// ---------- Settings ----------
const byte MIN_LEN = 4;
const byte MAX_LEN = 8;
const byte MAX_ATTEMPTS = 3;
const unsigned long LOCKOUT_MS  = 30000UL;  // 30 s lockout after 3 wrong tries
const unsigned long AUTOLOCK_MS = 10000UL;  // relock 10 s after opening

// EEPROM layout: [0] = 0xA5 marker, [1] = length, [2..9] = digits
const int  EE_MARK = 0;
const int  EE_LEN  = 1;
const int  EE_PASS = 2;
const byte MARKER  = 0xA5;

char password[MAX_LEN + 1] = "1234";  // default password
char input[MAX_LEN + 1];
char newPass[MAX_LEN + 1];
byte inputLen = 0;
byte wrongAttempts = 0;

enum State { LOCKED, UNLOCKED, NEW_PASS, CONFIRM_PASS, LOCKOUT };
State state = LOCKED;
unsigned long stateStart = 0;
int lastSecondsShown = -1;

// ---------- Helpers ----------
void loadPassword() {
  if (EEPROM.read(EE_MARK) == MARKER) {
    byte len = EEPROM.read(EE_LEN);
    if (len >= MIN_LEN && len <= MAX_LEN) {
      for (byte i = 0; i < len; i++) password[i] = EEPROM.read(EE_PASS + i);
      password[len] = '\0';
    }
  }
}

void savePassword(const char *p) {
  byte len = strlen(p);
  EEPROM.update(EE_LEN, len);
  for (byte i = 0; i < len; i++) EEPROM.update(EE_PASS + i, p[i]);
  EEPROM.update(EE_MARK, MARKER);
  strcpy(password, p);
}

void clearInput() {
  inputLen = 0;
  input[0] = '\0';
}

void showScreen(const char *line1, const char *line2) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(line1);
  lcd.setCursor(0, 1);
  lcd.print(line2);
}

void showMasked() {
  lcd.setCursor(0, 1);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  for (byte i = 0; i < inputLen; i++) lcd.print('*');
}

void enterState(State s) {
  state = s;
  stateStart = millis();
  lastSecondsShown = -1;
  clearInput();
  switch (s) {
    case LOCKED:
      lockServo.write(LOCKED_ANGLE);
      showScreen("Enter Password:", "");
      break;
    case UNLOCKED:
      lockServo.write(UNLOCKED_ANGLE);
      showScreen("Access Granted", "A:NewPass D:Lock");
      break;
    case NEW_PASS:
      showScreen("New pass (4-8):", "");
      break;
    case CONFIRM_PASS:
      showScreen("Confirm pass:", "");
      break;
    case LOCKOUT:
      showScreen("Too many tries", "Wait 30 s");
      break;
  }
}

// ---------- Setup ----------
void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lockServo.attach(SERVO_PIN);
  loadPassword();
  enterState(LOCKED);
}

// ---------- Loop ----------
void loop() {
  unsigned long now = millis();

  // Lockout: ignore every key until the timer runs out
  if (state == LOCKOUT) {
    keypad.getKey();  // read and discard
    unsigned long elapsed = now - stateStart;
    if (elapsed >= LOCKOUT_MS) {
      wrongAttempts = 0;
      enterState(LOCKED);
    } else {
      int secondsLeft = (LOCKOUT_MS - elapsed + 999) / 1000;
      if (secondsLeft != lastSecondsShown) {
        lastSecondsShown = secondsLeft;
        lcd.setCursor(0, 1);
        lcd.print("Wait ");
        lcd.print(secondsLeft);
        lcd.print(" s    ");
      }
    }
    return;
  }

  // Auto-relock
  if (state == UNLOCKED && now - stateStart >= AUTOLOCK_MS) {
    enterState(LOCKED);
    return;
  }

  char key = keypad.getKey();
  if (!key) return;
  Serial.print("Key: ");
  Serial.println(key);

  // Door is open: A = change password, D = lock
  if (state == UNLOCKED) {
    if (key == 'A') enterState(NEW_PASS);
    else if (key == 'D') enterState(LOCKED);
    return;
  }

  // LOCKED, NEW_PASS, CONFIRM_PASS all collect digits
  if (key >= '0' && key <= '9') {
    if (inputLen < MAX_LEN) {
      input[inputLen++] = key;
      input[inputLen] = '\0';
      showMasked();
    }
  } else if (key == '*') {
    clearInput();
    showMasked();
  } else if (key == '#') {
    if (state == LOCKED) {
      if (strcmp(input, password) == 0) {
        wrongAttempts = 0;
        enterState(UNLOCKED);
      } else {
        wrongAttempts++;
        if (wrongAttempts >= MAX_ATTEMPTS) {
          enterState(LOCKOUT);
        } else {
          showScreen("Wrong Password", "");
          lcd.print(MAX_ATTEMPTS - wrongAttempts);
          lcd.print(" tries left");
          delay(1500);
          enterState(LOCKED);
        }
      }
    } else if (state == NEW_PASS) {
      if (inputLen < MIN_LEN) {
        showScreen("Use 4-8 digits", "");
        delay(1500);
        enterState(NEW_PASS);
      } else {
        strcpy(newPass, input);
        enterState(CONFIRM_PASS);
      }
    } else if (state == CONFIRM_PASS) {
      if (strcmp(input, newPass) == 0) {
        savePassword(newPass);
        showScreen("Password Saved", "");
        delay(1500);
      } else {
        showScreen("No match.", "Not changed");
        delay(1500);
      }
      enterState(LOCKED);
    }
  } else if (key == 'D' && state != LOCKED) {
    enterState(LOCKED);  // cancel a password change
  }
  // B and C are free for your own features
}

Try it

  1. Upload the sketch. The LCD shows Enter Password: and the servo moves to 0ยฐ.

  2. Type 1234 and press #. The LCD shows Access Granted and the servo turns to 90ยฐ.

  3. Wait 10 seconds. The servo returns to 0ยฐ on its own.


Arduino password door lock with 4x4 keypad, I2C LCD and SG90 servo

If the LCD lights up but shows no text, the I2C address or contrast is usually the cause. Follow our I2C LCD not working fix guide.

Changing the Password and Adding a Lockout

We built both features into the sketch above. Here is how to use and adjust them.

Change the password from the keypad

  1. Unlock the door with the current password.

  2. Press A. The LCD shows New pass (4-8):.

  3. Type a new 4 to 8 digit code and press #.

  4. Type it again at Confirm pass: and press #.

If both entries match, the LCD shows Password Saved and the door locks. If they do not match, the old password stays. Press D at any point to cancel.

We only allow a password change while the door is unlocked, so someone at a locked door cannot replace it.

Why EEPROM?

A password stored in a normal variable resets to 1234 every time the Arduino loses power. That is why we save the new code to EEPROM, which keeps data with the power off. On startup, loadPassword() checks for the 0xA5 marker byte and loads the saved code. A brand-new board has no marker, so it uses 1234.

EEPROM.update() writes a byte only when the value changes. This matters because each EEPROM cell is rated for about 100,000 writes.

How the lockout works

Each wrong password adds 1 to wrongAttempts, and the LCD shows how many tries are left. On the third wrong try, the lock enters lockout:

  • The LCD counts down from 30 seconds.

  • Every key press is read and thrown away, so even the correct code does nothing.

  • When the timer ends, the counter resets to 0 and the lock asks for the password again.

The countdown uses millis() instead of delay(), so the Arduino keeps running and the display updates every second.

Settings you can change

Setting

Default

What it controls

password

"1234"

Code used until you save a new one

MIN_LEN / MAX_LEN

4 / 8

Allowed password length

MAX_ATTEMPTS

3

Wrong tries before lockout

LOCKOUT_MS

30000

Lockout time in milliseconds

AUTOLOCK_MS

10000

Time before the door relocks on its own

LOCKED_ANGLE / UNLOCKED_ANGLE

0 / 90

Servo positions for your latch


If you change LOCKOUT_MS, also change the "Wait 30 s" text in enterState() so the first screen matches.

Tip: to reset a forgotten password, upload a one-line sketch that runs EEPROM.write(0, 0); in setup(). Then upload the lock sketch again. It will start with 1234.

Troubleshooting: Wrong Keys, No Response

Most keypad problems come down to pin order or loose jumpers. We always run the test sketch first, since it takes the LCD and servo out of the picture.

Problem

Likely cause

Fix

Wrong characters print (pressing 1 shows D, or rows look swapped)

Row and column pins are in a different order on your keypad

Swap the rowPins and colPins arrays, or reverse one of them. Confirm the order with a multimeter.

One whole row or column never responds

A loose jumper or bad header on that line

Reseat the wire and check that pin with continuity

No keys respond at all

Keypad plugged in one pin off, or pins do not match the sketch

Recount from pin 1 and check every jumper against the pinout table

One press prints the same key twice

Worn membrane or very short debounce

Add keypad.setDebounceTime(50); in setup()

Keys work in the test sketch but not in the lock

A pin clash with another module

Keep the keypad off D10, A4 and A5, which the servo and LCD use

LCD backlight on, no text

Wrong I2C address or contrast

Try 0x3F instead of 0x27, and turn the blue contrast screw on the I2C module

Arduino resets or the LCD flickers when the servo moves

The servo pulls too much current from USB

Power the servo from a separate 5V supply with a common GND

Correct password is rejected

Password was changed earlier and saved in EEPROM

Clear EEPROM as shown in the tip above


If the LCD is still blank, the I2C LCD troubleshooting guide walks through an I2C scanner sketch.


Excerpt

Learn how a 4x4 Arduino keypad works, its 8-pin pinout and Keypad library code, then build an Arduino password lock with an SG90 servo and I2C LCD.

Frequently Asked Questions

Q1. How many pins does a 4x4 keypad have?

A 4x4 keypad has 8 pins: 4 row pins (R1 to R4) and 4 column pins (C1 to C4). It has no VCC or GND pin because it is only a grid of switches.

Q2. Which library do we use for a keypad?

Use the Keypad library by Mark Stanley and Alexander Brevig. It handles scanning, debouncing and key mapping, and works with 3x4 and 4x4 keypads.

Q3. Can we use a keypad without the library?

Yes. Set the row pins as INPUT_PULLUP and the column pins as outputs. Drive one column LOW at a time, read each row with digitalRead(), and set the column HIGH again. A LOW row means the key at that crossing is pressed. We would also need our own debounce delay. The library handles all of this, which is why most projects use it.

Q4. Why does my keypad print the wrong keys?

The row and column order in the sketch does not match the keypad. Swap the rowPins and colPins arrays, or reverse one of them, until each key prints the right character.

Q5. Can we use a keypad with ESP32?

Yes. The Keypad library supports ESP32, and the keypad works at 3.3V because it has no electronics inside. Avoid GPIO 34 to 39 for row pins, because they are input-only and have no internal pull-ups. Rows on 32, 33, 25, 26 and columns on 27, 14, 16, 17 work well.

Q6. Membrane vs hard keypad: which is better?

It depends on the build. A membrane keypad is thin, has an adhesive back and suits door panels and enclosures. A hard matrix keypad gives a clear click and plugs into a breadboard, so it suits prototyping. The code is the same for both.

Q7. Can we connect a 4x4 keypad using fewer Arduino pins?

Yes. A PCF8574 I2C expander lets the keypad share the A4 and A5 lines with the I2C LCD, using the Keypad_I2C library. Another option is a resistor ladder that gives each key a different voltage on a single analog pin. Both are useful when your board is running out of pins.

Q8. Why does the Arduino reset when the servo opens the lock?

The SG90 draws a current spike as it starts moving. USB power often cannot keep up, so the voltage dips and the board resets. Power the servo from a separate 5V supply and connect its GND to the Arduino GND.

Prev Post
Next Post

Leave a comment

Please note, comments need to be approved before they are published.

Thanks for subscribing!

This email has been registered!

Shop the look

Choose Options

Edit Option
Back In Stock Notification
Compare
Product SKU Description Collection Availability Product Type Other Details

Choose Options

this is just a warning
Login
Shopping Cart
0 items
FREE SHIPPING!
โ‚น100 OFF
โ‚น200 OFF
โ‚น999
โ‚น2500
โ‚น4900
WhatsApp Chat Chat