Often you may wish to control modules with a higher voltage with the Raspberry Pi. For this purpose, relays can be used on the Raspberry Pi. The relay is essentially a switch that is switched by means of a low-voltage pulse. Relay modules generally come in sizes ranging from 1 channel to 16 channels. Relays are widely used on Raspberry Pi projects that involve home automation. For example, switching on and off a light using voice commands.
- Any Raspberry Pi with GPIO pins – 3B/3B+ recommended
- Jumper Wires
- 12v DC Switching Power Supply
- A 12v device to test with, i.e PC fan, motor, LED strip etc
Setting up the Hardware
In the setup in the diagram below, we demonstrate using a 12v PC fan.
Complete the below jumper cabling plan between the Pi, power supply, relay and fan/device you choose to use. Some people may find it easier to follow the image above, rather than the cable map below. They’re identical.
Pin 2 (5v) on Pi <=> VCC on relay
Pin 6 (ground) on Pi <=> GND on relay
Pin 40 (BCM21) on PI <=> IN1 on relay
Negative wire from fan <=> Negative terminal on 12v DC power supply
Positive wire from fan <=> Normally Open (NO) terminal of relay
Positive wire from 12v DC power supply <=> Common (C) terminal of relay (the middle one)
Setting up the Software
By following the above hardware setup exactly, you have chosen BCM21 as the GPIO pin for switching the relay on/off.
We need to ensure the Pi is up to date and has some essential software installed.
sudo apt-get update
sudo apt-get install nano
Create a file called script.py in /home.pi
Paste the below code inside and save the file.
import RPi.GPIO as GPIO import time #GPIO pin number channel = 21 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.OUT) # Turn fan on def motor_on(pin): GPIO.output(pin, GPIO.HIGH) # Turn fan off def motor_off(pin): GPIO.output(pin, GPIO.LOW) if __name__ == '__main__': try: motor_on(channel) time.sleep(2) motor_off(channel) time.sleep(2) GPIO.cleanup() except KeyboardInterrupt: GPIO.cleanup()
Run the script