import network
import time
from machine import Pin
import urequests
import dht
# Conexión a WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Definición del sensor
sensor = dht.DHT22(Pin(15))
# Función para codificar URL
def urlencode(params):
return '&'.join('{}={}'.format(key, str(value).replace(' ', '%20')) for key, value in params.items())
# Definición del timer
def timer_software(diccionario):
nuevos = {'acc_ms': 0, 'last_ms': 0}
for clave, valor in nuevos.items():
diccionario.setdefault(clave, valor)
diccionario['acc_ms'] = time.ticks_ms() - diccionario['last_ms']
if diccionario['acc_ms'] >= diccionario['pre_ms']:
diccionario['callback']()
diccionario['last_ms'] = time.ticks_ms()
# Función para enviar solicitud con reintentos
def send_request_with_retry(url, retries=3):
for attempt in range(retries):
try:
response = urequests.get(url)
if response.status_code == 200:
return response
else:
response.close()
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
time.sleep(1) # Esperar un segundo antes de reintentar
return None
# Callback para enviar datos
def hola_mundo1():
try:
sensor.measure()
idFormulario = "10mbMYQrWEezcwAxxoNztu7IqtwLhYlYJ0RTT2_q3peo"
idCampo = "703680858"
payload = sensor.temperature()
print(payload)
url_dtl = f"https://docs.google.com/forms/d/{idFormulario}/formResponse?entry.{idCampo}={payload}"
response = send_request_with_retry(url_dtl)
if response and response.status_code == 200:
print("Datos enviados correctamente")
print("Response:", response.status_code)
else:
print("Error al enviar los datos o sin respuesta")
if response:
response.close()
except Exception as e:
print("Error:", e)
finally:
# Recolector de basura para liberar memoria
import gc
gc.collect()
response.close()
# Callback para una segunda tarea (se puede modificar según necesidad)
def hola_mundo2():
print("Hello 2, ESP32! " + str(timer1['acc_ms']))
def msg1():
print("mensaje 1")
def msg2():
print("mensaje 2")
# Configuración de los timers
timer1 = {'pre_ms': 1000, 'callback': msg1}
timer2 = {'pre_ms': 5000, 'callback': msg2}
# Bucle principal
while True:
timer_software(timer1)
timer_software(timer2)