代码基于MicroPyhon。esp-8266 SPI Flash 只有 8Mbit,无法写入更多的功能。
DHT-11 温度±2 ,这里的检测频率在30s/次。
web展示代码 :
def web_main8(addr):
ip = addr
port = 80
webserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
webserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 设置给定套接字选项的值
webserver.bind((ip, port)) # 绑定IP地址和端口号
webserver.listen(5) # 监听套接字
print("服务器地址: {}:{}".format(ip, port))
while True:
conn, addr = webserver.accept()
request = conn.recv(1024)
if len(request) > 0:
request = request.decode()
result = search("(.*?) (.*?) HTTP/1.1", request)
if result:
method = result.group(1)
url = result.group(2)
print(url)
conn.send("HTTP/1.1 200 OK\r\n")
conn.send("Server: Esp8266\r\n")
conn.send("Content-Type: text/html;charset=UTF-8\r\n")
conn.send("Connection: close\r\n")
conn.send("\r\n")
if url == "/ht":
utime.sleep(2)
ht = humiture()
hts = 'Temperature:{};Humidity:{}'.format(ht[0], ht[1])
conn.send(hts)
else:
utime.sleep(2)
#conn.sendall(html)
ht = humiture()
hts = 'Temperature:{};Humidity:{}'.format(ht[0], ht[1])
conn.sendall(hts)
conn.send("\r\n") # 发送结束
else:
print("not found url")
else:
print("no request")
conn.close()
温湿度检测:
def humiture():
try:
dht = DHT11(Pin(2))
dht.measure()
t = dht.temperature() # eg. 23 (°C)
h = dht.humidity() # eg. 41 (% RH)
print('Temperature: {} | Humidity: {}'.format(t, h))
utime.sleep(30)
return (t, h)
except Exception as e:
print('humiture() Exception info: ', e)
建议通讯应使用MQTT,8266仅实现最精简的的功能即可。其他功能应该在服务器上实现。