Sunday, September 14, 2014

Python + bottle@Raspberry Pi: Web based GPIO control

This example show how to program in Python with bottle on Raspberry Pi, to implement web base GPIO control.

bottle is a Python web server library. To install bottle on Raspberry Pi, enter the command:
sudo apt-get install python-bottle

from bottle import route, run
import RPi.GPIO as GPIO

host = ''

pinButton = 17
pinLed = 18
# pin 17 as input with pull-up resistor
GPIO.setup(pinButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(pinLed, GPIO.OUT)

LedState = False

def read_button():
    if GPIO.input(pinButton):
        return 'Released'
        return 'Pressed'

def update_led():
    GPIO.output(pinLed, LedState)
def toggleLed():
    global LedState
    LedState = not LedState
def index(arg=""):
    if arg == "toggle":
    response = "<html>\n"
    response += "<body>\n"
    response += "<script>\n"
    response += "function changed()\n"
    response += "{window.location.href='/toggle'}\n"
    response += "</script>\n"
    response += "Button: " + read_button() +"\n"
    response += "<br/><br/>\n"
    response += "<input type='button' onClick='changed()' value=' LED '/>\n"
    response += "</body></html>\n"
    return response
run(host=host, port=80)

Run it:
$ sudo python

- Web control to display on Pi connected LCD Module, with Python and bottle

No comments: