What's the standard way to do atomic assignments on teensy 4.1

samm_flynn

Well-known member
Context:
I have a timer interrupt running at 1 kHz that performs calculations. For these calculations, I need 6 float values, which are received over USB serial. The serialEvent() function (called at over 7 MHz) assigns values to these 6 floats. Given that the Teensy 4.1 is a 32-bit microcontroller and each float assignment takes 1 cycle(I am assuming), there’s a risk that the timer interrupt might trigger in the middle of these assignments. This would result in unsynchronized data being used in the timer callback.

Question:
How can I ensure that the 6 float assignments occur atomically—that is, without a timer interrupt occurring in the middle of the assignment process? Specifically, if I disable interrupts around the assignment block (using something like noInterrupts(); assignment(); interrupts(), will the timer interrupt be queued and executed after interrupts are re-enabled, or will it be completely skipped?

Are there any way to read variable inside the interrupt safely? Is there a special way to do this?
 
You can have atomic variables (see the c++ std::atomic class) but the issue here is that you have a collection of variables rather than one. You can either disable/enable interrupts (any triggered interrupts will execute when they are re-enabled) or you can change what the interrupt handler does - have it set a flag that gets periodically checked outside of serialEvent() (the EventResponder class is designed for this).
 
To expand on what @jmarsh is saying, write as many variables as you want, and then write the flag variable last, so the only thing that matters is whether read/write of the flag is atomic. On this CPU, the flag can be 8-, 16-, or 32-bit, as long as it's properly aligned, which the compiler does by default, unless you tell it not to.
 
How can I ensure that the 6 float assignments occur atomically—that is, without a timer interrupt occurring in the middle of the assignment process?
Disable interrupts around the assignment sequence. This is called a "critical section" in the literature.
 
Back
Top