Home · Academy · Robotics & Coding · Arduino · Libraries

Libraries

Learn to use ready-made libraries safely with #include and the Library Manager.

LESSON COMPASS

What will you use this page for?

Core idea

A library is a piece of code that other people have already written and packaged, so you can add it to your project and do difficult jobs with short commands.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Forgetting the #include line If you write a library command but do not add the #include line, Arduino says "I do not recognise this command" and gives a compile error. The #include line at the top is required for every library. Calling a library without installing it You wrote #include <NewPing.h> but did not install…

Next connection

Splitting Code Structure into Functions: We will learn to make code more readable by breaking a growing loop block into our own functions, each doing a single job.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration30–45 min
PrerequisiteThe Motor Driver
ContentStandard lesson · 1,575 words
Last updated

One-sentence summary

A library is a piece of code that other people have already written and packaged, so you can add it to your project and do difficult jobs with short commands.

Why does it matter?

In the previous lesson we ran a motor with a driver board. Setting the driver pins to HIGH and LOW by hand worked, but it was a little long. If we wanted to drive a servo motor or a distance sensor from scratch, things would get even trickier: we would need to calculate the exact timing down to the microsecond.

Here is the good news: many people have already solved these hard problems and shared their solutions. These shared solutions are called libraries. When you use a library you write less code, and you build on a base that has already been tested. That is why real projects almost always rely on ready-made libraries.

What is a library?

The name is not a coincidence. Think of a public library: you do not write the information you need from scratch, you take a book that is already on the shelf and use it. Code libraries work the same way.

A library is code that gathers together ready-made functions for a particular job. For example, there are libraries for turning a servo motor, measuring distance with an ultrasonic sensor, or writing text on a small screen.

Two everyday examples

In both examples the idea is the same: someone solved the hard part once, and you use the result the short way.

Calling a library with #include

Before you can use a library, you have to tell Arduino, "include this ready-made code in my work." We do this at the very top of the program with an #include line.

#include <Servo.h>   // add the Servo library to the project

The name inside the angle brackets is the file name of the library you want to use. Thanks to this line you can reach all of the commands that the library offers. We always write #include lines at the top of the file, before the void setup() and void loop() blocks.

Installing with the Library Manager

Some libraries (such as Servo) come ready with Arduino. But libraries written by other people, like NewPing, have to be installed on your computer first. For this we use the Library Manager inside the Arduino IDE.

  1. In the Arduino IDE, open the Sketch → Include Library → Manage Libraries menu.
  2. Type the name of the library in the search box (for example NewPing).
  3. When you find the right library, click the Install button.
  4. After it installs, add the #include line to the top of your program.

The Library Manager downloads libraries from a trusted list. So instead of downloading a file from a random website, use the Library Manager or the library's official page whenever you can. That way you get both the correct version and protection from risky code from unknown sources.

Shorter code with a library

A comparison shows the benefit of libraries best. Let's say we want to move a servo motor to 90 degrees.

Without a library

A servo learns which angle to turn to from pulses sent every 20 milliseconds. For 90 degrees the pulse length is about 1500 microseconds. Doing this by hand looks like this:

// Driving 90 degrees by hand: this pulse must be repeated continuously
digitalWrite(9, HIGH);
delayMicroseconds(1500);   // pulse length for 90 degrees
digitalWrite(9, LOW);
delay(20);                 // wait until the next pulse

If we get the timing even slightly wrong, the servo jitters or moves to the wrong angle. On top of that, we have to do this calculation for every angle ourselves.

With the Servo library

We write the same job much more readably with a library:

#include <Servo.h>

Servo doorServo;          // create a servo object

void setup() {
  doorServo.attach(9);    // servo signal is on pin 9
}

void loop() {
  doorServo.write(0);     // go to 0 degrees
  delay(1000);
  doorServo.write(90);    // go to 90 degrees
  delay(1000);
}

The line doorServo.write(90) does the pulse calculation for us. We just say the angle we want. The code is both shorter and much easier to understand.

Second example: measuring distance with NewPing

There is also a ready-made library for measuring distance with an ultrasonic sensor. Thanks to NewPing we do not have to manage the sensor's trig and echo signals by hand.

#include <NewPing.h>

#define TRIG_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200  // largest distance to measure (cm)

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
}

void loop() {
  int distance = sonar.ping_cm();   // measure distance in centimetres
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(500);
}

sonar.ping_cm() takes the measurement in one line and gives the result in centimetres. Writing the same job from scratch would take dozens of lines and careful timing.

Mini task

Combine the Servo example above with your own project:

  1. Open the Library Manager and check that Servo is installed (it comes ready with Arduino).
  2. Upload the program and watch the servo move back and forth between 0 and 90 degrees.
  3. Change the write(90) line to write(180). Where does the servo go now?
  4. If you change the delay(1000) values to delay(300), how does the movement change?
  5. Challenge: try changing the program so the servo moves when you press a button.

After each change, change only one thing and watch the result. Small experiments like these help you truly understand a library's commands.

Common mistakes

Forgetting the #include line

If you write a library command but do not add the #include line, Arduino says "I do not recognise this command" and gives a compile error. The #include line at the top is required for every library.

Calling a library without installing it

You wrote #include <NewPing.h> but did not install the library from the Library Manager, so Arduino cannot find the file. Install first, then call.

Writing the library name incorrectly

Library names are case-sensitive. You write <Servo.h>, not <servo.h>. Even a single wrong letter causes an error.

Downloading from unknown sources

A library downloaded from a random website may work incorrectly and may not be safe. Whenever possible, use the Library Manager or the library's official page.

Safety note

Lesson summary

Check questions

  1. What is a library and why do we use one?
  2. Which line do we write, and where, so we can use a library in a program?
  3. What is the difference between installing the Servo and NewPing libraries?
  4. What difficult job does the doorServo.write(90) command do for us?
  5. Why should we download a library from the Library Manager instead of a random website?

Answers

  1. A library is code that gathers together ready-made functions for a particular job. It lets us do difficult jobs with short commands and write less, more reliable code.
  2. We write the #include <LibraryName.h> line at the top of the program, before the setup and loop blocks.
  3. Servo comes ready with Arduino and does not need to be installed separately. NewPing is written by other people; it must be installed from the Library Manager before use.
  4. It calculates the pulse timing needed to move the servo to 90 degrees (pulses of about 1500 microseconds) for us; we just state the angle.
  5. The Library Manager downloads libraries from a trusted list. That way we get the correct version and stay away from faulty or risky code from unknown sources.

Source and verification note

For “Libraries”, verification focuses on whether the relationship between What is a library? and Calling a library with #include remains consistent across examples. Pin, voltage and current limits can differ between Arduino-compatible boards. Compiling code does not guarantee a safe circuit; loads such as motors and servos require a suitable driver and external power where appropriate.

Next lesson

Splitting Code Structure into Functions: We will learn to make code more readable by breaking a growing loop block into our own functions, each doing a single job.

Start QuizBack to Arduino
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.