Ground Embedded KO Subscribe

Notes / C Language

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.

GROUND EMBEDDED · NOTEC Language 03Control flow 1volatile uint32_t *ODR 2 = (uint32_t*)0x40020014; 3*ODR |= (1u << 5); 4while (1) { 5 if (flag) toggle(); 6}

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 break and 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.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →