Functions in Arduino allow you to encapsulate code into reusable blocks, making your programs modular, readable, and efficient.
In this tutorial, we’ll explore how to create and use functions in Arduino with practical examples.
Table of Contents
1. What Are Functions?
A function is a block of code designed to perform a specific task. Functions are used to:
- Encapsulate reusable logic.
- Simplify complex programs.
- Reduce code duplication.
Syntax
returnType functionName(parameters) { // Code to execute return value; // Optional, based on return type }
2. Built-in Functions in Arduino
Arduino provides several built-in functions, such as:
- pinMode(pin, mode) — Configures a pin as input or output.
- digitalWrite(pin, value) — Sets a pin HIGH or LOW.
- digitalRead(pin) — Reads the value of a digital pin.
- delay(ms) — Pauses the program for the specified time in milliseconds.
- millis() — Returns the number of milliseconds since the program started.
Example: Using Built-in Functions
const int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); // Configure pin as output } void loop() { digitalWrite(ledPin, HIGH); // Turn LED on delay(1000); // Wait for 1 second digitalWrite(ledPin, LOW); // Turn LED off delay(1000); // Wait for 1 second }
3. Creating and Using Custom Functions
Custom functions allow you to define specific tasks for your program.
Example: Create and Call a Function
Blinking an LED Using a Custom Function
const int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { blinkLED(3); // Call the custom function to blink the LED 3 times } // Custom function to blink an LED void blinkLED(int times) { for (int i = 0; i < times; i++) { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); } }
4. Function Parameters and Return Values
4.1 Function with Parameters
Parameters allow you to pass values to a function when calling it.
Example: Function with Parameters
void turnOnLED(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); } void setup() { turnOnLED(13); // Call the function with pin number 13 } void loop() { // Empty }
4.2 Function with Return Value
A function can return a value to the caller.
Example: Function Returning a Sensor Value
int readSensor(int sensorPin) { return analogRead(sensorPin); // Read and return the sensor value } void setup() { Serial.begin(9600); } void loop() { int sensorValue = readSensor(A0); // Call the function and store the result Serial.println(sensorValue); // Print the sensor value delay(1000); }
5. Practical Examples
Example 5.1: Toggle LED State
const int ledPin = 13; bool ledState = false; void setup() { pinMode(ledPin, OUTPUT); } void loop() { toggleLED(); delay(1000); } // Custom function to toggle LED state void toggleLED() { ledState = !ledState; // Invert the LED state digitalWrite(ledPin, ledState); }
Example 5.2: Calculate Average of Array Values
int calculateAverage(int values[], int length) { int sum = 0; for (int i = 0; i < length; i++) { sum += values[i]; } return sum / length; } void setup() { Serial.begin(9600); int readings[] = {10, 20, 30, 40, 50}; int avg = calculateAverage(readings, 5); Serial.print("Average: "); Serial.println(avg); } void loop() { // Empty }
Example 5.3: Display Text on Serial Monitor
void displayText(String text) { Serial.println(text); } void setup() { Serial.begin(9600); displayText("Welcome to Arduino!"); } void loop() { // Empty }
Example 5.4: Blink Multiple LEDs
const int ledPins[] = {2, 3, 4, 5}; const int numLeds = 4; void setup() { for (int i = 0; i < numLeds; i++) { pinMode(ledPins[i], OUTPUT); } } void loop() { for (int i = 0; i < numLeds; i++) { blinkLED(ledPins[i], 2); // Blink each LED twice } } // Custom function to blink a specific LED void blinkLED(int pin, int times) { for (int i = 0; i < times; i++) { digitalWrite(pin, HIGH); delay(300); digitalWrite(pin, LOW); delay(300); } }
6. Best Practices for Using Functions
- Use Descriptive Names:
- Name functions clearly to indicate their purpose.
- Example: Use calculateTemperature() instead of tempFunc().
- Keep Functions Short:
- A function should perform one specific task.
- Break complex tasks into multiple smaller functions.
- Minimize Global Variables:
- Pass variables as parameters to avoid relying on global variables.
- Document Your Functions:
- Add comments to describe what the function does and its parameters.
// Function to blink an LED // Parameters: // - pin: the pin connected to the LED // - times: the number of times to blink void blinkLED(int pin, int times) { // Implementation }
- Test Functions Independently:
- Test each function separately before integrating them into the main program.
Conclusion
Functions are an essential part of Arduino programming, allowing you to write modular and reusable code. By using functions effectively, you can simplify your programs, improve readability, and make debugging easier.
This tutorial provides a foundation for creating and using functions in Arduino projects.
For more details, visit the official Arduino reference.