Day 5

Web server

Concepts

Things to do to allow apache to connect to gpio:

  1. Add www-data to the gpio group in /etc/groups
  2. Enable apache 2 to run cgi
  3. Restart apache2

An example:

CGI - explanation

This will flash the LED connected to pin 16 5 times.  Then display Flash.

<html>
<head>
<title>This is a form</title>
</head>
<body>
<h1>I'm a form.</h1>
Enter times to blink 1 - 10 and delay 1 - 3:<br>
<form action="cgi-bin/blinkNum.py" method="post">
How many times do you want to blink <input type="text" name="number"><br>
How long do you want to delay between blinks <input type="text" name="delay"><br>
<input type="submit">
</form>
</body>
</html>

  • Python - collecting form variables

  • # Build dictionary of post inputs.
    import sys
    POST = {}
    # Split each input parameter on ampersand.
    args = sys.stdin.read().split('&')
    for arg in args:
        # split the name value pairs and add them to the POST dictionary
        inp = arg.split('=')
        POST[inp[0]] = inp[1]

    #! /usr/bin/python

    # Flash a LED
    # Import the libraries we need
    import RPi.GPIO as GPIO
    import time

    # Build dictionary of post inputs.
    import sys
    POST = {}
    # Split each input parameter on ampersand.
    args = sys.stdin.read().split('&')
    for arg in args:
        # split the name value pairs and add them to the POST dictionary
        inp = arg.split('=')
        POST[inp[0]] = inp[1]


    #Get the post information and convert to integer
    number = int(POST['number'])
    delay = int(POST['delay'])

    # Check if the input is OK.
    if number <= 0 or number > 10 or delay < 1 or delay > 3:
        print ("Content-Type: text/html\n\n")
        print ("<html><body><h1>Oops!</h1></body></html>")

        # This print for debugging.  Take it out when working    
        print (POST) 
        sys.exit()

    # Send out the http header info etc.

    print ("Content-Type: text/html\n\n")
    print ("<html><body><h1>Flash</h1></body></html>")

    # Set the pin mode to Broadcom mode this time.
    GPIO.setmode(GPIO.BCM)
    pin = 16

    # Set the pin to be an output
    GPIO.setup(pin, GPIO.OUT)

    i=0

    # Loop turning it on and off
    while i < number:
        GPIO.output(pin, 1)
        time.sleep(delay)
        GPIO.output(pin, 0)
        time.sleep(delay)
        i = i + 1

    # Set the pins back to default
    GPIO.cleanup()

    Log Files of interest:


    Your Turn
      Then if time permits:

    You may be tempted to open up your Pi to the World.  Don't!  Not yet.

    Tools


    Victoria Pi Makers and Others.  Who are we?