Reference   Language (extended) | Libraries | Comparison

Functions

Functions allow a programmer to create modular pieces of code that performs a defined task and then returns to the area of code from which the function was "called". The typical case for creating a function is when one needs to perform the same action multiple times in a program.

For programmers accustomed to using BASIC, functions in Arduino provide (and extend) the utility of using subroutines (GOSUB).

Standardizing code fragments into functions has several advantages:

  • Functions help the programmer stay organized. Often this helps to concpetualize the program.

  • They codify one action in one place so that the function only has to be thought out and debugged once.

  • This also reduces chances for errors in modification, if the code needs to be changed.

  • Functions make the whole sketch smaller and more compact because sections of code are reused many times.

  • They make it easier to reuse code in other programs by making it more modular, and as a nice side effect, using functions also often makes the code more readable.

Example

In a program to keep track of school records, we move a student up a grade if they are old enough, or if they have passed a test, but only if they have paid their tuition.

if (student_age > x) {
  if (tuition == "paid") {
    student_grade++;
  }
}
if (test_score > y) {
  if (tuition == "paid") {
    student_grade++;
  }
}

However, if we later want to change tuition to a numerical test showing that they owe us less than a hundred dollars -- tuition < 100; -- we have to change the code in two places, greatly increasing the risk of bugs if we change it one place and forget to change it in the other.

A function helps by giving a block of code a name, then letting you call the entire block with that name. As a result, when you need to changed the named code, you only have to change it in one place.

Our function looks like this:

// tell us the type of data the function expects
void tuitionTest(int tuition_balance) {
  if (tuition_balance < 100) {
    student_grade++;
  }
}

And our code looks like this:

if (student_age > x) {
  tuitionTest(tuition_balance);
}
if (test_score > y) {
  tuitionTest(tuition_balance);
}

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.