import machine
from machine import Pin
from machine import ADC
import time
from umqtt.simple import MQTTClient
import micropython
import network
import utime
from utime import sleep
#Red wifi y clave
ssid = 'Wokwi-GUEST'
wifipassword = ''
#conexion a server adafruit
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'sofirimada'
password = 'aio_zVFT65hKH45deb8KbP9TP52jYHbS'
#topicos
client_id = 'Panel'
topic_ENCENDIDO = 'sofirimada/feeds/botonencendido'
topic_MANUAL = 'sofirimada/feeds/controlmanual'
topic_POTENCIOMETRO = 'sofirimada/feeds/potenciometro'
topic_LDR = 'sofirimada/feeds/ldr'
topic_MOTORPP = 'sofirimada/feeds/motorpp'
#Variables de Adafruit
Activo = False #flag para conocer estado del sistema
LEDtestigo = Pin(1, Pin.OUT) #led testigo
ActManual = False
LEDmanual = Pin(10, Pin.OUT)
ValorMinLuz = 0
AnguloRot = 0.0
#definimos modo station
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())
def callback(topic, msg):
global Activo, LEDtestigo, ActManual, LEDmanual, ValorMinLuz, AnguloRot
#Decodificar msg
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print(f"Mensaje en topico: {topicrec}: {dato}")
if topicrec == topic_ENCENDIDO and "ON" in dato:
Activo = True
else:
Activo = False
Activo2=Activo
LEDtestigo.value(Activo2)
if topicrec == topic_MANUAL and "ON" in dato:
ActManual = True
else:
ActManual = False
LEDmanual.value(ActManual)
if topicrec == topic_POTENCIOMETRO:
try:
ValorMinLuz = int(dato)
print(f"Nuevo valor del potenciometro recibido: {ValorMinLuz}")
except ValueError:
print("Error al recibir valor del potenciometro")
if topicrec == topic_MOTORPP:
try:
AnguloRot = float(dato)
print(f"Nuevo valor del potenciometro recibido: {AnguloRot}")
except :
print("Error al recibir valor del Angulo")
#Conexion al broker
try:
conexionMQTT = MQTTClient(client_id, mqtt_server, user=user, password=password, port = int(port))
conexionMQTT.set_callback(callback)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_ENCENDIDO)
conexionMQTT.subscribe(topic_POTENCIOMETRO)
conexionMQTT.subscribe(topic_MANUAL)
conexionMQTT.subscribe(topic_MOTORPP)
print("Conectado con Broker MQTT")
except OSError as e:
print("Conexion fallida, reiniciando...")
time.sleep(5)
machine.reset()
#Proceso
STEP=Pin(5, Pin.OUT)
DIR=Pin(4, Pin.OUT)
LDR=ADC(Pin(2))
prevLDR=0
valorLDR=0
ultimoenvio=0
DIR.value(1)#gira en sentido horario
print("Comienzo de Programa")
valorLDR=LDR.read()
print(valorLDR)
while True:
try:
conexionMQTT.check_msg()
#conexionMQTT.ping() para que no se desactive por inactividad
utime.sleep_ms(100)
Cantpasos=0
if Activo == True:
if ActManual == False:
valorLDR=LDR.read()
while valorLDR > ValorMinLuz: #mientras el ldr detecte un nivel inferior al requerido
conexionMQTT.check_msg()
#conexionMQTT.ping()
utime.sleep_ms(100)
STEP.value(1)
utime.sleep_ms(10)
STEP.value(0)
utime.sleep_ms(10)
#con cada flanco ascendente da un paso
valorLDR=LDR.read()
if valorLDR <= ValorMinLuz:
if valorLDR!=prevLDR and (time.time()-ultimoenvio) > 5:
conexionMQTT.publish(topic_LDR, str(valorLDR))
#Al ser una entrada analogica, mientras mas luz haya, menor sera el valor
print("Posicion del panel fijada")
prevLDR = valorLDR
ultimoenvio = time.time()
conexionMQTT.check_msg()
#conexionMQTT.ping()
utime.sleep_ms(100)
else:
Cantpasos = AnguloRot/1.8
for i in range(Cantpasos):
STEP.value(1)
utime.sleep_ms(10)
STEP.value(0)
utime.sleep_ms(10)
else:
STEP.value(0)
except OSError as e:
print("Error al conectar, reiniciando...", str(e))
machine.reset()
#Para que de un giro completo son 200 pasos