Skip to content

Instantly share code, notes, and snippets.

@fasaxc
Created January 12, 2024 21:48
Show Gist options
  • Select an option

  • Save fasaxc/518b0e80c7502eb45a5eda19368869a7 to your computer and use it in GitHub Desktop.

Select an option

Save fasaxc/518b0e80c7502eb45a5eda19368869a7 to your computer and use it in GitHub Desktop.
import time
from machine import Pin
import micropython
import rp2
@rp2.asm_pio()
def measure_high_time():
wrap_target()
# x = 0xffffffff
mov(x, invert(null))
# Wait for a HIGH.
wait(1, pin, 0)
label("high_loop")
jmp(x_dec, "cont_high_loop")
label("cont_high_loop")
nop()
jmp(pin, "high_loop")
mov(isr, x)
push(noblock)
wrap()
@rp2.asm_pio()
def measure_interval():
wrap_target()
# x = 0xffffffff
mov(x, invert(null))
# Wait for LOW->HIGH transition.
wait(0, pin, 0)
wait(1, pin, 0)
label("loop_while_high")
jmp(x_dec, "cont_loop_while_high")
label("cont_loop_while_high")
nop()
jmp(pin, "loop_while_high")
label("loop_while_low")
jmp(x_dec, "cont_loop_while_low")
label("cont_loop_while_low")
jmp(pin, "send")
jmp("loop_while_low")
label("send")
mov(isr, x)
push(noblock)
wrap()
pin18 = Pin(18, Pin.IN, Pin.PULL_UP)
sm0 = rp2.StateMachine(0, measure_high_time, freq=125_000_000, in_base=pin18, jmp_pin=pin18)
sm1 = rp2.StateMachine(4, measure_interval, freq=125_000_000, in_base=pin18, jmp_pin=pin18)
# Start the StateMachine's running.
sm0.active(1)
sm1.active(1)
pin0 = Pin(0, Pin.OUT)
def run():
ivl = 0xffffffff - sm1.get()
while True:
pin0.low()
while 1:
high = 0xffffffff - sm0.get()
if sm0.rx_fifo() == 0:
break
pin0.high()
duty = high*4119//ivl - 15
if duty < 0:
duty = 0
if duty > 4095:
duty = 0
#print("{:6} {:6} {:4} {:.2f}".format(ivl, high, duty, duty*360/4096))
#print(duty*360/4096)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment