# RP2040 - set period square wave on GPIO-26 by statemachine.put
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-08-22  Initial release

from	machine		import	Pin
import	time
import	rp2

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

# Frequency on GPIO-26 is determined by value in X
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def freqY():
    set(x, 0)						# start with GPIO-25 = low
    label('loop')
    pull(noblock)					# OSR := TX_FIFO or X when empty
    mov(x, osr)
    jmp(not_x, 'loop')				# wait until x not 0
    mov(y, x)
    set(pins, 1)					# high for X clocks
    label('l1')
    jmp(y_dec, 'l1')
    mov(y, x)
    set(pins, 0)					# low fro X clocks
    label('l2')
    jmp(y_dec, 'l2')
    jmp('loop')

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

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


    # put value into sm.TX_FIFO
    def put(self, value):
        self.sm.put(value)
                 
# ========================== main ==============================

# alternating 6.12 and 3.12 kHz with trigger on frequency change
def main():
    sm      = PioMach(freqY, set_base=Pin(26))
    trigger = Pin(16, Pin.OUT)	# a oscilloscope trigger on frequency change
    while True:
        print('*', end='')		# monitor
        sm.put(10000)			# put into TX_FIFO		6.24 kHz
        trigger(0)
        time.sleep(1)
        print('!', end='')		# monitor
        sm.put(20000)			# put into TX_FIFO		3.12 kHz
        trigger(1)
        time.sleep(1)


main()

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