Accessing GPIO from a web server

After successfully accessing the GPIO pins from the command line, my next goal was to read and write pin values from a web site. The first step is to install a web server, and the obvious choice would normally be Apache, but with the Raspberry Pi being limited in CPU and memory resources, I decided to check out lighty (lighttpd) as it has a small memory footprint. Installation is reasonably easy:

sudo groupadd www-data
sudo adduser www-data www-data
sudo usermod -a -G www-data www-data
sudo chown -R www-data:www-data /var/www
sudo apt-get install lighttpd

The first four steps might not be necessary on  distributions more recent than Debian “Squeeze”, but for me, the installation failed with an error that user “www-data” doesn’t exist. Web files can now be placed in “/var/www”. At this point it’s time to decide on a server side programming language, my initial thoughts were PHP or Python. As Python is the “official” language of the Raspberry Pi, I decided to go with that.

To get Python to work with lighttpd, you need to enable CGI:

Open the lighttpd configuration file (/etc/lighttpd/lighttpd.conf), and uncomment the “mod_cgi” line (remove the # from the beginning of the line if one exists) or add this line if not present.

server.modules = (
            ...
            ...
            "mod_cgi",
)

Add the following to the bottom of the file:
$HTTP["url"] =~ "^/cgi-bin/" {
        cgi.assign = ( ".py" => "/usr/bin/python" )
}Restart the lighttpd daemon:

sudo service lighttpd force-reload

We can now create python files in the /var/www/cgi-bin/ directory. As it’s a bad idea to run a web server as a root, you need to access the GPIO from a non-root account. In order to do this, I used the “gpio” program from the WiringPi package. I created a “ReadGpio” function that looks like this:

# Read the GPIO pin using the gpio application

import subprocess as s

def ReadGpio(pin) :
process = s.Popen([“/usr/local/bin/gpio”, “-g”, “read”, pin], stdout = s.PIPE)
data, _ = process.communicate()

data = str.replace(data, “\r”, “”)
data = str.replace(data, “\n”, “”)

return data

Now that I’ve got GPIO integrated with a web server, I’m going to start looking at a Python web framework, as typing “print ‘<open bracket>Something</close bracket>'” gets a bit tedious :).

This entry was posted in GPIO, Hardware, LEDs, Raspberry Pi. Bookmark the permalink.

3 Responses to Accessing GPIO from a web server

  1. Pingback: Raspberry Pi Prank Tutorial – Making Your Co-Worker’s Desk “Magically” Go Up and Down | Lasse Christiansen Development

  2. Mike Alport says:

    Hi Mark,
    I endorse your choice of lighttpd, python and wiringpi, so was interested to hear which web framework you had chosen?
    I have looked at a few but couldn’t decide which was the best for Pi.
    Mike

Leave a comment