Nanosecond resolution with the Pico #650
Replies: 2 comments 2 replies
-
@Phoenix1747 You can count clock cycles, instead of microseconds, like this:
That's the 32 bit version. There's also a 64 bit version, p2040.getCycleCount64(), that takes a lot longer to repeat - about 4,000 years, I think. Here's an example to refer to, in the Examples section: If you use the 32 bit version, you have to allow for the wrap-around, when making a comparison based on adding a time increment which can take the result past zero (like a clock passing 12). That takes a bit of thinking about, and a few more instructions. Bear in mind that it's unsigned numbers, so the results of a subtraction are always either zero or positive - like moving the hands of a clock. If you use the 64 bit one, there's less to think about, but a trade off of having to do things in 64 bits, which is always slightly slower, per operation. For the 64 bit version, you need a 64 bit variable to put it in, of course:
|
Beta Was this translation helpful? Give feedback.
-
You're welcome, @Phoenix1747 :) Here's an example of how and how not to handle the wrap around problem, in this case with micros(). It tries to wait for 50 microseconds, but in the case of a wrap-around, it wouldn't wait. A worse problem can be missing the event and then waiting for it to come around again:
The reason the first version was wrong was because endtime (micros() + delta) can be a small value, if the current micros() is almost at the maximum - so micros() + delta overflows, passing zero. The comparison then doesn't do what was intended. In the corrected version, when micros() passes endtime, the result of endtime - micros() is a large positive number, much greater than delta, whether or not there was a wrap-around / overflow, so the comparison does what we want. The way to do it is to always take a difference, then compare it with an increment of time, like this:
In this case, the statement just does nothing, while waiting (it repeats the empty expression, before the semicolon). Normally, you'd probably want to do something every so often, rather than just wait for a period of time - something like this:
You can potentially have several blocks like that one, doing different things at different time intervals. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Theoretically the Pico's 133(+) MHz should give us about 8 ns of time resolution. With some computational overhead what could the limit to this resolution be in practice? Are <100ns reasonable? If yes, it would be pretty sweet to have a nanos() function just like the millis() and micros() macros of the Arduino IDE.
Beta Was this translation helpful? Give feedback.
All reactions