#
# steptime.py
#
# Internal resistor step-response loading measurement with RP2040 PIO
# As a library. 
#
# Neil Gershenfeld 9/8/25 (original hello.steptime.RP2040.py)
# Modified by Krisjanis rijnieks 2026-01-31 to work with QPad and as a library
#
# This work may be reproduced, modified, distributed,
# performed, and displayed for any purpose, but must
# acknowledge this project. Copyright is retained and
# must be preserved. The work is provided as is; no
# warranty is provided, and users accept all liability.
#
# install MicroPython
#    https://micropython.org/download/RPI_PICO/
#

import rp2

@rp2.asm_pio(set_init=rp2.PIO.OUT_HIGH)
def steptimer():
    #
    # initialize
    #
    pull()
    mov(y,osr) # move loop to y
    pull() # move settle to osr
    mov(x,null) # move count to x
    set(pins,0) # set pin low
    #
    # main loop
    #
    label('main loop')
    #
    # charge down
    #
    set(pindirs,1) # set pin to output
    #
    # settle down
    #
    mov(isr,x)
    mov(x,osr)
    label('down settle loop')
    jmp(x_dec,'down settle loop')
    mov(x,isr)
    #
    # charge through pull-up
    #
    set(pindirs,0) # set pin to input
    #
    # time up
    #
    label('up loop')
    jmp(pin,'up continue')
    jmp(x_dec,'up loop')
    #
    # loop
    #
    label('up continue')
    jmp(y_dec,'main loop')
    #
    # push count
    #
    mov(isr,x)
    push()
    
class STEPTIME:
    def __init__(self, sm_id, pin):
        self._sm = rp2.StateMachine(
            sm_id,
            steptimer,
            jmp_pin=pin,
            set_base=pin)
        self._sm.active(True)
        self.get = self._sm.get
        self.put = self._sm.put
