r/raspberrypipico • • 13d ago

uPython microPython - "Nudge Lock" and Sub-10ns Time-Stamping

Post image

I wanted to implement some precision time-stamping for a microPython project, whilst also keeping these timestamps aligned to the 1us counter (so script could use ticks_us() in tandem).

I wanted to do as much as possible in hardware, so that CPU timing was irrelevant (ie process is NOT affected by any CPU interrupts/blocking code).

Here is the scheme I invented...

  • Alignment - The "Nudge Lock" process aligns the 1us Tick and CLK_GPOUT0 clock, by reading the 'tick countdown' at the rising edge of CLK_GPOUT0 and 'nudging' CLK_GPOUT0 if they do not align. Once aligned, the Counter PIO can be started/sync'ed so it counts with 7.8125ns steps (1/128th of 1us).
  • Time-Stamping - After setup, the Detect and Relay PIOs are re-assigned to trigger from 1PPS (or other input), and the DMA then copies the 1us Counter (32bit) to the FIFO when triggered. Counter PIO simultaneously triggers and copies it's 7.8125ns count to FIFO.
  • Validation and Blend - the Counter PIO is exactly aligned with 1us Tick, the lower 7 bits contain a fractional 1us value and the 8th bit is 1us. Since the DMA might be slightly slow to access/copy the 1us counter, the 8th bit can be used to detect (and correct) this slow transfer.

Limitations:

  • CPU is overclocked to 256MHz, so that Counter PIO precisely matches with 1us.
  • For setup (initial sync) Counter(s) must be in same PIO block as 1st Detect as it uses inter-PIO IRQ. Other Detects may be in other PIO blocks

Notes:

  • For an 'electronics guy' it's handy to have the 1us tick rendered (on GPIO21) so that it can scoped.
  • Relay PIO are not strictly required, but I like the 'comfort' of knowing I have 4x buffer of samples and not a memory location will might be over-written by new sample if I am slow to process old sample.
  • With Relay PIO - RP2040 can be configured to 2x timestamped inputs, RP2350 can be configured to 4x timestamped inputs.
  • Without Relay PIO - RP2040 can be configured to 4x timestamped inputs, RP2350 can be configured to 6x timestamped inputs.
  • DMA can transfer 64bit us Counter, as 4x 32bit which are post-processed. This also removes my 'comfort' buffer.

If anyone found this interesting, or wants to try it out, I placed the code here:

https://github.com/orgs/micropython/discussions/19927#discussioncomment-19570374

17 Upvotes

0 comments sorted by