If you’re starting with C programming for your microcontrollers, this is an excellent place to start learning functions
Introduction
Functions in C make programming more readable and efficient. Imagine trying to write code that runs from start to finish in a single flow. This would be hard to maintain and would take up much code space. Having said this, functions can greatly help in code re-use, modularization, and well-defined program execution.
What are Functions in C?
Functions are modularized routines; once main code executes and encounters a function call, it will jump to the body of that routine to execute its statements. A function can have a return type (integer, char, etc.) or not at all (use the void type). A process (not visible to users) of saving specific special function register values in a hardware or software stack can happen before executing the function. These values can be retrieved after the function call ends, as these registers are essential for correct program execution.
Consider two simple functions to display a message and increment a counter variable on the serial monitor below.
byte ctr1;
void display_message1();
byte inc_ctr();
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
ctr1 = 0;
}
void loop() {
// put your main code here, to run repeatedly:
display_message1();
ctr1 = inc_ctr();
delay(500);
}
void display_message1()
{
Serial.println("Hello you have entered procedure 1");
Serial.println("The current value of counter 1 is: ");
Serial.println(ctr1);
Serial.println("");
}
byte inc_ctr()
{
ctr1 = ctr1 + 1;
return ctr1;
}
How Do You Use Them?
To use a function, you should declare it first. The declaration can be before or after the main loop. If you declare it after main, you should include a function prototype before main. This ensures the compiler recognizes the functions during compilation. Below is a diagram to illustrate how to declare and use functions.

Note that functions that return a value (does not have a void return type) should include a return statement. This return statement passes the value after it to the actual value of the function.
The functions can be invoked through function calls in the main loop. Functions can also include functions inside them.
Next topic... Function parameters
Functions can also have parameters that most programmers find helpful to abstract away the complexities of data usage. This will be discussed in another topic.