Build a keypad alarm with an LCD and phone alerts on the Raspberry Pi

Build a real home alarm: arm it with a PIN on a 4×4 keypad, leave during the exit delay, and if someone walks in without the PIN the siren sounds and your phone gets a push alert. You learn keypad...
  • Level:Advanced
  • Duration: 2 h
  • Ages 12+
  • Platform: Raspberry Pi
Build a keypad alarm with an LCD and phone alerts on the Raspberry Pi – EEMENTOR STEM™ lesson

Real alarm systems don't scream the moment you open the door. You type your PIN, the alarm gives you time to leave, and when someone comes in it gives them a few seconds to type the PIN before the siren starts. In this project you build exactly that with the Raspberry Pi: a 4×4 keypad for the PIN, a 1602 LCD that tells you what is happening, a PIR sensor that notices movement, a piezo siren, and a push alert on your phone when the alarm goes off. It builds on the motion alarm from the starter path, and this time you write the program as a proper state machine.

What you'll learn

  • How a keypad matrix works, and how to scan its 16 keys with only 8 pins
  • How to drive a 1602 LCD in 4-bit mode with your own small Python driver
  • How to organise a program as a state machine with timed delays
  • How to send a push notification to your phone with ntfy, without an account
  • How to store a setting, the PIN, in a file so it survives a restart

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS (see the first starter lesson) and its USB-C power supply
  • 4×4 keypad module (ESP32 IoT Starter Kit)
  • 1602 LCD display, a 10 kΩ potentiometer and a 220 Ω resistor (ESP32 IoT Starter Kit)
  • PIR motion sensor (ESP32 IoT Starter Kit)
  • Piezo buzzer (ESP32 IoT Starter Kit)
  • Breadboard, male-to-male wires and a 40-pin male header (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires from the Pi to the breadboard, or a female-female and a male-male Dupont wire from the kit plugged together
  • The free ntfy app on your phone (Android or iPhone), for the alerts

Look after your Pi: the GPIO pins work at 3.3 V and must never receive 5 V. The LCD and the PIR run on 5 V, which is safe here because the Pi only sends signals to the LCD: its RW pin is tied to GND, so the LCD can never send 5 V back. The PIR's OUT pin only outputs about 3.3 V. We use the piezo buzzer rather than the active buzzer because a piezo draws almost no current, so it is gentle on a GPIO pin. Shut the Pi down and unplug it before you change the wiring.

Wiring

This project uses 16 GPIO pins, so plan before you plug. The pins below leave the Pi's I2C pins (GPIO 2 and 3) and SPI pins (GPIO 7 to 11) free for later projects. The keypad's 8-pin socket is easiest to use with 8 pins of the male header pushed into the breadboard. Looking at the front of the keypad, the left four wires are the rows R1 to R4 and the right four are the columns C1 to C4.

Breadboard wiring diagram: 1602 LCD with RS on GPIO 26, E on GPIO 19, D4 to D7 on GPIO 13, 6, 5 and 21, contrast potentiometer and 220 ohm backlight resistor; 4x4 keypad rows on GPIO 17, 27, 22, 23 and columns on GPIO 24, 25, 16, 20; PIR OUT on GPIO 4; piezo buzzer on GPIO 18; rails from 5V pin 2 and GND pin 9 of a Raspberry Pi 4.
Breadboard view. Check each connection against the wiring table below.
Part Pin Raspberry Pi
LCD VSS, RW, K GND rail
LCD VDD 5V rail
LCD V0 Potentiometer middle pin (outer pins to 5V and GND)
LCD A (backlight +) 220 Ω resistor → 5V rail
LCD RS / E GPIO 26 (pin 37) / GPIO 19 (pin 35)
LCD D4 / D5 / D6 / D7 GPIO 13 (pin 33) / GPIO 6 (pin 31) / GPIO 5 (pin 29) / GPIO 21 (pin 40)
Keypad R1 / R2 / R3 / R4 GPIO 17 (pin 11) / GPIO 27 (pin 13) / GPIO 22 (pin 15) / GPIO 23 (pin 16)
Keypad C1 / C2 / C3 / C4 GPIO 24 (pin 18) / GPIO 25 (pin 22) / GPIO 16 (pin 36) / GPIO 20 (pin 38)
PIR VCC / OUT / GND 5V rail / GPIO 4 (pin 7) / GND rail
Piezo buzzer + / − GPIO 18 (pin 12) / GND rail
Rails + / − 5V (pin 2) / GND (pin 9)

Set the PIR's time knob fully anticlockwise and its jumper to H, as in the starter lesson. LCD pins D0 to D3 stay empty: in 4-bit mode each byte is sent as two halves on D4 to D7.

Set up the phone alerts

ntfy is a free, open-source notification service. A program sends a message to a topic, and every phone subscribed to that topic gets it, with no account and no keys. Install the ntfy app, tap +, and subscribe to a topic name. Topic names are public: anyone who guesses yours can read your alerts or send fake ones, so make it long and random, like eementor-alarm-k8w2q9zr4t. Type the same name into NTFY_TOPIC at the top of the program.

The program

Everything the program needs is already on Raspberry Pi OS: gpiozero for the pins, and Python's own urllib for the alert. Open Thonny, paste the program, save it as alarm.py and click Run. The first PIN is 1234.

# Keypad alarm with an LCD and phone alerts (gpiozero + ntfy.sh)
from gpiozero import Device, DigitalOutputDevice, MotionSensor, TonalBuzzer
from datetime import datetime
from time import sleep, monotonic
import threading
import urllib.request
import os

# ---------- settings ----------
NTFY_TOPIC = "eementor-alarm-change-me-7f3k9q2x"  # pick your own long, random name
EXIT_DELAY = 30       # seconds to leave the room after arming
ENTRY_DELAY = 15      # seconds to type the PIN after motion
SIREN_TIME = 120      # the siren stops after 2 minutes; the alarm stays on
WARM_UP = 60          # the PIR sensor needs about a minute after power-on
PIN_FILE = os.path.expanduser("~/alarm_pin.txt")


# ---------- the 1602 LCD in 4-bit mode ----------
class LCD:
    def __init__(self, rs, e, d4, d5, d6, d7):
        self.rs = DigitalOutputDevice(rs)
        self.e = DigitalOutputDevice(e)
        self.data = [DigitalOutputDevice(p) for p in (d4, d5, d6, d7)]
        self.lines = [None, None]
        sleep(0.05)
        for nibble in (0x3, 0x3, 0x3, 0x2):   # wake the LCD up, switch to 4-bit mode
            self._nibble(nibble)
            sleep(0.005)
        for cmd in (0x28, 0x0C, 0x06, 0x01):  # 2 lines, display on, move right, clear
            self.command(cmd)

    def _nibble(self, value):
        for bit, pin in enumerate(self.data):  # D4 gets bit 0 ... D7 gets bit 3
            pin.value = (value >> bit) & 1
        self.e.on()                            # a short pulse on E latches the 4 bits
        sleep(0.0001)
        self.e.off()
        sleep(0.0001)

    def _byte(self, value, is_char):
        self.rs.value = is_char               # RS low = command, RS high = character
        self._nibble(value >> 4)
        self._nibble(value & 0x0F)

    def command(self, cmd):
        self._byte(cmd, False)
        if cmd in (0x01, 0x02):
            sleep(0.002)                      # clear and home take longer

    def show(self, line1, line2=""):
        for row, text in enumerate((line1, line2)):
            text = text[:16].ljust(16)
            if text == self.lines[row]:
                continue                      # only rewrite a line that changed
            self.lines[row] = text
            self.command(0x80 | (0x40 * row))  # move to the start of the row
            for ch in text:
                self._byte(ord(ch) if ord(ch) < 128 else ord("?"), True)


# ---------- the 4x4 keypad ----------
class Keypad:
    KEYS = ["123A", "456B", "789C", "*0#D"]

    def __init__(self, rows, cols):
        factory = Device.pin_factory
        self.rows = [factory.pin(n) for n in rows]
        self.cols = [factory.pin(n) for n in cols]
        for pin in self.rows:
            pin.function = "input"            # a row only drives the pin while we check it
            pin.pull = "floating"
        for pin in self.cols:
            pin.function = "input"
            pin.pull = "up"                   # a column reads 1 until a key pulls it low
        self.last = None

    def scan(self):
        pressed = None
        for r, row in enumerate(self.rows):
            row.function = "output"
            row.state = 0                     # pull this row low...
            for c, col in enumerate(self.cols):
                if col.state == 0:            # ...a pressed key connects it to a column
                    pressed = self.KEYS[r][c]
            row.function = "input"
        new_key = pressed if pressed != self.last else None
        self.last = pressed                   # report each press once, not while held
        return new_key


lcd = LCD(rs=26, e=19, d4=13, d5=6, d6=5, d7=21)
keypad = Keypad(rows=[17, 27, 22, 23], cols=[24, 25, 16, 20])
pir = MotionSensor(4)
buzzer = TonalBuzzer(18)


def load_pin():
    try:
        with open(PIN_FILE) as f:
            code = f.read().strip()
        if code.isdigit() and 4 <= len(code) <= 8:
            return code
    except FileNotFoundError:
        pass
    return "1234"                             # the first PIN; change it with C


def notify(message, priority="default"):
    def send():
        try:
            request = urllib.request.Request(
                "https://ntfy.sh/" + NTFY_TOPIC, data=message.encode(),
                headers={"Title": "EEMENTOR alarm", "Priority": priority, "Tags": "rotating_light"})
            urllib.request.urlopen(request, timeout=10)
            print("Alert sent:", message)
        except Exception as error:
            print("Alert not sent:", error)
    threading.Thread(target=send, daemon=True).start()   # never let the network stop the alarm


pin_code = load_pin()
state = "WARM_UP"
since = monotonic()
typed = ""
wrong = 0
change_step = None        # None, "old", "new" or "again" while changing the PIN
new_pin = ""
flash, flash_until = "", 0.0
click_until = 0.0
tone_now = None
alarm_time = ""


def set_state(new):
    global state, since, typed, wrong, alarm_time
    state, since, typed = new, monotonic(), ""
    if new in ("DISARMED", "ARMED"):
        wrong = 0
    print(f"{datetime.now():%H:%M:%S}  {new}")
    if new == "ALARM":
        alarm_time = f"{datetime.now():%H:%M}"
        notify(f"Alarm at {alarm_time}! Motion and no PIN.", "urgent")


def say(text):
    global flash, flash_until
    flash, flash_until = text, monotonic() + 1.5


def handle_pin(entry):
    global change_step, new_pin, pin_code, wrong
    if change_step == "old":
        change_step = "new" if entry == pin_code else None
        say("New PIN + #" if change_step else "Wrong PIN")
    elif change_step == "new":
        if entry.isdigit() and 4 <= len(entry) <= 8:
            new_pin, change_step = entry, "again"
        else:
            change_step = None
            say("Use 4-8 digits")
    elif change_step == "again":
        change_step = None
        if entry == new_pin:
            pin_code = new_pin
            with open(PIN_FILE, "w") as f:
                f.write(pin_code)
            say("PIN changed")
        else:
            say("No match")
    elif entry == pin_code:
        if state == "DISARMED":
            set_state("EXIT")
        else:
            if state == "ALARM":
                notify("The alarm was switched off with the PIN.")
            set_state("DISARMED")
            say("Welcome home")
    else:
        wrong += 1
        say("Wrong PIN")
        if state in ("ARMED", "ENTRY") and wrong >= 3:
            set_state("ALARM")                # three wrong PINs = intruder


def on_key(key):
    global typed, change_step, click_until
    click_until = monotonic() + 0.05
    if state == "WARM_UP":
        return
    if key == "*":
        typed = ""
        change_step = None
    elif key == "C" and state == "DISARMED" and not typed:
        change_step = "old"
    elif key.isdigit() and len(typed) < 8:
        typed += key
    elif key == "#":
        entry, typed = typed, ""
        handle_pin(entry)


def tick():
    t = monotonic() - since
    if state == "WARM_UP" and t >= WARM_UP:
        set_state("DISARMED")
    elif state == "EXIT" and t >= EXIT_DELAY:
        set_state("ARMED")
    elif state == "ARMED" and pir.motion_detected:
        set_state("ENTRY")
    elif state == "ENTRY" and t >= ENTRY_DELAY:
        set_state("ALARM")


def sound():
    global tone_now
    t = monotonic() - since
    want = None
    if monotonic() < click_until:
        want = "A4"                           # a short click for every key
    elif state == "EXIT" and t % 1 < 0.1:
        want = "A4"                           # one beep per second while you leave
    elif state == "ENTRY" and t % 0.5 < 0.1:
        want = "A5"                           # fast beeps: type the PIN!
    elif state == "ALARM" and t < SIREN_TIME:
        want = "A5" if t % 0.8 < 0.4 else "E5"   # two-tone siren
    if want != tone_now:
        buzzer.play(want) if want else buzzer.stop()
        tone_now = want


def screen():
    t = monotonic() - since
    stars = "*" * len(typed)
    top = {"WARM_UP": "EEMENTOR alarm", "DISARMED": "Disarmed", "EXIT": f"Arming in {max(0, EXIT_DELAY - int(t))} s",
           "ARMED": "ARMED", "ENTRY": f"PIN! {max(0, ENTRY_DELAY - int(t))} s", "ALARM": "!!! ALARM !!!"}[state]
    bottom = {"WARM_UP": "Warming up...", "DISARMED": "PIN + # to arm", "EXIT": "Leave the room",
              "ARMED": "Watching...", "ENTRY": "Type PIN + #", "ALARM": f"Motion {alarm_time}"}[state]
    if change_step:
        top = {"old": "Old PIN + #", "new": "New PIN + #", "again": "Again + #"}[change_step]
        bottom = stars
    elif typed:
        bottom = "PIN: " + stars
    if monotonic() < flash_until:
        bottom = flash
    lcd.show(top, bottom)


def main():
    print("Warming up the PIR sensor. Keep still for a minute...")
    try:
        while True:
            key = keypad.scan()
            if key:
                on_key(key)
            tick()
            sound()
            screen()
            sleep(0.02)
    except KeyboardInterrupt:
        buzzer.stop()
        lcd.show("Alarm stopped", "")


if __name__ == "__main__":
    main()

To use it: wait a minute while the PIR warms up, type 1234# to arm and leave within 30 seconds. To change the PIN, press C while disarmed, then the old PIN, the new one and the new one again, each followed by #. * clears what you typed. The new PIN is saved in alarm_pin.txt in your home folder.

What you should see

After the warm-up the LCD says Disarmed. Typed digits appear as stars. After 1234# it counts down "Arming in 30 s" with a beep each second, then shows ARMED. Walk in front of the PIR and it beeps fast and asks for the PIN; wait 15 seconds and the siren starts, the screen shows the time of the alarm, and your phone buzzes with the ntfy alert. The Shell prints every change of state with the time.

What you should see: the LCD showing Disarmed with the PIN as stars, the exit delay countdown, the entry delay asking for the PIN, and ALARM with the time, plus an ntfy push notification on a phone.
The LCD in each state, and the alert on your phone.

How it works

How it works: the six states warm-up, disarmed, exit delay, armed, entry delay and alarm with the events that move between them, and a keypad scan where row 2 is pulled low and column 3 reads 0, meaning key 6.
A state machine runs the alarm; the keypad is scanned one row at a time.

The keypad. The 16 keys sit on a grid of 4 row wires and 4 column wires, and each key connects one row to one column. The columns are inputs with pull-up resistors, so they read 1. The program pulls one row low at a time and checks the columns: a column that reads 0 tells you which key in that row is pressed. Only the row being checked is driven; the other rows float as inputs, so pressing two keys at once can never short two outputs together. A full scan of all 4 rows takes a fraction of a millisecond and runs 50 times a second. scan() only reports a key when it changes, so holding a key types it once.

The LCD. The LCD has its own controller chip. RS says whether a byte is a command (clear, move the cursor) or a character, and a short pulse on E tells the LCD to read the data pins. In 4-bit mode each byte goes as two 4-bit halves, high half first. The start-up sequence (three times 0x3, then 0x2) is how the controller's datasheet says to switch into 4-bit mode. show() only rewrites a line when its text changes, which keeps the screen from flickering.

The state machine. The alarm is always in exactly one state: warming up, disarmed, exit delay, armed, entry delay or alarm. tick() checks the only events that can change the state, such as "30 seconds have passed" or "motion while armed", and set_state() remembers when the new state began. sound() and screen() then simply look at the state and the time since it started to decide what to beep and what to show. Because nothing in the loop waits, the keypad keeps working while the siren sounds.

The alert. notify() sends an HTTP POST to ntfy.sh/your-topic, with the title and priority in headers. It runs in a separate thread, so a slow or missing internet connection can never freeze the alarm. Three wrong PINs while armed count as an intruder and set the alarm off straight away.

Try this next

  • Start the alarm automatically when the Pi boots, with a systemd service as in the climate logger lesson.
  • Add a second sensor: a reed switch on a door, read with gpiozero.Button, which triggers the entry delay too.
  • Use the A key for a "home" mode that only watches the door, not the PIR.
  • Log every arm, disarm and alarm with the time, as in the motion logger.

Troubleshooting

  • The LCD shows a row of blocks or nothing at all: turn the potentiometer slowly until the text appears; the contrast setting is very sensitive. Blocks on the top row only mean the LCD gets power but no valid start-up sequence: check RS, E and D4 to D7.
  • The LCD shows strange characters: two data wires are swapped. Check D4 to D7 against the table. Most 1602 LCDs accept the Pi's 3.3 V signals; if yours shows garbage even with correct wiring, try another LCD.
  • Keys type the wrong character: the keypad's wires are in a different order, or rows and columns are swapped. Swap the numbers in rows=[...] and cols=[...] instead of rewiring.
  • The alarm goes off on its own: the PIR sees a heater, a window in the sun or a pet. Point it away, turn the sensitivity knob down, or make the entry delay longer.
  • "Alert not sent" in the Shell: the Pi has no internet, or the topic name has spaces. Test the topic from the Pi's terminal with curl -d "test" ntfy.sh/your-topic.
  • "GPIO busy" error: another program, perhaps an earlier copy of this one, still uses the pins. Stop it in Thonny or restart the Pi.

Next lesson

Control your Raspberry Pi with an IR remote: decode a TV-style remote with the Linux kernel and use its buttons to switch lights and a relay.