0

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!

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.