本帖最后由 zhao?J 于 2013-8-8 14:23 編輯
前面我們已經簡單地介紹了如何使用Python語言來對pcDuino的硬件進行控制編程,現在具體介紹幾個在pcDuino上的Python編程應用實例。
一、將你的pcDuino設置為web服務器
1、安裝Request(Requests 是一個 Python 的 HTTP 客戶端庫):
- $ sudo apt-get install python-requests
復制代碼
2、安裝python-pip(pip是一個可以替代easy_install的安裝和管python軟件包的工具 ) :
- $sudo apt-get install python-imaging python-imaging-tk python-pip python-dev git
復制代碼
注意:有時候運行這個指令會安裝失敗,那么需要輸入:$sudo apt-get update 后再輸入此指令。
4、 示例代碼:
- from flask import Flask
- app = Flask(__name__)
- @app.route("/")
- def hello():
- return " Welcome to pcDuino ! "
- if __name__ == "__main__":
- app.run(host='0.0.0.0', port=80, debug=True)
復制代碼
保存文件為hello-flask.py ,運行 $sudo python ./hello-flask.py
5、 輸入指令 $ifconfig 查看pcDuino的ip地址:
6、 在另外一臺與pcDuino共用同一個網絡的pc機上打開瀏覽器輸入 192.168.35 你會看到如下信息:
同時,在pcDuino的終端你會看到如圖信息:
表示有ip:192.168.1.25的客戶端在連接pcDuino服務器。
二、如何通過網頁來讀取pcDuino的GPIO狀態(tài)
1、 安裝Request(Requests 是一個 Python 的 HTTP 客戶端庫):
- $ sudo apt-get install python-requests
復制代碼
2、安裝python-pip(pip是一個可以替代easy_install的安裝和管python軟件包的工具 ) :
- $sudo apt-get install python-imaging python-imaging-tk python-pip python-dev git
復制代碼
注意:有時候運行這個指令會安裝失敗,那么需要輸入:$sudo apt-get update 后再輸入此指令。
4、 到GitHub下載“python-pcduino”這個庫文件放到 ubuntu下,打開Sample,復制“blink_led”更名為“hello-gpio”,然后在里面將
“blink_led”更名為“hello-gpio.py",”hello-gpio.py“代碼如下:
- 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/<pin>")
- 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、在文件夾”hello-gpio“的目錄下新建一個名為”templates“的文件夾,文件夾內包含2個文件:“main.html , pin.html”
main.html內容如下:
- <!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>
復制代碼
pin.html內容如下:
- <!DOCTYPE html>
- <head>
- <title>{{ title }} </title>
- </head>
- <body>
- <center>
- <h1>Pin Status </h1>
- <h2>{{ value }}</h2>
- <hr>
- <a href="http://www.">pcDuino.org</a>
- </center>
- </body>
- </html>
復制代碼
6、輸入: $sudo python ./hello-gpio.py 運行代碼:
7、查看pcduino的ip地址:$ifconfig :
8、在另外一臺與pcDuino共用同一個網絡的pc機上打開瀏覽器輸入 192.168.35 你會看到如下信息:
|