"""import time
import machine
import micropython
import network
from machine import Pin,PWM
from umqtt.simple import MQTTClient
from onewire import OneWire
from ds18x20 import DS18X20
#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 = 'Alanadriel13' #definido en adafruit
password = 'aio_JhSj05Ep1dymlGO9G7yWEjOdGnzo' #key adafruit
#Indicamos ID(unico) y topicos
client_id = 'MiHorno1'
topic_TEMP= 'Alanadriel13/feeds/SensorTemp'
topic_BOTONH = 'Alanadriel13/feeds/horno1_0'
#Usamos una variable para definir si EL HORNO esta activO
HORNO_ACTIVO=False
LEDESTADOHORNO = Pin(5,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_alarma(topic, msg):
global HORNO_ACTIVO,LEDESTADOHORNO
#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_BOTONH and "OFF" in dato:
HORNO_ACTIVO=False
else:
HORNO_ACTIVO=True
LEDESTADOHORNO.value(HORNO_ACTIVO)
#Intentamos conectarnos al broker MQTT
try:
conexionMQTT = MQTTClient(client_id, mqtt_server,user=user,password=password,port=int(port))
conexionMQTT.set_callback(callback_alarma)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_BOTONH)
print("Conectado 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()
SenTemp = Pin(14,Pin.IN)
LEDtemp = Pin(27,Pin.OUT)
SIRENA = PWM(Pin(18), freq=1200, duty_u16=32768)
SIRENA.duty(0)
estadosensor = SenTemp.value()
#ow = DS18X20(OneWire(Pin(14)))
#addr = ow.scan()
ow = OneWire(Pin(14))
ds = DS18X20(ow)
roms = ds.scan()
print('Sensores encontrados:', roms)
while True:
try:
#Tenemos que verificar si hay mensajes nuevos publicados por el broker
conexionMQTT.check_msg()
time.sleep_ms(500)
#actualizamos el LED
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
temp = ds.read_temp(rom)
print('Temperatura: {}°C'.format(temp))
conexionMQTT.publish(topic_TEMP, str(temp))
time.sleep(3)
# Si EL HORNO está activo...
# if HORNO_ACTIVO:
# Y el SENSOR SUPERA LA TEMPERATURA DESEADA
# if temp > 21:
# Entonces tiene que prender LedTemp
# LEDtemp.value(1)
# print("Temperatura alta detectada, LED encendido")
# else:
# LEDtemp.value(0)
# print("Temperatura baja detectada, LED apagado")
except OSError as e:
print("Error ",e)
time.sleep(5)
machine.reset()"""
import time
import machine
import network
from machine import Pin, PWM
from onewire import OneWire
from ds18x20 import DS18X20
from umqtt.simple import MQTTClient
# Configuración de la red WiFi
ssid = 'Wokwi-GUEST'
wifipassword = ''
# Datos del broker MQTT
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'Alanadriel13'
password = 'aio_JhSj05Ep1dymlGO9G7yWEjOdGnzo'
client_id = 'MiHorno1'
topic_temp_set = 'Alanadriel13/feeds/temp_set'
topic_time_set = 'Alanadriel13/feeds/time_set'
topic_temp_read = 'Alanadriel13/feeds/temp_read'
# Variables de estado
desired_temp = 0
preheat_time = 0
temp_reached = False
start_time = 0
HORNO_ACTIVO = False
# Pines de hardware
LEDESTADOHORNO = Pin(5, Pin.OUT)
SIRENA = PWM(Pin(18), freq=1200, duty=0)
# Configuración del sensor de temperatura DS18B20
ow = OneWire(Pin(14))
ds = DS18X20(ow)
roms = ds.scan()
print('Sensores encontrados:', roms)
# Conexión a la red WiFi
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("Conectando a WiFi")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Conectado a WiFi!")
print(sta_if.ifconfig())
# Función callback para MQTT
def callback(topic, msg):
global desired_temp, preheat_time, HORNO_ACTIVO, start_time
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print("Cambio en: " + topicrec + ":" + dato)
if topicrec == topic_temp_set:
desired_temp = float(dato)
print("Temperatura deseada:", desired_temp)
elif topicrec == topic_time_set:
preheat_time = int(dato)
print("Tiempo de pre-calentamiento:", preheat_time)
temp_reached = False
start_time = time.time()
if topicrec == topic_BOTONH and "OFF" in dato:
HORNO_ACTIVO=False
else:
HORNO_ACTIVO=True
LEDESTADOHORNO.value(HORNO_ACTIVO)
# Conexión al broker MQTT
try:
conexionMQTT = MQTTClient(client_id, mqtt_server, user=user, password=password, port=int(port))
conexionMQTT.set_callback(callback)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_temp_set)
conexionMQTT.subscribe(topic_time_set)
conexionMQTT.subscribe(topic_BOTONH)
print("Conectado al broker MQTT")
except OSError as e:
print("Falló la conexión al broker, reiniciando...")
time.sleep(5)
machine.reset()
# Bucle principal
while True:
try:
conexionMQTT.check_msg()
time.sleep_ms(500)
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
current_temp = ds.read_temp(rom)
print('Temperatura actual: {}°C'.format(current_temp))
conexionMQTT.publish(topic_temp_read, str(current_temp))
if HORNO_ACTIVO:
if current_temp >= desired_temp:
temp_reached = True
start_time = time.time()
elif current_temp >= desired_temp + 10:
HORNO_ACTIVO = False
LEDESTADOHORNO.value(0)
print("Horno apagado por sobretemperatura")
elif current_temp <= desired_temp - 10 and not HORNO_ACTIVO:
HORNO_ACTIVO = True
LEDESTADOHORNO.value(1)
print("Horno encendido nuevamente")
if temp_reached:
elapsed_time = time.time() - start_time
if elapsed_time >= preheat_time:
SIRENA.duty(512)
HORNO_ACTIVO = False
LEDESTADOHORNO.value(0)
print("Tiempo de pre-calentamiento completado, alarma activada")
else:
print("Tiempo restante:", preheat_time - elapsed_time)
else:
print("Esperando a que la temperatura deseada sea alcanzada")
except OSError as e:
print("Error ", e)
time.sleep(5)
machine.reset()
Loading
ds18b20
ds18b20