Introduction: Wifi Controlled 12v Led Strip Using Raspberry Pi With Tasker, Ifttt Integration.
In this project I will show you how to control a simple 12v analog led strip over wifi using a raspberry pi.
For this project you will need:
- 1x Raspberry Pi (I am using a Raspberry Pi 1 Model B+)
- 1x RGB 12v Led Strip [Ebay Australia]
- 3x IRFZ44N N-Channel Mosfet's [Ebay Australia]
- 1x Female DC power jack Adapter [Ebay Australia]
- Some Wires
- Display, Keyboard (Just For Setup)
Step 1: Install Raspbian OS Using Windows
To install Raspbian with windows you will need:
**IMPORTANT if done wrong you may lose all your data, Please backup your data before continuing**
- Plug in your SD card into a Card Reader and open My Computer
- Look for the Drive Letter
- Right Click the Win32DiskImager and Click "Run as Administrator"
- Then Click the little blue folder and browse to your image of the RaspbianOS
- Also click the dropdown box under Device and change it to the SD Card's Drive Letter
- Then Click "Write"
- A dialog box will open BEFORE Pressing Yes verify that the target device is correct
- Then remove the SD Card and insert it into the pi
Step 2: Install Raspbian OS Using Mac OS X
To install Raspbian with Mac you will need:
**IMPORTANT if done wrong you may lose all your data, Please backup your data before continuing**
- Open Disk Utility and look for your SD Card on the left hand side then click it
- Look for "Device" on the bottom of the window you should see something like diskXsX where x is a number
- Remember the "Device" Number and open ApplePi-Baker
- It will ask for you password due to it having to format your SD-Card
- Click the "Device" Number that is After /dev/ on the left hand side
- Click "Restore-Backup" Browse to your image of RaspbianOS.
- It will Start to erase the SD-Card and install Raspbian on to it
- When it is done a alert box will pop up that is telling you that you can remove the SD-Card, Remove it and put it into your pi.
Step 3: Setting Up the Pi
Before powering up the pi you will need to plug in a HDMI Display, Keyboard and a ethernet cable or usb wifi (We will set this up in the next step).
Power up the pi, You will see a bunch of text fill up the screen, This is normal and is part of the linux kernel startup. Just wait a bit until you see
raspberry login:
Your Username is pi and the password is raspberry (you won't see anything typing on the screen but it is still being entered)
Then when you login you will see:
pi@raspberrypi:~$
Then you have to enter:
sudo raspi-config
Your Screen will then be filled with a blue screen with options in a grey box in the centre,
- Using up and down keys, highlight and hit enter on "Expand Filesystem" option after a few seconds you will be taken to a alert saying that "root filesystem has been resized", click Enter
- Then press the down arrow and go to Boot Options and click enter, then click enter when 'Desktop / CLI' is selected, Then highlight 'Console Autologin' and click enter
- Then select Advanced options and click enter
- Then scroll down to ssh and click enter then select yes
- then press the right arrow until back is highlighted and press enter
- Then goto the bottom again and click finish then say yes to reboot
After it reboots if you are connected via ethernet then you need to enter this command to find your IP address so we can ssh into the pi
Find ip:
hostname -I
Step 4: Setup Wifi
To setup the wifi on the pi we need to edit a file
1. enter into the command line
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
2. Go to the end of the file and enter
network={ ssid="Your_Wifi_Name" psk="Your_wifi_password" }
3. Then reboot your pi with
sudo reboot
After your pi reboots get it's IP address by typing
hostname -I
you should get your IP address But if the retuned text is blank that means that the pi could not connect to your network. double check if you have entered you wifi name and password correctly as it is case sensitive.
Step 5: Remotely Connect to Your Pi Using Windows
Now that we have the pi connected to the internet we can remove the keyboard mouse and display, and remotely connect to it using "ssh"
To ssh into the pi with windows you need to download
putty: [Download]
- Open putty, in the IP address box enter the raspberry pi ip then press open
- you will get a dialog box that look's like picture 2 press yes
- you will then see a new dialog that says "login as" enter "pi"
- then it will ask for a password enter "raspberry"
You are now connected to the pi over ssh
Step 6: Remotely Connect to Your Pi Using Mac
Now that we have the pi connected to the internet we can remove the keyboard and mouse and remotely connect to it using "ssh"
1. Open "Terminal"
2. Type in
ssh pi@IP_ADDRESS
3. Then you might get a message saying that the host key is not saved, Just type "yes"
4. Then when promoted enter the raspberry pi password which is "Raspberry"
You are now connected to the pi over ssh
Step 7: Installing the Software
As we now have remote access to the pi we need to install some software to control the led strip
We will need to install
- pigpio (This turns all the GPIO pins from digital to PWM)
- flask (server side script that talks to pigpio and the webserver)
- apache2 (Webserver)
Install pigpio
1. First we need to download a zip folder contains the uncompiled pigpio software, using this command
wget <a href="http://abyz.me.uk/rpi/pigpio/pigpio.zip"> http://abyz.me.uk/rpi/pigpio/pigpio.zip>
2. We then need to unzip and go into the directory
unzip pigpio.zip && cd PIGPIO
3.now that we are in the directory we need to compile and install the software
make -j4 && sudo make install
4.Now open rc.local so we can tell the pi to run pigpiod when starting up
sudo nano /etc/rc.local
then just before the exit line enter
sudo pigpiod
You have now installed the pigpio software
Install flask
first we need to update the list of software to do this enter
sudo apt update && sudo apt upgrade -y
then install pip
sudo apt-get install python-pip
now we can install flask
sudo pip install flask
Install Apache2
sudo apt-get install apache2 -y
sudo apt-get install libapache2-mod-wsgi -y
Install git
sudo apt install git -y
After everything has finished installing shutdown the pi with
sudo shutdown now
Step 8: Wiring Up the Power
First we need to wire up the power connector to the bread board
- Connect the black wire to the negative connector on the power jack
- Connect the Red wire to the positive connector on the power jack
- Connect the Other end of the Red wire to the positive side of the breadboard
- Connect the Other end of the Black wire to the positive side of the breadboard
- Then connect the ground pin from the pi (as seen in the image) into the negative pin on the breadboard
Now we have to connect the mostfet.
Step 9: Wiring Up the Mosfets and Connecting the Pi
A Mosfet allows you to control how much power can travel to the led lights, we will need three mosfets as we need to control the red, green and blue lights separately.
The mosfet has three pins, on the left it has the "Gate" pin which will be connected to the pi to control how much power can flow to the led light's
The centre pin is called "Drain" which will go to the led light's and supply the voltage that the gate allows to past
and the pin on the right is the "Source" pin. This pin goes to the ground on the breadboard.
Connecting the Red Led
- Put one mosfet into the breadboard
- connect a black wire from GND on the breadboard to the source (right pin)
- then connect a red wire from the centre pin on the mosfet to the red pin on the led strip
- then connect a red wire from the left pin to GPIO 17 on the pi
Connecting the Green Led
- Put the 2nd mosfet into the breadboard
- then just like before connect a black wire from GND on the breadboard to the source (right pin)
- then connect a green wire from the centre pin on the mosfet to the green pin on the led strip.
- then connect a green wire from the left pin to GPIO 22 on the pi
Connecting the Blue Led
- Put the last mosfet into the breadboard
- the connect another black wire from GND on the breadboard to the source (right pin)
- then connect a blue wire from the centre pin on the mosfet to the blue pin on the led strip.
- then connect a blue wire from the left pin to GPIO 24 on the pi
Then you will have one more pin on the led strip that will eider be white or black, just connect a wire from the positive pin on the breadboard to that extra pin on the led strip
Now that we are done we can start to test it out.
Step 10: Downloading and Testing the Led Strip
To download the Source code for controlling the Led strip
git clone https://github.com/DavidMontesin/Raspberry-PI-Wifi-Led-Strip.git && cd Raspberry-PI-Wifi-Led-Strip/
To test the led strip run the test.py file.
python Test.py
if for some reason some of the colour's do not light up, please check if everything is plugged in correctly.
how does this script work?
if you open the python script you might wonder how it works, on the first line you will see:
import time
this little library allows us to pause the script so we can keep the lights on faster
import pigpio
this library allows us to communicate with the led strip
pi = pigpio.pi()
setup a variable so we can use pi.set_pw... insted of pigpio.pi().set_pw...
RedPin = 17
GreenPin = 22
BluePin = 24
these are just variables that allows us to tell the script what led are connected on
print("tesing for red")
this will just print text to the command line
pi.set_PWM_dutycycle(RedPin, 255)
this command is part of the pigpio libary and is saying to set the "RedPin" which it looks for the number we set before and sets it's brightness to "255" which is the max
time.sleep(2)
this is part of the time library and will just pause the script for 2 seconds
these supple command will repeat for the other leds until
pi.stop()
which will stop talking to the led strip and tun all the colours off.
Attachments
Step 11: Programing the Server Side Script
**Before you start, I recommend you read about python and flask:
Here are some guides:
http://www.pythonforbeginners.com
http://docs.python-guide.org/en/latest/intro/learn...
As Main.py is in the git directly this step is just explaining the code.
First we have the libraries
from flask import Flask, render_template, request import pigpio from thread import start_new_thread
then we need to set some variables
app = Flask(__name__) CurrentColour = "White" RedColourCode = 0 BlueColourCode = 0 GreenColourCode = 0 RedBeforeEffect = 0 BlueBeforeEffect = 0 GreenBeforeEffect = 0 pi = pigpio.pi()
the first variable is for flask which is our web server we will call it app so it's easier to call and run. Then there are 6 variables that the first three will contain what colour to change two and the other three will contain the colour previous.
@app.route('/', methods=['GET'])
This Line says that if someone types the pi's IP address in a web browser then it will run the script below it, it also has a GET method when means that, any text after ?Colour= will be passed to the web server and will be used to change the colour of the led strip.
def Main(): global CurrentColour
the text def Main() means that it will create a function called main that can be called from anywhere in the script. and the global line means that it will update the variable in the whole script.
if request.args.get('Colour'): CurrentColour=request.args.get('Colour') if CurrentColour == "White": FadeTORGB(255,255,255) elif CurrentColour == "Red": FadeTORGB(255,0,0) elif CurrentColour == "Green": FadeTORGB(0,255,0) elif CurrentColour == "DarkBlue": FadeTORGB(0,0,255) elif CurrentColour == "LightBlue": FadeTORGB(0,255,255) elif CurrentColour == "Orange": FadeTORGB(255,15,0) elif CurrentColour == "Pink": FadeTORGB(255,0,192) elif CurrentColour == "Yellow": FadeTORGB(255,157,0) elif CurrentColour == "Purple": FadeTORGB(123,0,255) elif CurrentColour == "Black": FadeTORGB(0,0,0) return render_template('index.html')
This script will get any name after the GET Method "Colour" and saves it. it will then check for that name and will call a function that will can 3three other functions to change the red, green and blue light's simultaneously
def FadeTORGB(RedNum,BlueNum,GreenNum): start_new_thread(FadeUpRed,(RedNum,)) start_new_thread(FadeUpBlue,(BlueNum,)) start_new_thread(FadeUpGreen,(GreenNum,))
This will call three other function that will change the amount of power going to each led with a fade effect.
def FadeUpRed(REDUpNum): global RedColourCode if RedColourCode < REDUpNum: while RedColourCode < REDUpNum: RedColourCode +=1 pi.set_PWM_dutycycle(RedPin, RedColourCode) elif RedColourCode > REDUpNum: while RedColourCode > REDUpNum: RedColourCode -=1 pi.set_PWM_dutycycle(RedPin, RedColourCode)
def FadeUpBlue(BlueUpNum): global BlueColourCode if BlueColourCode < BlueUpNum: while BlueColourCode < BlueUpNum: BlueColourCode +=1 pi.set_PWM_dutycycle(BluePin, BlueColourCode) elif BlueColourCode > BlueUpNum: while BlueColourCode > BlueUpNum: BlueColourCode -=1 pi.set_PWM_dutycycle(BluePin, BlueColourCode)
def FadeUpGreen(GreenUpNum): global GreenColourCode if GreenColourCode < GreenUpNum: while GreenColourCode < GreenUpNum: GreenColourCode +=1 pi.set_PWM_dutycycle(GreenPin, GreenColourCode) elif GreenColourCode > GreenUpNum: while GreenColourCode > GreenUpNum: GreenColourCode -=1 pi.set_PWM_dutycycle(GreenPin, GreenColourCode)
if __name__ == "__main__": app.run(host="0.0.0.0")
Attachments
Step 12: Programing the Webserver
Now that we have the server we need to design a website.
As the server is in the templates and static folders in the git directly this step is just explaining the code.
I also recommend you read about html, css, javascript
HTML
First we need to program html, this is where all the content goes that then can be styled using css
1. Creating the Head (title, linking files,)
<!DOCTYPE html> <html> <head> <title> Wifi Led Strip </title>
The first two tags tells the web browser that it is a webpage, Then the third line is telling the browser to hide any text inside the block and under that is the title that will appear in the tab
Making the webpage fullscreen on iOS
To make the page fullscreen enter this code under the tag
<meta name="viewpoint" content = "width = device-width, initial-scale = 1.0, minimum-scale = 1, maximum-scale = 1, user-scalable = no" /> <meta name="apple-mobile-web-app-title" content="Wifi Led" /> <meta name="apple-mobile-web-app-capable" content="yes" />
Next we will add references to the css file we will make latter this will be a different way then usual due to flask is way of file management
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='Style.css') }}">
Then after this you MUST close the tag and create a body tag
</head> <body>
The body tag means that any tags inside it will appear onto the web page
Now we are going to make the colours buttons that can change the led strip.
We will create one for each colour and put it in a table
<table class="Colours" cellspacing="10" border="0">
This create's the outside frame of the table
<tr>
this will create a row for the table
Now let's create a orange button
<td onClick="SendColour('Orange')" class="button" style="background-color:rgb(255,136,0);"></td>
the tag td creates a cell, then the "onClick" function will call a javascript function that we will create latter, them the "class" function is used to style the button and the style is just to colour it.
We will just have to change the sendColour text and the style for each other button but after every 2nd button we will close the row and create a new row
<td onClick="SendColour('Red')" class="button" style="background-color:red"></td> </tr> <tr>
Etc...
Then after you have put all the colour in you need to close the table
</table>
Javascript
Now we need to add the "SendColour" function that we had referenced before to do this we first need to add a tag telling the web browser that there is some javascript
<script>
then create a function
function SendColour(ClickedColour) {
This function will send a Ajax request to the raspberry pi that will tell it to change to the colour that you had clicked on
xhttp = new XMLHttpRequest(); xhttp.open("GET", "?Colour=" + ClickedColour, false); xhttp.send(); }
Now we need to close the javascript and html
</script> </body> </html>
CSS
Now we are going to design the website
first cd out of the templates folder and go into the static folder
cd .. && cd static
now create the Style.css file
nano Style.css
First lets make the table fill the whole screen.
.Colours { width: 100%; }
.button { padding: 25px 35px; border-radius: 4px; }
Testing the server
to test the server go into the web server folder
cd ..
then enter
python Main.py
this will start the server, then on your computer open the web browser and navigate to
http://YOUR_PI_PI:5000
the :5000 at the end is important for now as it is the port that the web server is running on.
if your goto the webpage and get a "Internal Server Error" then look at the console (putty or terminal) and you will see a bunch of text, just look at the last line and it should. tell you what is going on, you can google to find the answer,
but if the see the colours on the screen you can click on one and you should see the led strip goto that colour, if it doesn't then check if the power is plugged in and turned on or that the html code has been entered right.
Attachments
Step 13: Making It Work With Apache2
Now that we have tested it we have to get it to talk to apache so it can run at startup and on port 80 (standard web port)
1. inside your WebServer folder make a wsgi file
nano wifiled.wsgi
Then in the file enter
import sys sys.path.insert(0, '/home/pi/Webserver/') from Main import app as application
then add the user pi to a group called www-data, this will allow apache to look in the web server folder
sudo usermod -a -G www-data pi
then remove the default config
sudo a2dissite 000-default
then make a file in the Apache config folder
sudo nano /etc/apache2/sites-available/wifiled.conf
and enter
<VirtualHost *:80> ServerName WifiLed ServerAdmin admin@mywebsite.com WSGIScriptAlias / /home/pi/Webserver/wifiled.wsgi <Directory /home/pi/Webserver> Order allow,deny Allow from all Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
then tell apache to read the config by entering
sudo a2ensite wifiled.conf
Now restart the pi, when it reboots enter into your web browser
http://YOUR_PI_IP
Step 14: Setting Up Tasker and Ifttt and Other Services
Before we setup these programs you must setup port fording on your router as every router is different you can read how to here
Tasker
on your android device open taker
then create a new profile basted on a Event, you can choose any trigger. I have chose "Phone Ringing" and had set the colour to anyone "C:ANY", Then it will ask you to select a task, click "New Task" and name it basted on your action. I will call it "Phone Call" then press add action and look for "HTTP Head" and set the Server:Port to your_raspberry_pi_IP then under path you can either set a solid colour with "/?Colour=Green" or you can create a effect we will do this in the next step. Then click back and back again.
IFTTT
first goto ifttt and create a new applet Choose any trigger (I chose Button) and then for action choose the maker channel and said to make a we request then for the url enter YOUR_PUBLIC_PI/?Colour=LightBlue if you don't know your public ip just enter "My Ip" on google. Then for method enter HEAD then click "Create Action" now when your action happens ifttt make a request to your pi to change colour.
Other Services
You can also connect other services that make HTTP HEAD or GET request.
Step 15: Creating Custom Effects
In Main.py add a import statement, under import os enter
import time
also before we create a effect we need to add a variable just under GreenBeforeEffect add
CanChangeColour = True
then change if request.args.get('Colour'):
to
if request.args.get('Colour') and CanChangeColour:
section just under return render_template('Main.html') add
@app.route('/Effect', methods=['GET']) def Effect():
Then set the variables to global
x = 0 global RedColourCode global BlueColourCode global GreenColourCode global RedBeforeEffect global BlueBeforeEffect global GreenBeforeEffect
now lets create our first effect
if request.args.get('Call'): RedBeforeEffect = RedColourCode BlueBeforeEffect = BlueColourCode GreenBeforeEffect = GreenColourCode FadeTORGB(0,0,0) time.sleep(2)
This action will run when the pi receive's a request like "/?Effect=Call" and will save the current colour so we can call it back, We then make the led strip black and wait until it happens.
Now we are going to make the led fade from black to green then to black again and I want to do this five times
while x <= 5: FadeTORGB(0,255,0) x +=1 time.sleep(1) FadeTORGB(0,0,0) time.sleep(1) CanChangeColour = True time.sleep(2) FadeTORGB(RedBeforeEffect,BlueBeforeEffect,GreenBeforeEffect)
This will count up to five but every time it will fade to green and then wait a second and go to black. Then what that finishes it will change the colour back to the ones you had before changing.
Now we just to create a response.
return ""
Also Reboot you raspberry pi
sudo reboot