Ever asked how to control your home light system wirelessly over the Internet from any place in the world?! in this step-by-step tutorial we will learn how to do that.
Used Components
Used Software
- Autodesk Eaglecad (Optional).
- Firebase Database.
- Python Editor (Any Editor will work fine).
Introduction
Today, we will learn how to control any RGB LED Strip ambient light wirelessly over Wifi using a custom-built Andoird application connected with the awesome Raspberry Pi board through the Firebase database.
To build this project we need to deal with some stuff like how to build an android mobile app, how to build a firebase database server, how to connect the raspberry pi and the android app together through firebase, how to take different actions based on the incoming data, some power management, electronics Wiring, …
But yo hold on! Don’t worry we will cover all these topics in detail in today’s tutorial. So, bear with me and I promise it will be worth it.
Project Overview/Features
Simply, today we will build a smart device that allows the user to control his/her home ambient lighting system wirelessly over Wifi using any android smartphone, our project is divided into four main parts
- Android mobile application.
the mobile app is the control panel which the user will interact with to send his/her commands to the lighting system. - Database.
is the global server which acts as a postman who takes mails from one person to deliver it to someone else. Firebase database will receive some data from the mobile app and send it to the raspberry pi to take some actions like changing the LED strip light intensity or light color, and other many stuff. - Electronic and control circuit.
the control circuit will be based on the raspberry pi board which running a python script reading the incoming data from the firebase database and according to these data will take some different actions. - Power management.
it’s the most crucial part, it’s the part which responsible for providing the device with the necessary power to operate properly without damages.
How does the project work?
Simply, the mobile app and the raspberry pi board are connected to the same firebase database. this database saves the data which comes from the mobile app and syncs it with the raspberry pi board in milliseconds, according to these data the raspberry pi board will take some specific actions like turning on the light, changing its brightness, and so on.
Control Three LEDs brightness using GPIO PWM
To control the RGB LED Strip light brightness you need to be familiar with the PWM technique in the raspberry pi world and how to use it. So, let’s start by a simple one and start controlling some normal 5mm LEDs brightness to get familiar with the PWM technique. As I promised you at the beginning of the tutorial, we will start it from scratch to understand every part of the project.
PWM stands for “Pulse Width Modulation” which is used to generate analog values using a digital technique. PWM is usually used to control LEDs brightness, DC Motor speed control, Servo motor rotation angle and that happens by outputting some variable voltage level.
But as we all know that the RPi and any computer is entirely digital system. But at the same time, we need to generate some analog signals from it. So, we need to find a way to convert that digital output signal to an analog output signal. Here comes the PWM technique!
Most of the devices around us are responding relatively in the world of electronics slowly to the signal that they are getting. So, let’s take a normal DC motor as an example, let’s say that we need to run this DC motor at its half speed. So, we need to give it half of its voltage to run at half of its speed. Basically, we are only capable of giving a 3.3V(logic 1) or 0V (logic 0) we can’t give value in between because it’s a digital system as we said before. But here comes the PWM role to modulate the signal up(3.3V) for half the time and down(0V) for half the time with a square wave which is called the duty cycle. that process happens very very rapidly and the motor can’t respond instantaneously to the change of the voltage so it takes some time to accelerate and decelerate which results, the motor averaging the voltage to something near 1.6V and will run at half of its speed. And you can change the motor speed by changing the duty cycle value.
If we take a normal LED as an example we will do the same previous process applying PWM, but because the LED is a simple diode it responds fairly quickly (faster than the motor) to the change of the signal, so your eyes as a human will make the averaging thing. As a result, you will see the LED changing its brightness.
- Period: It’s the sum of the HIGH(3.3V) time and the LOW(0V) time.
- Duty Cycle: Its the percentage of time where the signal was HIGH(3.3V) during the time of period.
Enough Theory! Let’s make some stuff. Let’s take a look at the wiring diagram.
Wiring Diagram
The wiring diagram is very simple, connect each LED on a different PWM pin
Red LED | GPIO 12(PWM0) |
Green LED | GPIO 18(PWM0) |
Blue LED | GPIO 19(PWM1) |
The raspberry pi has two different schemes in numbering its GPIO pins. you can use either pin numbers(BOARD) or the Broadcom GPIO pin numbers(BCM). You can only use one numbering scheme in each program.
GPIO Board: Referring to the pin by its number of the plug, the pin number on the physical board which printed on it. Example: PIN#1, PIN#2, …..
GPIO BCM: Referring to the pin by its “Broadcom SOC Channel” number, these are the numbers after the GPIO word. Example: GPIO12, GPIO19, ….
Neither way is wrong, both ways are good and work well without any differences. You have to pick the one which you feel comfortable more with.
The Raspberry Pi 3 Model B has two PWM channels (PWM0, PWM1) each channel has two different GPIO PWM pins available for use.
GPIO BCM | GPIO BOARD | PWM channel |
GPIO12 | Pin#32 | PWM0 |
GPIO18 | Pin#12 | PWM0 |
GPIO19 | Pin#35 | PWM1 |
GPIO13 | pin#33 | PWM1 |
These three PWM pins GPIO12, GPIO 13, GPIO19 are used by the A/V output audio jack. So, if you don’t need to use the A/V audio jack in your project, these three GPIO PWM pins will be free and available to get used. But you can’t use the A/V output Audio jack and these PWM pins at the same time. In today’s project, we don’t need to use the A/V audio jack so all the PWM pins will be free and available for us to use.
Code
import RPi.GPIO as GPIO #import the raspberry pi GPIO library, to be able to use them. from time import sleep #import the sleep library, which responsible to do the timing stuff. redLED = 18 #red LED connected on PWM pin GPIO18 blueLED = 12 #blue LED connected on PWM pin GPIO12 greenLED = 19 #green LED connected on PWM pin GPIO19 GPIO.setwarnings(False) #disable warnings GPIO.setmode(GPIO.BCM) #set pin numbering system to the (Broadcom chip channel numbering). GPIO.setup(redLED,GPIO.OUT) #set the red LED pin(GPIO18) to an output pin. GPIO.setup(blueLED,GPIO.OUT) #set the blue LED pin(GPIO12) to an output pin. GPIO.setup(greenLED,GPIO.OUT) #set the green LED pin(GPIO19) to an output pin. red_pwm = GPIO.PWM(redLED,1000) #create PWM instance with 1000Hz frequency. blue_pwm = GPIO.PWM(blueLED,1000) #create PWM instance with 1000Hz frequency. green_pwm = GPIO.PWM(greenLED,1000) #create PWM instance with 1000Hz frequency. red_pwm.start(0) #start red LED PWM pin with 0% initial Duty Cycle (OFF). blue_pwm.start(0) #start blue LED PWM pin with 0% initial Duty Cycle (OFF). green_pwm.start(0) #start green LED PWM pin with 0% initial Duty Cycle (OFF). print("AH Shit! Here we go again! Press CTRL+C to exit") #Take Care, Meme LORD. try: while True: #the start of the actual program. for duty in range(0,101,1): #imolement a "for loop" responsible for increasing the red LED light brightness. red_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100. sleep(0.01) #wait 0.01 sec. between each iteration. sleep(0.5) #wait 0.5 sec. after the "for loop" is done. for duty in range(100,-1,-1): #implement a "for loop" responsible for decreasing the red LED light brightness. red_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 100-0. sleep(0.01) #wait 0.01 sec. between each iteration. sleep(0.5) #wait 0.5 sec. after the "for loop" is done. for duty in range (0, 101, 1): #repeat the previous logic but this time with the blue LED. blue_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) for duty in range (100, -1, -1): #repeat the previous logic but this time with the blue LED. blue_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) for duty in range(0,101,1): #repeat the previous logic but this time with the green LED. green_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) for duty in range(100,-1,-1): #repeat the previous logic but this time with the green LED. green_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly: red_pwm.stop() # stop red PWM blue_pwm.stop() # stop blue PWM green_pwm.stop() # stop green PWM GPIO.cleanup() # cleanup all GPIO
Code Explanation
The code is pretty simple and straightforward, first, we need to import two important modules to allow us to use the raspberry pi GPIO pins. Also, import the time module that will make the timing work for us. without importing this module you will not be able to use the sleep()
method.
import RPi.GPIO as GPIO from time import sleep
then we need to initialize three variables called redLED
, blueLED
, greenLED
referring to the three PWM pins that we will use to control our LEDs. Yeah as you noticed we are using the GPIO BCM numbering scheme.
redLED = 18 blueLED = 12 greenLED = 19
Then we need to set the numbering scheme of raspberry pi pins to “GPIO BCM”, then set all the three pins as output pins.
GPIO.setmode(GPIO.BCM) GPIO.setup(redLED,GPIO.OUT) GPIO.setup(blueLED,GPIO.OUT) GPIO.setup(greenLED,GPIO.OUT)
create three PWM instances(instance for each pin) red_pwm
, blue_pwm
, green_pwm
with 1000Hz frequency that will help us to generate the PWM signal. After that, we need to set the initial state of these pins to 0% duty cycle which means that the three pins will be OFF at the beginning of the program.
red_pwm = GPIO.PWM(redLED,1000) blue_pwm = GPIO.PWM(blueLED,1000) green_pwm = GPIO.PWM(greenLED,1000) red_pwm.start(0) blue_pwm.start(0) green_pwm.start(0)
Here is the fun part! inside the while loop
we write the set of commands(program) that we need to keep executing forever until we force-stop it.
inside the while loop
implement a “for loop” it’s initial value 0, at every iteration it will increment by 1 until it reaches 100. This for loop
responsible for increasing the red LED light brightness.
while True: for duty in range(0,101,1): red_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5)
The second for loop
it’s initial value 100, at every iteration will decrease by 1 until it reaches 0. this for loop
is responsible for decreasing the red LED light brightness.
for duty in range(100,-1,-1): red_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5)
then repeat the previous logic with the remaining two LEDs. After finishing your code, close and save it, run it by writing python fileName.py
in the terminal.
After running it, It’s expected to see this sentence got printed on the terminal AH Shit! Here we go again! Press CTRL+C to exit
then the three LEDs light brightness will start to increase and decrease.
I will assume that you did that and it’s working fine with you. VOILA! Officially you are now promoted to the next level. Let’s make it more interesting and control the beefy RGB LED Strip.
Control RGB LED Strip Lighting
Actually, controlling an RGB LED it’s not very different from controlling a normal LED. RGB LED means red, green and blue LED which combines all these three LEDs in one combo. with these three different colors, you can produce almost any color by mixing them with different intensities. To adjust LED intensity we use the PWM technique.
For example, to generate a pure red color, we need to set the red LED to the highest intensity and the green, blue to the lowest intensity. To generate a white color we have to set all the three LEDs to the highest intensity. And By adjusting the intensity of each LED you will generate a new color.
RGB LED Strip pinout
There are two main types of RGB LED strips. The common anode, and the common cathode. In the common anode RGB LED strip, the three LEDs share the same positive lead (Anode), and in the common cathode RGB LED strip, the three LEDs share the same negative lead (Cathode). As a result of that, the RGB LED strip has four leads, one for each LED (red, green, blue) and one common anode or common cathode.
The RGB LED strip that we will use today is Common Anode.
Power Management
Before we connect the RGB LED strip with raspberry pi we need to ask ourselves, Does the raspberry pi board able to provide the beefy RGB LED strip with the needed power to operate properly? The short answer is, of course not.
If you are a math nerd let’s do some calculations. we need to know how much current our RGB LED Strip is going to draw. each RGB cell contains three LEDs(red, green, blue) each LED in the cell draws 20mA at full intensity. So, each RGB cell will draw a current of total 60mA at full intensity, the RGB LED Strip that we are using today contains 20 cells/one meter, and we have a 4-meter long strip. So, Which means that the total drawn current at maximum intensity is equal to:
4(Meter)*20(cell/meter)*60(mA) = 4800MA.
this amount of drawn current will vary depending on the intensity of the LED brightness that you are working with, but we made the calculations at the highest values to work freely and be on the safe side. Now we need a power source that can provide us with those 4.8A at 12V.
The best option I found for that job, is a power supply/converter that converts an AC power to DC, the power supply/converter that we will use today offers 5A at 12VDC which is exactly what we need.
The Power Supply Connections
A power supply is an electrical device that converts one type of electrical type to another. In our case, we will convert a 220VAC to 12VDC.
From the left side, the first three terminals are the input from the AC power source:
- L: life.
- N: neutral.
- GND: earth.
The last four terminals are the 12VDC output, the first two terminals are the GND and the second two terminals are positive.
- V-: GND.
- V+: positive.
And we connect them as follow:
- Brown wire (AC Power source): L (Power supply).
- Blue wire (AC Power source): N (Power supply).
- Green wire (AC Power source): Earth (Power supply).
And the red, and the black wire are the 12VDC output:
- Red Wire: 12VDC Output (V+).
- Black Wire: GND Output (V-).
Wiring Diagram
As we stated before, the RGB LED strip needs 4.8A at 12VDC to operate properly. But at the same time, the Raspberry pi board can’t provide all that power to the RGB LED strip. So, we need a component that can take orders from the Raspberry pi board but provide power from the external 12VDC power supply.
Here comes the TIP122 Darlington transistor, this transistor can drive high power loads by using a small amount of current and voltage.
The TIP122 transistor can handle current up to 5A(Continous) and 8A(Peak) which satisfies our needs.
TIP122 Transistor Pinout
TIP122 Transistor acts like a switch that can drive loads with higher electrical requirements, so by a small amount of current and voltage can drive a high power load, at this example we gonna use the TIP122 which completes the LED strip circuit with the 12-volt power supply, the TIP122 has three legs(base, collector, emitter). The collector will get connected to the load(LED strip), and the emitter will get connected to the ground. And by a small amount of current on the base pin, will close the circuit between the collector and the emitter.
Make it More Professional
What about transferring our breadboard circuit to a professional printed circuit board (PCB) to make our project more rigid and solid.
Raspberry Pi HAT files (PCB)
I designed the project circuit using Autodesk Eagle software. all the PCB files are open-source you can access it from that link. We love open source 😉
You can order your own PCB From PCBWay company these guys have a very good reputation in this field and they ship to more than 170 countries around the world with reasonable prices. all you have to do is to open the project PCB files link and click “Add to cart”. That’s it!
This PCB can get mounted over the Raspberry pi board easily as a normal raspberry pi HAT, it will organize your wiring and will make your project easier to debug.
With that slide switch, you can turn on and off the RGB LED Strip power.
Raspberry Pi Enclosure
I designed a laser cutting enclosure using Autodesk fusion 360, feel free to download the DXF files from that link.
Code
#We will use the same previous Code without any changes.
Code Explanation
The same previous explanation since we are using the same code with the same logic.
After finishing the wiring and your code, close and save it, Run your program by writing python fileName.py
in your terminal. Like the last example, After running your program, It’s expected to see this sentence got printed on the terminal AH Shit! Here we go again! Press CTRL+C to exit
then the three LEDs light brightness will start to increase and decrease.
After getting sure that everything is working as expected, let’s level it up and build our firebase database.
Building The Firebase Database
The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. If you want to know more check out this link.
As we stated before, the realtime database will receive some data from the mobile app based on the user interaction and will sync it with the raspberry pi in milliseconds. So, to be able to use firebase you need to sign in using your normal Gmail account. then go to your project console to create a new project.
First things first, you need to create a new project in your console.
Then, give a name to your project
We don’t need to set up google analytics now
After creating your project successfully, your project overview page should look something like this. From the left menu, We need to select “Database”
We will choose “Realtime database” and click the “Create Database” button
After that, select “Test Mode” and click “Enable”
Now, your Realtime database should look something like this.
After building the Realtime Database, we need to build the mobile app that will send the data to the firebase database.
Building The Android Mobile APP
Now we need to build the mobile app that the user will use to control the RGB LED Strip from, we used the amazing tool the “MIT APP Inventor” to build it. It’s fast and very easy to use.
App inventor lets you develop android mobile applications using a web browser and a physical mobile phone or just the emulator, the MIT app inventor saves your projects in their clouds to keep tracking your work
First, you need to go to the MIT app inventor official website and login with your Gmail account, then press on the “create apps” button, then start building your mobile app. Easy HA!
To build your mobile app using the app inventor tool, you should deal with two main parts
- The design of the app.
- The programming of the app.
The App Design
The mobile application consists of Six buttons to control the lighting mode(Mode One, Mode Two, …), three sliders to control each LED color lighting intensity, and a button named “power button” to control the state of the LEDs(turning it ON or OFF). The most important part here is to add the “firebaseDB” client components to the app to allow us sending data to our firebase database project that we created before.
After adding the “FirebaseDB” component to the app, we need to put our created Firebase database URL to the mobile application “FirebaseDB” component to specify where does the data will get saved, the Firebase database URL can be found here.
The Programming Of The App
After designing the interface of our app we need to give it life, adding some functionality to each button and slider.
Let’s take the “Mode One” button as an example to see how the logic works. When the user clicks on the “Mode One” button it will send the value “mode1” with the tag “lightMode” to the firebase database project that we created before. and if we opened the firebase database dashboard page we will see that new entry got added to our database. Congrats!
But, when the user clicks the “Mode Two” button the “lightMode” tag value will get updated to the new value which in this case will be “mode2”.
The same logic applies to the remaining buttons, when the user clicks on a button, a specific piece of data will get sent to the database depending on what button the user clicked.
Building the app APK file
download the following .aia file and import it to your “MIT app inventor” account projects dashboard, it will open up the project source, don’t forget to update the “FirebaseURL” to your firebase project database URL.
You can download the .aia source file from that link.
Then build the app APK file and download it to your computer, then send the APK file to your mobile and install it.
Programming The Raspberry Pi
After building the mobile app and sending data successfully from it to the database, the raspberry pi will read that data from the “firebase database” and according to the read data, it will take different actions like changing the lighting mode or increasing the brightness and so on.
Installing The Pyrebase Module
Before we start writing any code, we need to install the “Pyrebase” python module on the raspberry pi board to allow us to communicate with the “Firebase Database” servers. Because by default the “Firebase” doesn’t support the “Python Programming Language” So, some cool guys wrote a python module to allow the python developers to use “Firebase” easily. If you are a Python NERD you can check out the module documentation on their Github page.
We will use “pip” to install the “Pyrebase” module. So, check to see if you currently have pip installed by running the command in the terminal.
pip --version
If it is not currently installed, you can install pip by running the following command
curl https://bootstrap.pypa.io/get-pip.py | python
After getting sure that we have “pip” on our raspberry pi board, we will start installing “Pyrebase” by running this command, and don’t worry if it takes some time.
sudo pip3 install Pyrebase
After finishing installing the “Pyrebase” module, we are now ready to write the final python script that will read data from the “Firebase database” to take some different actions according to that data.
Code
#OK! #Author: Ahmed Ibrahim #Date: 2/10/2019 #Website: makesomestuff.org import RPi.GPIO as GPIO #import the RPi.GPIO module to allow us use the board GPIO pins. import pyrebase #import the pyrebase module which allows us to communicate with the firebase servers. from time import sleep #import the time modulde to allow us do the delay stuff. config = { #define a dictionary named config with several key-value pairs that configure the connection to the database. "apiKey": "ENTER YOUR API KEY", "authDomain": "ENTER YOUR AUTH DOMAIN URL", "databaseURL": "ENTER YOUR DATABASE URL", "storageBucket": "ENTER YOUR STORAGE BUGET URL" } firebase = pyrebase.initialize_app(config) #initialize the communication with the "firebase" servers using the previous config data. redLED = 12 #the "redLED" variable refers to the GPIO pin 12 which the red LED is connected on. blueLED = 19 #the "blueLED" variable refers to the GPIO pin 19 which the blue LED is connected on. greenLED = 18 #the "greenLED" variable refers to the GPIO pin 18 which the green LED is connected on. GPIO.setmode(GPIO.BCM) #Set the GPIO Scheme numbering system to the BCM mode. GPIO.setwarnings(False) #disable warnings GPIO.setup(redLED,GPIO.OUT) #set the "redLED" variable pin (12) as an output pin. GPIO.setup(blueLED,GPIO.OUT) #set the "blueLED" variable pin (19) as an output pin. GPIO.setup(greenLED,GPIO.OUT) #set the "greenLED" variable pin (18) as an output pin. red_pwm = GPIO.PWM(redLED,1000) #create PWM instance named "red_pwm" with frequency 1000. blue_pwm = GPIO.PWM(blueLED,1000) #create PWM instance named "blue_pwm" with frequency 1000. green_pwm = GPIO.PWM(greenLED,1000) #create PWM instance named "green_pwm" with frequency 1000. red_pwm.start(0) #start the program with 0% duty cycle (red LED will be OFF). blue_pwm.start(0) #start the program with 0% duty cycle (blue LED will be OFF). green_pwm.start(0) #start the program with 0% duty cycle (green LED will be OFF). print("AH Shit! Here we go again! Press CTRL+C to exit") #print "AH Shit! Here we go again! Press CTRL+C to exit" at the beginning of the program. # function name: mode6 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode6 (redIntensity, greenIntensity, blueIntensity): for duty in range (0, redIntensity, 1): red_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.3) for duty in range (redIntensity - 1, -1, -1): red_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.3) for duty in range (0, blueIntensity, 1): blue_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.3) for duty in range (blueIntensity - 1, -1, -1): blue_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.3) for duty in range (0, greenIntensity, 1): green_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100. sleep(0.01) sleep(0.3) for duty in range (greenIntensity - 1, -1 ,-1): green_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100 sleep(0.01) sleep(0.3) # function name: mode5 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode5(redIntensity, greenIntensity, blueIntensity): for duty in range (0, redIntensity, 1): red_pwm.ChangeDutyCycle(duty) sleep(0.001) sleep(0.3) for duty in range (redIntensity - 1, -1, -1): red_pwm.ChangeDutyCycle(duty) sleep(0.001) sleep(0.3) for duty in range (0, blueIntensity, 1): blue_pwm.ChangeDutyCycle(duty) sleep(0.001) sleep(0.3) for duty in range (blueIntensity - 1 , -1, -1): blue_pwm.ChangeDutyCycle(duty) sleep(0.001) sleep(0.3) for duty in range (0, greenIntensity, 1): green_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100. sleep(0.001) sleep(0.3) for duty in range (greenIntensity - 1 , -1, -1): green_pwm.ChangeDutyCycle(duty) #provide duty cycle in the range 0-100 sleep(0.001) sleep(0.3) # function name: mode4 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode4(redIntensity, greenIntensity, blueIntensity): for duty in range (0, redIntensity, 1): red_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) green_pwm.ChangeDutyCycle(0) sleep(0.2) green_pwm.ChangeDutyCycle(greenIntensity - 1) for duty in range (0, blueIntensity, 1): blue_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) blue_pwm.ChangeDutyCycle(0) sleep(0.2) blue_pwm.ChangeDutyCycle(blueIntensity - 1) for duty in range (0,greenIntensity,1): green_pwm.ChangeDutyCycle(duty) sleep(0.01) sleep(0.5) red_pwm.ChangeDutyCycle(0) sleep(0.2) red_pwm.ChangeDutyCycle(redIntensity - 1) red_pwm.ChangeDutyCycle(0) green_pwm.ChangeDutyCycle(0) blue_pwm.ChangeDutyCycle(0) # function name: mode3 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode3(redIntensity, greenIntensity, blueIntensity): red_pwm.ChangeDutyCycle(0) green_pwm.ChangeDutyCycle(0) blue_pwm.ChangeDutyCycle(0) red_pwm.ChangeDutyCycle(redIntensity - 1) blue_pwm.ChangeDutyCycle(blueIntensity - 1) green_pwm.ChangeDutyCycle(greenIntensity - 1) # function name: mode2 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode2(redIntensity, greenIntensity, blueIntensity): red_pwm.ChangeDutyCycle(0) green_pwm.ChangeDutyCycle(0) blue_pwm.ChangeDutyCycle(0) blue_pwm.ChangeDutyCycle(blueIntensity - 1) sleep(0.1) blue_pwm.ChangeDutyCycle(0) sleep(0.1) green_pwm.ChangeDutyCycle(greenIntensity - 1) sleep(0.1) green_pwm.ChangeDutyCycle(0) sleep(0.1) red_pwm.ChangeDutyCycle(redIntensity - 1) sleep(0.1) red_pwm.ChangeDutyCycle(0) sleep(0.1) # function name: mode1 # arguments: # redIntensity: the brightness intensity of the red LED. # greenIntensity: the brightness intensity of the green LED. # blueIntensity: the brightness intensity of the blue LED. # return: this funtion return nothing. # this function is responsible for the pattern of the lighting mode. Feel free to change the lighting pattern as you want. def mode1(redIntensity, greenIntensity, blueIntensity): red_pwm.ChangeDutyCycle(redIntensity - 1) sleep(0.02) red_pwm.ChangeDutyCycle(0) sleep(0.02) red_pwm.ChangeDutyCycle(redIntensity - 1) sleep(0.02) red_pwm.ChangeDutyCycle(0) sleep(0.02) green_pwm.ChangeDutyCycle(greenIntensity - 1) sleep(0.02) green_pwm.ChangeDutyCycle(0) sleep(0.02) green_pwm.ChangeDutyCycle(greenIntensity - 1) sleep(0.02) green_pwm.ChangeDutyCycle(0) sleep(0.02) blue_pwm.ChangeDutyCycle(blueIntensity - 1) sleep(0.02) blue_pwm.ChangeDutyCycle(0) sleep(0.02) blue_pwm.ChangeDutyCycle(blueIntensity - 1) sleep(0.02) blue_pwm.ChangeDutyCycle(0) sleep(0.02) try: while True: #the beginning of the main program. database = firebase.database() #take an instance from the firebase database which is pointing to the root directory of your database. RGBControlBucket = database.child("RGBControl") #get the child "RGBControl" path in your database and store it inside the "RGBControlBucket" variable. powerState = RGBControlBucket.child("powerState").get().val() #read the power state value from the tag "powerState" which is a node inside the database. # print("power state is: " + str(powerState)) # if the "powerState" variable value is equal to "true" if "true" in powerState.lower(): database = firebase.database() #take an instance from the firebase database which is pointing to the root directory of your database. RGBControlBucket = database.child("RGBControl") #get the child "RGBControl" path in your database and store it inside the "RGBControlBucket" variable. redLightIntensity = RGBControlBucket.child("redLightIntensity").get().val() #read the red LED intensity value from the tag "redLightIntensity" which is a node inside the database then store that value inside the "redLightIntensity" variable. # print("red Light Intensity is: " + str(redLightIntensity)) database = firebase.database() #take an instance from the firebase database which is pointing to the root directory of your database. RGBControlBucket = database.child("RGBControl") #get the child "RGBControl" path in your database and store it inside the "RGBControlBucket" variable. blueLightIntensity = RGBControlBucket.child("blueLightIntensity").get().val() #read the blue LED intensity value from the tag "blueLightIntensity" which is a node inside the database then store that value inside the "blueLightIntensity" variable. # print("blue Light Intensity is: " + str(blueLightIntensity)) database = firebase.database() #take an instance from the firebase database which is pointing to the root directory of your database. RGBControlBucket = database.child("RGBControl") #get the child "RGBControl" path in your database and store it inside the "RGBControlBucket" variable. greenLightIntensity = RGBControlBucket.child("greenLightIntensity").get().val() #read the green LED intensity value from the tag "greenLightIntensity" which is a node inside the database then store that value inside the "greenLightIntensity" variable. # print("green Light Intensity is: " + str(greenLightIntensity)) database = firebase.database() #take an instance from the firebase database which is pointing to the root directory of your database. RGBControlBucket = database.child("RGBControl") #get the child "RGBControl" path in your database and store it inside the "RGBControlBucket" variable. lightPresetMode = RGBControlBucket.child("lightMode").get().val() #read the light preset mode value from the tag "lightMode" which is a node inside the database then store that value inside the "lightPresetMode" variable. # print("light preset mode is: " + str(lightPresetMode)) # if the variable "lightPresetMode" value is equal to "mode6", call the mode6 function. if "mode6" in lightPresetMode.lower(): mode6(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is equal to "mode5", call the mode5 function. elif "mode5" in lightPresetMode.lower(): mode5(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is equal to "mode4", call the mode4 function. elif "mode4" in lightPresetMode.lower(): mode4(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is equal to "mode3", call the mode3 function. elif "mode3" in lightPresetMode.lower(): mode3(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is equal to "mode2", call the mode2 function. elif "mode2" in lightPresetMode.lower(): mode2(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is equal to "mode1", call the mode1 function. elif "mode1" in lightPresetMode.lower(): mode1(int(redLightIntensity), int(greenLightIntensity), int(blueLightIntensity)) # if the variable "lightPresetMode" value is not equal to any of the above values, print "DAMN, the power state is: false" on the terminal for debugging purposes. else: print("DAMN, the power state is: " + powerState) except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly: red_pwm.stop() # stop red PWM blue_pwm.stop() # stop blue PWM green_pwm.stop() # stop green PWM GPIO.cleanup() # cleanup all GPIO
Code Explanation
the most important part here is to connect your python script to the “Firebase database” servers to be able to read the data from it. We define a dictionary named config
with several key-value pairs that configure the connection to the database. The apiKey, authDomain, databaseUrl, and storageBucket values needed to connect to your database can be found in the Firebase console.
config = { #define a dictionary named config with several key-value pairs that configure the connection to the database. "apiKey": "ENTER YOUR PROJECT API KEY", "authDomain": "ENTER YOUR AUTH DOMAIN URL", # "projectId.firebaseapp.com" "databaseURL": "ENTER YOUR DATABASE URL", # "https://databaseName.firebaseio.com" "storageBucket": "ENTER YOUR STORAGE BUGET URL" # "projectId.appspot.com" }
To find the “API Key”, “authDomain”, “databaseURL”, “storageBucket” values, go to your database dashboard click on the gear icon, then “Project settings”.
Then you will find your project API key. Copy and paste it inside your python script. To find the “authDomain” you need to get the project ID, after getting your Project ID your “authDomain” will be like this “projectId.firebaseapp.com”.
your “storageBucket” will be like this “projectId.appspot.com”.
and to get your “databaseURL” go to your project database dashboard and copy that URL. That’s It!
If you want more code explanation, please read the code comments it’s well documented.
How does It Work?
After finishing the wiring and your code, close and save it, Run your program by writing python3 fileName.py
in your terminal.
Like the last example, After running your program, It’s expected to see this sentence got printed on the terminal AH Shit! Here we go again! Press CTRL+C to exit
then you will be able to control the LED Strip from your mobile app, Voila!
Note: You must run your program using python3, because the “pyrebase” module only works with python3 any other python version will not work.
Troubleshooting
If you see that error message when you run your program
don’t worry open your terminal and execute that commands
pip install --upgrade pyasn1-modules
this command will install your missing modules.
Running The Program Automatically On Startup
We don’t need to run the program manually by ourselves every time we boot up our raspberry pi board, it will be a good idea if we get our program to run automatically whenever the raspberry pi boots.
After the desktop environment starts (LXDE-pi, in this case), it runs whatever commands it finds in the profile’s autostart script, which is located at /home/pi/.config/lxsession/LXDE-pi/autostart for our Raspberry Pi.
First, we need to create a .desktop File, Open a terminal, and execute the following commands to create an autostart directory (if one does not already exist) and edit a .desktop file for our project code
mkdir /home/pi/.config/autostart
nano /home/pi/.config/autostart/IoTUsingRaspberryPi.desktop
Copy in the following text into the “IoTUsingRaspberryPi.desktop” file. Feel free to change the Name and Exec variables to your particular application.
[Desktop Entry]
Type=Application
Name=IoTUsingRaspberryPiAndFirebase
Exec=/usr/bin/python3 /your program absolute path/programName.py
That’s it! Now, at every time you boot up your raspberry pi, the program will start running automatically.
Troubleshooting
your script does not run as soon as you see the desktop?!
there could be several issues. First, make sure that you have logged in (autostart does not start until you have logged in). You could also try enabling auto-login in raspi-config
. Second, make sure you are using the absolute directory path (e.g. /home/pi/IoTUsingRaspberryPi.py
). Third, make sure that you are using the python version 3 not anything else.
My Setup
Final
We are done! in today’s tutorial, we learned how to build a simple mobile app using MIT App inventor. Also, we learned how to control RGD LED strips using the raspberry pi board, and how to communicate with the firebase database servers through a python script. Lastly, how to control an RGB LED strip wirelessly from anywhere in the world.
Lastly, if you have any questions drop it in the comments section below, I will be more than happy to hear from you