Tutorial 21: Control a Relay with GPIO

The Raspberry Pi Foundation had released two cameras designed to plug directly into the Raspberry Pi board: the regular Pi Camera and the Pi NOIR Camera. In the previous tutorial I showed you how to connect the camera and take a picture with it using Bash commands. In this tutorial I show you how to take pictures using Python 3!

This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson.


DIFFICULTY
MEDIUM
LINUX UNDERSTANDING
LITTLE
CIRCUITRY FAMILIARITY
SOME
PYTHON PROGRAMMING
SOME
ABOUT
0
MINUTES
  • Limitations of using a standalone relay in your design.
  • How to build a circuit to operate 5VDC devices from the GPIO header
  • How to turn on a light bulb using a relay controlled from the Raspberry Pi
You can copy / paste the code below if you’re having issues with typos or want a shortcut. However I recommend that you follow along in the tutorial to understand what is going on!


import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

blinkCount = 3
count = 0
relayPin = 22
buttonPin = 5

# Setup the pin the LED is connected to
GPIO.setup(relayPin, GPIO.OUT)
# Setup the button
GPIO.setup(buttonPin, GPIO.IN, pull_up_down = GPIO.PUD_UP)

buttonPress = True
relayState = False

try:
    while count < blinkCount:
        print("Come on man, press the button!")
        buttonPress = GPIO.input(buttonPin)
        if buttonPress == False and relayState == False:
            GPIO.output(relayPin, True)
            print("relay ON")
            relayState = True
            sleep(0.5)
        elif buttonPress == False and relayState == True:
            GPIO.output(relayPin, False)
            print("relay OFF")
            relayState = False
            count += 1
            sleep(0.5)
        sleep(0.1)
finally:
    # Reset the GPIO Pins to a safe state
    GPIO.output(relayPin, False)
    GPIO.cleanup()




#>
See below for some supporting documentation about the parts used in this tutorial:

Part 1: Circuit Building & Programming

Part 2: Safety Note