The Python code to turn the relays on and off

The Raspberry Pi Python code for the light project

We need python code on the web Server side to fire the local relays and also to let the slave side know to turn its lights on or off. The following code files do this work. you could choose any GPIO output pin to control the relays, and choose any unassigned port for your socket connections, but this gives you a working framework.

This Python script, placed in /var/www/cgi-bin turns the relays off. This Python program is called directly from the WebServer when a user selects the Lights Off button on the web page. It needs to fire the local relays and also let the slave Pi know to take action.

This Python script, placed in /var/www/cgi-bin turns the relays on. This files is similar to the one above with the exception that it is turning the lights on.

This Python script, started at boot up turns the slave Pi relays on. This python program needs to be running in the background on the slave Pi, always waiting for a socket connection on a specific port. When it sees a connection on that port, it turns the local lights on and then closes the connection. The port numbers could be any unassigned port. By using the convention of one port number being assigned for lights on, and one for lights off, you have two very similar programs running, the second one, which turns the lights off is shown below.

This Python script, started on boot up, turns the slave Pi relays off.

You can easily run programs at start up by adding lines to the /etc/rc.local file (edit it as sudo). An example line to add would be:

sudo python /home/pi/projects/ &

If you wanted to run in the background. Since we are using GPIO pins, we have to run as SUDO, but later versions of the OS may remove this restriction.

The "slave" pi, 101 in my example, just runs 4 background programs, all in the "production" directory, and all started with rc.local. One just blinks some lights in a circular fashion, one watches for the local switch, and the other two listen for an on or off command for the local flood light.

The master Pi is running a background program to watch for it's local switch, started at boot time (using rc.local), and then the web server which has a home page waiting for "button" inputs, either from a regular web client or from one of the python scripts. These buttons then trigger the local python code to turn lights on or off (in the cgi_bin directory), and these python programs also create a socket connection to the slave pi to control it's light.