19 min read

In this article by Sai Yamanoor and Srihari Yamanoor, authors of the book Raspberry Pi Mechatronics Projects Hotshot, have picked a Christmas-themed project to demonstrate controlling appliances connected to a local network using Raspberry Pi.

We will design automation and control of Christmas lights in our homes. We will decorate our homes with lights for any festive occasion and work on a article that enables us to build fantastic projects. We will build a local server to control the devices. We will use the web.py framework to design the web server. We’d like to dedicate this article to the memory of Aaron Swartz who was the founder of the web.py framework.

Mission briefing

In this article, we will install a local web server-based control of GPIO pins on the Raspberry Pi. We will use this web server framework to control it via a web page.Raspberry Pi Mechatronics Projects HOTSHOT

The Raspberry Pi on top of the tree is just an ornament for decoration

Why is it awesome?

We celebrate festive occasions by decorating our homes. The decorations reflect our heart and it can be enhanced by using Raspberry Pi.

This article involves interfacing AC-powered devices to Raspberry Pi. You should exercise extreme caution while interfacing the devices, and it is strongly recommended that you stick to the recommended devices.

Your objectives

In this article, we will work on the following aspects:

  • Interface of the Christmas tree lights and other decorative equipment to the Raspberry Pi
  • Set up the digitally-addressable RGB matrix
  • Interface of an audio device
  • Setting up the web server
  • Interfacing devices to the web server

You can buy your sustainable and UK grown Christmas trees from christmastrees.co.uk.

Mission checklist

This article is based on a broad concept. You are free to choose decorative items of your own interest. We chose to show the following items for demonstration:

Item

Estimated Cost

Christmas tree * 1

30 USD

Outdoor decoration (optional)

30 USD

Santa Claus figurine * 1

20 USD

Digitally addressable strip * 1

30 USD approximately

Power Switch Tail 2 from Adafruit Industries (http://www.adafruit.com/product/268)

25 USD approximately

Arduino Uno (any variant)

20 – 30 USD approximately

Interface the devices to the Raspberry Pi

It is important to exercise caution while connecting electrical appliances to the Raspberry Pi. If you don’t know what you are doing, please skip this section. Adult supervision is required while connecting appliances.

In this task, we will look into interfacing decorative appliances (operated with an AC power supply) such as the Christmas tree. It is important to interface AC appliances to the Raspberry Pi in accordance with safety practices. It is possible to connect AC appliances to the Raspberry Pi using solid state relays. However, if the prototype boards aren’t connected properly, it is a potential hazard. Hence, we use the Power Switch Tail II sold by Adafruit Industries.

The Power Switch Tail II has been rated for 110V.

According to the specifications provided on the Adafruit website, Power Switch Tail’s relay can switch up to 15A resistive loads. It can be controlled by providing a 3-12V DC signal. We will look into controlling the lights on a Christmas tree in this task.Raspberry Pi Mechatronics Projects HOTSHOT

Power Switch Tail II – Photo courtesy: Adafruit.com

Prepare for lift off

We have to connect the Power Switch Tail II to the Raspberry Pi to test it. The follow Fritzing schematic shows the connection of the switch to the Raspberry Pi using Pi Cobbler. Pin 25 is connected to in+, while the in- pin is connected to the Ground pin of the Raspberry Pi.Raspberry Pi Mechatronics Projects HOTSHOT

The Pi Cobbler breakout board is connected to the Raspberry Pi as shown in the following image:Raspberry Pi Mechatronics Projects HOTSHOT

The Raspberry Pi connection to the Power Switch Tail II using Pi Cobbler

Engage thrusters

  1. In order to test the device, there are two options to control the device the GPIO Pins of the Raspberry Pi. This can be controlled either using the quick2wire GPIO library or using the Raspi GPIO library.

The main difference between the quick2wire gpio library and the Raspi GPIO library is that the former does not require that the Python script to be run with root user privileges (to those who are not familiar with root privileges, the Python script needs to be run using sudo). In the case of the Raspi GPIO library, it is possible to set the ownership of the pins to avoid executing the script as root.

  1. Once the installation is complete, let’s turn on/off the lights on the tree with a three second interval. The code for it is given as follows:
# Import the rpi.gpio module.
import RPi.GPIO as GPIO
#Import delay module.
from time import sleep
#Set to BCM GPIO
GPIO.setmode(GPIO.BCM)
# BCM pin 25 is the output.
GPIO.setup(25, GPIO.OUT)
# Initialise Pin25 to low (false) so that the Christmas tree lights are switched off.
GPIO.output(25, False)
while 1:
GPIO.output(25,False)
sleep(3)
GPIO.output(25,True)
sleep(3)
  • In the preceding task, we will get started by importing the raspi.gpio module and the time module to introduce a delay between turning on/off the lights:
import RPi.GPIO as GPIO
#Import delay module
from time import sleep
  • We need to set the mode in which the GPIO pins are being used. There are two modes, namely the board’s GPIO mode and the BCM GPIO mode (more information available on http://sourceforge.net/p/raspberry-gpio-python/wiki/). The former refers to the pin numbers on the Raspberry Pi board while the latter refers to the pin number found on the Broadcom chipset. In this example, we will adopt the BCM chipset’s pin description.
  • We will set the pin 25 to be an output pin and set it to false so that the Christmas tree lights are switched off at the start of the program:
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, False)
  • In the preceding routine, we are switching off the lights and turning them back on with a three-second interval:
while 1:
GPIO.output(25,True)
sleep(3)
GPIO.output(25,False)
sleep(3)
  1. When the pin 25 is set to high, the device is turned on, and it is turned off when the pin is set to low with a three-second interval.

Connecting multiple appliances to the Raspberry Pi

Let’s consider a scenario where we have to control multiple appliances using the Raspberry Pi.

It is possible to connect a maximum of 15 devices to the GPIO interface of the Raspberry Pi. (There are 17 GPIO pins on the Raspberry Pi Model B, but two of those pins, namely GPIO14 and 15, are set to be UART in the default state. This can be changed after startup. It is also possible to connect a GPIO expander to connect more devices to Raspberry Pi.)

In the case of appliances that need to be connected to the 110V AC mains, it is recommended that you use multiple power switch tails to adhere to safety practices.

In the case of decorative lights that operate using a battery (for example, a two-feet Christmas tree) or appliances that operate at low voltage levels of 12V DC, a simple transistor circuit and a relay can be used to connect the devices. A sample circuit is shown in the figure that follows:Raspberry Pi Mechatronics Projects HOTSHOT

A transistor switching circuit

In the preceding circuit, since the GPIO pins operate at 3.3V levels, we will connect the GPIO pin to the base of the NPN transistor. The collector pin of the transistor is connected to one end of the relay.

The transistor acts as a switch and when the GPIO pin is set to high, the collector is connected to the emitter (which in turn is connected to the ground) and hence, energizes the relay.

Relays usually have three terminals, namely, the common terminal, Normally Open Terminal, and Normally Closed Terminal. When the relay is not energized, the common terminal is connected to the Normally Closed Terminal. Upon energization, the Normally Open Terminal is connected to the common terminal, thus turning on the appliance.

The freewheeling diode across the relay is used to protect the circuit from any reverse current from the switching of the relays.

The transistor switching circuit aids in operating an appliance that operates at 12V DC using the Raspberry Pi’s GPIO pins (the GPIO pins of the Raspberry Pi operate at 3.3V levels). The relay and the transistor switching circuit enables controlling high current devices using the Raspberry Pi.

It is possible to use an array of relays (as shown in the following image) and control an array of decorative lighting arrangements. It would be cool to control lighting arrangements according to the music that is being played on the Raspberry Pi (a project idea for the holidays!).

The relay board (shown in the following image) operates at 5V DC and comes with the circuitry described earlier in this section. We can make use of the board by powering up the board using a 5V power supply and connecting the GPIO pins to the pins highlighted in red. As explained earlier, the relay can be energized by setting the GPIO pin to high.Raspberry Pi Mechatronics Projects HOTSHOT

A relay board

Objective complete – mini debriefing

In this section, we discussed controlling decorative lights and other holiday appliances by running a Python script on the Raspberry Pi. Let’s move on to the next section to set up the digitally addressable RGB LED strip!

Setting up the digitally addressable RGB matrix

In this task, we will talk about setting up options available for LED lighting. We will discuss two types of LED strips, namely analog RGB LED strips and digitally-addressable RGB LED strips.

A sample of the digitally addressable RGB LED strip is shown in the image that follows:Raspberry Pi Mechatronics Projects HOTSHOT

A digitally addressable RGB LED Strip

Prepare for lift off

As the name explains, digitally-addressable RGB LED strips are those where the colour of each RGB LED can be individually controlled (in the case of the analog strip, the colors cannot be individually controlled).

Where can I buy them?

There are different models of the digitally addressable RGB LED strips based on different chips such as LPD6803, LPD8806, and WS2811. The strips are sold in a reel of a maximum length of 5 meters. Some sources to buy the LED strips include Adafruit (http://www.adafruit.com/product/306) and Banggood (http://www.banggood.com/5M-5050-RGB-Dream-Color-6803-IC-LED-Strip-Light-Waterproof-IP67-12V-DC-p-931386.html) and they cost about 50 USD for a reel. Some vendors (including Adafruit) sell them in strips of one meter as well.

Engage thrusters

Let’s review how to control and use these digitally-addressable RGB LED strips.

How does it work?

Most digitally addressable RGB strips come with terminals to powering the LEDs, a clock pin, and a data pin. The LEDs are serially connected to each other and are controlled through the SPI (Serial Peripheral Interface).

The RGB LEDs on the strip are controlled by a chip that latches data from the microcontroller/Raspberry Pi onto the LEDs with reference to the clock cycles received on the clock pin.

In the case of the LPD8806 strip, each chip can control about 2 LEDs. It can control each channel of the RGB LED using a seven-bit PWM channel. More information on the function of the RGB LED strip is available at https://learn.adafruit.com/digital-led-strip.

It is possible to break the LED strip into individual segments. Each segment contains about 2 LEDs, and Adafruit industries has provided an excellent tutorial to separate the individual segments of the LED strip (https://learn.adafruit.com/digital-led-strip/advanced-separating-strips).

Lighting up the RGB LED strip

There are two ways of connecting the RGB LED strip. They can either be connected to an Arduino and controlled by the Raspberry Pi or controlled by the Raspberry Pi directly.

An Arduino-based control

It is assumed that you are familiar with programming microcontrollers, especially those on the Arduino platform.

Raspberry Pi Mechatronics Projects HOTSHOT

An Arduino connection to the digitally addressable interface

In the preceding figure, the LED strip is powered by an external power supply. (The tiny green adapter represents the external power supply. The recommended power supply for the RGB LED strip is 5V/2A per meter of LEDs (while writing this article, we got an old computer power supply to power up the LEDs). The Clock pins (the CI pin) and the Data pins (DI) of the first segment of the RGB strip are connected to the pins D2 and D3 respectively. (We are doing this since we will test the example from Adafruit industries. The example is available at https://github.com/adafruit/LPD8806/tree/master/examples.)

Since the RGB strip consists of multiple segments that are serially connected, the Clock Out (CO) and Data Out (DO) pins of the first segment are connected to the Clock In (CI) and Data In (DI) pins of the second segment and so on.

Let’s review the example, strandtest.pde, to test the RGB LED strip. The example makes use of Software SPI (Bit Banging of the clock and data pins for lighting effects). It is also possible to use the SPI interface of the Arduino platform.

In the example, we need to set the number of LEDs used for the test. For example, we need to set the number of LEDs on the strip to 64 for a two-meter strip. Here is how to do this:

  1. The following line needs to be changed:

    int nLEDs = 64;
  2. Once the code is uploaded, the RGB matrix should light up, as shown in this image:Raspberry Pi Mechatronics Projects HOTSHOT

    8 x 8 RGB matrix lit up

  3. Let’s quickly review the Arduino sketch from Adafruit. We will get started by setting up an LPD8806 object as follows:
    //nLEDS refer to number of LEDs in the strip. This cannot exceed 160 LEDs/5m due to current draw.
    LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin);
  4. In the setup() sectionof the Arduino sketch, we will initialize the RGB strip “as follows:
    // Start up the LED strip
    strip.begin();
    // Update the strip, to start they are all 'off'
    strip.show();
  5. As soon as we enter the main loop, scripts such as colorChase and rainbow are executed.
  6. We can make use of this Arduino sketch to implement serial port commands to control the lighting scripts using the Raspberry Pi.

This task merely provides some ideas of connecting and lighting up the RGB LED strip. You should familiarize yourself with the working principles of the RGB LED strip. The Raspberry Pi has an SPI port, and hence, it is possible to control the RGB strip directly from the Raspberry Pi.

Objective complete – mini debriefing

In this task, we reviewed options for decorative lighting and controlling them using the Raspberry Pi and Arduino.

Interface of an audio device

In this task, we will work on installing MP3 and WAV file audio player tools on the Raspbian operating system.

Prepare for lift off

The Raspberry Pi is equipped with a 3.5mm audio jack and the speakers can be connected to that output. In order to get started, we install the ALSA utilities package and a command-line mp3 player:

sudo apt-get install alsa-utils
sudo apt-get install mpg321

Engage thrusters

In order to use the alsa-utils or mpg321 players, we have to activate the BCM2835’s sound drivers and this can be done using the modprobe command:

sudo modprobe snd_bcm2835

After activating the drivers, it is possible to play the WAV files using the aplay command (aplay is a command-line player available as part of the alsa-utils package):

aplay testfile.wav

An MP3 file can be played using the mpg321 command (a command-line MP3 player):

mpg321 testfile.mp3

In the preceding examples, the commands were executed in the directory where the WAV file or the MP3 file was located. In the Linux environment, it is possible to stop playing a file by pressing CTRL + C.

Objective complete – mini debriefing

We were able to install sound utilities in this task. Later, we will use the installed utilities to play audio from a web page.

It is possible to play the sound files on the Raspberry Pi using the module available in Python. Some examples include: Snack sound tool kit, Pygame, and so on.

Installing the web server

In this section, we will install a local web server on Raspberry Pi. There are different web server frameworks that can be installed on the Raspberry Pi. They include Apache v2.0, Boost, the REST framework, and so on.

Prepare for lift off

As mentioned earlier, we will build a web server based on the web.py framework. This section is entirely referenced from web.py tutorials (http://webpy.github.io/). In order to install web.py, a Python module installer such as pip or easy_install is required. We will install it using the following command:

sudo apt-get install python-setuptools

Engage thrusters

The web.py framework can be installed using the easy_install tool:

sudo easy_install web.py

Once the installation is complete, it is time to test it with a Hello World! example.

We will open a new file using a text editor available with Python IDLE and get started with a Hello World! example for the web.py framework using the following steps:

  1. The first step is to import the web.py framework:

    import web
  2. The next step is defining the class that will handle the landing page. In this case, it is index:
    urls = ('/','index')
  3. We need to define what needs to be done when one tries to access the URL. “We will like to return the Hello world!text:
    class index:
    def GET(self):
    return "Hello world!"
  4. The next step is to ensure that a web page is set up using the web.py framework when the Python script is launched:
    if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
  5. When everything is put together, the following code is what we’ll see:
    import web
    urls = ('/','index')
    class index:
    def GET(self):
    return "Hello world!"
    if __name__ == '__main__':
    app = web.application(urls,globals())
    app.run()
  6. We should be able to start the web page by executing the Python script:
    python helloworld.py

We should be able to launch the website from the IP address of the Raspberry Pi. For example, if the IP address is 10.0.0.10, the web page can be accessed at http://10.0.0.10:8080 and it displays the text Hello world. Yay!Raspberry Pi Mechatronics Projects HOTSHOT

A Hello world! example using the web.py framework

Objective complete – mission debriefing

We built a simple web page to display the Hello world text. In the next task, we will be interfacing the Christmas tree and other decorative appliances to our web page so that we can control it from anywhere on the local network.

It is possible to change the default port number for the web page access by launching the Python script as follows:

python helloworld.py 1234

Now, the web page can be accessed at http://<IP_Address_of_the_Pi>:1234.

Interfacing the web server

In this task, we will learn to interface one decorative appliance and a speaker. We will create a form and buttons on an HTML page to control the devices.

Prepare for lift off

In this task, we will review the code (available along with this article) required to interface decorative appliances and lighting arranging to a web page and controlled over a local network. Let’s get started with opening the file using a text editing tool (Python IDLE’s text editor or any other text editor).

Engage thrusters

  1. We will import the following modules to get started with the program:

    import web
    from web import form
    import RPi.GPIO as GPIO
    import os
  2. The GPIO module is initialized, the board numbering is set, and ensure that all appliances are turned off by setting the GPIO pins to low or false and declare any global variables:
    #Set board
    GPIO.setmode(GPIO.BCM)
    #Initialize the pins that have to be controlled
    GPIO.setup(25,GPIO.OUT)
    GPIO.output(25,False)
  3. This is followed by defining the template location:
    urls = ('/', 'index')
    render = web.template.render('templates')
  4. The buttons used in the web page are also defined:
    appliances_form = form.Form(
    form.Button("appbtn", value="tree", class_="btntree"),
    form.Button("appbtn", value="Santa", class_="btnSanta"),
    form.Button("appbtn", value="audio", class_="btnaudio")
    •    In this example, three buttons are used, a value is assigned to each button along with their class.
    •    In this example, we are using three buttons and the name is appbtn. A value is assigned to each button that determines the desired action when a button is clicked. For example, when a Christmas tree button is clicked, the lights need to be turned on. This action can be executed based on the value that is returned during the button press.
  5. The home page is defined in the index class. The GET method is used to render the web page and POST for button click actions.
    class index:
    def GET(self):
    form = appliances_form()
    return render.index(form, "Raspberry Pi Christmas lights controller")
    def POST(self):
    userData = web.input()
    if userData.appbtn == "tree"
    global state
    state = not state
    elif userData.appbtn == "Santa":
    #do something here for another appliance
    elif userData.appbtn == "audio":
    os.system("mpg321 /home/pi/test.mp3")
    GPIO.output(25,state)
    raise web.seeother('/')
    •    In the POST method, we need to monitor the button clicks and perform an action accordingly. For example, when the button with the tree value is returned, we can change the Boolean value, state. This in turn switches the state of the GPIO pin 25. Earlier, we connected the power tail switch to pin 25.
  6. The index page file that contains the form and buttons is as follows:
    $def with (form,title)
    <html>
    <head>
    <title>$title</title>
    <link rel="stylesheet" type="text/css" href="/static/styles.css">
    </head>
    <body&gt
    <P><center><H1>Christmas Lights Controller</H1></center>
    <br />
    <br />
    <form class="form" method="post">
    $:form.render()
    </form>
    </body>
    </html>
  7. The styles of the buttons used on the web page are described as follows in styles.css:
    form .btntree {
    margin-left : 200px;
    margin-right : auto;
    background:transparent url("images/topic_button.png") no-repeat top left;
    width : 186px;
    height: 240px;
    padding : 0px;
    position : absolute;
    }
    form .btnSanta{
    margin-left :600px;
    margin-right : auto;
    background:transparent url("images/Santa-png.png") no-repeat top left;
    width : 240px;
    height: 240px;
    padding : 40px;
    position : absolute;
    }
    body {background-image:url('bg-snowflakes-3.gif');
    }
  8. The web page looks like what is shown in the following figure:Raspberry Pi Mechatronics Projects HOTSHOT

    Yay! We have a Christmas lights controller interface.

Objective complete – mini debriefing

We have written a simple web page that interfaces a Christmas tree and RGB tree and plays MP3 files. This is a great project for a holiday weekend.

It is possible to view this web page from anywhere on the Internet and turn these appliances on/off (Fans of the TV show Big Bang Theory might like this idea. A step-by-step instruction on setting it up is available at http://www.everydaylinuxuser.com/2013/06/connecting-to-raspberry-pi-from-outside.html).

Summary

In this article, we have accomplished the following:

    • Interfacing the RGB matrix
    • Interfacing AC appliances to Raspberry Pi
    • Design of a web page
    • Interfacing devices to the web page

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here