In Arduino, define a function by writing its return type, name, parameters, and body in C++: for example, int add(int a, int b) { return a + b; }. A function gives a sketch a named, reusable task; call it from setup(), loop(), or another function whenever that task is needed.
What a Function Does in an Arduino Sketch
An Arduino sketch is a C++ program built around two special functions: setup(), which runs once after startup or reset, and loop(), which runs repeatedly. You can define additional functions to keep the work in those two functions manageable. For instance, a sketch might have a function to read a sensor, another to convert its reading, and another to control an output.
Functions help separate a program into named jobs. Instead of copying the same sequence of commands in several places, write the sequence once and call it where required. This can make a sketch easier to read, change, and troubleshoot. A function does not run simply because it appears in the file: execution reaches it only when the program calls it, except for the special entry behavior of setup() and loop().
Arduino functions use C++ syntax. There is no separate Arduino-only keyword for defining a function. Arduino’s libraries also provide functions, such as pinMode() and digitalWrite(); a function you write follows the same basic language rules.
Basic Function Syntax
A function definition has a return type, a name, a pair of parentheses for parameters, and a body in braces. The return type specifies what kind of value the function sends back. Use void when it does not return a value. The parameters, if any, are local names for information passed in by the caller.
int add(int a, int b) {
return a + b;
}
Here, int is the return type, add is the function name, and int a and int b are its parameters. The body calculates a sum. The return statement sends that sum back to the code that called the function. A call such as int total = add(4, 7); stores 11 in total.
A function that performs an action without returning a value can be written like this:
void turnLedOn() {
digitalWrite(LED_BUILTIN, HIGH);
}
Its name is turnLedOn, and it has no parameters. Calling turnLedOn(); executes the statement in its body. The semicolon belongs after the call, while the function definition itself ends with its closing brace, not a semicolon.
Defining and Calling a Function
A complete sketch can call a function from loop(). This example blinks the built-in LED using a helper function to set its state and wait:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
setLed(HIGH);
delay(500);
setLed(LOW);
delay(500);
}
void setLed(int state) {
digitalWrite(LED_BUILTIN, state);
}
Each time through loop(), the sketch calls setLed() twice, passing HIGH and then LOW. The parameter named state receives the value for that particular call. The function definition occurs after loop() here; that arrangement is commonly accepted in Arduino sketches because the Arduino build process generates function prototypes for many sketches. A prototype is a declaration that tells the compiler a function’s name, return type, and parameters before its definition is encountered.
For clarity and portability, especially when moving code into ordinary C++ files or working with complicated declarations, you can put a prototype before the first call:
void setLed(int state);
Then place the function definition later in the sketch. The prototype ends in a semicolon and has no function body. Arduino’s automatic prototype generation is a convenience of the sketch build process, not a rule of the C++ language; it does not remove the need to use valid C++ declarations.
Parameters, Arguments, and Return Values
Parameters let a function work with different inputs without duplicating its body. In the definition void setLed(int state), state is a parameter. In a call such as setLed(HIGH), HIGH is the argument supplied for it. A function can have several parameters, separated by commas, or none at all. If it has none, keep the parentheses: void reportStatus().
In ordinary value parameters, the function receives its own copy of the value. Changing a parameter inside the function does not change the caller’s original variable. When a function should provide a result, give it a suitable non-void return type and return a value of a compatible type:
float voltsFromReading(int reading) {
return reading * (5.0 / 1023.0);
}
The example illustrates the conversion used by a 10-bit analog reading with a 5-volt reference. Actual reference voltage and analog resolution depend on the board and its configuration, so adapt the calculation to the hardware. The function returns a float; its caller can store or use that result. A function declared with a non-void return type should return an appropriate value on every path that reaches its end.
C++ also supports reference parameters, which let a function operate on a caller’s object rather than a copy. References and pointers can be useful for larger data or when a function needs to modify an argument, but they introduce details beyond a simple value parameter. Use them deliberately, and make it clear in the function’s name or documentation if it changes supplied data.
Scope, Naming, and Organizing Code
Variables declared inside a function body are local to that function. A local variable is created for the function’s execution and cannot normally be named directly from a different function. Variables declared outside all functions have global scope and can be accessed from multiple functions, subject to declarations and other C++ rules. Prefer passing needed values as parameters when practical: this makes dependencies visible and often makes code easier to reuse.
Give functions names that describe an action or result, such as readTemperature(), updateDisplay(), or isButtonPressed(). C++ is case-sensitive, so readSensor and readsensor are different names. Function names cannot contain spaces, and reserved C++ keywords cannot be used as names. A small function should generally express one clear job; a function that mixes sensor reading, display formatting, and unrelated output control can be harder to understand and test.
As a project grows, functions can be organized into separate files. Arduino sketches may include additional .cpp and header files in the sketch folder. A header commonly contains declarations, while a source file contains definitions. Unlike the main .ino sketch file, a regular C++ source file is compiled as C++ directly and does not receive the same Arduino sketch prototype-generation treatment. Include the appropriate declarations and required headers when using that structure.
Common Function Errors and How to Fix Them
- Calling a function with the wrong number of arguments: A call must match the function’s declared parameters, unless an applicable default argument or overload exists. Compare the call with the definition or prototype.
- Using the wrong return type: If a function promises an
intorfloat, return a suitable value. If it only performs an action, declare itvoidrather than trying to use a nonexistent result. - Forgetting parentheses: A function call needs parentheses, even when it takes no arguments. Write
reportStatus();, not justreportStatus;. - Missing braces or semicolons: Check that the function body has a matching opening and closing brace. Function calls and declarations usually require semicolons; a definition’s closing brace does not.
- Defining the same function twice: Two identical definitions cause a compilation error. A prototype is not a second definition because it has no body.
- Assuming a function runs automatically: A helper function runs only when called. Put the call on a path that the program actually reaches, such as inside
loop().
When compilation fails, read the first meaningful error and check the line it identifies as well as the lines just before it. A missing brace or semicolon earlier in the file can make the compiler report a confusing problem at a later function. If the sketch compiles but behaves incorrectly, trace the call sequence and inspect the values passed into each function.
Choosing Between a Function and Inline Code
Use a function when a set of statements has a clear purpose, is needed in multiple places, or makes a long section of loop() easier to follow. A helper such as readButton() can give a meaningful name to details that do not need to be repeated throughout the sketch. Functions also make it easier to change a behavior in one place.
Not every single statement needs a function. A tiny one-use operation may be clearer where it is written, especially if extracting it would add an unclear name or require unnecessary parameters. The useful test is whether the function makes the program’s structure more understandable, not whether the sketch has the maximum possible number of functions.
Functions are not the same thing as Arduino library methods, although both are functions in C++. A library function is supplied by a library and may be called by your sketch; a user-defined function is one you write. Nor does defining a function make its work happen in parallel: normal function calls run in sequence. A function that contains delay(), for example, pauses the current flow of execution rather than starting a background task.
Memory and Hardware Considerations
On a microcontroller, code size, global data, and the call stack all matter. Calling a function uses some stack space for information such as local variables and return bookkeeping. Most ordinary helper functions are unremarkable, but deep or unbounded recursion can consume limited stack space and cause unreliable behavior. Recursion means a function calls itself, directly or through other functions; iterative loops are often easier to reason about on small boards.
A function call does not automatically make a sketch faster or slower in a way that can be judged without the specific code, compiler, and board. Clear structure is usually more important than trying to avoid every helper function. If timing is critical, measure the behavior on the intended hardware and consider how delays, peripheral operations, interrupts, and library calls affect the timing. Keep interrupt service routines especially focused; ordinary functions that block or take a long time may be unsuitable to call from an interrupt context.
Frequently Asked Questions
Do Arduino functions have to be defined before they are called?
In standard C++, the compiler needs a declaration before a function call. Arduino’s sketch build process typically generates prototypes for functions in an .ino sketch, which often lets you define a helper later in the file. In regular C++ source files, provide a declaration before use.
What does void mean in an Arduino function?void as the return type means the function does not send a value back to its caller. It can still perform actions, such as setting a pin or printing data. A function with no parameters still uses parentheses.
Can a function be called from setup() and loop()?
Yes. A function can be called from either one, and it can also be called from another function, as long as its declaration is available and the call matches its parameters. For example, a setup routine can call a helper to configure several pins.
Why does my function compile but not run?
Defining a function does not execute it. Check that a call to it exists and that program flow reaches that call. Also check conditions around the call, since an if condition that is false can skip it.
Can Arduino functions return more than one value?
A function has one declared return type, but it can return a struct or another object containing multiple fields. Another option is to pass values through reference parameters. For simple sketches, separate return values or a clearly designed data structure may be easier to understand than modifying several arguments.
Related
- Chemistry Balance Equation Worksheet: Practice and Answers
- Is the Balance of Payments Always Zero? Explained
- Split String Into an Array in Excel
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- XLOOKUP in Excel: Find a Value and Return Matching DataTo find a value in Excel and return its matching result, use XLOOKUP: with product IDs in A2:A6,…
- Excel Month to Date Average FormulaThe simplest Excel formula for a month-to-date average is =AVERAGEIFS(values, dates, ">="&DATE(YEAR(TODAY()),MONTH(TODAY()),1), dates, "="&DATE(YEAR(TODAY()),MONTH(TODAY()),1), A2:A100, "="&DATE(YEAR(D1),MONTH(D1),1), A2:A100, "="&DATE(YEAR(TODAY()),MONTH(TODAY()),1),…
- Excel Filter Merged Cells: Why Only the First Row ShowsYes—when a cell is merged vertically across several rows, Excel stores its value only in the top-left cell,…
- Paste Numbers in Excel Without Formulas: Paste ValuesTo paste formula results as fixed numbers in Excel, copy the cells, select the destination, then choose Home…
- Median Formula Examples in Excel and by HandThe median is the middle value after a set of numbers is arranged from smallest to largest; with…
- SUMIF Excel Multiple Columns: Formulas and ExamplesTo use SUMIF with multiple columns, add separate SUMIF results for each value column, then combine them with…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.