# Esp32 - Driver for 4 x 7-segmet LED display on kit FKS0001
# provided by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-06-19  initial release

from 	machine 	import 	Pin, I2C, freq;		freq(240_000_000)
import	time

# Implemented:
# led7Init(pin_scl=22, pin_sda=21)
# led7Show(value=0, dp=None, hex=False)

# ===================== 4 digit 7 segment LED ==========================

i2c	= None

# Setup I2C channel for 4 digit 7-segment LED display
def led7Init(pin_scl=22, pin_sda=21):
    global i2c
    i2c = I2C(0, scl=Pin(pin_scl), sda=Pin(pin_sda), freq=400000)
    
       
# Display value on 4 digit 7-segment LED display
def led7Show(value=0, dp=None, hex=False):
    CHARS    = b' 0123456789ABCDEF'
    PATTERNS = bytes.fromhex('00 3F 06 5B 4F 66 6D 7D 07 7F 6F 77 7C 39 5E 79 71')

    if value is None: b4=b'    '
    elif hex: b4 = bytes(f'{value:04X}', 'ascii')
    else    : b4 = bytes(f'{value:4}', 'ascii')
    dig0 = PATTERNS[CHARS.index(b4[0].to_bytes())];
    dig1 = PATTERNS[CHARS.index(b4[1].to_bytes())]
    dig2 = PATTERNS[CHARS.index(b4[2].to_bytes())]
    dig3 = PATTERNS[CHARS.index(b4[3].to_bytes())]
    if   dp == 4: dig0 += 0x80 
    elif dp == 3: dig1 += 0x80 
    elif dp == 2: dig2 += 0x80 
    elif dp == 1: dig3 += 0x80 
    i2c.writeto(36, b'\x31')				# 0x24
    i2c.writeto(52, dig0.to_bytes())		# 0x34
    i2c.writeto(53, dig1.to_bytes())		# 0x35
    i2c.writeto(54, dig2.to_bytes())		# 0x36
    i2c.writeto(55, dig3.to_bytes())		# 0x37

# ========================= Test =============================

def test():
    led7Init()
    while True:
        led7Show(None);	              time.sleep(2)
        led7Show(1000, 3);        time.sleep(2)		# 10.00
        led7Show(1000, hex=True); time.sleep(2)
        
        
test()

# ===================== End =========================
