Bird
0
0
Arduinoprogramming~5 mins

Using sensor libraries in Arduino

Choose your learning style9 modes available
Introduction

Sensor libraries help your Arduino understand and use sensors easily. They save you time by giving ready-made code to read sensor data.

When you want to read temperature from a sensor like DHT11 or DHT22.
When you need to get distance measurements from an ultrasonic sensor.
When you want to use a light sensor to detect brightness.
When you want to avoid writing complex code to communicate with sensors.
When you want reliable and tested code to get sensor readings.
Syntax
Arduino
#include <SensorLibrary.h>

SensorType sensor(pin);

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

void loop() {
  int value = sensor.read();
  Serial.println(value);
  delay(1000);
}

#include adds the sensor library to your program.

You create a sensor object with the pin number where the sensor is connected.

Examples
This example uses the DHT library to read temperature from a DHT11 sensor on pin 2.
Arduino
#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();
  Serial.println(temp);
  delay(2000);
}
This example uses the NewPing library to measure distance with an ultrasonic sensor.
Arduino
#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  unsigned int distance = sonar.ping_cm();
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(1000);
}
Sample Program

This program reads temperature from a DHT11 sensor every 2 seconds and prints it to the Serial Monitor. It also checks if the reading failed.

Arduino
#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
  Serial.println("DHT11 sensor starting...");
}

void loop() {
  float temperature = dht.readTemperature();
  if (isnan(temperature)) {
    Serial.println("Failed to read from sensor!");
  } else {
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
  }
  delay(2000);
}
OutputSuccess
Important Notes

Always check if the sensor reading is valid before using it.

Make sure to install the sensor library in your Arduino IDE before using it.

Use the correct pin numbers and sensor types when creating sensor objects.

Summary

Sensor libraries make reading sensors easy and reliable.

Include the library, create a sensor object, start it in setup(), then read values in loop().

Always check for errors in sensor readings to avoid wrong data.