from machine import Pin, ADC, SoftI2C
from utime import sleep, ticks_ms, ticks_diff
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
i2c_addresses = i2c.scan()
print("I2C addresses found:", i2c_addresses)
if not i2c_addresses:
raise Exception("No I2C devices found")
lcd_address = i2c_addresses[0]
lcd = I2cLcd(i2c, lcd_address, 2, 16)
POT_PIN = 34
X = 5000 # Time period (ms)
HYSTERESIS = 25
# States
INCREASING = 1
DECREASING = -1
STABLE = 0
def display_potentiometer_value():
pot = ADC(Pin(POT_PIN))
pot.atten(ADC.ATTN_11DB)
simulated_value = 0
last_meaningful_pot_value = pot.read() #Initialize
state = STABLE
start_time = ticks_ms()
while True:
pot_value = pot.read()
# State Detection
diff = pot_value - last_meaningful_pot_value
if diff > HYSTERESIS and state != INCREASING:
state = INCREASING
start_time = ticks_ms()
last_meaningful_pot_value = pot_value #Store it
print("Increasing")
elif diff < -HYSTERESIS and state != DECREASING:
state = DECREASING
last_meaningful_pot_value = pot_value #Store it
print("Decreasing")
elif abs(diff) <= HYSTERESIS:
state = STABLE
print("Stable")
# Value Calculation
if state == INCREASING:
elapsed_time = ticks_diff(ticks_ms(), start_time)
progress = min(1.0, elapsed_time / X)
simulated_value = int(last_meaningful_pot_value + (pot_value - last_meaningful_pot_value) * progress)
else:
simulated_value = pot_value
# Display
lcd.clear()
lcd.putstr("Pot: {}".format(pot_value))
lcd.putstr("\nSim: {}".format(simulated_value))
sleep(0.1)
display_potentiometer_value()