標籤:gpio 連網 注意 jpg templates cep rpi.gpio bug strftime
做過一些物聯網的作品;因為不想一直做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_templateimport datetime#匯入系統時間import RPi.GPIO as GPIO #匯入GPIOapp = 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")#抓取系統時間函數到timeStringtry: 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.htmlif __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資料,不太人性化,那麼就設定網頁重新整理時間就好了;根據瀏覽器來選擇,博主用的Firefox。在樹莓派上名字是iceweasel
安裝方式是sudo apt-get install iceweasel;
安裝好後;然後選擇外掛程式 Reladevery 安裝; 重啟瀏覽器;在你想要的網頁右擊 relad_every 自定時間,最短一秒,看到讀取效果還可以。科科
下篇介紹網頁控制GPIO
樹莓派安裝FLASK服務;並在端網頁讀取 GPIO狀態和系統時間