Hello World Program for an Embedded C Application

Embedded C for microcontrollers



In this article, we go over how to build a first basic program of C for embedded applications.

The first example will serve as the classic, beginning "Hello, World!" This serves to teach the beginning features of a C program for embedded applications.

The first thing about a C program is that must have at least one function, namely the main() function. The function main() is the foundation of a C language program, and it is the starting point when the program code is executed. This means the program begins executing where the main() function is located. All functions are invoked by main() either directly or indirectly.

An embedded C program in its simplest form appears as follows:

void main()
{
while(1); //do forever...
}

The program above will compile and operate, but you won't know it because it doesn't do anything. To see actual results, we will add to the program, so that you can see its output.

#include <stdio.h>

void main()
{
printf("Hello World"); //prints Hello World
while(1); //do forever
}

The program will print the words "Hello World" to the standard output, which is most likely a serial port.

At the top of the program is a line that contains #include and then a file. This is the first of the common preprocessor compiler directives. #include tells the compiler to include a file called stdio.h as part of this program. stdio.h includes input and output functions so that a user can type input into a program and display output. In this program, we do not use any input functions but we do use output. The function printf() is provided for in an external library, and is made available because of this preprocessor compile directive. This allows us to display "Hello World" as output.

In this program, the microcontroller will sit and wait, forever until the microprocessor is reset.

This demonstrates one of the major differences between a personal computer program and a program that is designed for an embedded microcontroller; it is the fact that the embedded microcontroller applications contain an infinite loop. Personal computers have an operating system, and once a program has been executed, 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 an infinite loop built into it somewhere, such as the while(1) example above. This prevents the program from running out of things to do and doing random ethings that may be undesirable.


HTML Comment Box is loading comments...