Make real 50.000ms delay

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
farnots
Posts: 1
Joined: Tue Jan 26, 2016 2:01 pm

Make real 50.000ms delay

Post by farnots » Tue May 24, 2016 5:05 pm

Hi,

I try to save value every 50ms. But when I make a delay each time I take value, I don't have a true 50ms between each value but more 49.619ms ; 49.67ms ; 49.792ms ....

So when I check the pyb.delay time to operation I have the same precision with this code :

import pyb
from pyb import Pin, Timer

micros = pyb.Timer(8, prescaler=167, period=0x3fffffff)


print("start")
micros.counter(0)
start_micros = micros.counter()
pyb.delay(50)
pyb.delay(50-micros.counter)
end_micros = micros.counter()
print (micros.counter()/1000)
print("end")

I would like to know if it is possible to have a 50.000ms between each delay.
Thanks

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Make real 50.000ms delay

Post by dhylands » Tue May 24, 2016 5:57 pm

That's extremely doubtful, even in C.

The issue is that there are interrupts running in the background, and these will always cause some variation somewhere.

You can setup a hardware timer to fire exactly every 50,000 msec, but there is no guarantee that your callback will execute exactly the same amount of time after the interrupt occurs. Your callback will fire with an average of 50,0000 msec, but not exactly.

To get repetitive exact times typically requires hardware, or very well constrained software (and python isn't going to give that to you).

mianos
Posts: 84
Joined: Sat Aug 22, 2015 6:42 am

Re: Make real 50.000ms delay

Post by mianos » Tue May 24, 2016 10:52 pm

The normal way to do this is in two stages. Use a hardware timer to trigger a reading interrupt handler. Read the value in the interrupt handler and save it to a circular buffer, doing the least amount of of work. This can now be read outside of the interrupt. If your interrupt priority is set up correctly, your interrupt handler will not be interrupted until you reset the mask. I have gotten uS precision on 12MHz CPUs doing this. It is mainly a problem of reading the data sheets as the actual code is generally very small because it has to be.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Make real 50.000ms delay

Post by pythoncoder » Wed May 25, 2016 5:24 am

@mianos This is fine so long as you can guarantee that a higher priority interrupt won't be running at the time yours occurs.
Peter Hinch
Index to my micropython libraries.

Post Reply