物聯網基本功能就是透過Web介面進行遠端控制,以樹莓派來說就是使用Web介面來進行GPIO控制

材料:
1.LED紅色1、LED綠色1
2.220Ω2
3.麵包版1
4.跳線2
5.杜邦線3
紅色LED連接GPIO18,綠色LED連接GPIO23

from bottle import route, run
from gpiozero import LED
leds = [LED(18), LED(23)]
states = [False, False]
def update_leds():
    for i, value in enumerate(states):
        if value == True:
            leds[i].on()
        else:
            leds[i].off()   
			
@route('/')
def index():
    return html()
    
@route('/<led>')
def toggle(led):
    if led >= '0' and led <='1':
        pos = int(led)
        states[pos] = not states[pos]
        update_leds()
    return html()
    
def html():
    res = "<script>"
    res += "function changed(led) {"
    res += "    window.location.href='/' + led"  
    res += "}"
    res += "</script>"
    res += "<h1>Web Interface GPIO Control</h1>"
    res += "<h2>LED 0: " + str(states[0]) + "</h2>"
    res += "<h2>LED 1: " + str(states[1]) + "</h2>"
    res += "<input type='button' onClick='changed(0)'"
    res += " value='LED 0'/> | "
    res += "<input type='button' onClick='changed(1)'"
    res += " value='LED 1'/>"
    return res
run(host='0.0.0.0', port=8080)
程式解說:
第2行:匯入GPIO ZERO模組的LED
第4.5行:建立兩個清單,ststes持存LED狀態
第7行:update_led()函數依據states更新兩個LED
,8-12行的for迴圈依序取出兩個LED燈
第9-12行:if/else判斷是否點亮、熄滅
第14-16行:index()函數傳回html()函數的HTML標籤字串
//Python(@)符號表是可以將函數作為參數來呼叫//
第18-24行:toggle()函數定義/,if判斷0或是1
第26-39行:html()函數建立回應的HTML網頁內容
第41行:以IP位置還有8080port來啟動Web伺服器
打開瀏覽器輸入:http://0.0.0.0:8080/便會出現以下畫面,True表示點亮,False表示熄滅
實作網址(https://www.youtube.com/watch?v=XHCKUV5wGSs)
結語:進入了樹莓派的應用物聯網了,現在還是很淺慢慢地加深如有錯誤請各位大大提出,小弟我立馬會及時修正萬分感謝