from machine import Pin
import utime

# 定义引脚
data_pin = Pin(2, Pin.IN)   # Q7
clock_pin = Pin(6, Pin.OUT) # CP
latch_pin = Pin(3, Pin.OUT) # PL

# 定义位的数量,假设是单个74HC165,有8位
num_bits = 8

def setup():
    # 这里不需要初始化串口,因为MicroPython默认已经配置好
    pass

def read_shift_register():
    # 读取8位数据
    data = 0
    for i in range(num_bits):
        
        data |= (data_pin.value() << i) if data_pin.value() else 0
        clock_pin.value(1)
        utime.sleep_us(1)  # 等待稳定
        clock_pin.value(0)
    return data

def loop():
    # Step 1: Sample
    latch_pin.value(0)
    utime.sleep_us(1)  # 等待稳定
    latch_pin.value(1)

    # Step 2: Shift and read
    data = read_shift_register()
    
    # 打印8位二进制数据
    print('  ', end='')
    print(f'{data:08b}', end='\r')

    utime.sleep(0.2)  # 1秒延迟

# 主循环
while True:
    setup()
    loop()
74HC165