Embedded Systems & Firmware
You want to run a control calculation every 1 ms on a microcontroller without an OS. Which implementation is most suitable?
- ASet a flag in a 1 ms timer interrupt, and have the main loop perform the calculation when it sees the flag
- BInsert an empty loop in the main loop that takes roughly 1 ms to create the interval
- CReboot the microcontroller after each calculation
Show answer and explanation
Answer: A. Set a flag in a 1 ms timer interrupt, and have the main loop perform the calculation when it sees the flag
Timing with an empty loop drifts with the duration of other processing and with compiler optimization, so it is inaccurate. A hardware timer counts precisely regardless of processing, so using a 1 ms interrupt as the reference keeps the interval constant. A short calculation can be done directly in the interrupt, but a longer one is better signaled by a flag and done in the main loop so it does not delay other interrupts.
- A. Correct. A hardware timer gives an accurate interval.
- B. The interval varies with other work and is inaccurate.
- C. Rebooting is unnecessary.