I've downloaded webserver code from https://docs.micropython.org/en/v1.8/esp8266/esp8266/tutorial/network_tcp.html, it worked well. But after adding code reading dht11 values, webserver stops responding. What's wrong with my code?
import machine
import dht
import socket
import network
sta_if = network.WLAN(network.STA_IF)
sta_if.connect(SSID, PASS)
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
d = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
def measure():
d.measure()
temp = d.temperature()
hum = d.humidity()
return temp, hum
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = measure()
cl.send(response)
cl.close()
I see two problems with your code:
First, to read the DHT11 sensor you need to use a DHT object. Try replacing
d = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
with
d = dht.DHT11(machine.Pin(5))
Second, the output of your measure()
function is a numeric tuple and you're passing that directly to cl.send()
, but that method needs a bytes
object. You need to encode the two values into a string then convert that into bytes first. Instead of
cl.send(response)
you probably want something like
message = 'Temperature {} Humidity {}'.format(response[0], response[1])
cl.send(bytes(message, 'utf-8'))