import time
import machine
import micropython
import network
from machine import Pin, ADC, SoftI2C
from umqtt.simple import MQTTClient
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
#Indicamos red WIFI y clave
ssid = 'Wokwi-GUEST'
wifipassword = ''
#Datos Server MQTT (Broker)
#Indicamos datos MQTT Broker (server y puerto)
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'facuquiles' #definido en adafruit
password = 'aio_ZCMG14aKk6WV06YWozCuVq23Axyc' #key adafruit
#Indicamos ID(unico) y topicos
client_id = 'Termotanque'
topic_HOT = 'facuquiles/feeds/estadollama'
topic_ON_OFF = 'facuquiles/feeds/termotanquebanopa'
#Usamos una variable para definir si el termotanque esta prendido
TERMOTANQUE = False
LEDESTADO = Pin(13,Pin.OUT)
#Definimos modo Station (conectarse a Access Point remoto)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
#Conectamos al wifi
sta_if.connect(ssid, wifipassword)
print("Conectando")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Conectado a WIFI!")
#Vemos cuales son las IP
print(sta_if.ifconfig())
#Antes de conectarnos al broker, vamos a definir una funcion
#que sera llamada cada vez que se produzca un publish sobre
#un topico donde estamos suscriptos
def callback_termotanque(topic, msg):
global TERMOTANQUE, LEDESTADO
#Cuando se ejecuta esta funcion quere decir que
#hubo un mensaje nuevo en algun topico, verificamos esto
#Dado que lo que llega viene en UTF-8, lo decodificamos
#para que sea una cadena de texto regular
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print("Cambio en: "+topicrec+":"+dato)
#Nos fijamos si es el topico esperado y el valor del dato
if topicrec == topic_ON_OFF and "OFF" in dato:
TERMOTANQUE=False
else:
TERMOTANQUE=True
LEDESTADO.value(TERMOTANQUE)
#Intentamos conectarnos al broker MQTT
try:
conexionMQTT = MQTTClient(client_id, mqtt_server,user=user,password=password,port=int(port))
conexionMQTT.set_callback(callback_termotanque) #Funcion callback para recibir del broker mensajes
conexionMQTT.connect() #Hacemos la conexion
conexionMQTT.subscribe(topic_ON_OFF) #Nos suscribimos a un topico luego del connect
print("Conectando con Broker MQTT")
except OSError as e:
#Si fallo la conexion, reiniciamos todo
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
LedAmarillo = Pin(0, Pin.OUT)
LedNaranja = Pin(2, Pin.OUT)
LedRojo = Pin(4, Pin.OUT)
pot = ADC(Pin(34))
pot.width(ADC.WIDTH_10BIT)
pot.atten(ADC.ATTN_11DB)
Slider = Pin(27,Pin.IN,Pin.PULL_UP)
# Configuración de la pantalla LCD I2C
I2C_ADDR = 0x27
totalRows = 4
totalColumns = 20
# Configuración de pines I2C
scl_pin = Pin(17)
sda_pin = Pin(16)
i2c = SoftI2C(scl=scl_pin, sda=sda_pin, freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
print("Empezando a testear la Tempertatura")
#Le damos el rango de temperatura al valor del potenciometro
def map_value(value, in_min, in_max, out_min, out_max):
return (value - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
tempNueva = 0
tempHambiente = 10
tempTermo = tempHambiente
band = 0
llama_prendida = False
conexionMQTT.publish(topic_HOT,str(0))
while True:
#Si se produce una excepcion, por ejemplo se corta el wifi
#o perdemos la conexion MQTT, simplemente vamos a reiniciar
#el micro para que comience la secuencia nuevamente, asi que
#usamos un bloque Try+Except
try:
#Tenemos que verificar si hay mensajes nuevos publicados por el broker
conexionMQTT.check_msg()
time.sleep_ms(500)
if TERMOTANQUE:
agua = Slider.value()
pot_value = pot.read() # Lee el valor del potenciometro
temp = map_value(pot_value, 0, 1023, 30, 70)
if temp != tempNueva or band == 1:
llama_prendida = False
tempNueva = temp
time.sleep(1.5)
print("Temp = {} C".format(temp))
lcd.clear()
lcd.putstr("Temperatura \nSelecta: {} C".format(temp))
band = 0
# Aplicar la lógica de histeresis
if llama_prendida and tempTermo >= temp:
llama_prendida = False
conexionMQTT.publish(topic_HOT,str(0))
elif not llama_prendida and tempTermo <= temp - 5:
llama_prendida = True
conexionMQTT.publish(topic_HOT,str(1))
# Actualizar la temperatura del termotanque
if agua and tempTermo >= tempHambiente:
tempTermo -= 0.25
if llama_prendida:
tempTermo += 0.18
if tempTermo >= tempHambiente:
tempTermo -= 0.03
time.sleep(0.01)
print("Temperatura del termotanque = {} C".format(tempTermo))
if tempTermo >= tempHambiente and tempTermo < temp - 20:
LedAmarillo.value(1)
LedNaranja.value(0)
LedRojo.value(0)
elif tempTermo >= temp - 20 and tempTermo < temp - 10:
LedAmarillo.value(0)
LedNaranja.value(1)
LedRojo.value(0)
elif tempTermo >= temp - 10 and tempTermo < temp:
LedAmarillo.value(0)
LedNaranja.value(0)
LedRojo.value(1)
else:
conexionMQTT.publish(topic_HOT,str(0))
lcd.clear()
LedAmarillo.value(0)
LedNaranja.value(0)
LedRojo.value(0)
band = 1
while not TERMOTANQUE:
agua = Slider.value()
print("Temperatura del termotanque = {} C".format(tempTermo))
if agua and tempTermo >= tempHambiente:
tempTermo -= 0.25
if tempTermo >= tempHambiente:
tempTermo -= 0.03
time.sleep(0.1)
except OSError as e:
print("Error ",e)
time.sleep(5)
machine.reset()