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

from	machine			import	freq;			freq(240_000_000)
import	time
from	array	import	array
from	fks_drivers_01	import	lprint, i2c

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

# write string[4] to 7-segm Led's using utf-8 strings
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')
    
#    t1 = time.ticks_us()
    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
#    t2 = time.ticks_us()
#    print(t2-t1)													# 1540 uSec


# write 4 ascii bytes to 7-segm Led's, 31% speed improvement using bytes
def s7WriteB(b4):
    CHARS    = b' 0123456789ABCDEF'
    PATTERNS = bytes.fromhex('00 3F 06 5B 4F 66 6D 7D 07 7F 6F 77 7C 39 5E 79 71')

#    t1 = time.ticks_us()
    i2c.writeto(36, b'\x31')														# 0x24
    i2c.writeto(52, PATTERNS[CHARS.index(b4[0].to_bytes())].to_bytes())		# 0x34
    i2c.writeto(53, PATTERNS[CHARS.index(b4[1].to_bytes())].to_bytes())		# 0x35
    i2c.writeto(54, PATTERNS[CHARS.index(b4[2].to_bytes())].to_bytes())		# 0x36
    i2c.writeto(55, PATTERNS[CHARS.index(b4[3].to_bytes())].to_bytes())		# 0x37
#    t2 = time.ticks_us()
#    print(t2-t1)															# 1171 uSec


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

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

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

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

    x   = 1234;		      				print('x  :', type(x),    x)
    b4  = bytes(f'{x:4}', 'ascii');		print('b4 :', type(b4),  b4)
    ch  = b4[1];						print('ch :', type(ch),  ch)
    idx = CHARS.index(ch.to_bytes());	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')														# 0x24
    i2c.writeto(53, bpt)				# see: '_2__'
    
    
# Print Hello world to LCD 1602 @ 5V Vdd
def test3():
    lprint('Hello')
    lprint('   world!')
    
 
test1()

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