from machine import Pin
import time

# Define pins
SHCP_PIN = Pin(2, Pin.OUT)  # Clock pin (previously A2)
STCP_PIN = Pin(1, Pin.OUT)  # Latch pin (previously A1)
DS_PIN = Pin(0, Pin.OUT)    # Data pin (previously A0)

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

# LED pins
led1 = Pin(3, Pin.OUT)  # Previously pin 2
led2 = Pin(4, Pin.OUT)  # Previously pin 3

# Bar graph pins (previously pins 4-13)
bar_graph_pins = []
for i in range(5, 15):
    bar_graph_pins.append(Pin(i, Pin.OUT))

# Initialize variables
current_number = 0
led_state = False

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

def display_number(num):
    """Display a two-digit number on the 7-segment displays"""
    tens_code = segment_codes[num // 10]
    units_code = segment_codes[num % 10]
    
    # Send the data to shift registers - unit digit first, then tens
    shift_out(DS_PIN, SHCP_PIN, 1, units_code)  # 1 = MSBFIRST
    shift_out(DS_PIN, SHCP_PIN, 1, tens_code)
    
    # Latch the data
    STCP_PIN.value(1)
    STCP_PIN.value(0)

def update_bar_graph(segments):
    """Update the LED bar graph to show specified number of segments"""
    for i in range(10):
        bar_graph_pins[i].value(1 if i < segments else 0)

# Setup function
def setup():
    display_number(0)
    update_bar_graph(1)

# Main loop
def loop():
    global current_number, led_state
    
    while True:
        time.sleep(2)
        
        # Update counter and displays
        current_number = (current_number + 1) % 100
        display_number(current_number)
        update_bar_graph((current_number // 10) + 1)
        
        # Toggle LEDs
        led_state = not led_state
        led1.value(1 if led_state else 0)
        led2.value(0 if led_state else 1)

# Run the program
setup()
loop()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
74HC595
74HC595