# uPy - Testing RPi Pico SPI loopback
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-01-12  Initial release

from	machine		import	Pin, SPI
import	time

# ================== Hardware definitions ======================

pin_led         = 25					# on-board green led
pins_button		= (10, 11, 12, 13)
pins_led		= ( 0,  1,  2,  3)
pin_buzzer		= 14
pin_spi_sck		= 18
pin_spi_mosi	= 19
pin_spi_miso	= 16
pin_spi_cs		= 17

# ==================== Hardware setup  =========================

led		= Pin(pin_led, Pin.OUT, value=1)
buttons	= [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in pins_button]
leds	= [Pin(pin, Pin.OUT, value=0)    for pin in pins_led]
buzzer	= Pin(pin_buzzer, Pin.OUT, value=0)
spi	    = SPI(0, 10_000_000, sck=pin_spi_sck, mosi=pin_spi_mosi,
              miso=pin_spi_miso)
spi_cs  = Pin(pin_spi_cs, Pin.OUT, value=1)

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

# Buttons 1..4 control Leds 1..4, button 4 also operates the buzzer
def testGPIO():
    for _ in range(10):
        for button, led in zip(buttons, leds):
            led(button())			# led := button @ 10 Hz
        buzzer(buttons[3]())		# buzzer is Button 4
    

# a two byte SPI loop-back test
def testSPI(statics={0:0}):
        data_tx = bytearray(b'\x31\x32')	# or bytearray([0x31, 0x32])
        data_rx = bytearray(len(data_tx))
        spi_cs(0)
        spi.write_readinto(data_tx, data_rx)
        spi_cs(1)
        print(f'{statics[0]}  spi tx: {data_tx}, rx: {data_rx}')
        statics[0] += 1


# test GPIO and SPI loop back test
def test():
    while True:
        for _ in range(10):
            testGPIO()
            time.sleep_ms(100)
        testSPI()						# SPI test and monitor @ 1 Hz
        led(not led())					# on-board led 0.5 Hz
              
        
test()

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