ESP8266 DHT11 web server

Had some time over the long weekend to explore what fun you can have with micropython and a DHT11 sensor. Enjoy.

import time
import ntptime
import machine
import dht
import socket

print(‘system time from ntp to UTC 1st attempt’)
except OSError:
print(‘system time from ntp to UTC 2nd attempt’)
except OSError:
print(‘system time not set from ntp to UTC’)

temperature = 0
humidity = 0
hour = 0
minute = 0
second = 0
temp_cache = 24.0
hum_cache = 41.0
cached = True
sensor = 11

d = dht.DHT11(machine.Pin(2))

def get_DHT_data():
global temp_cache,hum_cache

#assume no reading available
temperature = temp_cache
humidity = hum_cache
cached = True

#get real reading 
    cached = False
except OSError:
    temperature = temp_cache
    humidity = hum_cache

#update cached for next time    
temperature = d.temperature()
humidity = d.humidity()

#Test reading
if temperature is None:
    humidity = hum_cache
    temperature = temp_cache
    cached = True
    hum_cache = humidity
    temp_cache = temperature
    cached = False

return temperature, humidity, cached

#start new code

html = “”"

Temperature and Humidity

DHT11 Sensor Data

Measure Value
Temperature {0}*
Humidity {1}%
Time {2:02}:{3:02}:{4:02}

addr = socket.getaddrinfo(‘’, 80)[0][-1]

s = socket.socket()

print(‘listening on’, addr)
cl, addr = s.accept()
while True:
cl, addr = s.accept()
print(‘client connected from’, addr)
#do web content
cl_file = cl.makefile(‘rwb’, 0)
#do sensor reading
print('reading values from sensor for ', addr)
temperature,humidity,cached = get_DHT_data()
(year, month, mday, hour, minute, second, weekday, yearday) = time.localtime()
print(“Received: {0:0.1f},{1:0.1f},{2},{3},{4},{5},{6}”.format(temperature, humidity,cached,hour,minute,second,sensor))
#do more web content
response = (html.format(temperature,humidity,hour,minute,second))
print('web page sent to ', addr)

1 Like

Very cool! You could probably plug this into Google Charts to add some data logging as well!

Keep up the cool projects! This would be a great project to post in the “Projects” section of our site! Just add a little explanation about how it all works so people can follow along!

Google charts is next.
I have plans to add open weather map data ( data to the mix, possibly network geolocated.

I have a Raspberry Pi version in the works.

1 Like