Python program 5: Interfacing Motor Relay with Raspberry Pi for ON/OFF Control

Objective:

To interface a motor relay with Raspberry Pi and write a Python program to control its ON/OFF operation.


Resources Required:


Theory:

A relay is an electrically operated switch. In this experiment, we are using a single-channel relay module to control a DC motor using the GPIO pin of the Raspberry Pi.

The relay has two sides:

  • Input Side (control side connected to Raspberry Pi)

  • Output Side (switching side connected to the motor and power source)

Relay Indicators:

  • Red LED: Lights up when the relay board is powered.

  • Green LED: Lights up when the relay is activated (ON state).

Switching Logic:

  • If the orange cable is connected to the bottom slot, the motor will be OFF/ON depending on the relay state.

  • If connected to the upper slot, the motor will be ON/OFF depending on the relay state.


Circuit Diagram



Python Code:

Below is the Python program to control the motor ON/OFF operation using a relay module.

import RPi.GPIO as GPIO import time # Suppress warnings and reset GPIO state GPIO.setwarnings(False) GPIO.cleanup() # Set pin numbering to BCM GPIO.setmode(GPIO.BCM) # Define the pin connected to the relay module pin1 = 22 # Set the relay pin as output GPIO.setup(pin1, GPIO.OUT) try: while True: # Turn motor ON GPIO.output(pin1, True) print("Motor ON") time.sleep(5) # Turn motor OFF GPIO.output(pin1, False) print("Motor OFF") time.sleep(5) except KeyboardInterrupt: GPIO.cleanup() print("Program stopped and GPIO cleaned up.") exit()


Result:

  • When the program is executed, the relay switches ON and OFF every 5 seconds.
  • The motor connected through the relay follows the ON/OFF logic as per the GPIO output.
  • The red LED lights up when power is supplied to the relay board.
  • The green LED lights up when the motor is powered (relay activated).

Conclusion:

This experiment demonstrates how a Raspberry Pi can control the ON/OFF operation of a motor using a relay module. The program alternates the GPIO output, which switches the relay and thus controls the motor.

The successful toggling of the motor validates the working of GPIO-controlled relay-based switching.


👉 If you found this helpful, don’t forget to like, follow, comment, and share! 💬🔁 

Let’s keep learning and growing together — team up with me, let’s complete this assignment together! 💻✨

Assignments:

  1. Two-Way Motor Control:
    Write a Python program to control motor direction (clockwise and anticlockwise) using two relay modules.

  2. Soil Moisture Controlled Motor:
    Write a Python program to interface a soil moisture sensor with Raspberry Pi. Based on the moisture level, turn the motor ON/OFF using a relay.

🕒 Check back in the comments tomorrow to see if your solution matches the correct one!


Comments

Popular posts from this blog

Fundamental of python : 1.Python Numbers