# Esp32 - Controlling 4 digit 7-segment Led's
# provided by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-05-30  initial release

from	machine	import	Pin, I2C
from	array	import	array

# ====================== 4 digit LCD driver =============================

i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)

# write string[4] to 7-segm LCD
def s7Write(s4):
    CHARS    = ' 0123456789ABCDEF'
    PATTERNS = bytes.fromhex('00 3F 06 5B 4F 66 6D 7D 07 7F 6F 77 7C 39 5E 79 71')
    
    i2c.writeto(36, b'\x31')										# 0x24
    i2c.writeto(52, PATTERNS[CHARS.index(s4[0])].to_bytes())		# 0x34
    i2c.writeto(53, PATTERNS[CHARS.index(s4[1])].to_bytes())		# 0x35
    i2c.writeto(54, PATTERNS[CHARS.index(s4[2])].to_bytes())		# 0x36
    i2c.writeto(55, PATTERNS[CHARS.index(s4[3])].to_bytes())		# 0x37


# write integer x in decimal format
def s7Decimal(x):
    s7Write(f'{x:4}')
    

# write integer x in hexadecimal format
def s7Hex(x):
    s7Write(f'{x:04X}')

# ============================ Tests =======================================

# Show decimal and hexadecimal on 4 digit 7-segm LCD
def test1():
    s7Write('ABCD')
#    s7Decimal(987)
#    s7Hex(990)
    
    
# encoder explanation as in s7Decimal
def test2():
    CHARS    = ' 0123456789ABCDEF'
    PATTERNS = bytes.fromhex('00 3F 06 5B 4F 66 6D 7D 07 7F 6F 77 7C 39 5E 79 71')

    x   = 987;		      		print('x  :', type(x),    x)
    s4  = f'{x:4}';	        	print('s4 :', type(s4),  s4)
    ch  = s4[1];				print('ch :', type(ch),  ch)
    idx = CHARS.index(ch);		print('idx:', type(idx), idx)
    pat = PATTERNS[idx];		print('pat:', type(pat), pat)
    bpt = pat.to_bytes();		print('bpt:', type(bpt), bpt, hex(bpt[0]))
    i2c.writeto(36, b'\x31')									
    i2c.writeto(53, bpt)
    
    
test1()

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