How to Use a Relay Module on Raspberry Pi

Relay modules allow Raspberry Pi users to control high-voltage, high-current devices using low-voltage signals from the Raspberry Pi GPIO pins. Common applications for relay modules include home automation, industrial control, and robotics. This article will guide you through the process of connecting and using a relay module with your Raspberry Pi, including hardware setup, software configuration, and a sample application.
1. Hardware Setup: Connecting a Relay Module to Raspberry Pi
To use a relay module with your Raspberry Pi, follow these steps for the hardware setup:
a. Ensure both the Raspberry Pi and the devices you want to control are powered off before you start the connection.
b. Identify the relay module's pins: VCC, GND, IN (input), and NO/NC/COM (output).
c. Connect the relay module to the Raspberry Pi:
- Connect the VCC pin on the relay module to a 5V power source on Raspberry Pi.
- Connect the GND pin on the relay module to a GND pin on the Raspberry Pi.
- Connect the IN pin on the relay module to a GPIO pin on the Raspberry Pi, e.g., GPIO 18.
d. Connect the controlled device to the relay module's output (NO/NC/COM) as required by the specific application. Please consult an electrician when working with high-voltage, high-current systems to ensure safe wiring.
2. Software Configuration: Controlling the Relay Module
To control the relay module using the Raspberry Pi GPIO pins, follow these steps for the software configuration:
a. Log in to your Raspberry Pi through SSH or the GUI and open a terminal window.
b. Update and upgrade your Raspberry Pi's package list and installed software:
sudo apt-get update
sudo apt-get upgrade
c. Install the required software dependencies:
sudo apt-get install python3-gpiozero
3. Sample Application
This example application demonstrates how to control an LED connected to the relay module using a Python script.
a. Create a new Python file:
b. Insert the following code into the `` file:
from gpiozero import OutputDevice
from time import sleep
# Replace "18" with the GPIO pin number you used for the relay module's IN pin
relay = OutputDevice(18)
while True:
c. Save the file and exit the nano text editor by pressing `Ctrl+X`, then `Y`, and finally `Enter`.
d. Run the Python script to control the relay module:
The relay module will switch the LED on and off every second.
Using a relay module with a Raspberry Pi allows users to control high-voltage, high-current devices easily and safely. By following the hardware setup and software configuration steps provided in this guide, you can start using a relay module in various projects and applications to enhance Raspberry Pi's capabilities in home automation, robotics, and industrial control systems. Always ensure you seek assistance from an expert when working with high voltage and high current devices to guarantee safe and reliable operation.