#import para acceso a red
import network
#Para usar protocolo MQTT
from umqtt.simple import MQTTClient
#Importar módulos necesarios para el control del hardware
from machine import Pin, PWM
from time import sleep
# Propiedades para conectar a un broker MQTT
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_CLIENT_ID = ""
MQTT_TOPIC = "utng/actuators"
MQTT_PORT = 1883
# Configuración del Servomotor en el pin 15
servo_pwm = PWM(Pin(15), freq=50) # Frecuencia típica para servos: 50 Hz
def angle_to_duty(angle):
"""
Convierte un ángulo (0 a 180 grados) a un valor de duty cycle adecuado para el servo.
Ajusta estos valores según tu servomotor.
Valores aproximados: 0° -> duty=40, 180° -> duty=115.
"""
duty_min = 40
duty_max = 115
return int((angle / 180) * (duty_max - duty_min) + duty_min)
def move_servo(angle):
"""
Mueve el servomotor al ángulo especificado.
"""
duty = angle_to_duty(angle)
servo_pwm.duty(duty)
print("Servo movido a {}° (duty {})".format(angle, duty))
def conectar_wifi():
"""
Conecta el dispositivo a la red WiFi.
"""
print("Conectando a 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="")
sleep(0.3)
print("\nWiFi Conectada!")
def subscribir():
"""
Conecta y suscribe al broker MQTT.
"""
client = MQTTClient(MQTT_CLIENT_ID,
MQTT_BROKER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASSWORD,
keepalive=0)
client.set_callback(llegada_mensaje)
client.connect()
client.subscribe(MQTT_TOPIC)
print("Conectado a %s, en el tópico %s" % (MQTT_BROKER, MQTT_TOPIC))
return client
def llegada_mensaje(topic, msg):
"""
Función callback que se ejecuta al recibir un mensaje MQTT.
Se espera que el mensaje contenga un ángulo (valor entre 0 y 180).
Luego de mover el servomotor, se publica 'true' si el ángulo es >= 90 o 'false' en otro caso.
"""
print("Mensaje recibido:", msg)
try:
# Convertir el mensaje a entero (ángulo)
angle = int(msg)
if 0 <= angle <= 180:
move_servo(angle)
# Publicar true si el ángulo es >= 90, false si es menor
if angle >= 90:
client.publish(MQTT_TOPIC, b"true")
print("Publicado: true")
else:
client.publish(MQTT_TOPIC, b"false")
print("Publicado: false")
else:
print("Ángulo fuera del rango permitido (0-180).")
except Exception as e:
print("Error al procesar el mensaje:", e)
# Conectar a WiFi
conectar_wifi()
# Conectarse al broker MQTT y suscribirse al tópico
client = subscribir()
# Bucle principal: se revisan los mensajes entrantes
while True:
client.check_msg()
sleep(0.1)