ESP32 Weather Station using DHT11 with MicroPython (Web Server)
Weather Station using ESP32 board and DHT11 Temperature and Humidity Sensor with MicroPython. Show Status on ESP32 Webserver.
MicroPython Code – ESP32 Weather Station using DHT11 on Web Server
from machine import Pin, SoftI2C
import network
import time
import socket
import _thread
import dht
# DHT11
d = dht.DHT11(Pin(23))
t = 0
h = 0
def check_temp():
print('Check Temp Starting...')
global t
global h
while True:
try:
d.measure()
time.sleep(2)
t = d.temperature()
h = d.humidity()
temp = 'Temp: {:.0f} C'.format(t)
humid = 'Humidity: {:.0f} %'.format(h)
print('DHT11:', t, h)
time.sleep(5)
except:
pass
# START
print('Starting...')
# WIFI
wifi = 'Your_ssid' # your wifi ssid
password = 'Your_Password' # your wifi password
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
time.sleep(3)
wlan.connect(wifi, password)
time.sleep(5)
status = wlan.isconnected() # True/False
ip ,_ ,_ ,_ = wlan.ifconfig()
if status == True:
print('IP:{}'.format(ip))
time.sleep(2)
print('Connected')
else:
print('Disconnected')
# HTML
html1 = '''
<!doctype html>
<html lang="en">
<body style="font-family:verdana;">
<div class="container">
<form>
<center>
<h2><b>ESP32 DHT11 Sensor<b></h2>
<h2>
'''
html2 = '''
</h2><br>
</center>
</form>
</div>
</body>
</html>
'''
html_br = '''
<br>
'''
# RUN
def runserver():
global t
global h
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 80
s.bind((host,port))
s.listen(5)
while True:
client, addr = s.accept()
print('Connection from: ', addr)
data = client.recv(1024).decode('utf-8')
print([data])
temp = 'Temp: {:.0f} C'.format(t)
humid = 'Humidity: {:.0f} %'.format(h)
client.send(html1 + temp + html_br + humid + html2)
client.close()
_thread.start_new_thread(runserver,())
_thread.start_new_thread(check_temp,())