Question about short delays

  • I assume the preferred (maybe the only practical) way to insert a short (i.e. less than 1 second) delay on PyCom's implementation of micropython, is to use time.sleep(), time.sleep_ms(), or time.sleep_us()? One example would be generating a 50ms pulse (i.e. toggle on then off) on a GPIO.

    I ask because there are other microphyton implementations that have sleep and delay functions on 'machine' or other implementation-specific libraries.

    What is the effective resolution of the sleep functions (i.e. the minimum accurate time that can be requested) and how accurate is it?

    Also, during the sleep period, are other threads allowed to run? If so, is there some "magic threshold" of sleep duration, below which they are not and above which they are?

  • Sleep() function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps. With multiple threads and processes, sleep() suspends your thread - it uses next to zero processing power.

  • @robert-hh Interesting idea; I'll give it a try, but I think I'll also compare it with a sleep_ms (if it's accurate enough, that would sure be simpler :)

  • @Eric24 I understood your intention. So the best way I would choose is to start a pulse by pulling GPIO low, and then set off an one shot timer, which at the end triggers an interrupt, pulling GPIO high again. that would have a jitter of about 300 us, 1 ms worst case. You can also use sleep_ms(), but that may be affected ba other threads, unless you have only one.

  • @robert-hh I think you may have interpreted my question as being "how to achieve a string of pulses", but I'm actually only interested in a single pulse (i.e. one high-to-low to low-to-high transition of a particular pulse duration). So I don't think PWM is a solution for that. I realize there will be some amount of latency and tolerance for any software-based delay, and that's really what my question is about--what is the preferred way to cause an "accurate as possible" delay and what is that level of accuracy?

  • @Eric24 For most of the questions you must try yourself. Sleep affects the thread which calls it. For a regular square wave of 100 ms period time (50ms on/off) the best choice is to use PWM, because that is purely done by hardware. Second best choice is a timer interrupt, but that will have a substantial jitter of about +/- 300 µs for each transition. For all other software based activities you have no timing guarantee. Always assume that a few ms of jitter may occur.

Log in to reply

Pycom on Twitter