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):
- $sudo apt–get install python–imaging python–imaging–tk python–pip python–dev git
Note: Some time the above commands will fail, we need:
- $sudo apt–get update
3. Install Flask (Flask is a light weight web application framework written by Python)
- $sudo pip install flask
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 import Flask, 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’:
The content of file ‘main.html”:
01
02
03
04
05
06
07
08
09
10
11
12
|
<!DOCTYPE html> < head > < title >{{ title }} </ title > </ head > < body > < center > < h1 >Welcome to pcDuino !</ hl > < h2 >The date and time on the server is :{{ time }}</ h2 > </ center > </ body > </ html > |
The content of ‘pin.html’ is as following:
01
02
03
04
05
06
07
08
09
10
11
12
13
|
<!DOCTYPE html> < head > < title >{{ title }} </ title > </ head > < body > < center > < h1 >Pin Status </ hl > < h2 >{{ value }}</ h2 > < hr > </ center > </ body > </ html > |
6. Type “$sudo python ./hello-gpio.py” to run the code:
7. Check IP address of pcDuino using “$ifconfig”:
8. Open a web browser on a PC that shares the same network, and enter the IP address of pcDuino found in step 7:
Enter 192.168.35/readpin/0 (this is to read GPIO 0), we will see :
192.168.35/readpin/7 will read GPIO 7.
Leave a Reply
You must be logged in to post a comment.