from machine import Pin, I2C, Timer
import time
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd

# Inicialización de pines y LCD
dout = Pin(19, Pin.IN)
pd_sck = Pin(18, Pin.OUT)
ready_pin = Pin(5, Pin.IN, Pin.PULL_UP)
led_pin = Pin(25, Pin.OUT)
i2c = I2C(1, sda=Pin(2), scl=Pin(3), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)

# Variables globales
OFFSET = 0
SCALE_FACTOR = 1
is_ready = False
last_debounce_time = 0

def read_hx711():
    count = 0
    pd_sck.value(0)
    while dout.value() == 1:
        pass
    for i in range(24):
        pd_sck.value(1)
        count = count << 1
        pd_sck.value(0)
        if dout.value():
            count += 1
    pd_sck.value(1)
    count ^= 0x800000
    pd_sck.value(0)
    return count

def get_offset(repetitions=10):
    total = 0
    for _ in range(repetitions):
        total += read_hx711()
        time.sleep(0.1)
    return total / repetitions

def get_scale_factor(known_weight_grams, offset, repetitions=10):
    total = 0
    for _ in range(repetitions):
        total += read_hx711()
        time.sleep(0.1)
    measured_value = total / repetitions
    return (measured_value - offset) / known_weight_grams

def convert_to_weight(raw_value, scale_factor, offset):
    return (raw_value - offset) / scale_factor

def on_ready_pin_change(pin):
    global is_ready, last_debounce_time
    current_time = time.ticks_ms()
    if (current_time - last_debounce_time) > 200:  # 200ms de debounce
        is_ready = not pin.value()
        last_debounce_time = current_time

ready_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=on_ready_pin_change)

lcd.putstr("Medidor ETO")
time.sleep(2)
lcd.clear()

while True:
    if is_ready:
        lcd.putstr("Configurando...")
        OFFSET = get_offset()
        time.sleep(2)
        lcd.clear()
        lcd.putstr("Coloca")
        lcd.move_to(0, 1)  # Mover el cursor a la primera posición de la segunda fila (fila 1, columna 0)
        lcd.putstr("el calibrador")
        is_ready = False  # Restablecer para la próxima señal
        while not is_ready:
            pass
        SCALE_FACTOR = get_scale_factor(100, OFFSET)
        lcd.clear()
        lcd.putstr(f"Factor: {SCALE_FACTOR:.2f}")
        is_ready = False  # Restablecer para iniciar la medición
        break  # Salir del bucle inicial, continuar con la medición

def update_lcd(timer):
    global last_weight
    raw_value = read_hx711()
    weight_grams = convert_to_weight(raw_value, SCALE_FACTOR, OFFSET)
    weight_kg = weight_grams / 1000.0
    if abs(weight_grams - last_weight) > 10:
        lcd.clear()
        lcd.putstr(f"Peso: {weight_kg:.2f} Kg")
        last_weight = weight_grams

last_weight = 0
timer = Timer()
timer.init(freq=0.5, mode=Timer.PERIODIC, callback=update_lcd)

led_pin.value(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT