arduino-funciones-librerias

Functions and Libraries in Arduino

  • 5 min

As your programs grow, you’ve probably noticed a problem: the loop() starts to become endless.

You have hundreds of lines of code, if inside if, for loops… and when you want to change something, you have to search through a sea of braces and semicolons 😱.

Furthermore, this has probably happened to you: you want to blink an LED at three different moments in the program, and you had to copy and paste the same block of code three times.

To solve this, functions exist. Today we are going to learn how to package our code into reusable blocks.

What is a function?

In Arduino, a function is a piece of code that performs a specific task, we give it a name, and we can call it from anywhere in the program.

Imagine a function as a cooking recipe to which you give a name.

Instead of explaining step by step how to make an omelet every time you’re hungry (“crack eggs”, “beat”, “heat oil”…), you simply say: Hey you, make an omelet.

In fact, you’ve already used functions!

  • setup() and loop() are functions.
  • digitalWrite() and delay() are functions.

These are functions that someone wrote for you. Now we are going to learn to write our own.

Creating your first function

The basic structure to define a function is:

returnType functionName(parameters) {
   // The recipe code
}

Copied!

Let’s see it better with a simple example, a simple function called blinkThreeTimes().

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

void loop() {
  // Instead of writing all the code here, we just call the function
  blinkThreeTimes(); 
  
  delay(2000); // We wait a bit
  
  blinkThreeTimes(); // We can reuse it as many times as we want!
}

// --- YOUR FUNCTIONS AREA ---
// (Usually written after the loop)

void blinkThreeTimes() {
  for(int i=0; i<3; i++) {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
}

Copied!
  1. void: Means “empty”. It indicates that this function does things (turns lights on), but does not return any result to us (it doesn’t give us a number).
  2. blinkThreeTimes: This is the name we gave it. (use descriptive names).
  3. (): Empty parentheses, because it doesn’t need extra information to work.
  4. { ... }: The body of the function.

Thanks to this, your loop() becomes very clean and easy to read. Anyone who reads blinkThreeTimes() understands what happens without needing to see the internal digitalWrite statements.

Functions with parameters

The previous function is fine, but it’s a bit rigid. It always blinks 3 times. What if I want it to blink 5? Or 10?

We can pass information to the function through the parentheses. These are called Parameters of the function.

Let’s improve our function:

void blink(int numberOfTimes) {
  for(int i=0; i < numberOfTimes; i++) {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
}

Copied!

Now, when we call it from the loop, we have to give it the data:

void loop() {
  blink(5);  // Blinks 5 times
  delay(1000);
  blink(2);  // Blinks 2 times
}

Copied!

We have created a generic tool that adapts to what we need.

Libraries: Using other people’s code

A library is nothing more than a set of functions that we can add to our project to avoid reinventing the wheel.

Very smart people have dedicated their time to writing hundreds of super useful functions to control motors, displays, complex sensors, or connect to the Internet.

Furthermore, that “someone” has packaged all those functions into a file and shared it for free. That is a Library.

How to use them

To use a library, we first have to tell our program that we want to include it. This is done with the #include command.

For example, to control a Servomotor (a motor we can move to an exact angle), we would use the Servo.h library that already comes installed with Arduino.

#include <Servo.h> // We include the "toolbox" for the Servo

Servo myMotor; // We create our motor object

void setup() {
  myMotor.attach(9); // We tell it the motor is on pin 9
}

void loop() {
  // Look how easy! We don't need to know how the electrical pulses work.
  // We just use the "write" function that comes in the library.
  
  myMotor.write(90); // "Go to 90 degrees"
  delay(1000);
  myMotor.write(0);  // "Go to 0 degrees"
  delay(1000);
}

Copied!

Without the library, we would have had to write dozens of lines of complex code with digitalWrite and microseconds to move that motor. With the library, it’s a single line.

Where do I get libraries?

Arduino has a built-in Library Manager.

  1. Go to Sketch > Include Library > Manage Libraries...
  2. Search for what you need (e.g., “DHT11” for temperature, “NeoPixel” for colored lights).
  3. Click Install.

Before struggling to program a complex sensor from scratch, search on Google “Arduino library [sensor name]”. 99% of the time, someone has already done the hard work for you.