#web_clock.py
import machine
import network
import ntptime
import time
import socket
from machine import Pin, SoftI2C, RTC
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import dht # DHT11 感測器模組
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
SSID = "Bili-Net"
PASSWORD = "0932388283"
rtc = RTC()
wifi_status = False # 初始化 Wi-Fi 狀態為未連線
# 初始化 DHT11 感測器 (接在 GPIO13)
dht_sensor = dht.DHT11(Pin(13))
# 將 GPIO12 設定為輸出以為 DHT11 提供電源
dht_power = Pin(12, Pin.OUT)
dht_power.value(1) # 拉高 GPIO12 提供電源
# GPIO14設置為輸入針腳,用於背光控制
backlight_control = Pin(14, Pin.IN, Pin.PULL_UP)
def set_timezone():
offset = 8 * 3600 # Offset for UTC+8
now = time.time() + offset
tm = time.localtime(now)
rtc.datetime((tm[0], tm[1], tm[2], 0, tm[3], tm[4], tm[5], 0))
print('Timezone set to Taipei (UTC+8). Current RTC time:', rtc.datetime())
def connect_wifi():
global wifi_status
wifi_status = False # 初始為未連線狀態
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
max_attempts = 10 # 設置最大嘗試連線次數
attempt_count = 0 # 初始化嘗試次數
while not wifi.isconnected() and attempt_count < max_attempts:
print("等待 Wi-Fi 連線... 嘗試次數:", attempt_count + 1)
time.sleep(1)
attempt_count += 1
if wifi.isconnected():
print("Wi-Fi 連線成功:", wifi.ifconfig())
wifi_status = True # 更新 Wi-Fi 狀態為已連線
# 取得 IP 地址
ip_info = wifi.ifconfig()
ip_address = ip_info[0]
# 將 IP 地址顯示在 LCD
lcd.move_to(0, 0) # 移動到 LCD 第一行
lcd.putstr("WiFi IP:")
lcd.move_to(0, 1) # 移動到 LCD 第二行
lcd.putstr(ip_address) # 顯示 IP 地址
else:
print("Wi-Fi 連線失敗,已達最大嘗試次數")
lcd.move_to(0, 0)
lcd.putstr("WiFi Fail")
def sync_time():
try:
ntptime.settime()
set_timezone()
print("時間校對完成:", time.localtime())
except:
print("時間校對失敗")
def control_backlight():
# 根據 GPIO14 的狀態控制 LCD 背光
if backlight_control.value() == 0:
lcd.backlight_off() # 假設有此方法,需要實際檢查您的 lcd 模組
else:
lcd.backlight_on() # 假設有此方法,需要實際檢查您的 lcd 模組
# 初始化 LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# Wi-Fi 連接
connect_wifi()
sync_time()
# 網頁伺服器功能
def web_page():
# 讀取 DHT11 溫溼度
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
except OSError as e:
temp = "Error"
hum = "Error"
# 取得目前日期時間
current_time = rtc.datetime()
# 建立 HTML 網頁內容
html = """<html>
<head>
<title>環境監控</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="5" /> <!-- 每5秒自動刷新 -->
</head>
<body>
<h1>環境監控系統</h1>
<p>日期: {}/{}/{} </p>
<p>時間: {}:{}:{} </p>
<p>溫度: {}℃ </p>
<p>濕度: {}% </p>
</body>
</html>""".format(current_time[0], current_time[1], current_time[2], # 年, 月, 日
current_time[4], current_time[5], current_time[6], # 時, 分, 秒
temp, hum)
return html
# 建立 Socket 並等待連線
def start_web_server():
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)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = web_page()
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: text/html\r\n')
cl.send('Connection: close\r\n\r\n')
cl.sendall(response)
cl.close()
# 啟動網頁伺服器
start_web_server()
LCD 會顯示出所取得的IP
http://所取得的IP
web 畫面