Introduction: How to Control a Device Using Raspberry Pi and a Relay - THE BASICS
This is a basic and straight forward tutorial on how to control a device using Raspberry Pi and a Relay, helpful for making IoT Projects
This tutorial is for beginners, it is friendly to follow along even if you have zero knowledge of using Raspberry Pi and it includes how to set up your raspberry pi
Supplies
Raspberry Pi - I'm using model 4B
Micro SD card, with Micro SD card reader
Screen or TV, Keyboard, and Mouse
Relay - I got mine from https://www.digital-loggers.com/
Any device
Step 1: Format Your Micro SD Card
Plug your Micro SD card to the card reader, then plug it to your mac Go to Disk Utility and find your SD card Click on Erase
name it and choose MS-DOS (FAT) for its format, then click Erase
Second: Download NOOBS
Go to https://www.raspberrypi.org/downloads/noobs/ and download NOOBS ZIP file, (DO NOT DOWNLOAD THE LITE VERSION)
Unzip the file, copy and paste it in your Micro SD card
Third: Instal Plug your Micro SD to your Raspberry Pi Then Plug in your mouse and keyboard to the USB port
Step 2: Connect Your Raspberry Pi
Insert the Micro SD card underneath the Raspberry Pi on the left side
Connect your mouse and keyboard to the USB port
Connect your screen to the USB port and Micro USB port
Connect the power cable to USB-C port and plug it to a power supply
(refer to pictures attached)
Step 3: Start Up Your Raspberry Pi
Connect your Raspberry Pi to an outlet and it should turn on automatically
A window will appear to install NOOBS, click on Raspbian Full [Recommended], then hit install
finish setting up your Raspberry Pi, it will take a few minutes
Step 4: Connect Relay to Raspberry Pi
Shut down your Raspberry Pi and unplug it
Plugin the relay
Plug Raspberry Pi to [always ON] outlet in the relay
Plugin your desired device to one of [normally OFF] outlets
Step 5: Connect Jumper Wires
Take the input connector out of the relay
Screw-in jumper wires
Return the input connector to its place
Connect the positive jumper wire to GPIO 17 pin
Connect the negative jumper wire to Ground pin (refer to GPIO picture)
Step 6:
Turn on Raspberry Pi
Go to Raspbian > Programing > Thonny Python IDE
Type your code, you can use the one below:
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) PWR = 17 GPIO.setwarnings(False) GPIO.setup(PWR,GPIO.OUT) GPIO.output(PWR, True) time.sleep(5) GPIO.output(PWR, False) GPIO.cleanup()
Hit [Run]
Your device should turn on for 5 seconds
Note: you can change the duration by changing the number 5 to your preferred time [time.sleep(5)]