Baking Pi’s 3: A Networked Rafigh

In the “Baking Pi’s” series of posts, I describe a number of projects with the Raspberry Pi that I have been doing in the last few weeks. In this post, I will describe how to make a networked Rafigh using a Raspberry Pi. I will first describe how to connect the Raspberry Pi to the physical world and how to control it over the Internet. Next, I will describe how to connect this setup to a small water pump and living mushroom colony to create a networked version of Rafigh. I will be mostly using Raspberry Pi 1 (and later also try out Raspberry Zero). The same approach can easily be used with Raspberry Pi B+ as well. I will also use a Mac computer to connect to the Pi via wifi.

Setting up and Testing the Circuit

Starting from a Pi with the latest Raspbian OS, I connect it to a simple circuit that controls an LED light. For information on how to initially set up your Pi, please see my previous post. To check GPIO lists and locations on different Raspberry Pi boards, see here and here.

So using an example described in the excellent Make book, Getting Started with Raspberry Pi by Matt Richardson and Shawn Wallace, I use a breadboard to connect a single LED using female to male jumper wires to the Pi. I connect, Pi’s Ground to the Ground bus of the breadboard and the negative leg of the LED, and the Pi’s pin 24 to the positive leg of the LED. Next, I use the following Python code to blink the LED:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.OUT)

While True:
   GPIO.output(24, GPIO.HIGH)
   time.sleep(1)
   GPIO.output(24, GPIO.LOW)
   time.sleep(1)

I save these in a file called blink.py and run it using the following command:

sudo python blink.py

You might notice that there are some warning messages when you run this code. Specifically, when you interrupt the program with a Ctrl+C you get a warning and also when running the script you get a warning about the channel being already in use. You can get ride of these warnings by putting the loop in an exception clause, like so:

while True:
   try:
      GPIO.output(24, GPIO.HIGH)
      time.sleep(1)
      GPIO.output(24, GPIO.LOW)
      time.sleep(1)
   except KeyboardInterrupt:
      GPIO.cleanup()
      exit()
Screen Shot 2016-02-10 at 7.02.59 PM

Using the Pi to turn on and off a light

Controlling the Light over the Internet

Once you can blink the LED, it’s time to control it over the Internet! Again, I’m using ideas from the excellent book, Getting Started with Raspberry Pi by Matt Richardson and Shawn Wallace. To access the Pi over the Internet, I turn it into a server and have it load a dynamic page which you can use to control the LED.

I’ll start by installing Flask which is a Python web framework and can be used to turn the Pi into a dynamic web server. The following commands should install Flask:

sudo apt-get install python-pip
sudo pip install flask

With Flask installed, I can create a dynamic web server that can interact with the GPIO pins. First, I create a directory called rafigh to put all the code in:

sudo mkdir rafigh 
cd rafigh

Here, I create a subfolder called templates that will hold the html files that can be accessed via the server. Now, we need to write the code to run the server. It will be in a file called rafigh.py:

import RPi.GPIO as GPIO
from flask import Flask, render_template, request
app = Flask(__name__)

GPIO.setmode(GPIO.BCM)

#I'm only using 1 pin (pin 25), if you use more, you can add more pins here. 
pins = {
     24 : {'name' : 'lamp', 'state' : GPIO.LOW}
     }

for pin in pins: 
   GPIO.setup(pin, GPIO.OUT)
   GPIO.output(pin, GPIO.LOW)

@app.route("/")
def main():
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)
   templateData = {
      'pins' : pins
      }
   return render_template('rafigh.html', **templateData)

@app.route("/<changePin>/<action>")
def action(changePin, action):
   changePin = int(changePin)
   deviceName = pins[changePin]['name']
   if action == "on":
      GPIO.output(changePin, GPIO.HIGH)
      message = "Turned " + deviceName + " on."
   if action == "off":
      GPIO.output(changePin, GPIO.LOW)
      message = "Turned " + deviceName + " off."
   if action == "toggle":
      GPIO.output(changePin, not GPIO.input(changePin))
      message = "Toggled " + deviceName + "."
   
   for pin in pins: 
      pins[pin]['state'] = GPIO.input(pin)

   templateData = {
      'message' : message,
      'pins' : pins
   }

   return render_template('rafigh.html', **templateData)

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

This code will run the server and provide dynamic data to the html page. Now, it’s time create the html page, rafigh.html, that will sit in the template folder:

<!DOCTYPE html>
<head>
  <title>Current Status</title>
</head>

<body>

<h1> Device Listing and Status </h1>

{% for pin in pins %}
<p>The {{ pins[pin].name }}
{% if pins[pin].state == true %}
   is currently on (<a href="/{{pin}}/off">turn off</a>)
{% else %}
   is currently off (<a href="/{{pin}}/on">turn on</a>)
{% endif %}
</p>
{% endfor %}

{% if message %}
<h2>{{ message }}</h2>
{% endif %}


</body>
</html>

Now, if you point your browser at the Pi’s address (either you Pi’s ip address, or if you are using Bonjour, rafigh.local), you will see a webpage that allows you to turn on and off the light.

Finally, we will to connect to the networked light from outside of the local network, which allows us to control the Pi from wherever we are, as long as we are connected to the Internet! There are several ways to do this including setting up port forwarding on your router or using a web-based forwarding service liked Weaved.  This service requires you to first create a free account on the Weaved website and then to download and install it on your Pi, using the following commands:

sudo apt-get install weavedconnectd
sudo weavedinstaller

Once setup, you can initiate SSH and HTTP services on Weaved and access your Pi by logging into your account on Weaved.

Finally, you want to let the Pi know to run the script at startup. To do this, follow these instructions.

Migration to Raspberry Pi Zero

Before putting everything together, I decided to make a Raspberry Pi Zero (sometimes referred to as #PiZero) version of the project. The Pi Zero is an ultra light, low-cost (~$5!) version of the Raspberry Pi and was released in late 2015. If you don’t want to use Raspberry Pi Zero, you can skip this section.

Screen Shot 2016-02-10 at 7.03.06 PM

Clockwise from bottom right: Raspberry Pi zero, a 2×20 Male header strip, a 3D printed case, a USB OTG Cable and a Wifi dongle

To prepare the Pi Zero, I first soldered a 2×20 Male header strip to the Pi and then 3D printed an enclosure for it so that I don’t accidentally break it! With all these in place, I  cloned the SD card that I had set up in the previous steps, using the  dd command. I placed the prepared SD card in the card reader. Then, I found the SD card disk number (disk 2) by using diskutil list. Finally, I copied the the contents of the disk into an image file on the Mac machine:

sudo dd if=/dev/disk1 of=~/Desktop/2016-2-9-rafigh.dmg 

This took a while and I checked the command’s progress using Ctrl+t. Once the image was created, I copied it to a fresh SD card. Again, I placed the new card in the reader, found out what its disk number was using diskutil list (in my case it was in disk3). Next, I unmounted it:

diskutil unmountDisk /dev/disk3

Finally, I copied the image to the SD card:

sudo dd if=~/Desktop/2016-2-9-rafigh.dmg of=/dev/disk3

Again, this might take a while and you can check the progress using Ctrl+t. Once this is done, I plugged the new SD card into the Pi Zero, attached a USB OTG Cable to one of the usb ports (this allowed me to connect a wifi dongle to the Pi). Finally, I connected the Pi Zero’s GPIO pins to the circuit (Pi Zero has the same GPIO pin layout at Raspberry Pi B+ and A+) and powered up the Pi.

Screen Shot 2016-02-10 at 7.03.16 PM

Assembled Pi Zero

Once the Pi Zero is booted up, I could SSH into it, start the server and control the light as before. Voila!

Screen Shot 2016-02-11 at 1.53.12 PM.png

Off/On

If you are using Bonjour service, it might be a good idea to change the host name by following the steps here.

A Networked Light: Putting Things Together

Now, we have all the pieces together and can replace the LED light with a Powerswitch Tail 2 that can control any small AC-powered device, like a lamp or water pump.

To do this, I connect (directly or via a breadboard) the “+in” pin of the power switch to Pin 24 of the Pi and the “-in” pin to the Ground. Next, I connect (directly or via a breadboard) the power switch to a wall plug and a lamp and test by booting up the Pi and navigating to the Pi’s local address (e.g., rafigh.local or rafighzero.local) on my browser. This allowed me to turn on and off the current from my computer.

With the weaved service setup, I was able to connect to the network remotely (over the Internet rather than the local wifi network) and control the light. Next, I will describe how to connect this setup to a small water pump and a living mushroom colony to create a networked Rafigh.

A Networked Rafigh

With all the pieces assembled above, we can now create a networked Rafigh that can be controlled remotely. Rafigh is a digital living media system that can be used to motivate children to  conduct desirable activities such as using learning and therapeutic digital applications. For more information on Rafigh, see this previous post.

20150130_133533

Rafigh

To create the networked Rafigh, we need to replace the lamp with a small water pump. I have been using the Tom Aquarium Aqua Lister Pump, which I would recommend for its low power pressure (which you need, in order not to flood the mushrooms!). Next, I connect a small water container to the input valve of the water pump and connect the output valve to the mushroom colony (I’ve been using Fungaea’s The ShroomBox) using a water tube. All the electronics and the mushroom colony are placed in the custom made Rafigh enclosure.

With the system powered up, I can access the Pi remotely via my weaved account. From here, I can either activate the water pump using the dynamic website created above.

Before ending this post, I will also briefly describe how to schedule watering times using the existing setup and Linux’s crontab. First, we need to create a simple script to turn on and off the pump from the command line. I create a file called turnPumpOn.sh:

#!/bin/bash
echo Exporting pin 24.
echo 24 > /sys/class/gpio/export
echo Setting direction to out.
echo out > /sys/class/gpio/gpio24/export
echo Turning on the pump.
echo 1 > /sys/class/gpio24/value

I also create another file called turnPumpOff.sh:

#!/bin/bash
echo Turning off the pump.
echo 0 > /sys/class/gpio24/value
echo Unexporting pin 24
echo 24 > /sys/class/gpio/unexport

I put both of these files in the same rafigh directory that I created for the project before. This helps makes things organized. I make both files executable using chmod:

chmod +x turnPumpOn.sh
chmod +x turnPumpOff.sh

Now, I can turn on and off the pump using the command:

./turnPumpOn.sh
./turnPumpOff.sh

With these two scripts in place, we can schedule specific times for the pump to be turned on and off by editing the crontab file, using the following command:

crontab -e

For example, to turn the pump on for 2 minutes everyday at 7pm, we can add the following two lines to the bottom of the file:

0 19 * * * /home/pi/rafigh/turnPumpOn.sh

2 19 * * * /home/pi/rafigh/turnPumpOff.sh

For details on how to schedule tasks in the crontab file, follow this link.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s