This question is about programming small microcontrollers without an OS. In particular, I am interested in PIC at the moment, but the question is general.
I saw several times the following pattern for saving time:
Timer interrupt code (say, the timer fires every second):
... if (sec_counter > 0) sec_counter--; ...
Main line code (without interruption):
sec_counter = 500; // 500 seconds while (sec_counter) { // .. do stuff }
The main line code can be repeated, set the counter to various values ββ(not just seconds), etc.
It seems to me that there is a race condition where the assignment of sec_counter in the main code is not atomic. For example, in PIC18, assignment is translated into 4 ASM statements (loading each byte at a time and selecting the right byte from the memory bank before). If the interrupt code is in the middle of this, the final value may be corrupted.
Interestingly, if the assigned value is less than 256, the destination is atomic, so there is no problem.
Am I right about this issue? What patterns do you use to correctly implement this behavior? I see several options:
- Disabling interrupts before each assignment of sec_counter and turning on after is not a good thing.
- Do not use interrupt, but a separate timer that starts and then polls. It is clean, but uses the entire timer (in the previous case, the 1 second on timer can be used for other purposes).
Any other ideas?
source share