Raspberry Pi - Keypad - Servo Motor

This tutorial instructs you how to use Raspberry Pi and keypad to control servo motor. In detail:

The code for Raspberry Pi also allows for multiple passwords to be used.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Servo Motor
1×5V Power Adapter
1×DC Power Jack
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Keypad and Servo Motor

If you are unfamiliar with keypad and servo motor (including pinout, functionality, programming, etc.), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and keypad servo motor

This image is created using Fritzing. Click to enlarge image

Please note that the wiring diagram shown above is only suitable for a servo motor with low torque. In case the motor vibrates instead of rotating, an external power source must be utilized to provide more power for the servo motor. The below demonstrates the wiring diagram with an external power source for servo motor.


Please do not forget to connect GND of the external power to GND of Arduino Raspberry Pi.

Raspberry Pi Code - rotates Servo Motor if the password is correct

If the password is correct, the servo motor will be set to 90° for a duration of 5 seconds. Once the 5 seconds have elapsed, the servo motor will be reset to 0°.

Detailed Instructions

  • 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:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file keypad_servo.py and add the following code:
# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-keypad-servo-motor import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'] ] # Define GPIO pins for rows, columns, and servo motor ROW_PINS = [17, 27, 22, 24] COL_PINS = [25, 8, 7] SERVO_PIN = 16 # Adjust this to the actual GPIO pin connected to the servo motor # Passwords to unlock PASSWORDS = [ [1, 2, 3, 4], # 1st password 1234 [5, 6, 7, 8], # 2nd password 5678 [9, 0, 1, 2] # 3rd password 9012 ] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROW_PINS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COL_PINS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) # Set up servo pin as an output GPIO.setup(SERVO_PIN, GPIO.OUT) servo = GPIO.PWM(SERVO_PIN, 50) # 50 Hz frequency # Function to move servo to a specified angle def move_servo(angle): duty_cycle = (angle / 18) + 2.5 servo.ChangeDutyCycle(duty_cycle) time.sleep(1) # Adjust this sleep duration based on servo response time def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COL_PINS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROW_PINS): if GPIO.input(row_pin) == GPIO.LOW: key = KEYPAD[row_num][col_num] # Wait for key release while GPIO.input(row_pin) == GPIO.LOW: time.sleep(0.05) GPIO.output(col_pin, GPIO.HIGH) return key def check_password(input_password): return input_password in PASSWORDS entered_keys = [] try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") if pressed_key == '*': entered_keys = [] # reset the input password elif pressed_key == '#': if check_password(entered_keys): print("Password correct! Access granted.") move_servo(90) time.sleep(20) # Wait for 20 seconds move_servo(0) else: print("Incorrect password. Try again.") entered_keys = [] # reset the input password else: entered_keys.append(pressed_key) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 keypad_servo.py

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

  • Press 12345#
  • Enter 5642B#
  • Check out the outcome on Serial Monitor and the position of the servo motor.
PuTTY - Raspberry Pi
The incorrect password! try again The correct password! Rotating Servo Motor to 90° Rotating Servo Motor to 0°

Code Explanation

The valid passwords are pre-defined in the Raspberry Pi code. A string, referred to as input_password, is used to store the password inputted by users. On the keypad, two keys (* and #) are used for special purposes: clearing the password and terminating the password. When a key on the keypad is pressed:

  • If the pressed key is not one of the two special keys, it will be added to the input_password.
  • If the pressed key is *, the input_password will be cleared. This can be used to start or re-start inputting the password.
  • If the pressed key is #:
    • The Raspberry Pi checks if the input_password matche with one of the pre-defined passwords, the servo motor will rotate to 90°.
    • Regardless of whether the password is correct or not, the input_password will be cleared for the next input.
    • After a period of time, ESP8266 rotates the servo motor to 0°.

Video Tutorial


  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!