Bird
Raised Fist0
Arduinoprogramming~10 mins

Using sensor libraries in Arduino - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Using sensor libraries
Include sensor library
↓
Create sensor object
↓
Initialize sensor in setup()
↓
Read sensor data in loop()
↓
Use sensor data (print, control)
↓
Repeat loop
This flow shows how to include a sensor library, create and initialize the sensor, then read and use its data repeatedly.
Execution Sample
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 code uses the DHT sensor library to read temperature from a DHT11 sensor connected to pin 2 and prints it every 2 seconds.
Execution Table
StepActionEvaluation/Function CallResult/Output
1Include DHT library#include <DHT.h>Library functions available
2Define sensor pin and type#define DHTPIN 2 #define DHTTYPE DHT11Constants set
3Create sensor objectDHT dht(DHTPIN, DHTTYPE);Sensor object ready
4Start Serial communicationSerial.begin(9600);Serial ready at 9600 baud
5Initialize sensordht.begin();Sensor initialized
6Read temperaturefloat temp = dht.readTemperature();temp gets sensor value or NAN if error
7Print temperatureSerial.println(temp);Temperature printed on Serial Monitor
8Wait 2 secondsdelay(2000);Pause before next reading
9Loop back to Step 6Repeat reading and printingContinuous temperature updates
10ExitNever (loop runs forever)Continuous operation
💡 Loop runs forever to keep reading sensor data continuously.
Variable Tracker
VariableStartAfter 1 loopAfter 2 loops...final
tempundefined23.5 (example)23.7 (example)varies with sensor reading
Key Moments - 3 Insights
Why do we need to call dht.begin() in setup()?
dht.begin() initializes the sensor hardware and prepares it for reading. Without it, readings may fail or return errors as shown in Step 5 of the execution_table.
What happens if the sensor reading fails?
If reading fails, dht.readTemperature() returns NAN (not a number). This is important to check before using the value, as seen in Step 6 where temp may be NAN.
Why is there a delay(2000) after printing?
delay(2000) pauses the program for 2 seconds to avoid flooding the Serial Monitor with data and to give the sensor time between readings, as shown in Step 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the purpose of Step 4?
ATo start communication with the sensor hardware
BTo start Serial communication for output
CTo define sensor pin number
DTo read temperature from the sensor
💡 Hint
Check Step 4 in execution_table where Serial.begin(9600) is called.
At which step does the sensor actually provide a temperature reading?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Look at Step 6 where dht.readTemperature() is called.
If delay(2000) was removed, what would happen to the output?
ATemperature would print faster and flood the Serial Monitor
BSensor would stop working
CTemperature readings would be more accurate
DProgram would crash
💡 Hint
Refer to Step 8 delay(2000) purpose in execution_table.
Concept Snapshot
#include <SensorLibrary.h>
Create sensor object with pin and type
Initialize sensor in setup() with sensor.begin()
Read sensor data in loop() with sensor.read()
Use data (print/control)
Add delay to space readings
Full Transcript
This example shows how to use a sensor library in Arduino. First, include the sensor library to get access to its functions. Then define the sensor pin and type. Create a sensor object with these details. In the setup function, start Serial communication and initialize the sensor with begin(). In the loop function, read the sensor data using the library's read function, then print the value to the Serial Monitor. Add a delay to avoid flooding the output and to give the sensor time between readings. The loop repeats forever to keep updating sensor data.

Practice

(1/5)
1. What is the first step when using a sensor library in an Arduino sketch?
easy
A. Include the sensor library at the top of the sketch
B. Read sensor values in the loop() function
C. Create a sensor object inside the loop()
D. Start the sensor in the loop() function

Solution

  1. Step 1: Understand the library usage

    Before using a sensor, you must include its library so Arduino knows how to communicate with it.
  2. Step 2: Identify correct placement

    Including the library is done at the top of the sketch, before setup() and loop().
  3. Final Answer:

    Include the sensor library at the top of the sketch -> Option A
  4. Quick Check:

    Include library first = A [OK]
Hint: Always include libraries before setup() [OK]
Common Mistakes:
  • Trying to create sensor object before including library
  • Starting sensor in loop() instead of setup()
  • Reading sensor before initializing it
2. Which of the following is the correct way to create a sensor object for a DHT sensor using its library?
easy
A. DHT sensor = DHT(2);
B. DHT sensor = new DHT(2, DHT11);
C. DHT sensor(2, DHT11);
D. DHT sensor = DHT11(2);

Solution

  1. Step 1: Recall object creation syntax in Arduino C++

    Objects are created by calling the constructor directly, like ClassName objectName(parameters); without '=' or 'new' keyword.
  2. Step 2: Match correct syntax for DHT library

    The DHT library uses: DHT sensor(pin, type); so DHT sensor(2, DHT11); matches this exactly.
  3. Final Answer:

    DHT sensor(2, DHT11); -> Option C
  4. Quick Check:

    Object creation = ClassName object(params); [OK]
Hint: Create objects without '=' or 'new' in Arduino [OK]
Common Mistakes:
  • Using '=' sign when creating objects
  • Using 'new' keyword which is not typical in Arduino sketches
  • Confusing sensor type and pin order
3. Given the code below, what will be printed if the sensor reading fails?
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  float h = dht.readHumidity();
  if (isnan(h)) {
    Serial.println("Failed to read humidity!");
  } else {
    Serial.print("Humidity: ");
    Serial.println(h);
  }
  delay(2000);
}
medium
A. Failed to read humidity!
B. Humidity: 0.00
C. Humidity: NaN
D. No output

Solution

  1. Step 1: Understand the isnan() check

    The code checks if the humidity reading is 'NaN' (not a number), which means the sensor failed to read.
  2. Step 2: Determine output when reading fails

    If isnan(h) is true, the code prints "Failed to read humidity!" to Serial.
  3. Final Answer:

    Failed to read humidity! -> Option A
  4. Quick Check:

    isnan true prints error message [OK]
Hint: Check isnan() to detect sensor read failure [OK]
Common Mistakes:
  • Assuming sensor returns 0 on failure
  • Printing raw value without checking for NaN
  • Not calling dht.begin() in setup()
4. Identify the error in this Arduino sketch snippet using a sensor library:
#include <DHT.h>
DHT dht(2, DHT11);

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

void loop() {
  dht.begin();
  float t = dht.readTemperature();
  Serial.println(t);
  delay(1000);
}
medium
A. readTemperature() returns int, not float
B. dht.begin() should be called in setup(), not loop()
C. Missing #define for sensor pin
D. Serial.begin() should be called in loop()

Solution

  1. Step 1: Locate sensor initialization

    dht.begin() initializes the sensor and should be called once in setup() to avoid repeated initialization.
  2. Step 2: Identify why calling dht.begin() in loop() is wrong

    Calling dht.begin() repeatedly in loop() can cause sensor communication issues and slow down the program.
  3. Final Answer:

    dht.begin() should be called in setup(), not loop() -> Option B
  4. Quick Check:

    Initialize sensor once in setup() [OK]
Hint: Initialize sensors once in setup() [OK]
Common Mistakes:
  • Calling sensor start functions repeatedly in loop()
  • Confusing Serial.begin() placement
  • Assuming readTemperature() returns int
5. You want to read temperature and humidity from a DHT11 sensor and turn on an LED if humidity is above 70%. Which code snippet correctly uses the sensor library and controls the LED?
hard
A.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define LEDPIN 13
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  float h = dht.readHumidity();
  if (!isnan(h) || h > 70) {
    digitalWrite(LEDPIN, HIGH);
  } else {
    digitalWrite(LEDPIN, LOW);
  }
  delay(2000);
}
B.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define LEDPIN 13
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  float h = dht.readHumidity();
  if (h > 70) {
    digitalWrite(LEDPIN, HIGH);
  } else {
    digitalWrite(LEDPIN, LOW);
  }
  delay(2000);
}
C.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define LEDPIN 13
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  float h = dht.readHumidity();
  if (h < 70) {
    digitalWrite(LEDPIN, HIGH);
  } else {
    digitalWrite(LEDPIN, LOW);
  }
  delay(2000);
}
D.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define LEDPIN 13
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  float h = dht.readHumidity();
  if (!isnan(h) && h > 70) {
    digitalWrite(LEDPIN, HIGH);
  } else {
    digitalWrite(LEDPIN, LOW);
  }
  delay(2000);
}

Solution

  1. Step 1: Check sensor initialization and pin setup

    #include <DHT.h>
    #define DHTPIN 2
    #define DHTTYPE DHT11
    #define LEDPIN 13
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(9600);
      dht.begin();
      pinMode(LEDPIN, OUTPUT);
    }
    
    void loop() {
      float h = dht.readHumidity();
      if (!isnan(h) && h > 70) {
        digitalWrite(LEDPIN, HIGH);
      } else {
        digitalWrite(LEDPIN, LOW);
      }
      delay(2000);
    }
    
    correctly calls dht.begin() in setup() and sets LED pin as output.
  2. Step 2: Verify humidity check and LED control logic

    #include <DHT.h>
    #define DHTPIN 2
    #define DHTTYPE DHT11
    #define LEDPIN 13
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(9600);
      dht.begin();
      pinMode(LEDPIN, OUTPUT);
    }
    
    void loop() {
      float h = dht.readHumidity();
      if (!isnan(h) && h > 70) {
        digitalWrite(LEDPIN, HIGH);
      } else {
        digitalWrite(LEDPIN, LOW);
      }
      delay(2000);
    }
    
    checks if humidity is not NaN and greater than 70 before turning LED on, which prevents errors from failed reads.
  3. Final Answer:

    The code snippet with !isnan(h) check and && h > 70 -> Option D
  4. Quick Check:

    Initialize sensor + check isnan + control LED = A [OK]
Hint: Always check isnan() before using sensor values [OK]
Common Mistakes:
  • Not calling dht.begin() in setup()
  • Missing isnan() check causing wrong LED behavior
  • Using || instead of && in humidity condition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard