Control LEDs remotely over the web

Reading Time: 2 minutes

In this article, we are going to create a django project that will enable website visitors from anywhere in the world control LEDs.

What you need to get setup:

  1. Any Raspberry pi (would recommend version 3 or 4)
  2. Three LEDs and three resistors
  3. Connecting wires (Female to male if you intend to connect directly to the GPIO pins)
  4. Optional – Extension bus (male to male connecting wires should be used in this place)
  5. Text editor, vscode preferably since there is an arm version to run on the pi

Steps to follow:

  1. Connect the circuit by choosing preferable GPIO pins for your leds(as a precaution, test whether the LEDs are working properly by connecting them to either the 3 or 5 Volts GPIO pins before building the final circuit)
  2. For this project, we are connecting only 3 LEDs(red, purple and green)
  3. Create a django project and app(work in a virtual environment)
  4. Using pip, also install the gpiozero  package to enable us use the GPIO pins in our project. Note that if you are not working in a virtual environment then gpiozero is already installed system wide
  5. Using you text editor, type the code the below
  6. Install ngrok to help with secure port forwarding and also will generate a custom link that you will insert in the ALLOWED_HOSTS configuration in our file
  7. When all is done, run the server and use the link generated by ngrok to access your website from anywhere ----- begins

#to help us render html httprespnses
from django.shortcuts import render 

#to be used in creating led objects 
from gpiozero import LED

#for pausing our app
from time import sleep 

#objects to represent leds
red = LED(18) 
purple = LED(21)
red = LED(18)

#home view to render homepage
def home(request):
    return render(request, 'home.html')

#Handle the red led
def red_led(request):
    return render(request, 'home.html')

#Handle the purple led
def purple_led(request):
    return render(request, 'home.html')

#Handle the green led
def green_led(request):
    return render(request, 'home.html') --- ends

home.html ----- begins
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <li><a href="{% url 'red_led' %}">RED LIGHT</a></li>
        <li><a href="{% url 'purple_led' %}">PURPLE LIGHT</a></li>
        <li><a href="{% url 'green_led' %}">GREEN LIGHT</a></li>

home.html ----- ends  ----- begins
from django.urls import path
from . import views

urlpatterns = [
    path('home/', views.home, name="home"),
    path('red/',, name="red_led"),
    path('purple/', views.purple, name="purple_led"),
    path('green/',, name="green_led"),
]  ----- ends --- begins

ALLOWED_HOSTS = [''] --- ends

Leave a Reply

Your email address will not be published. Required fields are marked *