做過一些物聯網的作品;因為不想一直做APP來控制,因為不能每個人都去下載你自己做的APP,瀏覽器大家都是有的;那么每個人通過瀏覽器WEB來訪問我們服務器,豈不是很簡單和方便,采用flask+python。
Flask是一個使用 Python 編寫的輕量級 Web 應用框架,操作簡單,上手容易。
安裝FLask:
sudo apt-get install python-pip
sudo pip install flask
然后一個簡單的服務器就安裝好了,都存在我們的樹莓派下,估計大家要寫幾個程序,那么:
mkdir flask && cd flask
mkdir read_gpio && cd read_gpio
sudo nano hello-gpio.py
from flask import Flask, render_template import datetime#導入系統時間 import RPi.GPIO as GPIO #導入GPIO app = Flask(__name__) GPIO.setmode(GPIO.BCM)#設置GPIO模式為BCM @app.route("/") def readPin(): now = datetime.datetime.now()#抓取時間 timeString = now.strftime("%Y-%m-%d %H:%M:%S")#抓取系統時間函數到timeString try: GPIO.setup(20, GPIO.IN)#讀取BCM_gpio_20 if GPIO.input(20) == True: response = "BCM_gpio_20 is high!" else: response = "BCM_gpio_20 is low!" except: response = "There was an error reading pin" templateData = { 'time': timeString 'title' : 'Status of Pin' + pin, 'response' : response } return render_template('read_pin.html', **templateData)#把templates送到read_pin.html if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True)
sudo nano read_pin.html
<!DOCTYPE html> <head> <title>{{ title }}</title> </head> <body> <h1>Pin Status</h1> <h2>{{ response }}</h2> <h2>{{ time }}</h2> </body> </html>
注意:html文件要在.py同行目錄下新建子目錄文件夾templates,不然找不到template會報錯;
格式如下:
read_gpio(文件夾)--
---hello-gpio.py
---templates(文件夾)
---read_pin.html
然后一個讀取GPIO狀態的就建好了,我們讀的是BCM_gpio_20,可以修改;
然后在瀏覽器訪問你樹莓派的IP地址 ifconfig
在你的不管手機還是Pc只要和你的樹莓派在同一局域網下都可以訪問你的網頁;讀取樹莓派系統時間和GPIO狀態。game_over,看一下狀態。
最后再說一點吧:可能大家也想不能實時觀看我們的網頁,只是一個網頁狀態;可以不停點刷新網頁去get數據,不太人性化,那么就設置網頁刷新時間就好了;根據瀏覽器來選擇,博主用的火狐。在樹莓派上名字是iceweasel
安裝方式是sudo apt-get install iceweasel;
安裝好后;然后選擇插件 Reladevery 安裝; 重啟瀏覽器;在你想要的網頁右擊 relad_every 自定時間,最短一秒,看到讀取效果還可以。科科
下篇介紹網頁控制GPIO