from machine import Pin, ADC, I2C
from time import sleep_ms, ticks_ms, ticks_diff
from i2c_lcd import I2cLcd
import _thread

# Define pin connections
S0_PIN = 14  # Example pin for S0
S1_PIN = 27  # Example pin for S1
S2_PIN = 26  # Example pin for S2
S3_PIN = 25  # Example pin for S3
SIG_PIN = 33 # Example pin for SIG
en_pin = 12

# Initialize pins
s0 = Pin(S0_PIN, Pin.OUT)
s1 = Pin(S1_PIN, Pin.OUT)
s2 = Pin(S2_PIN, Pin.OUT)
s3 = Pin(S3_PIN, Pin.OUT)
adc = ADC(Pin(SIG_PIN))
en = Pin(en_pin, Pin.OUT)
sys_mode = Pin(32, Pin.IN, Pin.PULL_DOWN)

# LCD Pins
i2c_sda = 21
i2c_scl = 22
lcd_addr = 0x27
i2c = I2C(0, sda=Pin(i2c_sda), scl=Pin(i2c_scl), freq=400000)
lcd = I2cLcd(i2c, lcd_addr, 2, 16)

# Function to initialize the multiplexer pins
def startup():
    s0.value(0)
    s1.value(0)
    s2.value(0)
    s3.value(0)

# Function to read from a specific channel
def read_channel(channel):
    s0.value(channel & 0x01)
    s1.value(channel & 0x02)
    s2.value(channel & 0x04)
    s3.value(channel & 0x08)
    return adc.read()

def mux_read_loop(threshold):
    count = 0
    sampled_values = [[] for _ in range(16)]  # List to store sampled values for each channel
    while count < threshold:
        for channel in range(16):
            data = read_channel(channel)
            # Thresholding the data
            threshold_value = 1000  # Adjust the threshold as needed
            digital_data = 1 if data > threshold_value else 0
            sampled_values[channel].append(digital_data)
            sleep_ms(10)  # Adjust as needed
        # print(count)
        count += 1
    
    # Calculate average for each channel
    averaged_values = [int(sum(samples) / len(samples)) if samples else 0 for samples in sampled_values]
    print(averaged_values)

def button_thread():
    while True:
        if sys_mode.value() == 1:
            pressed_time = ticks_ms()
            lcd.clear()
            lcd.putstr("pressed")
            while sys_mode.value() == 1:  # Wait for button release
                sleep_ms(10)
            released_time = ticks_ms()
            time_pressed = ticks_diff(released_time, pressed_time)
            lcd.clear()
            lcd.putstr("{}s Pressed".format(time_pressed))
            lcd.clear()
            if 500 <= time_pressed <= 2000:
                # mode_change()
                pass
            elif 2001 <= time_pressed <= 4000:
                # reset()
                pass
        sleep_ms(10)

def loop():
    startup()
    sleep_ms(2)
    _thread.start_new_thread(button_thread, ())  # Start the button thread
    mux_read_loop(20)  # Change the threshold value as needed

# Run the main function
if __name__ == "__main__":
    while True:
        loop()

Loading
esp32-devkit-c-v4
Loading
cd74hc4067