Control flow: why firmware is an infinite loop
Building flow with if, switch, for and while, and why embedded programs are written as a loop that never ends.
A PC program exits when its work is done. An MCU has no operating system to return to, so main must never end. That is why nearly all firmware is initialisation followed by an infinite loop.
int main(void) {
init_clock();
init_gpio();
while (1) {
read_sensor();
update_control();
send_status();
}
}
Choosing a statement
- if / else: two or three conditions
- switch: branching on one value, such as a state or a command number. Forget a
breakand execution falls into the next case. - for: a fixed number of repetitions
- while: waiting until a condition changes. A loop that waits on a flag must always have a timeout.
The trap in waiting loops
Code that waits on a hardware flag, such as while (!(USART->SR & TXE));, stops forever if the hardware never responds. Leaving a way out with a counter or a timer is standard practice.