Arduino Libraries: Installing and Using Third-Party Code
Arduino libraries are collections of pre-written code that extend what your board can do — from reading temperature sensors to connecting to WiFi or controlling displays.
Libraries make Arduino development easier by providing ready-to-use functions for complex hardware. You can install them through the Library Manager or manually via .zip files.
Installing Libraries via Library Manager
The Arduino Library Manager is the easiest way to install libraries:
- Open the Arduino IDE
- Go to Sketch → Include Library → Manage Libraries...
- Search for your library (e.g., "DHT sensor")
- Click Install on the library you want
Installing from .zip Files
For libraries not in the Library Manager:
- Download the library as a .zip file
- In Arduino IDE: Sketch → Include Library → Add .ZIP Library...
- Select the downloaded file
Using a Library
Once installed, include the library at the top of your sketch:
#include <DHT.h> // Include DHT sensor library
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
void setup() {
Serial.begin(9600);
dht.begin(); // Initialize the sensor
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("°C");
delay(2000); // Wait 2 seconds between readings
}Finding Libraries
| Library | What it does | Install via |
|---|---|---|
| Adafruit Unified Sensor | Base class for Adafruit sensors | Library Manager |
| Adafruit DHT Sensor Library | DHT11/DHT22 temperature & humidity | Library Manager |
| PubSubClient | MQTT client for Arduino | Library Manager |
| NewPing | HC-SR04 ultrasonic distance | Library Manager (.zip) |
| ArduinoJson | JSON encoding/decoding | Library Manager |
| Wire | I2C communication | Built-in |
| SPI | SPI communication | Built-in |
Key Takeaways
- Libraries extend Arduino functionality with pre-written code
- Install via Library Manager (easiest) or .zip files
- Include with
#include <LibraryName.h> - Many libraries require initialization in
setup() - The Wire and SPI libraries are built-in for I2C/SPI communication
Resources
- Arduino Libraries - Installing: https://docs.arduino.cc/software/ide-v1/tutorials/installing-libraries
- Arduino Library Manager: https://www.arduino.cc/en/guide/libraries
- Adafruit DHT Sensor Library: https://github.com/adafruit/Adafruit_DHT_sensor_library
- PubSubClient for Arduino: https://github.com/knolleary/pubsubclient
- ArduinoJson: https://arduinojson.org/