MicroPython ESP32网页实时更新DHT11数据显示
- 相关篇《MicroPython ESP32 读取DHT11温湿度传感器数据》
- 《【Micropython esp32/8266】网页点灯控制示例》
- ✨本例综合以上两篇文章内容实现:在本地网页中显示DHT11温度传感器数据。可以做到在线监测湿度度数据变化。
- ✨本示例基于
Thonny
平台下开发。✨
- 固件版本:
esp32-20220618-v1.19.1
应该也兼容最新的版本。
- 效果如下:
- 工程架构
⛳注意事项
- 运行程序前,DHT11传感器必须已经接到指定定义的引脚上了,否则运行会报错!!!
- 在boot.py为文件中需要修改成个人的WiFi信息。
- 本地路由器设置不能开启AP隔离功能,否则设备与设备直接无法正常访问。
- 设备端和访问端必须在同一个网络环境下。
- 不支持5G网络。
步骤
代码实现
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import uos, machine
#uos.dupterm(None, 1) # disable REPL on UART(0)
#import gc
#import webrepl
#webrepl.start()
#gc.collect()
try:
import usocket as socket
except:
import socket
from machine import Pin
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
# wifi信息
ssid = 'MERCURY_D268G' # 填写自己的WiFi信息
password = 'pba5ayzk' # 填写自己的WiFi信息
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
led = Pin(2, Pin.OUT)
import dht
import machine
d = dht.DHT11(machine.Pin(4))
#d.measure()
#t=d.temperature() # eg. 23 (°C)
#h=d.humidity() # eg. 41 (% RH)
def web_page():
d.measure()
html = """-8">
<meta http-equiv="refresh" content="6">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,"><style>body { text-align: center; font-family: "Trebuchet MS", Arial;}
table { border-collapse: collapse; width:45%; margin-left:auto; margin-right:auto;}
th { padding: 12px; background-color: #0043af; color: white; }
tr { border: 1px solid #ddd; padding: 12px; }
tr:hover { background-color: #bcbcbc; }
td { border: none; padding: 12px; }
.sensor { color:red; font-weight: bold; background-color: #bcbcbc; padding: 1px;
</style></head><body><h1>ESP Web DHT11 DATA</h1>
<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>
<tr><td>Temperature</td><td><span class="sensor">""" + str(d.temperature()) + """ °C</span></td></tr>
<tr><td>Humidity</td><td><span class="sensor">""" + str(d.humidity()) + """ %</span></td></tr></body></html>"""
return html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
try:
if gc.mem_free() < 102000:
gc.collect()
conn, addr = s.accept()
# conn.settimeout(5.0)
print('Got a connection from %s' % str(addr))
# request = conn.recv(1024) # 为了减少内存开销,取消打印信息
# conn.settimeout(None)
# request = str(request)
# print('Content = %s' % request)
print('Content = %s' % request)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
conn.close()
except OSError as e:
conn.close()
print('Connection closed')