Raspberry Pi - Button - Relay

This tutorial instructs you how to use the Raspberry Pi and button to control the relay. By connecting the relay to a soleniod lock, light bulb, LED strip, motor, or actuator..., we can use a button to control the them. We will learn two different applications:

Application 1 - The relay state is synchronized with the button state. In detail:

Application 2 - The relay state is toggled each time the button is pressed. More specifically:

In the Application 2, We need to debounce the button to make sure it works properly. We'll see why it's important by comparing how the relay behaves when we use the Raspberry Pi code with and without debouncing the button.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Push Button
1×(Optional) Panel-mount Push Button
1×Relay
1×Breadboard
1×Jumper Wires
1×(Optional) Solenoid Lock
1×(Optional) 12V Power Adapter
1×(Optional) DC Power Jack
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 Relay and Button

If you are unfamiliar with relay and button (including pinout, operation, and programming), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and Button relay

This image is created using Fritzing. Click to enlarge image

Application 1 - The relay state is in sync with the button state

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 button_relay.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-button-relay import RPi.GPIO as GPIO # Constants won't change. They're used here to set pin numbers: BUTTON_PIN = 18 # The number of the pushbutton pin RELAY_PIN = 16 # The number of the relay pin # Variables will change: button_state = 0 # Variable for reading the pushbutton status # Set up GPIO GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering GPIO.setup(RELAY_PIN, GPIO.OUT) # Initialize the relay pin as an output GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the pushbutton pin as a pull-up input try: while True: # Read the state of the pushbutton value: button_state = GPIO.input(BUTTON_PIN) # Control relay according to the state of the button if button_state == GPIO.LOW: # If the button is pressed GPIO.output(RELAY_PIN, GPIO.HIGH) # Turn on relay else: # Otherwise, the button is not pressed GPIO.output(RELAY_PIN, GPIO.LOW) # Turn off relay except KeyboardInterrupt: # Clean up GPIO on program exit GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 button_relay.py
  • Press the button and hold it for a few seconds.
  • Check out the change in the relay's condition.

You will see that the relay state is in sync with the button state.

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

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Application 2 - Button toggles Relay

Detailed Instructions

  • Create a Python script file button_toggle_relay.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-button-relay import RPi.GPIO as GPIO import time # Constants won't change BUTTON_PIN = 18 # The number of the pushbutton pin RELAY_PIN = 16 # The number of the relay pin # Variables will change relay_state = GPIO.LOW # The current state of the relay prev_button_state = GPIO.LOW # The previous state of the button button_state = GPIO.LOW # The current state of the button # Set up GPIO GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering GPIO.setup(RELAY_PIN, GPIO.OUT) # Initialize the relay pin as an output GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the pushbutton pin as a pull-up input try: while True: # Read the state of the pushbutton value prev_button_state = button_state # Save the last state button_state = GPIO.input(BUTTON_PIN) # Read new state if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: time.sleep(0.1) # 100 milliseconds debounce time print("The button is pressed") # Toggle the state of the relay if relay_state == GPIO.LOW: relay_state = GPIO.HIGH else: relay_state = GPIO.LOW # Control relay according to the toggled state GPIO.output(RELAY_PIN, relay_state) except KeyboardInterrupt: # Clean up GPIO on program exit GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 button_toggle_relay.py
  • Press and release the button several times.
  • Check out the change in the relay's state. You will see that the relay's state is changed each time you press the button.

Video Tutorial

※ OUR MESSAGES

  • 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!