Sub topic 11
Writing your own functions
A function is a named block of code that you can run from anywhere in a sketch. You have already called functions such as pinMode(), digitalWrite(), and delay(). This chapter shows you how to write your own. The next chapter covers parameters and return values in more depth, so here we focus on why functions help, how to define and call them, and the mistakes that cause trouble.
Prerequisites
This chapter assumes you can do the following:
- Upload a sketch with the Arduino IDE and open the Serial Monitor.
- Explain what
setup()andloop()do. - Declare variables and know the basic data types (
int,byte,bool,unsigned long). - Write
ifstatements andforloops. - Tell local variables from global variables.
Why write functions
Without functions, a sketch grows into one long loop(). The same few lines get copied in several places. When you fix a bug in one copy, you forget the others. Functions solve three problems:
- Repetition. You write the code once and call it many times.
- Readability. A name like
flashWarning()tells the reader what happens. The reader does not have to decode ten lines ofdigitalWrite()calls. - Testing. You can check a small function on its own before you rely on it.
You have been using functions all along. setup() and loop() are functions too. The Arduino core calls them for you. Your own functions work the same way, except that you decide when to call them.
The anatomy of a function
A function definition has four parts:
return_type name(parameters) {
body
}- The return type is the data type of the value the function hands back. Use
voidif it returns nothing. - The name follows the same rules as a variable name. Use letters, digits, and underscores, and do not start with a digit.
- The parameter list in parentheses holds the inputs. It can be empty.
- The body in braces is the code that runs when you call the function.
Here is the first version of a blink sketch that uses a custom function:
const byte ledPin = LED_BUILTIN;
void flashOnce() {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
flashOnce();
flashOnce();
flashOnce();
delay(1000);
}The function flashOnce() takes no input and returns nothing. Each call turns the LED on for 100 ms and off for 100 ms. The loop() calls it three times and then pauses for one second, which produces a triple flash.
What happens when you call a function
When code calls a function, execution jumps to the start of that function. It runs the body, then returns to the line after the call. The diagram shows this for one pass through loop().
Each call gets its own set of local variables, which exist only while the function runs. That is why local variables cannot keep a value between calls unless you declare them static, as the scope chapter showed.
Adding parameters
A function that always does the same thing is useful, but a function that accepts input is more flexible. Parameters are variables declared in the parentheses. They receive the values you pass in the call.
const byte ledPin = LED_BUILTIN;
void flash(byte times, unsigned int onMs) {
for (byte i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(onMs);
digitalWrite(ledPin, LOW);
delay(onMs);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
flash(3, 100);
delay(1000);
flash(2, 400);
delay(1000);
}The call flash(3, 100) copies 3 into times and 100 into onMs. Arguments are matched to parameters by position, so the order matters. Swapping them compiles without complaint but gives the wrong behavior.
By default, Arduino C++ passes arguments by value. The function receives a copy, so changing times inside flash() does not change anything in the caller.
Returning a value
A function with a return type other than void must send back a value with return. The return statement ends the function immediately.
int readAverage(int pin, byte samples) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
delay(2);
}
return total / samples;
}
void setup() {
Serial.begin(9600);
}
void loop() {
int average = readAverage(A0, 10);
Serial.println(average);
delay(500);
}Notice three details:
totalis alongbecause ten readings of up to 1023 can exceed what a 16-bitintholds on an Uno (32767 maximum). With more samples, aninttotal would overflow.- The result of
total / samplesis converted tointon return. - The caller stores the result in
average. You can also use a call directly inside an expression, such asSerial.println(readAverage(A0, 10));.
A function can have several return statements, for example inside if branches. Every path through a non-void function should end in a return. If one does not, the compiler may warn you, and the value the caller receives is undefined.
Functions that answer a question
A common pattern is a function that returns bool and is named like a question. It keeps conditions short and readable.
const byte buttonPin = 2;
const byte ledPin = LED_BUILTIN;
bool isButtonPressed() {
return digitalRead(buttonPin) == LOW;
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (isButtonPressed()) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}With INPUT_PULLUP, a pressed button reads LOW. Hiding that detail inside isButtonPressed() means the rest of the sketch reads naturally. If you later change the wiring so a press reads HIGH, you edit one line.
Where to put functions
The Arduino IDE helps you here. Before compiling, it scans your .ino file and generates declarations (prototypes) for your functions. This is why you can usually define a function below the place where you call it.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(square(7));
delay(1000);
}
int square(int value) {
return value * value;
}The sketch above works in the IDE even though square() is defined after loop(). Automatic prototype generation has limits. It can fail with some unusual parameter types, such as custom struct types, and in files other than the main .ino. When that happens, write the prototype yourself near the top of the file:
int square(int value);A prototype is the function's first line followed by a semicolon. It tells the compiler the name, parameter types, and return type before the full definition appears.
Choosing what a function should do
Good functions are small and do one thing. Use these guidelines:
- Name the function with a verb for actions (
flash,printStatus) and a question for tests (isButtonPressed). - Keep the body short enough to read without scrolling.
- Pass in what the function needs rather than reading global variables. This makes the function reusable and easier to test.
- Return results rather than printing them from inside, unless printing is the function's purpose.
The table compares the common function shapes.
| Shape | Example | Typical use |
|---|---|---|
| No input, no output | `void flashOnce()` | Fixed action |
| Input, no output | `void flash(byte times, unsigned int onMs)` | Configurable action |
| No input, output | `bool isButtonPressed()` | Read or test something |
| Input and output | `int readAverage(int pin, byte samples)` | Calculation or measurement |
Common errors
- Missing return type. Writing
flash(byte times)withoutvoidis a compile error. - Missing return value. A function declared
intthat finishes withoutreturngives undefined results. - Wrong argument count.
flash(3)fails to compile ifflashtakes two parameters. The compiler reports "too few arguments to function". - Using a local variable outside its function. A variable declared inside a function does not exist elsewhere. The compiler reports it as "not declared in this scope".
- Expecting parameters to change the caller's variable. Arguments are copies. To modify the caller's variable you need a reference parameter, such as
void addOne(int &value), which is an advanced feature. - Calling a function that blocks. A function that uses
delay()freezes the whole sketch while it runs. A call toflash(10, 500)holdsloop()for ten seconds. The last chapter shows how to replace such waits withmillis(). - Integer overflow in the return type. Returning a
longsum through anintreturn type truncates the result silently on 8-bit boards.
Default arguments and overloading
Arduino code is C++, so two more features are available.
A default argument gives a parameter a value when the caller leaves it out:
const byte ledPin = LED_BUILTIN;
void flash(byte times = 1, unsigned int onMs = 200) {
for (byte i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(onMs);
digitalWrite(ledPin, LOW);
delay(onMs);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
flash(); // 1 flash, 200 ms
delay(1000);
flash(3); // 3 flashes, 200 ms
delay(1000);
flash(2, 50); // 2 flashes, 50 ms
delay(1000);
}Defaults must be the rightmost parameters. You cannot skip times and supply only onMs.
Overloading means defining several functions with the same name but different parameter lists. The compiler picks the one that matches the call. Serial.print() is overloaded this way, which is why it accepts integers, floats, and text. Use overloading sparingly in small sketches, because default arguments often do the job with less confusion.
Putting it together
This sketch combines a test function, an action function with parameters, and a function that returns a value. The loop() stays short and reads like a description of the behavior.
const byte buttonPin = 2;
const byte ledPin = LED_BUILTIN;
bool isButtonPressed() {
return digitalRead(buttonPin) == LOW;
}
void flash(byte times, unsigned int onMs) {
for (byte i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(onMs);
digitalWrite(ledPin, LOW);
delay(onMs);
}
}
byte flashesFor(int reading) {
if (reading > 700) {
return 5;
}
if (reading > 300) {
return 3;
}
return 1;
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (isButtonPressed()) {
int reading = analogRead(A0);
byte count = flashesFor(reading);
Serial.print("Reading: ");
Serial.print(reading);
Serial.print(" flashes: ");
Serial.println(count);
flash(count, 150);
delay(300);
}
}When the button is pressed, the sketch reads a potentiometer on A0, picks a flash count from the value, prints both to the Serial Monitor, and flashes the LED. Each function can be tested alone. For example, you can call flashesFor(900) from setup() and print the result to confirm it returns 5.
Exercise
What is the output of this sketch's first Serial line, and why? Assume the Serial Monitor is open at 9600 baud. int triple(int value) { value = value * 3; return value; } void setup() { Serial.begin(9600); int x = 4; int y = triple(x); Serial.println(x); Serial.println(y); } void loop() {}
Show answer
The first line printed is 4. Arguments are passed by value, so triple() works on a copy of x. The assignment inside the function changes only that copy. The second line printed is 12, which is the value the function returned and stored in y.
Exercise
Write a function named clampToRange that takes three int parameters (value, low, high) and returns value limited to the range from low to high. For example, clampToRange(15, 0, 10) returns 10 and clampToRange(-3, 0, 10) returns 0.
Show answer
int clampToRange(int value, int low, int high) { if (value < low) { return low; } if (value > high) { return high; } return value; }
Exercise
A sketch calls flash(10, 500) from loop() and also needs to react to a button press within 100 ms. Why does this fail, and which technique from the final chapter addresses it?
Show answer
flash() uses delay(), so the call blocks for about ten seconds (10 flashes of 500 ms on plus 500 ms off). The sketch cannot read the button during that time. Timing with millis() lets the sketch check elapsed time on each pass through loop() without stopping, so the button can be read on every pass.