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
try:
ntptime.settime()
print(‘system time from ntp to UTC 1st attempt’)
except OSError:
try:
ntptime.settime()
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
try:
d.measure()
d.temperature()
d.humidity()
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
else:
hum_cache = humidity
temp_cache = temperature
cached = False
return temperature, humidity, cached
#start new code
html = “”"
Temperature and HumidityDHT11 Sensor Data
Measure | Value |
---|---|
Temperature | {0}* |
Humidity | {1}% |
Time | {2:02}:{3:02}:{4:02} |
addr = socket.getaddrinfo(‘0.0.0.0’, 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
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))
cl.send(response)
print('web page sent to ', addr)
cl.close()