Deterministic functions

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
rtborg
Posts: 16
Joined: Tue Sep 07, 2021 6:01 am

Deterministic functions

Post by rtborg » Sun Dec 05, 2021 3:06 pm

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?

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

Re: Deterministic functions

Post by pythoncoder » Mon Dec 06, 2021 10:38 am

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.
Peter Hinch
Index to my micropython libraries.

rtborg
Posts: 16
Joined: Tue Sep 07, 2021 6:01 am

Re: Deterministic functions

Post by rtborg » Mon Dec 06, 2021 2:41 pm

Thank you for the detailed explanation - using an external flip-flop will probably do the trick, I'll give it a try.

chuckbook
Posts: 135
Joined: Fri Oct 30, 2015 11:55 pm

Re: Deterministic functions

Post by chuckbook » Mon Dec 06, 2021 5:40 pm

I used to enable an EXTI on the UART RX pin and handle the rest in SW.

Post Reply