📚 Lesson 7: Using Arduino Libraries
⏱️ Estimated time: 25 minutes | Difficulty: Intermediate
Standing on Shoulders
Libraries are collections of code that make it easy for you to connect to a sensor, display, module, etc. They save you from writing complex code from scratch.
What are Libraries?
Libraries are pre-written code that add functionality to your Arduino. Install via: Sketch → Include Library → Manage Libraries.
Servo Motor Control
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9); // Servo on pin 9
}
void loop() {
for (int angle = 0; angle <= 180; angle++) {
myServo.write(angle); // Move to angle
delay(15);
}
for (int angle = 180; angle >= 0; angle--) {
myServo.write(angle);
delay(15);
}
}
LCD Display (LiquidCrystal)
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2); // 16 columns, 2 rows
lcd.print("Hello World!");
}
void loop() {
lcd.setCursor(0, 1); // Column 0, Row 1
lcd.print("Time: ");
lcd.print(millis() / 1000);
lcd.print("s ");
delay(500);
}
DHT Temperature & Humidity Sensor
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.print("Temp: "); Serial.print(temp); Serial.println(" °C");
Serial.print("Humidity: "); Serial.print(humidity); Serial.println(" %");
delay(2000);
}
✅ Quick Quiz
❓ How do you include a library?
❓ What does myServo.write(90) do?
❓ Where do you install Arduino libraries?