import time
import board
import digitalio
class CD4511:
def __init__(self, pins, latch_pin):
# Initialize the 4 BCD data pins
self.pins = []
for p in pins:
pin = digitalio.DigitalInOut(p)
pin.direction = digitalio.Direction.OUTPUT
self.pins.append(pin)
# Initialize the Latch (Store) pin
self.latch = digitalio.DigitalInOut(latch_pin)
self.latch.direction = digitalio.Direction.OUTPUT
def display(self, num):
# BCD Truth Table for 0-9 (Binary format)
bcd = [
(0,0,0,0), (1,0,0,0), (0,1,0,0), (1,1,0,0),
(0,0,1,0), (1,0,1,0), (0,1,1,0), (1,1,1,0),
(0,0,0,1), (1,0,0,1)
]
if 0 <= num <= 9:
# Set the four pins to the corresponding binary bits
for pin, val in zip(self.pins, bcd[num]):
pin.value = val
# Toggle the latch to "freeze" the number on the display
self.latch.value = True
self.latch.value = False
# Pin Definitions
bcd_tens = [board.GP2, board.GP3, board.GP4, board.GP5]
bcd_ones = [board.GP6, board.GP7, board.GP8, board.GP9]
# Create display objects
tens_display = CD4511(bcd_tens, board.GP0)
ones_display = CD4511(bcd_ones, board.GP1)
# Button Setup (Internal Pull-Up resistors)
btn_up = digitalio.DigitalInOut(board.GP15)
btn_up.direction = digitalio.Direction.INPUT
btn_up.pull = digitalio.Pull.UP
# Button Setup (Internal Pull-Down resistors)
btn_down = digitalio.DigitalInOut(board.GP16)
btn_down.direction = digitalio.Direction.INPUT
btn_down.pull = digitalio.Pull.UP
count = 0
while True:
# Check Increment Button
if not btn_up.value:
count = (count + 1) % 100
time.sleep(0.2) # Debounce
# Check Decrement Button
if not btn_down.value:
count = (count - 1) % 100
time.sleep(0.2) # Debounce
# Split the count into two digits
tens = count // 10
ones = count % 10
# Send digits to the hardware
tens_display.display(tens)
ones_display.display(ones)
print("Displaying:", count)
time.sleep(0.05)