Functions

When writing a program, you often have to execute the same set of instructions repeatedly at different points in your program. One way to do this would be to type the instructions every point in the program you need them. The big challenge with this approach is that if you need to make a change to that set of instructions, you will need to ensure that change is replicated everywhere you have used those instructions. This process can get quite cumbersome and error-prone, especially when your programs grow larger.

Functions are a way to solve this problem. Functions allow you to create a set of instructions and give them a name (just like a variable name). Then, wherever in your program you need to execute that set of instructions, you can use the function (this is known as calling the function, using its given name).

Functions accept what are known as parameters. Since the set of instructions may be the same, but the data they need to work on may be different each time, the data can be passed to the functions as parameters. And functions return a value, which is then used by the calling program at the point where and when the function is called.

The code below shows how functions can be used:

// Define a function with a name and a parameter
// Here it calculates the average of the array of values passed as a parameter.
function calculate_average(values_array){
  let average_value = 0;
  let sum_values =0;
    
  values_array.forEach(value => sum_values += value)
  average_value = sum_values/values_array.length;
 
  // The return statement passes the result of the function to the calling code.
  return average_value;
}
 
// The main code.
let sensor_data = [10, 20, 30, 40, 50];
// Call the function with the array of values as a parameter.
// Get the return value in the variable and print it.
let average_sensor_data = calculate_average(sensor_data);
console.log(average_sensor_data); // Will print 30

Libraries

As programming languages have grown quite complex, and as programmers have gathered years of experience in understanding what tasks all programs commonly need to perform, many languages provide what are known as libraries.

Libraries are a collection of commonly used functions that make it easy for the programmer to get started with writing application code. In many cases, the libraries include functions to do tasks that every programmer may not be able to do and can leverage the expertise of others who have created the libraries of functions.

We will be using several libraries when programming an Arduino and related modules. Since it is difficult and time-consuming to write programs from scratch for every module, these libraries, written by experts and made available for everyone to use, significantly simplify our task of writing application programs.