Arduino Functions: How to Write and Use Them in a Sketch

Formulas & functions · Updated November 22, 2026

To write a function in Arduino, give it a return type and name, add any input parameters in parentheses, and put its instructions inside braces. Then call it from setup() or loop(). Functions let you give a group of instructions a reusable name, making a sketch easier to read, change, and troubleshoot. You will need an Arduino board, the Arduino IDE or another compatible editor, and a sketch to work in.

What You’ll Need

  • An Arduino-compatible board and a USB cable if you want to upload and run the sketch.
  • The Arduino IDE, or another editor and toolchain that can compile Arduino sketches.
  • A sketch to edit. The first example below uses the board’s built-in LED, so no extra components are required.

Step-by-Step

  1. Identify repeated or related instructions. A function is useful when you want to perform a task as a named unit, such as blinking an LED, reading a sensor, or converting a measurement. It can also make loop() easier to follow by moving implementation details elsewhere. Start by deciding exactly what the task should do and what information it needs. For example, a function that blinks an LED needs to know which pin to control and how long to leave the LED in each state.
  2. Learn the basic function shape. A function definition has a return type, a name, optional parameters, and a body. This example switches a specified output on and off:
void blinkLed(byte pin, unsigned long intervalMs) {
  digitalWrite(pin, HIGH);
  delay(intervalMs);
  digitalWrite(pin, LOW);
  delay(intervalMs);
}

void means the function does not send a result back to the code that called it. blinkLed is the function name, and the values inside the parentheses are its parameters: pin is the output pin and intervalMs is the delay in milliseconds. The braces mark the function body. Each instruction inside runs when the function is called, in order. The function definition itself does not make the LED blink; it describes what should happen when the program reaches a call to it.

  1. Choose useful parameters and types. Parameters let one function handle different inputs rather than hard-coding one value. In the example, the caller can select a pin and interval. Use a type appropriate to the values: byte is suitable for a small pin number on many Arduino boards, while unsigned long is commonly used for millisecond durations accepted by delay(). A parameter is a named placeholder in the definition; an argument is the actual value supplied at the call site. The number, order, and compatible types of arguments should match the parameters.
  2. Add a return value if the function calculates or obtains a result. Replace void with the type of value the function returns, and use return to send that value back. For example, this function averages five analog readings:
int averageReading(byte pin) {
  long total = 0;

  for (int i = 0; i < 5; i++) {
    total += analogRead(pin);
  }

  return total / 5;
}

Because the return type is int, the function returns an integer. The long total gives the sum room to grow while readings are added; dividing by five produces the average, with any fractional part discarded when it is converted to an integer. A caller can store the result, for example with int reading = averageReading(A0); on a board that provides an A0 analog input. Every path through a non-void function should return an appropriate value.

  1. Call the function where you want its task performed. Use the function name followed by parentheses and provide arguments in the same order as the parameters. This small sketch sets up the built-in LED and calls the function repeatedly:
const byte ledPin = LED_BUILTIN;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  blinkLed(ledPin, 250);
}

void blinkLed(byte pin, unsigned long intervalMs) {
  digitalWrite(pin, HIGH);
  delay(intervalMs);
  digitalWrite(pin, LOW);
  delay(intervalMs);
}

Here, blinkLed(ledPin, 250) passes the pin and a 250-millisecond interval to the function. It turns the LED on for 250 milliseconds and off for 250 milliseconds. Since loop() runs repeatedly, the call repeats. The function contains blocking delay() calls, so the sketch cannot do other work during those waits; that is fine for a simple demonstration but may not suit a project that needs to check buttons or sensors continuously.

  1. Put definitions at the sketch level. Place a function definition outside the braces of setup(), loop(), and other functions. In the Arduino IDE, the build process usually generates function prototypes for ordinary sketches, so a function can often be defined after the place that calls it. If the compiler reports that a function was not declared, add a prototype near the top, before the first call. A prototype states the function’s signature and ends with a semicolon:
void blinkLed(byte pin, unsigned long intervalMs);

This declaration is not a second implementation; the definition with the braces must still appear somewhere in the sketch. Explicit prototypes are particularly helpful when working with more complicated declarations, custom data types, or build setups that do not apply the Arduino IDE’s usual preprocessing.

  1. Compile, upload, and check the behavior. Select the correct board and port in the IDE, then use Verify to compile before uploading. If compilation succeeds, upload and observe whether the function behaves as intended. For the LED example, check that the built-in LED turns on and off at the expected pace. If it does not, confirm the board’s built-in LED definition, the pin setup, and the argument values. Change one value at a time so it is clear which edit affects the result.
  2. Refine the function’s responsibility. Keep a function focused on one understandable task. A short function can still be worthwhile if its name clearly explains the action or it prevents the same code from being copied in several places. If a function becomes difficult to describe in one sentence, consider splitting it into smaller helpers. Keep related variables local to the function when they are only needed there; this reduces accidental changes to unrelated parts of the sketch.

Common Mistakes

  • Defining a function inside another function. Arduino sketches use C++, and ordinary function definitions belong outside the braces of setup() and loop(). Close the earlier function before writing the next definition.
  • Forgetting parentheses, braces, or a semicolon. Calls need parentheses, definitions need a pair of braces, and a prototype ends in a semicolon. A missing punctuation mark can cause an error message on a later line, so inspect the lines immediately above the reported location too.
  • Using the wrong capitalization. C++ names are case-sensitive: blinkLed, blinkled, and BlinkLed are different names. Make the spelling and capitalization identical in the definition, prototype, and every call.
  • Mismatching parameters and arguments. If a function expects two parameters, provide two arguments of compatible types in the correct order. A pin and a duration can both be numbers, so swapping them may compile but produce unexpected behavior.
  • Returning the wrong thing. A void function is not intended to return a value. A function declared as int should return an integer on every relevant path. Check that the declared return type agrees with what the function actually calculates.
  • Expecting a function to run just because it exists. Writing a definition only makes the code available. The program must reach a call to that function, and any required setup—such as setting a pin to OUTPUT—must happen as well.

Tips

  • Choose names that describe an action or result, such as readTemperature or setMotorSpeed. Consistent camel case is common in Arduino examples, but clear and consistent naming matters more than a particular style.
  • Use parameters for values that might change between calls. A setLed function that accepts a pin is easier to reuse than one tied to a single pin number.
  • Keep the main flow visible. If someone can understand the overall behavior by reading setup() and loop(), the functions are probably helping rather than hiding the program’s structure.
  • Remember that ordinary parameters are passed by value: the function receives a copy of a simple value such as an int. Changing that parameter does not change the caller’s original variable. References and pointers can provide other behavior, but they are not needed for basic functions.
  • Be cautious about long delays inside reusable functions. A delay may be acceptable for a simple task, but it pauses the sketch. For responsive projects, learn to schedule actions using millis() rather than waiting inside a function.
  • Compile after making a small change. Short edits followed by verification make it easier to locate a typo or type mismatch than changing several functions at once.

Troubleshooting

If Verify reports an error, read the first compiler error rather than starting with the last one; later messages may be consequences of the first. Look for missing braces, misspelled names, or a definition accidentally placed inside another function. Check that every call supplies the required arguments and that the function declaration, if present, exactly matches the definition. If the compiler says a function was not declared, move its definition above the call or add a correct prototype before the call.

If the sketch compiles but the function appears not to run, confirm that the code path reaches the call. Add a temporary Serial.println() message inside the function and start Serial Monitor at the same baud rate used by Serial.begin(). Remove the diagnostic message when finished. For hardware behavior, check pin mode, wiring, board pin labels, and whether the selected board supports the pin or constant you used. If a return value seems wrong, print the inputs and result, then check the calculation and the type used to store it. Integer division discards a fractional remainder, which can make an average differ from a decimal result you expected.

Frequently Asked Questions

Do Arduino sketches have to use functions?
Every standard sketch needs setup() and loop(), which are functions the Arduino framework calls. You can write additional functions when they make your program clearer or let you reuse a task.

Can I call a function from another function?
Yes. A function can call another function if its declaration is visible where the call occurs. For example, loop() can call a helper, and that helper can call a separate calculation function.

Can a function return more than one value?
A function has one declared return type and returns one value in the usual basic pattern. It can also change data passed by reference or use a structure to group related results, but beginners can often keep the design simple by returning one result or writing separate functions.

Why does my function compile but not change a variable in the caller?
Simple parameters are passed by value, so edits to the function’s local copy do not change the original variable. Return the updated value and assign it at the call site, or learn about references when shared modification is truly needed.

Should I put every function in a separate file?
No. For a small sketch, keeping functions in the main .ino file is straightforward. Larger projects can separate declarations and implementations into header and source files, but that adds organization and build details that are not necessary for learning the basics.

What is the difference between a function declaration and a definition?
A declaration, or prototype, tells the compiler a function’s name, return type, and parameters. A definition includes the body of instructions that runs when the function is called. A sketch needs a definition for any function it uses.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.