import time # Import time library for delays
import board # Import board library to access pins
import digitalio # Import digitalio to control pins
from cd4511 import CD4511 # Import CD4511 driver for 7-segment display
bcd_tens = [board.GP2, board.GP3, board.GP4, board.GP5] # BCD pins for tens digit
bcd_ones = [board.GP6, board.GP7, board.GP8, board.GP9] # BCD pins for ones digit
ten_display = CD4511(bcd_tens, board.GP0) # Setup tens digit display
ones_display = CD4511(bcd_ones, board.GP1) # Setup ones digit display
sw_up = digitalio.DigitalInOut(board.GP15) # Setup SW Up pin
sw_up.direction = digitalio.Direction.INPUT # Set as input
sw_up.pull = digitalio.Pull.UP # Enable pull-up resistor
sw_down = digitalio.DigitalInOut(board.GP16) # Setup SW Down pin
sw_down.direction = digitalio.Direction.INPUT # Set as input
sw_down.pull = digitalio.Pull.UP # Enable pull-up resistor
count = 0 # Counter value starts at 0
run = False # Counter not running by default
direction = 1 # 1 = count up, -1 = count down
last_up = 1 # Store previous state of SW Up
last_down = 1 # Store previous state of SW Down
while True:
ten_display.display(count // 10) # Show tens digit on left display
ones_display.display(count % 10) # Show ones digit on right display
up = sw_up.value # Read current state of SW Up
down = sw_down.value # Read current state of SW Down
if last_up == 1 and up == 0: # Detect SW Up button press
run = True # Start counter
direction = 1 # Set direction to count up
print("Count Up:", count) # Print current count
if last_down == 1 and down == 0: # Detect SW Down button press
run = True # Start counter
direction = -1 # Set direction to count down
print("Count Down:", count) # Print current count
last_up = up # Save current SW Up state
last_down = down # Save current SW Down state
if run: # Only update if counter is running
count = (count + direction) % 100 # Update count, wrap 0-99
if direction == 1:
print("COUNT UP:", count) # Print if counting up
else:
print("COUNT DOWN:", count) # Print if counting down
time.sleep(0.5) # Wait 0.5 seconds before next count