from machine import Pin
import network
import time
import dht
ssid = "UMARCECAT"
password = "UNIVERSIDAD"
d = dht.DHT22(Pin(15)) # inicializa al sensor
wf = network.WLAN(network.STA_IF)
wf.active(True)
def web_page():
d.measure() # Lee la información del sensor
tem = str(d.temperature()) # Obtiene la temperatura
hum = str(d.humidity()) # Obtiene la humedad
html = """
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sensor DHT22</title>
<script>
setInterval(updateValues, 5000);
function updateValues() {
location.reload();
}
</script>
</head>
<body>
<h1>Lectura de parámetros</h1>
<p>Temperatura """+tem+""" °C</p>
<p>Humedad """+hum+""" %</p>
</body>
</html>
"""
return html
wf.connect(ssid, password)
# Se destina un tiempo de 20 segundos para intentar la conexión
espera = 20
while (espera > 0) and (not wf.isconnected()):
print(".", end=' ')
time.sleep(1)
espera = espera - 1
bandera = False
if wf.isconnected():
print("\nConectado a Wifi!!!")
config = wf.ifconfig()
bandera = True
print(config)
else:
print("\nNo se pudo conectar.")
if bandera == True:
import usocket
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.bind((config[0], 80))
s.listen(5)
print("Socket listo, esperando conexiones")
while True:
try:
(sc, addr) = s.accept()
print("Cliente conectado: ", addr)
dato = sc.recv(1024)
dato = str(dato)
respuesta = web_page()
sc.send("HTTP/1.1 200 OK\n")
sc.send("Content-Type: text/html\n")
sc.sendall(respuesta)
sc.close()
except Exception as e:
print(e)