Arduino

Using functions in Arduino

In Arduino programming functions are used to make the code more readable by dividing the code in proper segments. Similarly, when programming in Arduino, functions are also needed when a task is to be performed at multiple places in the code to avoid the repetition of statements. This discourse explains the use of functions in Arduino programming.

Arduino Functions

The functions can be created for different types of tasks that are to be performed in Arduino programming. The functions can be created outside the set-up and loop functions in Arduino programming. The functions can be used by calling them by the name assigned to the declared function anywhere in the program. Similarly, creating a function can be done by using the following syntax.

// declaring the function
void function name-of-function(arguments-if-any)
{
Statement 1;
Statement 2;
…
}

Example codes of Function in Arduino programing

To give a clear idea about how to create and use the functions in Arduino programming for the reader. There are two codes that are given in the context as example:

Example 1 of function in Arduino programing

The first example is about performing a mathematical operation by declaring a function and then calling it in the set-up. The declared function always has the global variable in its Arguments and when it is called in the setup or loop function these variables are replaced by the variables declared in that function. Here in this example the addition operation is performed by declaring a function and then calling it in the setup function.

void setup(){
  Serial.begin(9600);
  int c = 4;
  int d = 5;
  int e;
  e = addition(c, d);
    Serial.print("the result for addition is ");
    Serial.println(e);
}
void loop() {
}
int addition(int a, int b){
  int f;
  f = a + b;
  return f;
}

Output

Example 2 of function in Arduino programing

The second and the last example of using functions in Arduino programming is declaring a function without passing any arguments.

void setup() {
  Serial.begin(9600);
  hello(); // function call
}
void loop() {
}
void hello(){  // function declaring
  Serial.println("Hello Arduino");
}

Output

Conclusion

In Arduino programming functions can be used to perform different operations. The use of the functions make the Arduino code easy to understand. Similarly, if different statements are required to be used repeatedly in the code of Arduino, instead of writing the whole code the function for those specific instructions is made and called anywhere in code where it is needed. This write-up describes the declaration and usage of function in Arduino programming.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.