Build a home alarm panel with a keypad, motion sensor and LCD

Build an alarm panel like the ones by the front door: arm it with a code, leave before the countdown ends, and if someone moves inside, they have ten seconds to type the code before the siren starts. You program...
  • Level:Advanced
  • Duration: 2 h
  • Ages 12+
  • Platform: Arduino

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Build a home alarm panel with a keypad, motion sensor and LCD – EEMENTOR STEM™ lesson

Real alarm panels follow a strict routine. You type your code and press arm; a countdown gives you time to leave; then the motion sensors watch the house. When someone comes in, the panel doesn't scream straight away: it gives them a few seconds to type the code. Only if they don't does the siren go off, and it keeps going until the right code is entered. In this capstone project you build exactly that with the UNO, a 4×4 keypad, a PIR motion sensor, the 1602 LCD and a buzzer. The heart of the project is a state machine: a clear list of states the panel can be in, and the events that move it from one to the next.

What you'll learn

  • How to design a program as a state machine with an enum and a switch
  • How exit and entry delays work in real alarm systems
  • How to read a code from a keypad, with clear and confirm keys
  • How to run countdowns and a siren with millis(), without delay()
  • How to share the UNO's pins between an LCD, a keypad and sensors

What you need

  • UNO R3 board and USB cable (UNO R3 Starter Kit)
  • 1602 LCD display, 10 kΩ potentiometer and a 220 Ω resistor (UNO R3 Starter Kit)
  • 4×4 keypad module (UNO R3 Starter Kit)
  • PIR motion sensor (UNO R3 Starter Kit)
  • Active buzzer (UNO R3 Starter Kit)
  • 1 red LED and a 220 Ω resistor (UNO R3 Starter Kit)
  • Breadboard and jumper wires (UNO R3 Starter Kit)
  • The free Arduino IDE and the Keypad library by Mark Stanley and Alexander Brevig from the Library Manager

This project builds on the LCD lesson, the keypad lesson and Do two things at once with millis(). If something is new to you, start there.

Wiring

The LCD and the keypad together need 14 pins, so the keypad rows use the analog pins A0–A3 as normal digital pins, and the PIR and buzzer use A4 and A5. This is the same LCD and keypad wiring as the keypad safe, so you can reuse that build. Set the PIR's time knob fully anticlockwise and its jumper to H.

Breadboard wiring diagram: 1602 LCD on UNO pins 12, 11, 5, 4, 3, 2 with a contrast potentiometer, 4x4 keypad rows on A0 to A3 and columns on 10, 8, 7, 6, PIR sensor output on A4, active buzzer on A5 and a red LED on pin 9.
Breadboard view. Check each connection against the wiring table below.
From To
LCD VSS, RW and K GND
LCD VDD 5V
LCD V0 Middle pin (W) of the potentiometer
LCD RS, E UNO pins 12, 11
LCD D4, D5, D6, D7 UNO pins 5, 4, 3, 2
LCD A (backlight +) 220 Ω resistor, then 5V
Potentiometer outer pins 5V and GND
Keypad R1, R2, R3, R4 UNO pins A0, A1, A2, A3
Keypad C1, C2, C3, C4 UNO pins 10, 8, 7, 6
PIR VCC, OUT, GND 5V, UNO pin A4, GND
Active buzzer + (longer leg), − UNO pin A5, GND
UNO pin 9 220 Ω resistor → red LED long leg (+); short leg (−) → GND

The keypad's eight wires are in the order R1, R2, R3, R4, C1, C2, C3, C4 when you look at the keys from the front with the cable at the bottom.

FREE

Build this circuit in EEMENTOR Lab

Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.

The UNO and the parts for this lesson laid out in EEMENTOR Lab, ready to wireBuild it yourself
  1. The UNO and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
  2. Missing a part? Add it from the parts list on the left.
  3. Press Run, then try the inputs: click, hold or slide them under Selected.
  4. Then try this lesson’s sketch: paste it into the Code tab and press Compile & Run.

EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab

The sketch

Install the Keypad library, copy the sketch into the Arduino IDE, choose Arduino Uno and the right port, and click Upload. The code is 1234; change CODE to your own.

// Home alarm panel: arm with the keypad, the PIR watches, the LCD shows the state
#include <Keypad.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);    // RS, E, D4, D5, D6, D7

const byte ROWS = 4, COLS = 4;
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = {10, 8, 7, 6};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

const int PIR_PIN = A4;
const int BUZZER_PIN = A5;
const int LED_PIN = 9;
const char CODE[] = "1234";                // change this to your own code
const unsigned long WARMUP_TIME = 60000;   // the PIR needs about a minute to settle
const unsigned long EXIT_TIME = 15000;     // time to leave after arming
const unsigned long ENTRY_TIME = 10000;    // time to type the code after coming in

enum State { WARMUP, DISARMED, EXIT_DELAY, ARMED, ENTRY_DELAY, ALARM };
State state = WARMUP;
unsigned long stateStart = 0;
char entered[5] = "";
byte len = 0;
long lastSecond = -1;

void showLine2(const char* text) {
  lcd.setCursor(0, 1);
  lcd.print(text);
  for (int i = strlen(text); i < 16; i++) lcd.print(' ');   // clear the rest of the line
}

void setState(State s) {
  state = s;
  stateStart = millis();
  len = 0;
  entered[0] = '\0';
  lastSecond = -1;
  digitalWrite(BUZZER_PIN, LOW);
  lcd.clear();
  switch (state) {
    case WARMUP:      lcd.print("Starting up...");  break;
    case DISARMED:    lcd.print("DISARMED");        showLine2("A = arm"); break;
    case EXIT_DELAY:  lcd.print("Leave now!");      break;
    case ARMED:       lcd.print("ARMED");           showLine2("Code + # = off"); break;
    case ENTRY_DELAY: lcd.print("Enter code!");     break;
    case ALARM:       lcd.print("!!! ALARM !!!");   showLine2("Code + # = off"); break;
  }
}

void showCountdown(unsigned long total, const char* label) {
  long left = (long)((total - (millis() - stateStart)) / 1000) + 1;
  if (left == lastSecond) return;           // only update once per second
  lastSecond = left;
  char line[17];
  snprintf(line, sizeof(line), "%s %2ld s %s", label, left, len ? "****" + (4 - len) : "");
  showLine2(line);
}

void handleKey(char key) {
  if (key == '*') {                         // clear what you typed
    len = 0;
    entered[0] = '\0';
  } else if (key == 'A' && state == DISARMED) {
    setState(EXIT_DELAY);
    return;
  } else if (key >= '0' && key <= '9' && len < 4) {
    entered[len++] = key;
    entered[len] = '\0';
  } else if (key == '#' && state != DISARMED && state != WARMUP) {
    if (strcmp(entered, CODE) == 0) {
      setState(DISARMED);
      showLine2("Code OK. A = arm");
      return;
    }
    len = 0;
    entered[0] = '\0';
    showLine2("Wrong code");
    lastSecond = -1;
    return;
  }
  if (state == ARMED || state == ALARM) {   // show stars for the digits typed
    char line[17];
    snprintf(line, sizeof(line), "Code: %s", "****" + (4 - len));
    showLine2(line);
  }
  lastSecond = -1;                          // redraw countdowns with the stars
}

void setup() {
  pinMode(PIR_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  lcd.begin(16, 2);
  setState(WARMUP);
}

void loop() {
  unsigned long now = millis();
  unsigned long inState = now - stateStart;
  char key = keypad.getKey();
  if (key) handleKey(key);

  switch (state) {
    case WARMUP:
      showCountdown(WARMUP_TIME, "Wait");
      if (inState >= WARMUP_TIME) setState(DISARMED);
      break;
    case DISARMED:
      digitalWrite(LED_PIN, LOW);
      break;
    case EXIT_DELAY:
      showCountdown(EXIT_TIME, "Exit in");
      digitalWrite(BUZZER_PIN, (inState % 1000) < 60);   // short tick every second
      digitalWrite(LED_PIN, (inState / 500) % 2);
      if (inState >= EXIT_TIME) setState(ARMED);
      break;
    case ARMED:
      digitalWrite(LED_PIN, (now % 2000) < 100);          // short flash every 2 s
      if (digitalRead(PIR_PIN) == HIGH) setState(ENTRY_DELAY);
      break;
    case ENTRY_DELAY:
      showCountdown(ENTRY_TIME, "Code");
      digitalWrite(BUZZER_PIN, (inState % 500) < 60);    // faster ticks
      digitalWrite(LED_PIN, HIGH);
      if (inState >= ENTRY_TIME) setState(ALARM);
      break;
    case ALARM:
      digitalWrite(BUZZER_PIN, (now / 300) % 2);          // siren on and off
      digitalWrite(LED_PIN, (now / 150) % 2);
      break;
  }
}

Try it

  1. Upload the sketch. The LCD says "Starting up..." and counts down 60 seconds while the PIR settles. Stay out of its view if you can.
  2. It shows DISARMED. Press A: "Leave now!" and a 15-second countdown with ticks. Walk out of the sensor's view.
  3. When the countdown ends, the LCD says ARMED and the LED flashes briefly every 2 seconds.
  4. Walk in front of the PIR. The LCD says "Enter code!" with a 10-second countdown, and the ticks get faster.
  5. Type 1234 and press #: back to DISARMED. Try again, but this time wait: when the countdown ends, the siren starts and only 1234 # stops it. A wrong code says "Wrong code"; * clears what you typed.

What you should see

Six LCD screens: DISARMED with A = arm, Leave now with the exit countdown, ARMED, Enter code with the entry countdown and stars, ALARM with the code being typed, and DISARMED with Code OK.
What the LCD shows in each state.

How it works

State diagram: WARMUP to DISARMED after 60 seconds, DISARMED to EXIT_DELAY with key A, EXIT_DELAY to ARMED after 15 seconds, ARMED to ENTRY_DELAY on motion, ENTRY_DELAY to ALARM after 10 seconds, and the right code plus # back to DISARMED from any active state.
Six states, and what moves the panel between them.

A state machine describes a system as a few named states and the events that move it between them. Here there are six: WARMUP, DISARMED, EXIT_DELAY, ARMED, ENTRY_DELAY and ALARM. The enum gives each state a name, and the variable state holds the current one. Every pass of loop(), the switch runs only the code for the current state. Moving to a new state always goes through setState(), which notes the time, clears the typed code and redraws the screen, so each state starts cleanly.

The events are simple: the A key (DISARMED → EXIT_DELAY), a timer running out (EXIT_DELAY → ARMED, ENTRY_DELAY → ALARM, WARMUP → DISARMED), the PIR seeing movement (ARMED → ENTRY_DELAY), and the right code followed by # (any active state → DISARMED). Writing the states and arrows down first, as in the picture, makes a tricky program easy to check: for every state you can ask "what happens if a key is pressed? if the time runs out? if someone moves?".

All the timing uses millis(): inState is how long the panel has been in its current state. That's how the countdowns, the ticks and the siren all run at once while the keypad is still read many times a second. A delay() anywhere would make the keypad miss presses. The countdown only redraws the LCD when the second changes, because writing to the LCD is slow and would make the display flicker.

Try this next

  • Add a panic button: pressing D starts the alarm at once, from any state.
  • Count wrong codes, and lock the keypad for 30 seconds after three in a row.
  • Save a new code in EEPROM, like the keypad safe does, so you can change it without uploading.
  • Add a reed switch on a door as a second sensor that skips the entry delay, like a back door that should never open.

Troubleshooting

  • The LCD lights but shows nothing, or only blocks: turn the potentiometer slowly until the text appears.
  • Keys give the wrong characters or nothing: the keypad wires are in the wrong order. Rows go to A0–A3, columns to 10, 8, 7, 6, in the order R1–R4, C1–C4.
  • It goes to "Enter code!" straight after arming: the PIR still sees you, or its time knob is turned up and it is still on from earlier. Turn the knob fully anticlockwise and leave the room during the exit countdown.
  • The motion sensor never triggers: check PIR VCC on 5V and OUT on A4, and give it the full minute of warm-up.
  • The buzzer is silent: its longer leg (+) must go to A5. A passive buzzer only clicks with digitalWrite(); use the active buzzer.