ESP32 S3 - Keypad - Electromagnetic Lock

Learning how to combine a keypad, relay, and electromagnetic lock with the ESP32 S3 is an excellent way to build real-world access control systems. This tutorial shows you how to read a password from a 3x4 keypad and use it to control an electromagnetic lock through a relay — including a timed-unlock variant that releases the door for a fixed period without blocking code execution.

What you'll build:

  1. A circuit connecting a 3x4 keypad and an electromagnetic lock (via relay) to the ESP32 S3
  2. Code that checks the entered password and unlocks the door if it matches one of the pre-defined codes
  3. An extended version that keeps the door unlocked for 5 seconds and then re-locks automatically
  4. Serial Monitor output showing whether each password attempt succeeded or failed

https://newbiely.com/images/cover/esp32-s3-keypad-electromagnetic-lock.jpg

Hardware Preparation

1×ESP32 S3 WROOM N16R8
1×Alternatively, ESP32 S3 SuperMini Dev Module
1×Alternatively, ESP32 S3 Uno-form Board
1×Alternatively, ESP32 S3 Camera Board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Keypad 3x4
1×Relay
1×Jumper Wires
1×Electromagnetic Lock
1×12V Power Adapter
1×Optionally, DC Power Jack
1×Recommended: Screw Terminal Expansion Board for ESP32 S3
1×Recommended: Breakout Expansion Board for ESP32 S3
1×Recommended: Power Splitter for ESP32 S3

Or you can buy the following kits:

1×DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Overview of Keypad and Electromagnetic Lock

A 3x4 matrix keypad lets users enter numeric codes using a compact 12-key layout, while an electromagnetic lock (maglock) uses magnetic force to hold a door closed whenever power is applied. Together with a relay that switches the lock's 12V supply, these components form a complete password-controlled access system that the ESP32 S3 can manage entirely in software.

Key Specifications

Unfamiliar with the keypad or electromagnetic lock and how to wire and program them individually? Review the dedicated tutorials below before proceeding:

Wiring Diagram

Connect the 3x4 keypad row and column pins to available GPIO pins on the ESP32 S3, then wire the relay signal pin to a separate GPIO. The electromagnetic lock connects to the relay's normally-open contacts and is powered by the 12V adapter, keeping the high-voltage lock circuit isolated from the ESP32 S3 logic.

Safety Notes

The electromagnetic lock operates at 12V and draws significant current when energised — always use the relay to switch the lock supply and never connect the lock wires directly to any ESP32 S3 GPIO pin. Ensure the 12V adapter is rated for at least the current draw listed on your electromagnetic lock, and verify that all high-voltage wiring is fully insulated before powering the system.

The wiring diagram between ESP32 S3 keypad electromagnetic lock

This image is created using Fritzing. Click to enlarge image

Component Pin ESP32 S3 Pin Notes
Keypad Row 1 GPIO17 First row of the 3x4 keypad
Keypad Row 2 GPIO16 Second row
Keypad Row 3 GPIO15 Third row
Keypad Row 4 GPIO7 Fourth row
Keypad Col 1 GPIO6 First column
Keypad Col 2 GPIO5 Second column
Keypad Col 3 GPIO4 Third column
Relay Signal (IN) GPIO18 Controls relay on/off
Relay VCC 5V Powers the relay module
Relay GND GND Common ground
Relay COM 12V Power + From power adapter
Relay NO EM Lock Wire 1 Normally open connection
EM Lock Wire 2 12V Power - Completes the circuit

Want a stronger connection than jumper wires? Put the ESP32 S3 on a Screw Terminal Block for ESP32 S3, then tighten each wire under a screw. This is how it looks with the screw terminal board:

The wiring diagram between ESP32 S3 keypad electromagnetic lock Screw Terminal

This image is created using Fritzing. Click to enlarge image

Or plug the ESP32 S3 into a GPIO Breakout Board for ESP32 S3. The same wiring then looks like this:

The wiring diagram between ESP32 S3 keypad electromagnetic lock GPIO Breakout Board

This image is created using Fritzing. Click to enlarge image

ESP32 S3 Code - Turn Electromagnetic Lock On If the Password Is Correct

The following code unlocks the electromagnetic lock when the user enters a correct password on the keypad and presses the # key. It pre-defines a list of valid passwords, accumulates key presses into an input string, clears that string when * is pressed, and compares the completed entry against each stored password when # is pressed — activating the relay if a match is found and printing the result to the Serial Monitor.

/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-keypad-electromagnetic-lock */ #include <Keypad.h> #define RELAY_PIN 18 // ESP32-S3 pin GPIO18 connected to the relay #define ROW_NUM 4 // keypad four rows #define COLUMN_NUM 3 // keypad three columns char keys[ROW_NUM][COLUMN_NUM] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte pin_rows[ROW_NUM] = {17, 16, 15, 7}; // ESP32-S3 pin: GPIO17, GPIO16, GPIO15, GPIO7 connected to the row pins byte pin_column[COLUMN_NUM] = {6, 5, 4}; // ESP32-S3 pin: GPIO6, GPIO5, GPIO4 connected to the column pins Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM ); const String password_1 = "1234"; // change your password here const String password_2 = "56789"; // change your password here const String password_3 = "901234"; // change your password here String input_password; void setup() { Serial.begin(9600); input_password.reserve(32); // maximum password size is 32, change if needed pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output. digitalWrite(RELAY_PIN, HIGH); // lock the electromagnetic lock } void loop() { char key = keypad.getKey(); if (key) { Serial.println(key); if (key == '*') { input_password = ""; // reset the input password } else if (key == '#') { if (input_password == password_1 || input_password == password_2 || input_password == password_3) { Serial.println("The password is correct => unlock"); digitalWrite(RELAY_PIN, LOW); } else { Serial.println("The password is incorrect, try again"); } input_password = ""; // reset the input password } else { input_password += key; // append new character to input password string } } }

Detailed Instructions

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Wire the keypad, relay, and electromagnetic lock to the ESP32 S3 according to the wiring diagram above.
  3. Connect the ESP32 S3 to your computer using a USB Type-C cable.
  4. Open the Arduino IDE on your computer.
  5. Select your board: choose the correct ESP32 S3 board from Tools > Board menu.
  6. Choose your port: select the correct COM port from Tools > Port menu.
  7. Click the Libraries icon on the left sidebar of the Arduino IDE.
  8. Search "keypad", then find the keypad library by DIYables.
  9. Click Install button to install the keypad library.
  • Search for DIYables_Keypad created by DIYables.io and click the Install button.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32S3 Dev Module
Library Manager
Type:
All
Topic:
All
DIYables_Keypad by DIYables.io
The library is designed for Arduino, ESP32, ESP8266... to use with keypad such as 3x4, 4x4 keypad. It also works with Arduino Uno R4 WiFi/Minima More info
1.0.1
INSTALL
Newbiely.ino
···
1 void setup() {
Output
Serial Monitor
Ln 1, Col 1
ESP32S3 Dev Module on COM15
1
  1. Copy the above code and paste it into the Arduino IDE.
  2. Click Upload button on Arduino IDE to upload code to ESP32 S3.
  3. Press 8123 keys and press #.
  4. Press 1234 keys and press #.
  5. Check the Serial Monitor and observe the state of the electromagnetic lock.
  6. Pro Tip: Press * at any time to clear the current input and start over — useful if you make a typing mistake mid-password.

Serial Monitor Output

Open the Serial Monitor at 115200 baud after uploading and enter passwords on the keypad. You will see status messages similar to the following output:

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32S3 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32S3 Dev Module' on 'COM15')
New Line
9600 baud
[2026-06-16 09:15:04] The password is incorrect, try again [2026-06-16 09:15:21] The password is correct => unlock [2026-06-16 09:15:43] The password is incorrect, try again [2026-06-16 09:16:02] The password is correct => unlock
Ln 11, Col 1
ESP32S3 Dev Module on COM15
2

Code Explanation

Authorized passwords are pre-defined in the ESP32 S3 code. A string is used to store the password entered by the user, called the input string. Two keys on the keypad (* and #) serve special purposes — clearing the input and finalising the entry. When a key is pressed:

  • If the pressed key is not one of the two special keys, it is appended to the input string.
  • If the pressed key is *, the input string is cleared so the user can start or restart entry.
  • If the pressed key is #:
    • The input string is compared against all pre-defined passwords. If it matches one of them, the electromagnetic lock is turned on.
    • Regardless of whether the password is correct or not, the input string is cleared for the next attempt.

ESP32 S3 Code - Turn the Electromagnetic Lock On for a Period of Time If the Password Is Correct

The following code extends the basic example by unlocking the electromagnetic lock for 5 seconds when the correct password is entered and then re-locking automatically. It uses the ezOutput library to manage the timed output in a non-blocking manner, so the keypad continues to respond during the unlock period.

/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-keypad-electromagnetic-lock */ #include <Keypad.h> #include <ezOutput.h> #define UNLOCK_TIME 5000 // in milliseconds #define RELAY_PIN 18 // ESP32-S3 pin GPIO18 connected to the relay #define ROW_NUM 4 // keypad four rows #define COLUMN_NUM 3 // keypad three columns char keys[ROW_NUM][COLUMN_NUM] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte pin_rows[ROW_NUM] = {17, 16, 15, 7}; // ESP32-S3 pin: GPIO17, GPIO16, GPIO15, GPIO7 connected to the row pins byte pin_column[COLUMN_NUM] = {6, 5, 4}; // ESP32-S3 pin: GPIO6, GPIO5, GPIO4 connected to the column pins Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM ); ezOutput relay(RELAY_PIN); const String password_1 = "1234"; // change your password here const String password_2 = "56789"; // change your password here const String password_3 = "901234"; // change your password here String input_password; void setup() { Serial.begin(9600); input_password.reserve(32); // maximum password size is 32, change if needed relay.high(); // lock the electromagnetic lock } void loop() { relay.loop(); // MUST call the loop() function first char key = keypad.getKey(); if (key) { Serial.println(key); if (key == '*') { input_password = ""; // reset the input password } else if (key == '#') { if (input_password == password_1 || input_password == password_2 || input_password == password_3) { Serial.println("The password is correct => unlock"); relay.high(); // set high before making a low pulse relay.pulse(UNLOCK_TIME); // deactivate the electromagnetic lock during UNLOCK_TIME duration } else { Serial.println("The password is incorrect, try again"); } input_password = ""; // reset the input password } else { input_password += key; // append new character to input password string } } }

Please note that the above code uses the ezOutput library, which makes it easy to manage timed outputs without blocking code execution. You can refer to ezOutput Library Installation Guide for installation instructions.

Real-World Applications

Combining a keypad, relay, and electromagnetic lock with the ESP32 S3 opens the door to a wide variety of security and automation applications, from simple prototypes to production-grade access control systems.

  1. Residential Door Lock: Replace a traditional key lock with a PIN-based entry system on a front or back door.
  2. Office Access Control: Restrict entry to specific rooms or areas using employee-assigned PINs with optional event logging.
  3. Lab or Tutorial Security: Prevent unauthorised access to sensitive equipment or materials using a code-secured maglock.
  4. Storage Cabinet: Secure a filing cabinet or tool locker electronically using a smaller relay and lock combination.
  5. Multi-User Access: Store multiple valid passwords in the sketch so different users can each have their own unique PIN.
  6. IoT-Enhanced Security: Extend the system with ESP32 S3 Wi-Fi to allow remote unlock or send alerts when an incorrect password is entered repeatedly.

Video Tutorial

Watch the step-by-step video walkthrough for this ESP32 S3 project below.

Challenge Yourself

Now that you have a working keypad-controlled electromagnetic lock on the ESP32 S3, try these progressively challenging extensions to build deeper access control skills.

  1. Beginner: Change one of the pre-defined passwords in the code and confirm the new code works and the old one no longer does.
  2. Beginner: Add an LED indicator that lights up green for a correct password and red for an incorrect one.
  3. Intermediate: Add a piezo buzzer that plays a short success melody on correct entry and a different tone on failure.
  4. Intermediate: Implement a lockout that disables keypad input for 60 seconds after three consecutive incorrect attempts.
  5. Advanced: Store the password list in NVS flash so it persists across power cycles and add an admin code that lets the user update passwords at runtime.
  6. Advanced: Integrate an RFID reader so the door can be unlocked with either a keypad PIN or an RFID card.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!