In this project I will show how to build an RGB LED console app that can be controlled from the local network or anywhere via the Internet. This allows the user to turn on or off the individual RGB LEDs via a web-browser app. The application will use the Python Flask framework and the SwishPi pHAT together with a Raspberry Pi Zero. The SwishPi pHAT is a modular shield that includes a number of sensor and interfaces such as medium range radio, serial to USB login, non-volatile memory, real time clock and sensor headers.
RGB app.Let's get started building a Flask app to control the RGB led. The easy route is to clone the Git repository link below and run the example by issuing:
sudo python app.py
The pre-requisite to this is having Python Flask installed. By default Flask is not installed so you will have to install it issuing:
sudo pip install flask flask-basicauth flask-lesscss
Below you can see the result of what we are trying to achieve. In this particular instance the blue and red LED's are turned on.
Python uses the RPi. GPIO library for controlling the GPIO (general purpose input/output) peripherals. This library is very versatile since it offers support for configuring the pins in different modes and it also handles interrupts. The module comes pre-installed on recent versions of Raspbian. If the module is not installed the easiest way is to install it by issuing the command:
sudo apt-get -y install python-rpi.gpio
The library uses two configuration schemes. The BCM numbering scheme for the pins follows the SOC pin numbering layout. So in this case, pin 24 of the header is named GPIO18.
RGB SPALet's take a look at the SPA (Single Page App). It's purpose is to turn on or off the RGB LEDs from the client browser side. This allows any device on the network to turn the RGB LEDs on or off.
First, we setup the pins directions. Then, we create individual functions that turn on or off the LEDs. Finally, we create an API by creating one route for the RGB app.
A POST request is used to parse the button Name and Status from the client side. Depending on the button status each RGB is either turned on or off.
@app.route("/RGB" ,methods=['POST'])
def RGB():
if request.method == 'POST':
button = str(request.json['name'])
bstatus = str(request.json['status'])
To beautify the app, JQuery and bootstrap are used. This keeps the amount of Javascript code to a minimum.
The button callbacks have been included, on the html page under the template folder. Every time a button is pushed on the client side a POST request happens, which gets processed from the Flask server.
Below you can see the RGB LED panel with the blue LED turned on.
This app uses the RGB LEDs at full power. A slightly more sophisticated example would make use of PWM to modulate the intensity of each individual LED. That's a project for next time.
Comments