# esp32 - driver for 8x8 leds array through MAX7219 SPI driver FKS0001
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-05-07  initial release

from	machine	import	Pin, SPI
import	time

# ============================= Leds64 =========================

class Leds64:
    
    # SPI setup pin_cs=CS, pin_mosi=DIN, pin_sck=CLK and pin_miso=not connected
    def __init__(self, pin_cs=2, pin_sck=0, pin_mosi=15, pin_miso=4):
        self.cs   = Pin(pin_cs, Pin.OUT, value=1)
        self.spi  = SPI(1, 1_000_000, polarity=0, phase=0, sck=Pin(pin_sck),
                        mosi=Pin(pin_mosi), miso=Pin(pin_miso))
        
        
    # Activate driver
    def on(self, intensity=3):
        self.cs(0); self.spi.write(b'\x0C\x01'); self.cs(1)			# mode = normal
        self.cs(0); self.spi.write(b'\x0A\x03'); self.cs(1)			# intensity 3/15
        self.cs(0); self.spi.write(b'\x0B\xFF'); self.cs(1)			# scan limit
        

    # De-activate driver
    def off(self):
        self.cs(0); self.spi.write(b'\x0C\x00'); self.cs(1)			# mode = off


    # display pattern as in 8-bytes
    # first byte: leds in most right bar, bit #0: bottom led, bit #7: top led
    # 8th   byte: leds in most left  bar, bit #0: bottom led, bit #7: top led
    def write(self, data=b'\x01\x80\x80\x80\x80\x80\x80\x02'):
        for idx in range(8):
            word = bytes([idx+1, data[idx]])
            self.cs(0); self.spi.write(word); self.cs(1)			# mode = off

# ======================= test ==========================

if __name__ == '__main__':
    
    # show default test pattern for five seconds
    def test():
        leds64 = Leds64()
        leds64.on()
        leds64.write()			# b'\x01\x80\x80\x80\x80\x80\x80\x02'
        time.sleep(5)
        leds64.off()


    test()

# ================================= end ====================================

    