# RP2040 - Generate configurable large range period square wave
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-08-22  Initial release

from	machine		import	Pin
import	rp2

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

# Frequency on GPIO-16 is 1 Hz   --> / 62_500_000 = $3B9ACA0 =
# 0x01 0x1B 0x13 0x0B 0x05 0x00 in 5 bit items
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def freq1HzY():
    set(y, 0)
    set(y, 0x01); in_(y, 5)				# shift 5 bit from Y --> ISR
    set(y, 0x1B); in_(y, 5)
    set(y, 0x13); in_(y, 5)
    set(y, 0x0B); in_(y, 5)
    set(y, 0x05); in_(y, 5)
    set(y, 0x00); in_(y, 5)
    mov(y, isr)
    label('loop')
    mov(x, y)
    set(pins, 1)
    label('l1')
    jmp(x_dec, 'l1')					# possible to add up to 31 * nop()
    mov(x, y)
    set(pins, 0)
    label('l2')
    jmp(x_dec, 'l2')
    jmp('loop')

# ======================= 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.active(True)

# ========================== main ==============================

sm = PioMach(freq1HzY, set_base=Pin(26))								# 1 Hz on GPIO-26

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