Reputation: 115
I have a question about generating square waves with finite length by using a Raspberry Pi Pico. For example, I want to generate a 20 kHz square wave with 100 periods, or to generate a 20 kHz square wave with an exact 1 ms. I cannot have accurate control over it.
To generate an infinite length of square waves is easy, as there are lots of examples online. I can use PIO to achieve it. For example, the following code could do so:
import rp2
from machine import Pin
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def blink():
set(pins, 1)
set(pins, 0)
sm = rp2.StateMachine(0, blink, freq=25000, set_base=Pin(26))
sm.active(1)
However, I don't know how to accurately control the length/periods of the square wave. By using time.sleep() is not accurate at all.
Thank you in advance!
Upvotes: 0
Views: 914
Reputation: 937
Use the "decrement X" instruction in the PIO to count the number of cycles you want. Might have to add some delays to get back a square wave. jmp(x_dec, "top_of_loop")
. You'd hang, waiting for some input, and read the X value from the input FIFO. Then you'd run the square-wave loop, decrementing X. When it hits zero, you jump to the outer loop, where you again wait for a new X value for the number of cycles. I think that's it!
Upvotes: 2