
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:
- Any Raspberry pi (would recommend version 3 or 4)
- Three LEDs and three resistors
- Connecting wires (Female to male if you intend to connect directly to the GPIO pins)
- Optional – Extension bus (male to male connecting wires should be used in this place)
- Text editor, vscode preferably since there is an arm version to run on the pi
Steps to follow:
- 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)
- For this project, we are connecting only 3 LEDs(red, purple and green)
- Create a django project and app(work in a virtual environment)
- 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
- Using you text editor, type the code the below
- 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 settings.py file
- When all is done, run the server and use the link generated by ngrok to access your website from anywhere
views.py ----- 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): red.on() sleep(2) red.off() return render(request, 'home.html') #Handle the purple led def purple_led(request): purple.on() sleep(2) purple.off() return render(request, 'home.html') #Handle the green led def green_led(request): green.on() sleep(2) green.off() return render(request, 'home.html') views.py --- ends home.html ----- begins <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <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> </ul> </body> </html> home.html ----- ends urls.py ----- begins from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name="home"), path('red/', views.red, name="red_led"), path('purple/', views.purple, name="purple_led"), path('green/', views.green, name="green_led"), ] urls.py ----- ends settings.py --- begins ALLOWED_HOSTS = ['site.ngrok.io'] settings.py --- ends