# RP2040 - PIO 1 Hz on-board Led using IRQ
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-08-22  Initial release

from	machine		import	Pin
import	time
import	rp2

# ======================= PIO functions ======================

# 1 Hz blinking on-board led GPIO-25
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def blinky():
                                        # Cycles: 1 + 1 + 6 + 32 * 31 = 1000
    set(pins, 1)						# pins = 1
    irq(rel(0))							# Set IRQ relative SM 0
    set(x, 31)                  [5]		# x = 31 
    label('delay_high')
    jmp(x_dec, 'delay_high')	[30]	# x -= 1, jump if True
                                        # Cycles: 1 + 7 + 32 * 31 = 1000
    set(pins, 0)
    set(x, 31)                  [6]
    label('delay_low')
    jmp(x_dec, 'delay_low')		[30]

# ======================= State machine ========================

# helper class for PIO StateMachines
class PioMach:
    
    def  __init__(self, program, freq=125_000_000, id=0, **kwargs):
        sm = rp2.StateMachine(id, program, freq, **kwargs)
        sm.irq(self.onPioIrq)
        sm.active(True)


    def onPioIrq(self, sender):
        print(sender, time.ticks_ms())
    
# ========================== main ==============================

sm = PioMach(blinky, freq=2000, set_base=Pin(25))						# 1 Hz on led

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