from machine import Pin, ADC
import time
# Pin definitions
SHCP_PIN = Pin(2, Pin.OUT) # Shift Register Clock (GPIO 2)
STCP_PIN = Pin(1, Pin.OUT) # Storage Register Clock (GPIO 1)
DS_PIN = Pin(0, Pin.OUT) # Data (GPIO 0)
LED1_PIN = Pin(3, Pin.OUT) # LED1 control (GPIO 3)
LED2_PIN = Pin(4, Pin.OUT) # LED2 control (GPIO 4)
POT1_PIN = ADC(26) # Potentiometer 1 (GPIO 26)
POT2_PIN = ADC(27) # Potentiometer 2 (GPIO 27)
POT3_PIN = ADC(28) # Potentiometer 3 (GPIO 28)
# 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
]
def shift_out(data_pin, clock_pin, bit_order, value):
"""
Shift out a byte of data one bit at a time.
Args:
data_pin: The pin where data is written
clock_pin: The pin to toggle with each bit
bit_order: MSB (most significant bit) or LSB (least significant bit) first
value: The byte to shift out
"""
for i in range(8):
if bit_order == "MSBFIRST":
bit_val = (value & (1 << (7 - i))) > 0
else:
bit_val = (value & (1 << i)) > 0
data_pin.value(bit_val)
clock_pin.value(1)
clock_pin.value(0)
def display_number(number):
"""
Display a number (0-99) on the 7-segment displays.
Args:
number: The number to display (0-99)
"""
tens = number // 10
ones = number % 10
tens_code = segment_codes[tens]
ones_code = segment_codes[ones]
# Shift out the one's digit first, then the ten's digit
shift_out(DS_PIN, SHCP_PIN, "MSBFIRST", ones_code)
shift_out(DS_PIN, SHCP_PIN, "MSBFIRST", tens_code)
# Latch the data to the output pins
STCP_PIN.value(1)
STCP_PIN.value(0)
# Setup
display_number(0) # Initialize display to 0
# Main loop
while True:
# Read potentiometer values (scale down to 0-1023 range)
# Pi Pico ADC is 16-bit (0-65535), Arduino is 10-bit (0-1023)
pot1_value = POT1_PIN.read_u16() // 64
pot2_value = POT2_PIN.read_u16() // 64
pot3_value = POT3_PIN.read_u16() // 64
# Map pot3 to 0-99 for display
displayed_number = int(pot3_value * 99 / 1023)
# Display the number on the 7-segment displays
display_number(displayed_number)
# Control LEDs based on the parity of the displayed number
if displayed_number % 2 == 0: # Even number
# LED1 is controlled by POT1
if pot1_value > 511:
LED1_PIN.value(1) # Turn LED1 on
else:
LED1_PIN.value(0) # Turn LED1 off
LED2_PIN.value(0) # LED2 is always off for even numbers
else: # Odd number
LED1_PIN.value(0) # LED1 is always off for odd numbers
# LED2 is controlled by POT2
if pot2_value > 511:
LED2_PIN.value(1) # Turn LED2 on
else:
LED2_PIN.value(0) # Turn LED2 off
# Delay to avoid rapid updates
time.sleep(0.1)