from machine import Pin, I2C
from utime import sleep, sleep_ms
import network, time
import ujson
from umqtt.simple import MQTTClient
servo PWM (Pin(14)), Frecuencia(50)
MQTT_CLIENT_ID = "clientId-A65cW2yudertm314"
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_SUB ="contro/apertura"
#ffuncion servomotor
def map_servo(x):
return int ((x-0) * (125-25)/ (180-0))
#conexion a wifi
def conectaWifi (red, password):
global miRed
miRed = network.WLAN(network.STA_IF)
if not miRed.isconnected(): #Si no está conectado…
miRed.active(True) #activa la interface
miRed.connect(red, password) #Intenta conectar con la red
print('Conectando a la red', red +"…")
timeout = time.time ()
while not miRed.isconnected(): #Mientras no se conecte..
if (time.ticks_diff (time.time (), timeout) > 10):
return False
return True
#conexion a la plataforma
if conectaWifi ("Wokwi-GUEST", ""):
print ("Conexión exitosa!")
print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())
# np[0]=(0,255,0)
#np.write()
print("Conectando a MQTT server... ",MQTT_BROKER,"...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
#np[0]=(0,0,255)
#np.write()
def sub_cb(topic, msg):
dato=msg.decode()
#dato=ujson.loads(msg.decode())
print(f'Recibido:{dato}')
if dato == "Abrir":
m = map:servo(180)
servo.duty(m)
elif dato == "cerrar":
m = map:servo(|0)
servo.duty(m)
elif dato == "Entreabrir":
m = map:servo(90)
servo.duty(m)
while True:
client.set_callback(sub_cb)
client.subscribe(MQTT_TOPIC_SUB)
print ("esperando")
client.wait_msg()
time.sleep(3)
#m=map_servo(45)
#servo.duty(m)
# print(m)
sleep(1)
else:
print("Imposibe conectar")
miRed.active (false)