How to use a relay with Raspberry Pi

Wire the relay

Program to turn relay on and off

Create python script named relay.py with below code

#!/usr/bin/env python3

import RPi.GPIO as GPIO
import sys

# Define the GPIO pin
RELAY_PIN = 17  # Change this according to your wiring

# Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT)

# Check command-line argument
if len(sys.argv) != 2 or sys.argv[1] not in ['on', 'off']:
    print("Usage: python script.py <on|off>")
    sys.exit(1)

if sys.argv[1] == 'on':
    print("Relay ON")
    GPIO.output(RELAY_PIN, GPIO.LOW)  # Active-low relay: LOW = ON
elif sys.argv[1] == 'off':
    print("Relay OFF")
    GPIO.output(RELAY_PIN, GPIO.HIGH)  # Active-low relay: HIGH = OFF
    GPIO.setup(RELAY_PIN, GPIO.IN)  # Set pin to input mode to keep state

# Do not clean up GPIO to maintain state

Execute the program

chmod +x relay.py
./relay.py on    # on the relay
./relay.py off   # off the relay

Leave a Reply

Your email address will not be published. Required fields are marked *