Page 1 of 1

Deterministic functions

Posted: Sun Dec 05, 2021 3:06 pm
by rtborg
I have a RPi Pico board which I am using to output a trigger when a certain message is sent out via the UART. The code is:

Code: Select all

uart.write(cmd)
trigger_pin.on() # This is the important trigger edge
response = uart.read(n)
trigger_pin.off()
Using a scope, I can see that the pin is not turned on at the same time every time the code above runs. The difference is quite small - in order of tens of microseconds, but it's still large enough to make the system not work.

I looked up online what I can do to make the code more deterministic, and I found this link, which proposes stopping the garbage collector before a critical call. I also watched Writing fast and efficient MicroPython, but did not find a direct reference to determinism. Can you advice what can be done to achieve deterministic behavior of critical sections of code?

Re: Deterministic functions

Posted: Mon Dec 06, 2021 10:38 am
by pythoncoder
I assume you're measuring the time difference between the leading edge of the UART output and the pin change. If this is the case, the lack of determinism may be in the UART handling. I've not studied the firmware driver (you might want to do this) but typically a UART driver works as follows. Characters are put in a buffer and an interrupt driven process is started. Whenever the UART is ready for data an interrupt occurs, which causes a character to be removed from the buffer and put into the UART hardware.

Interrupt handling typically involves some latency and potential conflict with higher priority interrupts. So, while the timing of an individual character is precise, there may be delays and latency between characters. And possibly between the byte stream being presented to the driver and the first character emerging from the UART.

You might want to consider doing this job in hardware, using the UART start bit to set an R-S flip flop which is cleared down by a pin controlled by code.

Re: Deterministic functions

Posted: Mon Dec 06, 2021 2:41 pm
by rtborg
Thank you for the detailed explanation - using an external flip-flop will probably do the trick, I'll give it a try.

Re: Deterministic functions

Posted: Mon Dec 06, 2021 5:40 pm
by chuckbook
I used to enable an EXTI on the UART RX pin and handle the rest in SW.