from machine import Pin, ADC
import time

# Pin definitions
LED1_PIN = 2  # GP2
LED2_PIN = 3  # GP3
LED3_PIN = 4  # GP4
SHCP_PIN = 7  # GP7 (Clock)
STCP_PIN = 6  # GP6 (Latch)
DS_PIN = 5    # GP5 (Data)
POT_PIN = 26  # GP26 (Analog)

# Create pin objects
led1 = Pin(LED1_PIN, Pin.OUT)
led2 = Pin(LED2_PIN, Pin.OUT)
led3 = Pin(LED3_PIN, Pin.OUT)
shcp = Pin(SHCP_PIN, Pin.OUT)
stcp = Pin(STCP_PIN, Pin.OUT)
ds = Pin(DS_PIN, Pin.OUT)
pot = ADC(POT_PIN)

# Seven segment display codes (common anode, 0 = ON)
segment_codes = [
    0b11000000,  # 0
    0b11111001,  # 1
    0b10100100,  # 2
    0b10110000,  # 3
    0b10011001,  # 4
    0b10010010,  # 5
    0b10000010,  # 6
    0b11111000,  # 7
    0b10000000,  # 8
    0b10010000   # 9
]

def shift_out(data_pin, clock_pin, bit_order, value):
    """
    Emulate Arduino's shiftOut function
    bit_order: MSBFIRST (1) or LSBFIRST (0)
    """
    for i in range(8):
        if bit_order == 0:  # LSBFIRST
            bit = (value >> i) & 1
        else:  # MSBFIRST
            bit = (value >> (7 - i)) & 1
            
        data_pin.value(bit)
        clock_pin.value(1)
        clock_pin.value(0)

def display_number(number):
    """
    Display a 2-digit number on the 7-segment displays
    """
    tens = number // 10
    ones = number % 10
    
    tens_code = segment_codes[tens]
    ones_code = segment_codes[ones]
    
    # Shifting data for ones digit first, then tens digit
    shift_out(ds, shcp, 1, ones_code)  # 1 = MSBFIRST
    shift_out(ds, shcp, 1, tens_code)  # 1 = MSBFIRST
    
    # Latch the data
    stcp.value(1)
    stcp.value(0)

# Initialize
led1.value(0)
led2.value(0)
led3.value(0)
display_number(0)

# Main loop
while True:
    # Read potentiometer
    # Convert 16-bit ADC reading (0-65535) to 10-bit range (0-1023)
    pot_value = int(pot.read_u16() * 1023 / 65535)
    mapped_value = int(pot_value * 99 / 1023)  # Map to 0-99
    
    # Control LEDs based on value
    if mapped_value <= 33:
        led1.value(1)
        led2.value(0)
        led3.value(0)
    elif mapped_value <= 66:
        led1.value(1)
        led2.value(1)
        led3.value(0)
    else:
        led1.value(1)
        led2.value(1)
        led3.value(1)
    
    # Display the number
    display_number(mapped_value)
    
    # Wait
    time.sleep(2)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
74HC595
74HC595