Samiad Designs

keep it simple

Raspberry Pi Relay

21st July 2014

I purchased this relay from eBay intending to use it with a Raspberry Pi. I connected this up to 5V, GND and Pin 12 on the Pi and switched pin 12 on and off but nothing happened.

I checked the signal pin with an oscilloscope and it was alternating between 3.3V and 0V expected but the relay (and the LED on the relay board) would not switch.

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)


while True:
    GPIO.setup(12, GPIO.OUT)
    time.sleep(1)
    GPIO.output(12, GPIO.LOW)
    time.sleep(1)

Then I pulled out the signal wire and the relay switched! So the Raspberry Pi has no problems providing the current to drive the relay.

Unfortunately the 3.3V signal from the GPIO pin is not high enough to switch the transistor arrangement on the relay board. However as it switches when we disconnect the signal wire there must be a pull-up resistor on the relay board pulling the signal to 5V.

We can get the Raspberry Pi to simulate the disconnection of the pin by reconfiguring the GPIO pin as a floating input (no pull up / down).

The following code successfully switches the relay on and off:

#!/usr/bin/env python

import optparse
import RPi.GPIO as GPIO


def main():
    parser = optparse.OptionParser()
    parser.add_option("--on", action="store_true", default=False)
    parser.add_option("--off", action="store_true", default=False)

    options, args = parser.parse_args()
    assert not (options.on and options.off)

    GPIO.setmode(GPIO.BOARD)

    if options.on:
        GPIO.setup(12, GPIO.OUT)
        GPIO.output(12, GPIO.LOW)

    if options.off:
        GPIO.setup(12, GPIO.IN)


if __name__ == "__main__":
    main()