How To Use A Keypad with Arduino For Password Security

How To Use A Keypad with Arduino For Password Security

This article will give you all the necessary information about how to interface the Keypad with the Arduino UNO board.

I will show you how to interface 4×3 and 4×4 Keypads to the Arduino UNO board.

In the end, I will also provide you with code for storing passwords in EEPROM and changing the existing password.

Supplies

Hardware components

Arduino Uno Rev3x1Amazon
4×4 Flat Matrix Keypadx1Amazon
4×3 Flat matrix Keypadx1Amazon
USB cable type A/Bx1Amazon

Software

Arduino IDEArduino IDE

Makerguides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to products on Amazon.com.

What is a Keypad?

A Keypad is a device that can be used to receive input data from a user and a systematic arrangement of buttons in horizontal and vertical positions. 

Why do you need a Keypad?

When we want to interface one key button to the microcontroller, then it needs one GPIO pin. But when we want to interface many keys like 9, 12, or 16, etc., then it may acquire all GPIO pins of the microcontroller.

To save some GPIO pins of the microcontroller, we can use the Keypad matrix. A matrix Keypad is nothing but keys arranged in rows and columns.

E.g., If we want to interface 16 keys to the microcontroller, then we require 16 GPIO pins, but if we use a matrix 4×4 Keypad, then we require only 8 GPIO pins of the microcontroller.

Why do you need a Keypad

Various types of Keypads are available in the market, but the most common sizes are 4×3, 4×4, and 4×5.

These numbers indicate the number of rows and columns of the Keypads.

For example, a 4×4 Keypad consists of 16 keys or buttons that are arranged in 4 Rows and 4 Columns.

What is the order of pins in a 4 by 4 Keypad?

The 4×4 Keypad has 4 rows and 4 columns. The first four pins are used as rows, and the last four pins are used as columns.

The rows are mentioned as R1, R2, R3, R4, and columns are mentioned as C1, C2, C3, and C4.

What is the order of pins in a 4 by 4 Keypad

Similarly, in 4 by 3 Keypads, the first 4 pins are for the rows, i.e., R1, R2, R3, R4, and the remaining 3 pins are for the column, i.e., C1, C2 C3.

4 by 3 Keypads

How does a 4×4 Keypad work on an Arduino?

There are multiple ways to scan a Keypad matrix. The working 4×4 Keypad can be understood by following steps.

Step 1: Initially, if no key is pressed, the rows pins, i.e., R1, R2, R3, and R4 are at logic 0, and column pins C1, C2, C3, and C4 are at logic 1.

How does a 4x4 Keypad work on an Arduino

Step 2: If you press the 9 number key, then row R3 will get contact with column C3, and thus C3 will get ground, and it will be at logic 0. 

Now, when the Arduino MCU scans and reads the column, it can identify that the C3 column key is pressed because the C3 value will change from logic 1 to 0.

when the Arduino MCU scans and reads the column

Step 3: To identify which key is pressed, Arduino will set row line High one bye one. When it reaches R3, C3 again becomes High, and thus Arduino can detect that Key 9 is pressed by the user.

identify which key is pressed, Arduino

How do I connect the 4×3 or 4×4 Keypad to the Arduino UNO?

The interfacing of a 4×3 or 4×4 Keypad is very simple. You only need to connect rows and columns of the Keypad to the pins of Arduino Uno.

Arduino UNO pin4×3 Keypad4×4 Keypad
12R1R1
11R2R2
10R3R3
9R4R4
8C1C1
7C2C2
6C3C3
5C4

Interfacing of 4×4 and 4×3 Keypad with Arduino Uno board is shown below.

4×4 Keypad
4×3 keypad

Keypad Library for Arduino

Now, I will tell you about how to install the Keypad library in your Arduino IDE.

Step 1: To install the Library go to the Sketch > Include Library> Manage Libraries.

To install the Library

Step 2: In the Manage Libraries window, Type the keypad in the search box, it will show results. You need to install Keypad by Mark Stanley and Alexander Brevig.

Now select the latest version of the board and click on install.

Manage Libraries window

Now, your Arduino IDE is ready to use the Keypad library.

-> Read our guide about What You Can Build with Adruino.

Arduino Code for 4×4 Keypad

#include <Keypad.h>

const byte row_count = 4;
const byte column_count = 4;

byte row_pins[row_count] = {12, 11, 10, 9};
byte column_pins[column_count] = {8, 7, 6, 5};

char password = 'D';
char key_value;

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

Keypad myKeypad = Keypad(makeKeymap(keys4x4), row_pins, column_pins, row_count, column_count);

void setup() {
  Serial.begin(9600);
  Serial.println("Keypad Test..");
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  
  key_value = myKeypad.getKey();
  
  if (key_value)
  {
    Serial.print(key_value);
    Serial.println(" Key is pressed");

    if (key_value == password) 
    {
      Serial.println("LED ON");
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);
    }
  }
}

Serial Monitor Output:

Serial Monitor Output

Arduino Code for 4×3 Keypad

#include <Keypad.h>
const byte row_count = 4;
const byte column_count = 3;

byte row_pins[row_count] = {12, 11, 10, 9};
byte column_pins[column_count] = {8, 7, 6 };

char password = '#';
char key_value;

char keys4x3[row_count][column_count] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

Keypad myKeypad = Keypad(makeKeymap(keys4x3), row_pins, column_pins, row_count, column_count);

void setup() {
  Serial.begin(9600);
  Serial.println("Keypad Test..");
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  
  key_value = myKeypad.getKey();
  
  if (key_value)
  {
    Serial.print(key_value);
    Serial.println(" Key is pressed");

    if (key_value == password) 
    {
      Serial.println("LED ON");
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);
    }
  }
}

Serial Monitor Output:

Serial Monitor Output

How the code works

First, include the Keypad library and set the number of rows and columns on the Keypad. For 4×4 Keypad, define 4 rows, and 4 columns, and for 4×3 Keypad define 4 rows and 3 columns.

#include <Keypad.h>
const byte row_count = 4;
const byte column_count = 3;

Then define which characters or numbers you want to print when a particular button is pressed on the Keypad.

The characters are laid out just as they appear on the Keypad.

You can define which characters are printed when you press a button.

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

Now define the pins of Arduino that you want to connect to a 4×4 Keypad. 

byte row_pins[row_count] = {12, 11, 10, 9};

byte column_pins[column_count] = {8, 7, 6, 5};

Then use the library function.

Keypad keypad = Keypad( makeKeymap(keys), rowpin, columnpin, ROW, COLUMN );

This constructor defines an object Keypad of the class Keypad and initializes it. 

rowpin and columnpin :- The pin configuration on Arduino UNO to which the rows and columns of the keypad are connected.

makeKeymap(keys) function is used to initialize the internal keymap to be equal to the user-defined keymap as per the defined above keys.

Keypad myKeypad = Keypad(makeKeymap(keys4x3), row_pins, column_pins, row_count, column_count);

In the void setup() function, I set up the serial port at a 9600 baud rate to display the key processed via Arduino IDE serial monitor using the Serial.begin() function. Inbuilt LED is defined as output and set as low.

In the void loop(), the function keypad.getKey() is used to scan and get the key pressed. The output display on the serial monitor uses the Serial.println() function.

When you press ‘D’ on the 4×4 Keypad or ‘#’ in the 4×3 Keypad, the LED will remain turned ON for 2 seconds.

 if (key_value == password) 
    {
      Serial.println("LED ON");
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);    
    }

-> Read our article about How Easy Is It To Learn Arduino?

Password Lock System Using Keypad

This section will provide you code for storing your password in EEPROM and allow you to change your password and reset it.

Note that interfacing of the circuit will remain the same as 4×4 interfacing.

Note that interfacing of the circuit will remain the same as 4x4 interfacing
#include <Keypad.h>
#include <EEPROM.h>

char new_pass[4], user_input_pass[4], eeprom_pass[4];
int i = 0;

char key_def, key_pass;
char default_pass[4] = "2468"; //set the defaul password here

const byte row_count = 4;
const byte column_count = 4;

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

byte row_pins[row_count] = {12, 11, 10, 9};
byte column_pins[column_count] = {8, 7, 6, 5};

Keypad myKeypad = Keypad(makeKeymap(keys4x4), row_pins, column_pins, row_count, column_count);

void setup()
{
  Serial.begin(9600);
  Serial.println("Please Follow the Menu\nPress A to Compare Password\nPress B to Change Password\nPress C to Set Default password\n");
  Serial.println("Press C If you are using code first time");
}
void loop()
{
  key_def = myKeypad.getKey();

  switch (key_def)
  {
    case 'A':
      Serial.print("Enter The Password:");
      while (i < 4)
      {
        key_pass = myKeypad.getKey();
        if (key_pass)
        {
          user_input_pass[i++] = key_pass;
          Serial.print(key_pass);
        }
        key_pass = 0;
      }
      if (i == 4)
      {
        delay(200);
        for (int j = 0; j < 4; j++)
          eeprom_pass[j] = EEPROM.read(j);
        if (!(strncmp(user_input_pass, eeprom_pass, 4)))
        {
          Serial.println();
          Serial.println("Password  Accepted");
          //Write your logic for correct password
        }
        else
        {
          Serial.println();
          Serial.println("Wrong Password...");
        }
        i = 0;
      }
      break;

    case 'B': 
      Serial.println("Change your Password:");
      change();
      break;

    case 'C': 
      reset_password();
      Serial.println("Set Default Password Done....");
      break;

  }
}

void change()
{
  int j = 0;
  Serial.println("Please Enter Your Current Password");
  while (j < 4)
  {
    char key = myKeypad.getKey();
    if (key)
    {
      user_input_pass[j++] = key;
      Serial.print(key);
    }
    key = 0;
  }
  delay(500);

  if ((strncmp(user_input_pass, eeprom_pass, 4)))
  {
    Serial.println();
    Serial.println("Wrong Password!");
    Serial.println("Try Again!");
    delay(1000);

    key_def = 0;
  }
  else
  {
    j = 0;
    Serial.println();
    Serial.println("Enter New Password:");
    while (j < 4)
    {
      char key = myKeypad.getKey();
      if (key)
      {
        new_pass[j] = key;
        Serial.print(key);
        EEPROM.write(j, new_pass[j]);
        j++;
      }
    }
    Serial.println();
    Serial.println("Password Successfully Updated...");
    delay(1000);
  }
}

void reset_password() {
  strncpy(eeprom_pass, default_pass, 4);
  for (int j = 0; j < 4; j++) {
    EEPROM.write(j, default_pass[j]);
  }
}

How The Code Works

This code can be used to set the password and store it in the EEPROM. You need to include #include <EEPROM.h> in your code to use the EEPROM library. 

In void setup(), it will print the menu, and don’t forget to set the baud rate as 9600 in your serial monitor.

In void loop(), I have used three different cases for password settings.

Case A is used to compare the user input password with the password stored in the EEPROM.

Case B is used to change the existing password stored in EEPROM.

Case C is used to reset the password, and the default password “2468” is going to be stored in the EEPROM.

void change() is used to change the current password and set a new password. This function is called when you press the B key.

void reset_password() is used to set the default password. This function is called when you press the C key. 

EEPROM.write(address, value) is used to write passwords in EEPROM memory.

EEPROM.write(j, new_pass[j]);

EEPROM.write(j, default_pass[j]);

EEPROM.read(address) is used to read the value stored at a particular address. 

strncpy(char *dest, const char *src, size_t n)

Strncpyy is used for copying the password from source to destination.

strncpy(eeprom_pass, default_pass, 4);

strncmp(const char *str1, const char *str2, size_t n)

Strncmp is used to compare the two password strings so that MCU can identify whether the entered password is correct or not.

 if ((strncmp(user_input_pass, eeprom_pass, 4)))

Serial Monitor Output:

Serial Monitor Output

Keypad Based Arduino Projects:

> Check out our guide to the Top 12 Best Arduino Online Courses

Conclusion

In this article, you have learned about how to use 4×4 and 4×3 Keypads with Arduino boards. 

Furthermore, I have also explained how you can store the password in the EEPROM of the Arduino board and how to change the password.

I hope you found this article informative. If you did, please share it with a friend who likes electronics and making things!

I would love to know what project you plan on building or have already made with the Keypad and Arduino.

If you have any questions or suggestions, or if you think things are missing in this tutorial, please leave a comment below.

Note that comments are held for moderation to prevent spam.