Raspberry Pi - Keypad - Relay
This tutorial instructs you how to combine a keypad, relay, and Raspberry Pi. If the user enters the correct password on the keypad, the Raspberry Pi will turn on the relay.
The tutorial also provides the Raspberry Pi code which activates a relay over a certain period of time and then deactivates it. Moreover, the Raspberry Pi code is capable of handling multiple passwords.
|Raspberry Pi 4 Model B
|(Optional) Screw Terminal Adapter for Raspberry Pi
Or you can buy the following sensor kit:
|DIYables Sensor Kit 30 types, 69 units
Overview of Keypad and Relay
If you are unfamiliar with keypad and relay (including pinout, functionality, programming, etc.), the following tutorials can help:
This image is created using Fritzing. Click to enlarge image
Raspberry Pi Code - turn relay on if the password is correct
- Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
- Make sure your Raspberry Pi is connected to the same local network as your PC.
- Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
- If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
- Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
- Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
- Create a Python script file keypad_relay.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- Enter 9765 followed by the # key, then 1234 followed by the # key.
- Check the Terminal for the result and the state of the relay.
The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.
Authorized passwords are pre-defined in the Raspberry Pi code. A string is used to store the password inputted by users, called input string. In keypad, two keys (* and #) are used for special purposes: clear password and terminate password. When a key on keypad is pressed:
- If the pressed key is not two special keys, it is appended to the input string.
- If the pressed key is *, the input string is cleared. This can be used to start or re-start inputing the password.
- If the pressed key is #:
- The Raspberry Pi verifies if input string match one of the pre-defined passwords, the relay is turned on.
- Regardless of whether the password is correct or not, the input string is cleared for the next input.
Raspberry Pi Code - turn a relay on in a period of time if the password is correct
If the password is correct, the relay will be turned on for 5 seconds. After that period of time, it will be switched off.