import network
import time
import machine
from umqtt.simple import MQTTClient
from mpu6050 import MPU6050
# Configuración Wi-Fi
ssid = "Wokwi-GUEST"
password = ""
# Configuración MQTT
AIO_SERVER = "io.adafruit.com"
AIO_PORT = 1883
AIO_USER = "drubine101"
AIO_KEY = "aio_NuTa661DyzjhFgL9uKizge91kDNj"
AIO_FEED = "drubine101/feeds/lectura_temp"
# Inicializar I2C y sensor MPU6050
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))
mpu = MPU6050(i2c)
# Conectar a Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Conectando a Wi-Fi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nConectado! IP:", wlan.ifconfig()[0])
# Conectar a MQTT
def connect_mqtt():
client = MQTTClient("esp32", AIO_SERVER, port=AIO_PORT, user=AIO_USER, password=AIO_KEY)
client.connect()
print("Conectado a MQTT")
return client
# Programa principal
connect_wifi()
mqtt_client = connect_mqtt()
while True:
temp = mpu.get_temp()
print("Temperatura:", temp, "°C")
try:
mqtt_client.publish(AIO_FEED, str(temp))
print("Publicado en el feed.")
except Exception as e:
print("Error al publicar:", e)
time.sleep(10)