While (1) in Embedded C- Explained 


               


While(1) in Embedded C- Explained

Embedded C for microcontrollers



In this article, we will explain what the line while(1) is and what it does in a C application.

The line while(1) is most popular used in applications for embedded microcontrollers, for reasons which will be explained below.

The line while(1) in a C program creates an infinite loop- this is a loop that never stops executing. It executes over and over and over again, unless the program is intentionally stopped or there is some condition under this loop that gets met that takes the program out of this infinite loop.

Let's take the following C program.


#include <stdio.h>

void main()
{
printf("Hello World");
while(1);
}


This program prints the words "Hello World" to the standard output, which is most likely a serial port.

After it prints it, it goes to execute the next line, while(1). This line makes the microcontroller sit and wait, forever or until the microcontroller is reset.

This is a very common way to code embedded applications. This demonstrates one of the major differences between a personal computer program and a program that is designed for an embedded microcontroller- chiefly that the embedded microcontroller applications contain an infinte loop.

Why do they contain an infinite loop? While personal computers have an operating system, embedded microcontrollers generally do not. Once a program has been executed on a personal computer, it returns control to the operating system of the computer. An embedded microcontroller, however, does not have an operating system and cannot be allowed to fall out of the program at any time. Hence, every embedded microcontroller application has infinite loop built into it somewhere, such as the line while(1). This prevents the program from running out of things to do and doing random things that may be undesirable.

HTML Comment Box is loading comments...