import network
import time
from machine import Pin
import dht
import ujson
import urequests as requests
import random
# URL del backend FastAPI
API_URL = "https://clima-backend-plpg.vercel.app/api/data"
# Inicialización del sensor DHT22 en el pin GPIO15
sensor = dht.DHT22(Pin(15))
# Conexión a la red WiFi
print("Conectando a la red 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(" ¡Conectado!")
# Variable para almacenar los datos previos
prev_weather = ""
while True:
try:
print("Midiendo condiciones meteorológicas... ", end="")
sensor.measure()
# Generación de datos simulados
temperatura = round(random.uniform(20, 60), 1)
humedad = round(random.uniform(10, 100), 1)
localizacion = "Cordoba"
# Mostrar en la terminal
print(f"Temperatura: {temperatura:.2f}°C, Humedad: {humedad:.2f}%, Localización: {localizacion}")
# Preparación de los datos
data = {
"temperatura": temperatura,
"humedad": humedad,
"localizacion": localizacion
}
print("Enviando datos al backend...")
response = requests.post(API_URL, json=data)
if response.status_code == 200:
print(f"Datos enviados exitosamente: {response.json()}")
else:
print(f"Error al enviar datos: {response.status_code} - {response.text}")
except Exception as e:
print(f"Error de conexión o medición: {e}")
time.sleep(3600)