iT邦幫忙

2024 iThome 鐵人賽

DAY 27
1
Python

使用 WiFiBoy Python 玩學機來學物聯網應用 系列 第 27

27. 透過網頁來控制玩學機

  • 分享至 

  • xImage
  •  

網頁傳入指令控制 LED 燈開關、播放音樂與顯示圖片

步驟 1: 設定無線網路連線

import network

def connect(ssid, password):
    station = network.WLAN(network.STA_IF)
    station.active(True)
    station.connect(ssid, password)
    
    while not station.isconnected():
        pass

    print('WiFi 連接成功')
    print('IP 設定:', station.ifconfig())
    return station

步驟 2: 設定網頁伺服器

# 簡單WebServer 程式
import socket
from machine import Pin, PWM
import wifi
from time import sleep

# 設定 WiFi 連線參數
SSID = '您家無線網路的 SSID'
PASSWORD = '您家無線網路的密碼'

# 設定 LED 與蜂鳴器
led = Pin(16, Pin.OUT)

snd_PinB = Pin(25, 2)
buzzer = PWM(snd_PinB)
def play(freq, t):
    buzzer.duty(80)
    buzzer.freq(freq)
    sleep(t)
    buzzer.duty(0)

# 設定控制程式
def handle_request(request):
    if 'led_on' in request:
        led.value(0)
        return '開啟內建 LED! '
    elif 'led_off' in request:
        led.value(1)
        return '關閉內建 LED!'
    elif 'play' in request:
        Pin(17, 2).value(1)
        play(740, 1)  # 播放高音fa (740Hz)
        return '播放聲音!'
    elif 'show_Pic' in request:
        f = open('/JPG/比熊.bin', "rb")
        data = bytearray(f.read())
        wb.showbuf(data) # 顯示內建圖檔
        return '圖片已顯示在玩學機螢幕!'
    else:
        return 'Invalid command'


# 連接 WiFi
station = wifi.connect(SSID, PASSWORD)

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

print('伺服器啟動,等待連接...')

while True:
    cl, addr = s.accept()
    print('客戶端連接來自', addr)
    
    # 接收 HTTP 請求
    request = cl.recv(1024)
    print('請求內容:', request)
    
    response = handle_request(request)
    cl.send('HTTP/1.1 200 OK\r\n')
    cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
    cl.send('<!DOCTYPE html><html lang="zh"><html><meta charset="UTF-8"><body><h1>' + response + '</h1></body></html>')
    
    # 關閉連接
    cl.close()

步驟三: 程式測試

本例的測試 IP 為: 192.168.1.106

  1. 輸入 192.168.1.106/?led_on 玩學機應該會開啟內建的 LED 燈。
  2. 輸入 192.168.1.106/?led_off 玩學機應該會關閉內建的 LED 燈。
  3. 輸入 192.168.1.106/?play 玩學機應該會播放高音 Fa。
  4. 輸入 192.168.1.106/?show_Pic 玩學機應該開啟內建的比熊圖檔。

透過網頁上按鈕元件來控制玩學機

步驟 1: 設定無線網路連線

使用之前的 wifi.py 即可

步驟 2: 設定網頁伺服器

from machine import Pin
import network
import socket
import time
import wifi

# 定義內建 LED 與 LCD 背光腳位
LED = Pin(16, Pin.OUT)
SCREEN = Pin(27, Pin.OUT)

# 設定初始值
LED.value(1)  # OFF
SCREEN.value(0)  # OFF

LED_state = "內建 LED 目前是關閉狀態"
SCREEN_state = "螢幕背光 目前是關閉狀態"

# 設定 WiFi 連線參數
SSID = 'DoraHome300M'
PASSWORD = '0975393503@'

wlan = network.WLAN(network.STA_IF)

# 連接 WiFi
station = wifi.connect(SSID, PASSWORD)

#HTML + CSS for webpage
html = """<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>玩學機網頁控制程式</title>
  <style>
    html {
      font-family: Arial;
      display: inline-block;
      margin: 0px auto;
      text-align: center;
    }
    
    h1 {
      font-family: Arial;
      color: #2551cc;
    }
    
    .button1,
    .button2 {
      -webkit-border-radius: 10;
      -moz-border-radius: 10;
      border-radius: 10px;
      font-family: Arial;
      color: #ffffff;
      font-size: 30px;
      padding: 10px 20px 10px 20px;
      text-decoration: none;
      display: inline-block;
      margin: 5px;
    }
    
    .button1 {
      background: #339966;
    }
    
    .button2 {
      background: #000000;
    }
  </style>
</head>

<body>
  <h1>玩學機網頁控制程式</h1>
  <p>%s</p>
  <p>
    <a href="/LED/on"><button class="button1">內建 LED 開啟</button></a>
    <a href="/LED/off"><button class="button2">內建 LED 關閉</button></a>
  </p>
  <p>%s</p>
  <p>
    <a href="/SCREEN/on"><button class="button1">LCD 螢幕背光 開啟</button></a>
    <a href="/SCREEN/off"><button class="button2">LCD 螢幕背光 關閉</button></a>
  </p>
</body>
</html>
"""

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setblocking(0)
s.bind(addr)
s.listen(1)

print('listening on', addr)

while True:
    if wlan.isconnected():
        try:
            cl, addr = s.accept()
            print('client connected from', addr)
            request = cl.recv(1024)
            print(request)

            request = str(request)
            # 判斷請求中的特定指令
            LED_on = '/LED/on' in request
            LED_off = '/LED/off' in request
            SCREEN_on = '/SCREEN/on' in request
            SCREEN_off = '/SCREEN/off' in request
            # 控制 LED
            if LED_on:
                print("內建 LED 開啟")
                LED.value(0)
                LED_state = "內建 LED 開啟"
            if LED_off:
                print("內建 LED 關閉")
                LED.value(1)
                LED_state = "內建 LED 關閉"
            if SCREEN_on:
                print("LCD 螢幕背光 開啟")
                SCREEN.value(1)
                SCREEN_state = "LCD 螢幕背光 開啟"
            if SCREEN_off:
                print("LCD 螢幕背光 關閉")
                SCREEN.value(0)
                SCREEN_state = "LCD 螢幕背光 關閉"
                
            response = html % (LED_state, SCREEN_state)
            cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
            cl.send(response)
            cl.close()
        except:
            pass
    time.sleep(0.1)

上一篇
26. 建立網頁伺服器
下一篇
28. 與 LED 燈板通訊
系列文
使用 WiFiBoy Python 玩學機來學物聯網應用 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言