How to Read/Control GPIO (turn on/off LED) on web page using Python

In this tutorial, we will create a web server on pcDuino using Python. We can then control/read GPIOs on pcDuino through the webpage. This is a prefect implementation of web lamp or any web powered devices.

1. Install Requests (Requests is a HTTP client library of Python):

$ sudo apt–get install python–requests

2. Install python-pip (pip is the tool used to install and manage python software packages):

4. Download python-pcduino from github, and put it under /home/ubuntu. Enter into directory Sample, and copy directory blink_led to a directory named hellp-gpio, and rename the file blink_led.py there to hello-gpio.py.

The code of hello-gpio.py is as following:

from flask importFlask, render_template

import datetime

import gpio

app =Flask(__name__)

channel ={0:‘gpio0’,1:‘gpio1’,2:‘gpio2’,3:‘gpio3’,4:‘gpio4’,

5:‘gpio5’,6:‘gpio6’,7:‘gpio7’,8:‘gpio8’,9:‘gpio9’,

10:‘gpio10’,11:‘gpio11’,12:‘gpio12’,13:‘gpio13’

}

@app.route(“/”)

def hello():

now = datetime.datetime.now()

timeString = now.strftime(“%Y/%m/%d %H:%M:%S”)

templateData ={

‘title’:‘HELLO!’,

‘time’:timeString

}

return render_template(‘main.html’,**templateData)

@app.route(“/readpin/”)

def readPin(pin):

gpio.pinMode(channel[int(pin)],gpio.INPUT)

value =” “

if(gpio.digitalRead(channel[int(pin)])== gpio.HIGH):

value =“Read GPIO”+ pin +” is high !”

else:

value =“Read GPIO”+ pin +” is low !”

templateData ={

‘title’:‘Status of GPIO’+ pin ,

‘value’: value

}

return render_template(‘pin.html’,**templateData)

if __name__ ==“__main__”:

app.run (host=‘0.0.0.0’,port=80,debug=True)

5. Create a directory named templates under directory hello-gpio, and create two files there “main.html” and “pin.html’: