Example Code for Raspberry Pi-Control Relay Module

Last revision 2026/01/05

In this part, we will control the Relay module with Python via Pi's GPIO.

Hardware Preparation

Software Preparation

  1. Python 2 Installed.
  2. Setup SSH on Raspberry Pi.

If you didn't install python. Please enter the following commands below into LX Terminal via SSH.

root@raspberrypi:/home/pi# sudo apt-get update
root@raspberrypi:/home/pi# sudo apt-get install python-rpi.gpio

Wiring Diagram

DFR0311_v1_RelayCD

Operating Steps

  1. Plug the Pi Meet Arduino shield to the Raspberry Pi, Which connected with the power and Ethernet.

  2. Connect the Relay module(or LED module) to your Pi as the hardware connection shown.

  3. Login in your Pi by Putty.

    DFR0311_Login_Page

  4. Create a Python example code using nano.

    root@raspberrypi:/home/pi# nano blink.py
    
    
    import RPi.GPIO as GPIO
    import time
    
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(4,GPIO.OUT)
    
    while True:
        GPIO.output(4,GPIO.HIGH)
        time.sleep(1)
        GPIO.output(4,GPIO.LOW)
        time.sleep(1)
    
  5. Run the python sample by the command below.And Check the effect. PS: The module is connected to the GPIO 4 matching the software configuration.

root@raspberrypi:/home/pi# python blink.py

Result

Result_Switching_Relay

Note: the switching of the relay module create the noise.

Was this article helpful?

TOP