from machine import Pin, SoftI2C
import onewire, ds18x20, time
import ssd1306
from umqtt.simple import MQTTClient
# Configurar sensor de temperatura DS18B20
ds_pin = Pin(4) # Conectar el pin de datos del sensor a GPIO4
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
if len(roms) == 0:
raise Exception("Sensor DS18B20 no encontrado")
# Configurar pantalla OLED
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = None
try:
oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)
oled.fill(0)
oled.text("Buscando", 0, 0)
oled.text("conexion...", 0, 15)
oled.show()
except Exception as e:
print("Error inicializando OLED:", e)
# Configurar pulsadores y salidas
start_button = Pin(0, Pin.IN, Pin.PULL_UP)
stop_button = Pin(2, Pin.IN, Pin.PULL_UP)
extruder = Pin(15, Pin.OUT)
# Estado inicial del extrusor y contadores
cycle_count = 0
extruder_status = 'inactivo'
start_pressed = False
stop_pressed = False
# Configuración MQTT
mqtt_server = 'your_mqtt_broker'
client_id = 'esp32'
topic_temp = b'esp32/temperature'
topic_status = b'esp32/status'
topic_cycles = b'esp32/cycles'
def sub_cb(topic, msg):
print((topic, msg))
client = None # Inicialización para uso local sin MQTT
# Intentar conectarse a WiFi si es posible
try:
import network
ssid = 'Angelo'
password = '241014afa'
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
# Esperar hasta que se establezca la conexión WiFi
timeout = time.time() + 10 # Esperar hasta 10 segundos máximo en modo local
while not station.isconnected() and time.time() < timeout:
pass
if station.isconnected():
print('Conexion establecida')
print(station.ifconfig())
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
else:
print('Conexion wifi no establecida, ejecutando en modo local')
except ImportError:
print('Conexion a la red no encontrado, ejecutando modo local')
# Bucle principal
last_update_time = time.ticks_ms()
while True:
# Leer la temperatura del sensor cada segundo
ds_sensor.convert_temp()
time.sleep(1)
temp = ds_sensor.read_temp(roms[0])
# Actualizar la pantalla OLED si está inicializada
if oled:
oled.fill(0)
oled.text(f'Temp: {temp:.2f}', 0, 0)
oled.text(f'Status: {extruder_status}', 0, 10)
oled.text(f'Cycles: {cycle_count}', 0, 20)
oled.show()
# Actualizar MQTT y consola cada 2 segundos si hay conexión
if client:
client.publish(topic_temp, str(temp))
client.publish(topic_status, extruder_status)
client.publish(topic_cycles, str(cycle_count))
print(f'Temperature: {temp:.2f} °C | Status: {extruder_status} | Cycles: {cycle_count}')
# Simular operación con botones o sensores (ejemplo)
if start_button.value() == 0 and not start_pressed:
print("Boton de encendido presionado")
extruder_status = 'activo'
start_pressed = True
last_update_time = time.ticks_ms() # Actualizar tiempo de último envío
if stop_button.value() == 0 and not stop_pressed:
print("Boton de apagado presionado")
extruder_status = 'inactivo'
stop_pressed = True
last_update_time = time.ticks_ms() # Actualizar tiempo de último envío
# Actualizar ciclos cada 500 ms si el extrusor está activo
current_time = time.ticks_ms()
if extruder_status == 'activo' and time.ticks_diff(current_time, last_update_time) >= 500:
cycle_count += 1
last_update_time = current_time
time.sleep(0.01) # Pequeña pausa para reducir el uso de CPU