Guide no. 55
Twelve keys on seven wires: the Keypad library reads what you press and Arduino checks the code. With light and sound.
By Ada Intelisano · informaticait.it technical team
- Pins from the left: rows to pins 2–5, columns to pins 8–10.
- Keypad library:
getKeyreturns the key pressed. - The digits are collected in a
String; # confirms, * clears. - No external resistors: the library uses the internal pull-ups.
Twelve keys like the ones on a phone, and a project everyone likes: a lock with a secret code. Type the digits, press #, and if the code is right the light turns on. If it is wrong, a low sound.
1Get the parts ready
- a 3×4 membrane keypad (thin and adhesive, with seven pins at the end of its tail)
- a passive buzzer (guide no. 38), Arduino UNO, seven male-to-male jumper wires
2Connect the seven pins
With the keypad in front of you, count the pins from the left: the first four are the rows and go to pins 2, 3, 4, 5; the last three are the columns and go to pins 8, 9, 10. The buzzer goes between pin 12 and GND. No resistors: the library takes care of it.
3Read the keys
From the Library Manager install Keypad by Mark Stanley and Alexander Brevig.
// The 3x4 keypad: prints the key you press in the Serial Monitor. #include <Arduino.h> #include <Keypad.h> const byte ROWS = 4, COLS = 3; char keys[ROWS][COLS] = { // how the keypad is laid out {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte rowPins[ROWS] = {2, 3, 4, 5}; // keypad pins 1-4 (with the ESP32: 13, 14, 27, 32) byte colPins[COLS] = {8, 9, 10}; // keypad pins 5-7 (with the ESP32: 26, 25, 33) Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(115200); } void loop() { char key = keypad.getKey(); // NO_KEY if you have not pressed anything if (key != NO_KEY) { Serial.println(key); } }
keys table copies the layout of the keypad: 4 rows of 3. That way the library knows that row 1 with column 2 is the “2” key.- The wrong keys come out: two pins are swapped. Check the order from the left again.
- A whole row or a whole column does not respond: that jumper wire is not making contact.
- You have a different keypad (4×4, or from another maker): the pin order changes, check its datasheet.
4The secret code
// The secret code: type the digits and press # to try it, * to clear. If it is right the small L light turns on. #include <Arduino.h> #include <Keypad.h> const byte ROWS = 4, COLS = 3; char keys[ROWS][COLS] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte rowPins[ROWS] = {2, 3, 4, 5}; // with the ESP32: 13, 14, 27, 32 byte colPins[COLS] = {8, 9, 10}; // with the ESP32: 26, 25, 33 Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); const String SECRET = "1234"; // change it to your own code const int LED = 13; // the small L light (with the ESP32: an LED on 23) const int BUZZER = 12; // with the ESP32 write 4 String typed = ""; // the digits pressed so far void setup() { pinMode(LED, OUTPUT); Serial.begin(115200); Serial.println("Type the code and press #"); } void loop() { char key = keypad.getKey(); if (key == NO_KEY) return; // nothing new: start the loop again tone(BUZZER, 2000, 30); // a small click for each key if (key == '*') { // clear typed = ""; Serial.println("Cleared"); } else if (key == '#') { // try the code if (typed == SECRET) { Serial.println("Right code!"); digitalWrite(LED, HIGH); delay(3000); // open for 3 seconds digitalWrite(LED, LOW); } else { Serial.println("Wrong code"); tone(BUZZER, 300, 600); // a low, long sound } typed = ""; } else { typed += key; // add the digit at the end Serial.print("*"); // you only see an asterisk, like at the ATM } }
typed += key adds the digit just pressed at the end; typed == SECRET compares the two texts.5Challenge yourself
- A real lock in miniature: with the right code the servo from guide no. 41 turns 90 degrees.
- After three wrong codes the keypad locks for 30 seconds.
- Show the digits on the display from guide no. 53 as you type them.
6And with the ESP32?
It works the same way: rows on GPIO 13, 14, 27, 32, columns on 26, 25, 33, buzzer on 4. We avoid GPIO 12, which the ESP32 reads at power-up to decide how to start.
- a matrix keypad uses 7 wires for 12 keys;
- the Keypad library does the scanning:
getKeygives you the key pressed; - a
Stringcollects the digits and is compared with the code.
Useful products
Other guides
- Resistor colour code and tolerances
- N-channel and P-channel MOSFETs
- Bipolar transistor (BJT) or MOSFET?
- Relays: how to drive them and how much current they draw
- THT and SMD/SMT components
- XIAO board pinouts
- LEDs: forward voltage and series resistor
- The multimeter: measuring voltage and current
- Wemos D1 mini: first steps
- MOSFET module with Arduino and ESP32
- Relay module with Arduino and ESP32
- 3D printing filaments: PLA, PETG and fibre-filled versions
- Analog and digital: the differences
- ADS1115: 16-bit converter with Arduino and ESP32
- From bits to real values: converting sensor readings
- DS3231 RTC clock with Arduino and ESP32
- Linear or switching regulator: which one to choose
- Step-down, step-up and buck-boost: choosing the right module
- Voltage divider: reading voltages higher than 5 V or 3.3 V
- Pull-up, pull-down and bounce: wiring a button properly
- 3.3 V and 5 V logic levels: getting an ESP32 and an Arduino to talk
- The I²C bus: addresses, pull-ups and the scanner
- Lithium batteries: voltages, charging and protection
- ESP32 power consumption and deep sleep: how long the battery lasts
- Temperature sensors compared
- ESP32: which pins to use and which to avoid
- Getting started with the ESP32 in Arduino IDE 2 and PlatformIO
- SSD1306 OLED display and 16×2 I²C LCD with Arduino and ESP32
- PIR motion sensor and HC-SR04 ultrasonic sensor
- Date and time from the Internet with the ESP32: NTP, Italian time zone and daylight saving time
- MicroSD data logger: saving measurements to CSV
- Solar-powered ESP32: panel, charger and the numbers for Italy
- Web server on the ESP32: control a relay from your phone
- Your first LED: wire it up and make it blink
- The button: let Arduino decide
- The potentiometer: turn a knob and read its value
- Soft light: adjusting the brightness of an LED
- The buzzer: playing notes and melodies
- The traffic light: three LEDs in sequence
- The thermometer: reading the temperature with the TMP36
- The servo motor: moving an arm with Arduino
- The night light: the photoresistor and your first decision
- The relay: switching on a light bulb with Arduino
- The LCD display: making Arduino write
- The electronic dice: your first complete project
- The RGB LED: every color from three lights
- The joystick: two-axis control with a shield
- The LED ring: twelve colors from a single pin
- The DC motor: driving it with a MOSFET
- Soil moisture: the plant that asks for water
- The stepper motor: turn exactly as far as you want
- The parking sensor: faster and faster beeps
- The 7-segment display: big, bright numbers
- Automatic watering: the plant that waters itself
- Networked weather station: values and chart on your phone
- A Telegram bot on the ESP32: your home from your phone
- MQTT with the ESP32: the language of connected devices
- Updating the ESP32 over Wi-Fi (OTA)
- ESP-NOW: two ESP32 boards talking without a router
- WebSocket with the ESP32: the LED that follows the slider
- Readings on a Google sheet, with deep sleep
- WiFiManager: choose the Wi-Fi from your phone
- Bluetooth LE with the ESP32: the phone without a network
- The camera in your browser with the ESP32-S3
- A portable Bluetooth speaker you build yourself
- Bluetooth desktop speakers, 2 × 20 W
- Stereo MP3 player with two buttons
- The shelf that plays music: a Visaton exciter
- How to solder well
- How much does it draw? Current and power with the INA219
- Load-cell scale with the HX711
- CO2 traffic light: when to open the windows
- RFID card door opener
- GPS: track logger on microSD
- LoRa: how far does it go? A range test with two boards
- Battery weather sign with an e-paper display
- Web radio with an ESP32 and an I2S amplifier
- Getting started with the Raspberry Pi Pico 2 in MicroPython
- Your first amplifier: the LM386 and a speaker
- Talking Arduino: the DFR0760 speech synthesis module
- The spectrum of your music on an LED matrix
- Drawing with 64 LEDs: the 8×8 matrix with the MAX7219
- A real voltage: the 12-bit MCP4725 DAC
- The heartbeat on Arduino: an ECG with the AD8232