import time
import board
import busio

# Segment patterns for digits 0 to 9 (bits a to g).
SEGMENTS = (0x3F, 0x06, 0x5B, 0x4F, 0x66,
            0x6D, 0x7D, 0x07, 0x7F, 0x6F)
CONTROL_ADDRESS = 0x24
DIGIT_ADDRESS = 0x34
BRIGHTNESS = 3

i2c = busio.I2C(board.GP5, board.GP4)  # SCL, SDA

def write_byte(address, value):
    while not i2c.try_lock():
        pass
    try:
        i2c.writeto(address, bytes((value,)))
    finally:
        i2c.unlock()

def show_number(number):
    text = "{:04d}".format(number)
    for position, character in enumerate(text):
        write_byte(DIGIT_ADDRESS + position,
                   SEGMENTS[int(character)])

count = 0
try:
    write_byte(CONTROL_ADDRESS, (BRIGHTNESS << 4) | 0x01)
    while True:
        show_number(count)
        count = (count + 1) % 10000
        time.sleep(0.1)
finally:
    try:
        write_byte(CONTROL_ADDRESS, 0x00)  # turn display OFF
    finally:
        i2c.deinit()  # release pins even if cleanup fails
