Fareed Mohmed← Project library

Engineering · Raspberry Pi · Project 40 of 47 · Games and logic · Intermediate

Button code lock

Enter a four-key code on three buttons. The right code turns the servo bolt for five seconds. A wrong code flashes the red lamp and counts a failed try.

▶ Open in the simulator

Raspberry Pi simulator drawing of the circuit for Button code lock: the board, its power supply and the parts wired to the 40-pin header

Parts in this circuit

PartType
Key APush button
Key BPush button
Key CPush button
Lock boltServo
Wrong codeLED
UnlockedLED

Wiring, pin by pin

Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.

#ColourFrom (part and leg)To (header pin)
1ColouredKey A - SignalPin 29 (GPIO5)
2BlackKey A - GNDPin 6 (GND)
3ColouredKey B - SignalPin 31 (GPIO6)
4BlackKey B - GNDPin 9 (GND)
5ColouredKey C - SignalPin 33 (GPIO13)
6BlackKey C - GNDPin 14 (GND)
7ColouredLock bolt - signalPin 11 (GPIO17)
8RedLock bolt - 5 VPin 2 (5V)
9BlackLock bolt - GNDPin 20 (GND)
10ColouredWrong code - anode +Pin 16 (GPIO23)
11BlackWrong code - cathode -Pin 25 (GND)
12ColouredUnlocked - anode +Pin 15 (GPIO22)
13BlackUnlocked - cathode -Pin 30 (GND)

Python code (gpiozero)

from gpiozero import AngularServo, Button, LED
from time import sleep

CODE = ["A", "B", "B", "C"]                    # the secret code
keys = {"A": Button(5), "B": Button(6), "C": Button(13)}
bolt = AngularServo(17, min_angle=-90, max_angle=90)   # 0 = locked, 90 = open
red = LED(23)
green = LED(22)

def wait_key():
    while True:
        for name, button in keys.items():
            if button.is_pressed:
                while button.is_pressed:
                    sleep(0.02)
                return name
        sleep(0.02)

bolt.angle = 0
fails = 0
while True:
    entered = []
    while len(entered) < len(CODE):
        entered.append(wait_key())
        print("Keys so far:", len(entered))
    if entered == CODE:
        print("Correct code: UNLOCKED")
        fails = 0
        bolt.angle = 90
        green.on()
        sleep(5)
        bolt.angle = 0
        green.off()
        print("Locked again")
    else:
        fails += 1
        print("Wrong code. Failed tries:", fails)
        for _ in range(3):
            red.on()
            sleep(0.2)
            red.off()
            sleep(0.2)
        if fails >= 3:
            print("Too many tries: locked for 10 seconds")
            sleep(10)
            fails = 0

How the code works

You will learn

  • Comparing lists
  • Building a list one key at a time
  • Limiting the number of tries

Try this

  • Hold the A, B, B and C key buttons in order.
  • Change the secret code.
  • Make the lock beep once for each key press.

On a real Pi

  • A code on three buttons is a toy. A real lock needs a keypad, strong code and tamper protection.
  • Do not keep the secret code in plain text on a device that others can read.
  • A real lock needs power-cut safety: use a manual key or battery backup.

Parts to buy

The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.

#ItemQtyBuy / compare
1Raspberry Pi 4 Model B
about 4000 to 9000 INR
1Robu.in Amazon.in ThinkRobotics
2Official 15 W USB-C power supply (5.1 V, 3 A)
Do not use an old phone charger
1Robu.in Amazon.in ThinkRobotics
3microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS)
And a card reader to write it
1Robu.in Amazon.in ThinkRobotics
45 mm LED, red1Robu.in Amazon.in ThinkRobotics
55 mm LED, green1Robu.in Amazon.in ThinkRobotics
6330 ohm resistor, 1/4 W
One per LED
2Robu.in Amazon.in ThinkRobotics
7Tactile push button (12 mm, with cap)3Robu.in Amazon.in ThinkRobotics
8SG90 micro servo1Robu.in Amazon.in ThinkRobotics
9Dupont jumper wires, male-to-female, 20 cm (pack of 40)1Robu.in Amazon.in ThinkRobotics
10Breadboard 830 points
For resistors and shared GND / 5 V
1Robu.in Amazon.in ThinkRobotics
← 39. Electronic dice on an LED barAll projects41. Greenhouse climate control →

This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.