Use a Raspberry PI and a relay to control a lamp

Use a Raspberry PI and a relay to control a lamp

I always wanted to see how could a Raspberry PI could control a lamp and contribute to the IOT and home automation.

For a prof-of-concept (To learn how to use a relay before using in more high voltages), we’re going to need:

  • Raspberry PI
  • Relay (I’m using Sainsmart 2-channel 5v relay – or a clone)
  • batteries to power the LED – separate power for RPi and LED – 4x AA
  • LED
  • 220ohm resistor

This is going to be a three part tutorial:

The relay

A relay is switch operated electrically. They can be really really useful for some projects. It can be connected to a range of microcontrollers . The one I’m going to use is a SRD-05VDC-SL-C with 2 channels.  It can drive great loads, such as 7A/240VAC,10A/125VAC,10A/28VDC.

PIN definitions

This relay has 2 channels.  We can connect there devices in one of two ways:

  • Always on until we activate the channel (light turns off) – (NC – normally close)
  • Always off until we activate the channel (light turns on) – (NO – normally open)

The pinout in the relay:

  • NO – Normally Open (connects when INT1 – if channel 1 – is set to 0v) – active low
  • COM – Common PIN (Source PIN – starts connected to NC and connects to NO when 0v applied)
  • NC – Normally Close (connected – disconnects when INT1 is set to 0v) – active low

The pinout for connection to the Raspberry PI

Relay RPI
VCC 5v
IN2 Control PIN for relay channel 2
IN1 Control PIN for relay channel 1 – PIN 16 – BCM23
GND  Ground


This particular relay will activate when the voltage on the control PIN will be below 2.0v (GND)  . This relay is active low.

Here’s a great article from Make: Magazine on relays ! I recommend you to read it




First, let’s install the necessary libraries

sudo apt-get install python-rpi.gpio

Create the python file to use the relay


import RPi.GPIO as GPIO
import time

relay_pin = 23


        while True:
                #set low
                print ("Setting low - LED ON")
                GPIO.output (relay_pin,GPIO.LOW)
                #set high
                print ("Setting high - LED OFF")
                GPIO.output (relay_pin, GPIO.HIGH)
except KeyboardInterrupt:
        print ("Bye")

To run it:

python (press ctrl+c to interrupt)

Now that it works, let’s create a web interface to control the lamp using our browser (our our smartphone).

We’ll be using Flask for it. Head to part two of the tutorial