Print Friendly, PDF & Email

Difficulty level: Beginner

Approx reading time:

Components Required:

1. Raspberry Pi 3 model B

2. MicroSD card 8 or 16 GB (Class 4 and above) with Raspbian

3. Windows PC / Linux PC (Tested on Windows 10, Ubuntu 14.04 LTS)

4. Ethernet cable (Category 5 – also called Cat 5)

5. Micro USB cable

6. Breadboard

7. 5 mm LED (your favourite colour)

8. 220 Ohms Resistor (colour code: Red, Red, Brown)

9. Push Button

10. Jumper Wires (Male to Female – Red for Power, Black for Ground, Yellow for GPIO pins Male to Male)

11. 5V 1 Channel Relay Module

Way to go ->

1. Login to your Pi using PuTTy or your Ubuntu terminal.

2. Login to your Pi GUI using VNC server (Linux / Windows).

3. In Python 3 (IDLE), create a new file.

4. The name could be: relayButton.py.

5. In the file relayButton.py, write the following code with comments (line starting with “#”) for clear understanding and save (press Cntrl + S on your PC keyboard) the file.

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)

buttonCount = 3  # Number of times you can switch on the Relay
count = 0
relayPin = 15
buttonPin = 40

# 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 < buttonCount:
        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()

6. Run the code by clicking on Run -> Run Module in the menu bar.

Hardware Connections ->

1. Raspberry Pi 3 GPIO Header.

pi3_gpio

2. Signal or IP Pin of the Relay module connected to Pin 15 – BOARD notation (GPIO22 – BCM notation). Push Button connected to Pin 40 – BOARD notation (GPIO21 – BCM notation).

GPIORelay_schem

GPIORelay_bb

Read full tutorial at

Rating widget: