giovedì 15 maggio 2014

Control Raspberry Pi GPIO from web

WiringPi

The best way to control the GPIO interface is to use WiringPi library. See https://projects.drogon.net/raspberry-pi/wiringpi/ for installation instructions and some basic examples.

In this case I connect a LED to the GPIO 17 (pin 0 for WiringPi)
So the command to turn on the led is
gpio mode 0 out
gpio write 0 1

CGI script

Default Apache script directory  is /usr/lib/cgi-bin. Save here the scripts

ledOn.cgi
#!/bin/bash

#ledOn.cgi
#Turn on led on GPIO 17

gpio mode 0 out
gpio write 0 1
echo -e "Content-type: text/html\n\n"
echo "<h1>LED ON</h1>"


ledOff.cgi
#!/bin/bash
#ledOff.cgi
#Turn off led on GPIO 17
gpio mode 0 out
gpio write 0 0
echo -e "Content-type: text/html\n\n"
echo "<h1>LED OFF</h1>"

The echo commands are used to print HTML text on the browser.

IMPORTANT! Don't forget to make files executable:
sudo chmod +x /usr/lib/cgi-bin/ledOn.cgi
sudo chmod +x /usr/lib/cgi-bin/ledOff.cgi

Web Interface

This is the web page, with a javascript that run CGI scripts
<html>
<head>
<script>
function ledOn()
{
document.location="cgi-bin/ledOn.cgi";}
function ledOff()
{
document.location="cgi-bin/ledOff.cgi";}
</script>
</head>
<body>
<h1>GREEN LED</h1>
<button onclick="ledOn()">ON</button>
<button onclick="ledOff()">OFF</button>
</body></html>

The Result


Nessun commento:

Posta un commento