import machine
import time
import network
from machine import Pin
from machine import ADC
from umqtt.simple import MQTTClient
dire = Pin(15, Pin.OUT)
paso = Pin(2, Pin.OUT)
luz = ADC(34)
led_verde = Pin(12, Pin.OUT)
led_rojo = Pin(13, Pin.OUT)
MAX_PASOS = 1000
estado = 0
toggle = False
modo_manual = False
ssid = 'Wokwi-GUEST'
wifipassword = ''
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("Conectando")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Conectado a Wifi!")
print(sta_if.ifconfig())
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'POOLOO73'
password = 'aio_TXai41gYHIeyRjHXYX1nxiqvXJ5m'
client_id = 'cortina_fse'
topic_motor_paso = 'POOLOO73/feeds/motor_paso'
topic_sensor_ldr = 'POOLOO73/feeds/sensor_ldr'
topic_modo = 'POOLOO73/feeds/modo'
def funcion_callback(topic, msg):
global toggle, modo_manual
dato = msg.decode('utf-8')
topic_rec = topic.decode('utf-8')
print("→ Recibido:", dato)
if topic_rec == 'POOLOO73/feeds/modo':
if "MANUAL" in dato:
modo_manual = True
if "AUTO" in dato:
modo_manual = False
if topic_rec == 'POOLOO73/feeds/motor_paso':
if "OFF" in dato:
toggle = False
if "ON" in dato:
toggle = True
try:
conexionMQTT = MQTTClient(client_id, mqtt_server, user=user, password=password, port=int(port))
conexionMQTT.set_callback(funcion_callback)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_motor_paso)
conexionMQTT.subscribe(topic_modo)
print("Conectado con Broker MQTT")
except OSError as e:
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
def mover_motor(sentido):
global estado
paso.value(0)
pasos = 1000
while pasos > 0:
pasos -= 1
paso.value(1)
time.sleep_ms(1)
paso.value(0)
time.sleep_ms(1)
if sentido == 1:
estado += 1
else:
estado -= 1
while True:
try:
conexionMQTT.check_msg()
time.sleep_ms(300)
led_rojo.value(0)
led_verde.value(0)
valor = luz.read()
print("Valor " + str(valor))
porcentaje_luz = 100 - ((valor / 4095) * 100)
conexionMQTT.publish(topic_sensor_ldr, str(porcentaje_luz))
time.sleep(2)
if modo_manual:
if toggle and estado < MAX_PASOS:
led_verde.value(1)
dire.value(1)
paso.value(0)
mover_motor(1)
if not toggle and estado > 0:
led_rojo.value(1)
dire.value(0)
paso.value(0)
mover_motor(0)
else:
if valor <= 680 and estado < MAX_PASOS:
led_verde.value(1)
dire.value(1)
paso.value(0)
mover_motor(1)
if valor > 680 and estado > 0:
led_rojo.value(1)
dire.value(0)
paso.value(0)
mover_motor(0)
except OSError as e:
print("Error ", e)
time.sleep(5)
machine.reset()