Being Green With Your Raspberry Pi and Python

Being green is never easy, but perhaps a Raspberry Pi can help us cut down on our carbon emissions and save the polar bears.

Why do this?

  • This is a great cross-curricular exercise for schools
  • Learn Python
  • Learn to use the Energenie wireless socket controller
  • Learn a little Minecraft hacking
  • Build a GUI in Python
  • Learn to work with sensors in Python

Tools required:

  • A Raspberry Pi Model Pi 2 or B+
  • An Energenie
  • For project 1 – A mobile phone charger
  • For project 2 and 3 a lamp
  • For project 3 a breadboard, 2 female to male jumper leads and 1 momentary switch
  • Python 2 installed on your machine

Electricity is something that we take for granted: we just turn it on and off, and only really think about how much we’re using when the bill arrives. In this tutorial we will use a device called Energenie to wirelessly connect our Raspberry Pi to a wall socket and control devices attached to it. We will conduct three projects to interface with the Energenie.

  • Project 1 Mobile phone charging station
  • Project 2 Minecraft user interface
  • Project 3 Remote control switch

Each of the projects can be completed in a one-hour computing lesson with time for class to explore possibilities of expanding the projects to meet their needs in the curriculum. These projects can be enhanced with cross-curricular activities.

Project 1 – mobile phone charging station

Image

The Energenie is a brilliant gadget, available for £20 from https://energenie4u.co.uk/index.phpcatalogue/product/ENER002-2PI.

Typically we leave our phone on charge overnight, but that really isn’t an energy-efficient solution. In this project we’ll use the Energenie power outlet and matching Raspberry Pi add-on to create a timed charging station. We will use a graphical user interface (GUI) using the EasyGUI library. Connect your Raspberry Pi as normal and gently insert the Energenie add-on onto the GPIO (General Purpose Input Output). It will fit over the first 26 pins from the SD card and it will overlap with the Raspberry Pi. With the board fitted, insert the power and boot your Raspberry Pi to the desktop.

We’ll be using EasyGUI to create an interface for our project, but it is not installed as standard so to install this library open a terminal and type the following followed by Enter.

sudo apt-get install python-easygui

We also need to install the Energenie library; helpfully Ben Nuttall from the Raspberry Pi Foundation has already created a handy package for us to install. You can find Ben’s code at https://github.com/bennuttall/energenie. In the terminal enter the following lines of code and press Enter after each line.

sudo apt-get install python-pip sudo pip install energenie

With that installed, keep the terminal open and type sudo idle to launch the Idle editor. We need to do this so that we can access the GPIO, as only a user with root privileges can use the GPIO.

Image

Careful when fitting the Energenie add-on to the Pi: GPIO pins can bend.

So let’s start coding!

In Idle, open a new file by going to File > New. I like to import the libraries necessary at the top of the script, as this means I only have one place to look for problems when I’m debugging the code.

from energenie import switch_on, switch_off from time import sleep import easygui as eg

Our first import brings two functions from the energenie library into our code, switch_on and switch_off (I think you can guess what they do). Our second import sees us bring the sleep function into our code; we will use this to time how long the charging station will operate. Our last import sees us import the easygui library and rename it to eg for easier use.

Next we shall create a function called timer. A function enables us to group a section of code under one name and then call the function by its name and have all of the code run in sequence, similar to a macro in office applications.

def timer():

You will see at the end of the line that there is a colon :, which instructs Python that this is the end of declaring the functions name and that the next lines will be the code that is contained therein.

t = float(eg.enterbox(title="Linux Voice Phone Charging?", msg="How long shall I charge your phone for (in minutes)?"))

Our first line of code for the function sees us create a variable called t, and in there we store the answer to the question “How long shall I charge your phone for?” We capture this using an enterbox from EasyGUI. This is a dialog box that can ask a question to the user and capture the answer. We give the dialog box a title and a message msg to the user to give us an answer in minutes. You will see that this is wrapped in a float function; this converts the answer given to a float value (a value that can have a decimal place).

t = t * 60

Our next line of code performs a little maths. We take the current value of t and then multiply it by 60 to give us the time in minutes but counted as seconds, so two minutes is 120 seconds.

switch_on() sleep(t) switch_off()

The next three lines of code turn on the Energenie unit, then it waits for the value of t before switching the unit off, and thus our phone stops charging. This is the end of the function, so now let’s look at the main body of code.

while True:

We start with an infinite loop (in Scratch this is called a forever loop), and this loop will go round and round until we break the loop or turn off the Raspberry Pi.

choice = eg.choicebox(title="Linux Voice Phone Charging",msg="Would you like to charge your phone?", choices=("Yes","No"))

The next line handles asking the user if they would like to charge their phone, and we use another dialog box from EasyGUI, this time the choicebox, which uses the same title and msg syntax as the enterbox, but you can see an extra value of choices that will appear as menu items in the dialog box.

Now we start a conditional statement, and it works like this.

If the value of choice is NOT equal to “No”

Then run the function called timer()

if choice != "No": timer() else: print("All off") switch_off() break

Our last section of code handles the user selecting not to charge their phone. It prints All off to the shell and then makes sure that the Energenie unit is turned off before finally breaking the infinite loop and stopping the application.

So that’s the code – now make sure that your mobile phone is plugged into its charger and that is plugged into the Energenie.

Run the code by going to Run > Run Module. Answer the questions correctly and you should see your phone charging. If for some reason nothing happens, press and hold the green button of your Energenie for five seconds and then run the script again. We’ve taken our first step to saving the planet!

Image

Our finished phone charger application isn’t pretty, but it will save you electricity.

Wireless communication

Connecting to a Raspberry Pi remotely can be accomplished in many different ways. To remotely control your Raspberry Pi on the command line (often called “Headless” mode) you can set up an SSH server on your Pi. In a terminal type sudo raspi-config and choose the SSH option from the Advanced menu.

To control your Pi over a network and use your mouse and screen there is a technology called VNC that can send the video from your Pi down a network. Head over to http://elinux.org/RPi_VNC_Server for more information. Please note that Minecraft does not work with VNC.

It’s also possible to connect to your Pi over radio using the Slice of Radio gadget from electronics vendor Ciseco and an SRF dongle from the Ciseco store: http://shop.ciseco.co.uk/raspberry-pi. This can have a range of many hundreds of metres, depending on line of sight.

The Energenie uses 433MHz transmitters to send a signal over radio from your Pi to the unit. 433MHz units can be found on eBay for a few pounds.

You could also set up a direct cable connection between your Raspberry Pi and computer via a cheap Ethernet cable. When used with SSH and VNC this enables you to use your Pi anywhere. Take a look at this great resource: https://pihw.wordpress.com/guides/direct-network-connection for a guide on how to use it.

Project 2 – Minecraft controlled lights

We’re going to use Minecraft to create an interface based on our player’s location. Specifically, we’re going to use the game to make a light come on in the real world. Open LXTerminal and type

sudo idle

Open a new file in Idle File > New.

Just like Project 1 we shall start our code with importing the libraries that enable us to do more with Python.

from mcpi import minecraft from energenie import switch_on, switch_off from time import sleep

Our first import is the Minecraft library, which contains all of the functions that we will need to interface with a running Minecraft game. Our next import handles the Energenie interface, and finally we import the sleep function from the time library. In this tutorial we do not use it, but it can be used as an extension activity in class or at home.

mc = minecraft.Minecraft.create() Image

As of December 2014 Raspbian comes with Minecraft installed as standard. If your version is older then you will need to update your distro.

Next we create a variable called mc, and in there we store a connection to the Minecraft game running. By prefacing any of our functions with mc we instruct Python to replace mc with the full text.

while True:

We start the main body of code with an infinite loop (again, in Scratch this is called a forever loop), and this loop will go round and round until we break the loop or turn off the Raspberry Pi.

pos = mc.player.getTilePos()

In order to constantly search for the player’s location we create a variable called pos, in which we store the player’s position in the Minecraft world. This is an X Y Z coordinate system based on blocks being 1 metre cubed. The getTilePos function rounds up our position so this gives us a coarse location, but one that is easier to work with.

if pos.x == -7.0:

Now we use an if statement to compare the location of Steve, our character in Minecraft, with a hard-coded value of -7.0 (this was a position near to where the game dropped me off at the start of the game). If this condition is true, then the following code is executed, turning on the lamp in the real world.

mc.postToChat("Light On") switch_on()

PostToChat is a method of sending text to users in a game, in this case us. We then call the switch_on function from Energenie to turn on the lamp attached to the unit.

else: switch_off()

Finally, we set the condition to say that when we are not at the coordinates, turn the lamp off.

So that is the code complete. Before you run it, open Minecraft and start a new world. You can find Minecraft in the Games menu. Once it has loaded, switch back to Idle, release the mouse with the Tab key, and run the code using Run > Run Module.

Plug a lamp into your Energenie and make sure it is set to come on if it has a switch. Move Steve to the -7.0 coordinate (you can see your current position in the top-left of the screen). Once you find the right square the lamp will light up.

If you’re having a little difficulty finding the square, edit this line

if pos.x == -7.0:

To read

if pos.y > 5.0:

Save and run the code again. Now in Minecraft double-tap the Space bar to fly and then hold on to it for a few seconds. Steve will fly into the air and your light will come on.

Project 3 – push-button lamp

Image

The low voltages in the Pi mean you’re safe when connecting components, but do be careful to avoid short circuits.

For our final project we will use a few cheap electronic components to create a simple remote switch to turn on the lamp. Physical computing is a great way for classes to understand the links between the real and virtual worlds. In this project we use a simple push button as our input, but we could use other types of inputs such as sensors.

To start the project you should have already set up your Raspberry Pi as per the instructions in Project 1.

Open LXTerminal and type sudo idle to start the Idle editor, then open a new file.

Just like the previous projects, we shall start our code with importing the libraries that enable us to do more with Python.

import RPi.GPIO as GPIO from time import sleep from energenie import switch_on, switch_off

We start our imports with RPi.GPIO, the library that enables Python to talk to the GPIO pins. We rename the library to GPIO, as it is easier to type.

The next two imports we have already used in the previous projects.

In order for us to use the GPIO pins we need to instruct Python as to how they are laid out. The Raspberry Pi has two pin layouts: BOARD and BCM.

BOARD relates to the physical layout on the board, with odd numbered pins on the left, and even on the right. Pin 1 is the top-left pin nearest the micro SD card slot.

BCM is short for Broadcom (the company that makes the Pi’s System-on-Chip (SoC)). This layout appears random, but the pins are labelled according to their internal reference on the SoC, which controls the Pi. BCM is considered the standard by the Raspberry Pi Foundation.

GPIO.setmode(GPIO.BCM)

In the next step we instruct Python that pin 26 is an input (GPIO.IN) and that it’s starting state should pulled high, in other words power is going to the pin.

GPIO.setup(26, GPIO.IN, GPIO.PUD_UP)

The next two lines of code handle resetting the light connected to our Energenie so that it starts in an off state. We then create a variable called status that stores the value off. We will use this to toggle the light.

switch_off() status = "off"

We start the main body of code with an infinite loop and this loop will go round and round until we break the loop or turn off the Raspberry Pi.

while True:

In this line of code we instruct Python to wait for the button press as this will cause pin 26 to go from a high to low state, in other words the power will flow from pin 26 to Ground causing a change of state on the pin.

GPIO.wait_for_edge(26, GPIO.FALLING)

When this happens the next line of code is executed

switch_on() status = "on" sleep(0.5)

As before, switch_on will trigger the lamp to turn on, and the next line changes the value of our status variable to on. We shall use this value in a moment. The last line for this section instructs Python to wait for half a second.

if status == "on":

So now we have an if condition that compares the value of the variable status with the hard-coded value on, and if the condition evaluates as True then the last four lines of code are executed.

GPIO.wait_for_edge(26, GPIO.FALLING) switch_off() status = "off" sleep(0.5)

So our light is on and the value of the status variable is on. This triggers Python to wait for another button press to occur, and when it happens it will turn off the light, change the status variable’s value to off and then wait for half a second before the loop starts again and waits for our button press once again.

That’s all the code completed. Save your work, but before running the code you’ll need to attach your button as per the photo above.

When ready, run the code using Run > Run Module and press the button on your breadboard. It should light up the lamp. Now go forth and build!

Image

Renaming modules when you import them can save a lot of tricky typing later on the code.

Code for this project

All of the code for this project is housed in a GitHub repository. GitHub uses the Git version control framework to enable you to work on your code and then push it to the cloud; changes made on your machine can be pushed when ready, updating the code in the cloud. Others can “fork” your code and work on “branches” for example creating new features. These are then submitted to you for approval and when ready you can merge them with the main branch.

You can download the code for this project from
https://github.com/lesp/LinuxVoice_Issue15_Education if you are a Github user, if not you can download a ZIP archive containing all of the files used from https://github.com/lesp/LinuxVoice_Issue15_Education/archive/master.zip.

Les Pounder divides his time between tinkering with hardware and travelling the United Kingdom training teachers in the new IT curriculum.