# Demo code for measurement of duration of low and high state on a selected input pin
# The test signal is generated with PWM.
# This is a public domain (or CC0) code written by Wojciech M. Zabolotny ([email protected])
# The code was developed with help of wokwi (https://wokwi.com) simulator
# and tested on real RPi Pico W
import time
import rp2
import machine as m
time.sleep(0.1) # Wait for USB to become ready
print("Pulse duration measurement")
p1=m.Pin(4,m.Pin.OUT)
pw1=m.PWM(p1)
pw1.freq(100)
pw1.duty_u16(32768//4)
#pw1.duty_u16(32768*3//2)

@rp2.asm_pio(in_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=False)
def read_pulse():
    set(y,1)
    in_(y,1)
    in_(null,30)
    #in_(null,1)
    mov(y,isr)
    push()
    wrap_target()
    mov(x, y)
    label("again_0")
    jmp(pin, "is_one")
    jmp(x_dec,"again_0")
    jmp("again_0")
    # Here we jump after rising edge
    label("is_one")
    in_(x,31)
    set(x,0)
    in_(x,1)
    push()
    mov(x,y)
    label("again_1")
    jmp(pin,"is_one_b")
    jmp("is_zero")
    label("is_one_b")
    jmp(x_dec,"again_1")
    label("is_zero")
    in_(x,31)
    set(x,1)
    in_(x,1)
    push()
    wrap()


p2 = m.Pin(2,m.Pin.IN)
if False: # Direct read
  while(True):
    print(p2.value())
if True: # Use PIO
  sm = rp2.StateMachine(0, read_pulse, freq=10000000, jmp_pin=p2)
  sm.active(1)
  print("Started!")
  while(True):
     print("Loop")
     b=sm.get()
     state=b & 1
     duration = (1<<30) - (b >> 1)
     print(state, duration)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT