26  Temperature Sensor Labs

In 60 Seconds

The DS18B20 is a digital temperature sensor using a 1-Wire bus, allowing multiple sensors on a single GPIO pin with unique 64-bit addresses. The DHT22 measures both temperature and humidity but requires a 2-second minimum interval between reads. Thermocouples handle extreme temperatures using the Seebeck effect. Always use proper pull-up resistors (4.7k ohm for 1-Wire, 10k ohm for DHT) and watch for error values like 85.0C (conversion not ready) and -127C (CRC error).

Key Concepts
  • Thermistor: a temperature-sensitive resistor whose resistance changes predictably with temperature, available as NTC (negative temperature coefficient) or PTC (positive temperature coefficient) types
  • RTD: Resistance Temperature Detector — a precision temperature sensor using pure metal wire (platinum PT100/PT1000) whose resistance increases linearly with temperature
  • Thermocouple: a temperature sensor formed by joining two dissimilar metals that generate a voltage proportional to temperature difference via the Seebeck effect
  • ADC Resolution: the number of discrete output values an analog-to-digital converter can produce; higher resolution (more bits) means finer temperature discrimination
  • Voltage Divider: a circuit using two resistors in series that produces an output voltage proportional to the ratio of resistances, used to read thermistor values with a microcontroller
  • Calibration: the process of comparing sensor readings to known reference values and applying correction factors to improve measurement accuracy
  • Signal Conditioning: amplifying, filtering, or converting a raw sensor signal into a form suitable for analog-to-digital conversion and microcontroller processing

26.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Interface DS18B20 sensors: Configure 1-Wire bus and read multiple temperature sensors on a single pin
  • Analyse thermocouple operation: Explain how thermocouples generate temperature-dependent voltages via the Seebeck effect and calculate output voltages using the Seebeck coefficient
  • Evaluate humidity sensors: Differentiate capacitive, resistive, and thermal conductivity sensing methods based on accuracy, response time, and application suitability
  • Construct temperature monitoring systems: Wire and program robust temperature acquisition circuits with correct pull-up resistors and multi-sensor addressing
  • Diagnose common sensor errors: Interpret the meaning of 85C, -127C, and NaN readings and apply targeted fixes for each failure mode

26.2 Prerequisites

Step-by-step sensor lab implementation workflow diagram showing the complete process from planning to deployment. Steps include: (1) Planning - select sensor, review datasheet, gather components; (2) Wiring - breadboard layout, power connections, signal wiring with pull-ups; (3) Software Setup - install libraries, write initialization code, implement read functions; (4) Testing - serial monitor debugging, verify readings against known references, check for noise; (5) Calibration - two-point or multi-point calibration, create correction formula; (6) Integration - combine with other sensors, add data logging, implement error handling. Includes common troubleshooting tips at each stage.

Sensor lab implementation workflow
Figure 26.1: Sensor lab workflow showing the complete implementation process from planning through deployment

Required Knowledge:

Hardware Requirements:

  • Arduino Uno/Nano or ESP32 development board
  • Breadboard and jumper wires
  • DS18B20 temperature sensor (or DHT22)
  • 4.7kOhm pull-up resistor (for DS18B20)
  • USB cable for programming

Software Requirements:

  • Arduino IDE installed and configured
  • Required libraries: OneWire, DallasTemperature (for DS18B20), DHT sensor library (for DHT22)

Skills Checklist:

Temperature sensors are among the most common sensors in IoT applications. Here is what makes them special:

Why Temperature Matters in IoT:

  • HVAC systems adjust heating/cooling based on readings
  • Cold chain monitoring ensures vaccine/food safety
  • Industrial processes require precise temperature control
  • Weather stations track environmental conditions

Common Temperature Sensor Types:

Sensor Interface Accuracy Best For
DS18B20 1-Wire digital +/-0.5C (in -10 to +85C range) Multi-sensor chains
DHT22 Proprietary digital +/-0.5C Temp + humidity combo
Thermistor Analog +/-1C (with calibration) Low cost, fast response
Thermocouple Analog (amplifier needed) +/-2C Extreme temperatures

Tip: DS18B20 is great for beginners because each sensor has a unique ID, allowing multiple sensors on one wire!

26.3 Temperature Sensors Overview

Implementing a temperature sensor project follows a structured workflow: research the sensor datasheet, wire the circuit with correct pull-up resistors, write initialization and read code, test against known references, calibrate if needed, then deploy. Figure 26.2 illustrates this complete pipeline, and Figure 26.3 provides a pre-power checklist to avoid common first-run failures.

Six-step sensor implementation workflow from research through wiring, coding, testing, calibration to deployment with debug feedback loop
Figure 26.2: Sensor Implementation Workflow: From Research to Deployment with Debug Loops
Sensor lab preparation checklist with pre-power checks, first test steps, and troubleshooting guide for common failures like no response, wrong values, unstable readings, and drift
Figure 26.3: Lab checklist view: Before powering on, verify voltage levels (3.3V vs 5V), ground connections, correct GPIO pins, and required pull-up resistors. First test should read raw values and check against known reference (ice water = 0C). Common failures have specific fixes: no response means wiring issue, wrong values indicate voltage/timing problems, unstable readings need filtering, and drift requires calibration.

26.4 DS18B20 (1-Wire Digital Temperature)

Time: ~25 min | Level: Intermediate | Code: P06.C10.U01

The DS18B20 is one of the most popular digital temperature sensors for IoT projects. It uses the 1-Wire protocol, which means multiple sensors can share a single GPIO pin – each sensor has a factory-programmed unique 64-bit address that distinguishes it on the bus.

Specifications:

  • Temperature Range: -55C to 125C (+/-0.5C accuracy in -10C to +85C range; +/-2C outside that range)
  • Interface: 1-Wire (multiple sensors on one pin)
  • Resolution: 9-12 bit configurable (93.75ms to 750ms conversion time)
  • Power: 3.0-5.5V, parasitic power mode available

ESP32 Implementation:

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 4  // GPIO4

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Store number of devices
int numberOfDevices;
DeviceAddress tempDeviceAddress;

void setup() {
  Serial.begin(115200);

  sensors.begin();

  // Get number of devices on the bus
  numberOfDevices = sensors.getDeviceCount();
  Serial.print("Found ");
  Serial.print(numberOfDevices);
  Serial.println(" temperature sensors");

  // Print addresses
  for(int i=0; i<numberOfDevices; i++) {
    if(sensors.getAddress(tempDeviceAddress, i)) {
      Serial.print("Sensor ");
      Serial.print(i);
      Serial.print(" Address: ");
      printAddress(tempDeviceAddress);
      Serial.println();
    }
  }
}

void loop() {
  sensors.requestTemperatures();

  for(int i=0; i<numberOfDevices; i++) {
    if(sensors.getAddress(tempDeviceAddress, i)) {
      float tempC = sensors.getTempC(tempDeviceAddress);

      // Check for error values before printing
      if(tempC == DEVICE_DISCONNECTED_C) {
        Serial.print("Sensor ");
        Serial.print(i);
        Serial.println(": ERROR - disconnected");
      } else {
        Serial.print("Sensor ");
        Serial.print(i);
        Serial.print(": ");
        Serial.print(tempC);
        Serial.println("C");
      }
    }
  }

  delay(1000);
}

void printAddress(DeviceAddress deviceAddress) {
  for (uint8_t i = 0; i < 8; i++) {
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

The DS18B20 stores temperature as a 16-bit signed integer in 12-bit resolution mode, where the lower 4 bits represent the fractional part and each LSB represents 0.0625C.

\[ T_{\text{celsius}} = \frac{\text{raw\_value}}{16} \]

Worked example: The DS18B20 returns raw bytes 0xD0 0x01 (little-endian: LSB first, MSB second). Calculate the temperature:

  1. Combine bytes (MSB:LSB): 0x01D0 = 464 decimal
  2. Apply formula: \(T = \frac{464}{16} = 29.0°C\)

Negative temperature example: The sensor returns 0x90 0xFF. Calculate the temperature:

  1. Combine bytes: 0xFF90 = -112 decimal (signed 16-bit, two’s complement)
  2. Apply formula: \(T = \frac{-112}{16} = -7.0°C\)

Power-on default: The sensor stores 0x0550 hex = 1360 decimal at power-on: \(T = \frac{1360}{16} = 85.0°C\) (the infamous “conversion not ready” value)

CRC error marker: The DallasTemperature library returns -127C (DEVICE_DISCONNECTED_C) when data integrity fails or the sensor is unreachable.

Use this calculator to convert DS18B20 raw register values to temperature, or enter a temperature to see its raw encoding.

How It Works: DS18B20 1-Wire Communication

The DS18B20 uses a single data line for bidirectional communication with strict timing requirements:

  1. Initialization – Master pulls line LOW for 480us minimum, then releases. The bus pull-up resistor returns the line HIGH.
  2. Presence pulse – Sensor responds by pulling the line LOW for 60-240us, signalling “I am here.”
  3. ROM command – Master sends a ROM command (e.g., 0x55 Match ROM to address a specific sensor, or 0xCC Skip ROM for single-sensor setups).
  4. Function command – Master sends 0x44 (Convert T) to start temperature conversion.
  5. Wait for conversion – The internal ADC converts the analog temperature to digital. This takes up to 750ms at 12-bit resolution, 375ms at 11-bit, 187.5ms at 10-bit, or 93.75ms at 9-bit.
  6. Read scratchpad – Master sends 0xBE (Read Scratchpad) and reads 9 bytes: temperature LSB, temperature MSB, T_H alarm register, T_L alarm register, configuration register, reserved bytes, and CRC.
  7. CRC check – Verify all 8 data bytes against the 9th byte (CRC) using the 1-Wire CRC8 algorithm.

Why 85C appears: The DS18B20’s scratchpad power-on reset value is 0x0550 = 85C. If you read before conversion completes, you get this default value.

Why -127C appears: The DallasTemperature library detects a CRC mismatch (bad wiring, electromagnetic interference, or cable too long) and returns DEVICE_DISCONNECTED_C (-127) as an error code.

Learning Points: DS18B20

Key Advantages:

  • Unique 64-bit address: Each sensor has a factory-programmed ROM code (family code + 48-bit serial + CRC)
  • Multi-sensor bus: Connect dozens of sensors on a single GPIO pin with one 4.7kOhm pull-up
  • Digital output: No ADC needed on the microcontroller side; noise-immune over long cables (up to 100m with proper wiring)
  • Parasitic power: Can operate with only 2 wires (data + ground) by drawing power from the data line

Common Issues and Fixes:

Problem Likely Cause Solution
No sensors found Missing pull-up resistor Add 4.7kOhm between data and VCC
Reads 85C Conversion incomplete Wait 750ms after requestTemperatures() at 12-bit
Reads -127C CRC error Check wiring, reduce cable length, add decoupling capacitor
Intermittent readings Long cables or EMI Use lower resolution (9-bit = 93.75ms) or shielded cable
All sensors same address Counterfeit sensors Verify vendor; genuine DS18B20 has unique addresses

26.5 Thermocouple-Based Temperature Sensors

Diagram showing thermocouple-based temperature sensors with junction points and voltage output circuitry for measuring temperature differences
Figure 26.4: Thermocouple-based temperature sensors

How Thermocouples Work:

Thermocouples generate a small voltage (on the order of microvolts per degree) based on the temperature difference between two junctions of dissimilar metals. This phenomenon is called the Seebeck effect. The voltage is proportional to the temperature gradient, not the absolute temperature at either junction.

Seebeck Coefficient:

For a K-Type thermocouple, the Seebeck coefficient is approximately 41 uV/C near room temperature. The output voltage for a given temperature difference is:

\[ V = S \times (T_{\text{hot}} - T_{\text{cold}}) \]

where \(S\) is the Seebeck coefficient and \(T_{\text{hot}}\) and \(T_{\text{cold}}\) are the hot junction and cold junction temperatures.

Thermocouple Types:

Type Metals Range Sensitivity Typical Use
K Chromel/Alumel -200 to 1250C ~41 uV/C General purpose, most common
J Iron/Constantan -40 to 750C ~52 uV/C Industrial, reducing atmospheres
T Copper/Constantan -200 to 350C ~43 uV/C Cryogenics, food processing
E Chromel/Constantan -200 to 900C ~68 uV/C Highest output, good for small changes

Estimate the output voltage of a thermocouple given the junction temperatures and type.

Cold Junction Compensation:

Thermocouples measure temperature difference, not absolute temperature. To determine the hot junction temperature, you must know the cold junction (reference) temperature. Most thermocouple amplifier ICs (MAX31855, MAX6675) include a built-in cold junction compensation sensor that measures the ambient temperature at the connector and adds it to the differential measurement.

26.6 Humidity Sensors Comparison

Comparison table of relative humidity sensors showing capacitive, resistive, and thermal conductivity types with accuracy ranges, response times, and typical operating conditions
Figure 26.5: Comparison of relative humidity sensors
Photograph showing a DHT22 temperature and humidity sensor (white plastic housing with ventilation slots) connected to a Raspberry Pi GPIO header via jumper wires on a breadboard. The setup demonstrates proper wiring: VCC to 3.3V power, GND to ground, and DATA pin to a GPIO pin with a pull-up resistor for reliable single-wire communication.
Figure 26.6: DHT22 temperature and humidity sensor connected to Raspberry Pi on breadboard

Source: NPTEL Internet of Things Course, IIT Kharagpur – The DHT22 is one of the most common temperature/humidity sensors for IoT projects due to its low cost, ease of use, and adequate accuracy for most applications.

DHT22 (AM2302) Implementation:

The DHT22 combines a capacitive humidity sensor and a thermistor in one package, making it popular for environmental monitoring where you need both readings from a single device.

Key DHT22 Characteristics:

  • Temperature: -40 to 80C (+/-0.5C)
  • Humidity: 0-100% RH (+/-2% typical, +/-5% max)
  • Sampling rate: 0.5 Hz (one reading every 2 seconds minimum)
  • Interface: Proprietary single-wire protocol (not compatible with 1-Wire)
  • Pull-up resistor: 4.7kOhm to 10kOhm between DATA and VCC
DHT22 Timing Requirement

The DHT22 requires a minimum 2-second interval between readings. Reading faster causes the sensor to return stale data or errors. Always include delay(2000) or use non-blocking timing in your loop when using DHT sensors.

#include <DHT.h>

#define DHTPIN 4      // GPIO4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  float temp = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temp) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
  } else {
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print("C  Humidity: ");
    Serial.print(humidity);
    Serial.println("%");
  }

  delay(2000);  // CRITICAL: Wait at least 2 seconds
}

26.7 Lab Exercises

Goal: Display temperature from one DS18B20 sensor on the serial monitor.

Wiring:

DS18B20 Red (VDD)   --> ESP32 3.3V
DS18B20 Black (GND) --> ESP32 GND
DS18B20 Yellow (DATA) --> ESP32 GPIO4
4.7kOhm resistor between DATA and VDD (pull-up)

Steps:

  1. Install the OneWire and DallasTemperature libraries from the Arduino Library Manager
  2. Upload the ESP32 Implementation code from the DS18B20 section above
  3. Open Serial Monitor at 115200 baud
  4. Verify the sensor is detected (should print “Found 1 temperature sensors”)
  5. Confirm readings match room temperature (typically 20-25C)

Troubleshooting: If no sensors are found, check that the 4.7kOhm resistor connects between the DATA pin and VCC (not GND).

Expected output: Room temperature 20-25C, updating every second

Goal: Read 3 DS18B20 sensors on one GPIO pin, identify each by address.

Challenge:

  1. Connect all 3 sensors to the same GPIO pin (parallel wiring – all VDD to VDD, all GND to GND, all DATA to GPIO4)
  2. Use a single 4.7kOhm pull-up resistor shared by all sensors
  3. Use getDeviceCount() to verify all 3 sensors are detected
  4. Read each sensor by its unique address using getTempC(address)
  5. Label sensors by placing them in different locations: “Living Room”, “Kitchen”, “Bedroom”

Key learning: Each DS18B20 has a unique 64-bit ROM code. The getAddress() function retrieves each sensor’s address during setup, allowing you to associate physical locations with specific sensors in your code.

Goal: Log temperature from 5 sensors every minute, trigger alert if any exceeds a threshold.

Features to implement:

  • Non-blocking temperature reads using setWaitForConversion(false) and millis() timing
  • Store readings to SD card with timestamp in CSV format
  • Send MQTT alert if temperature exceeds 30C
  • Web dashboard showing all 5 sensors (ESP32 async web server)
  • Calculate and display hourly averages

Bonus: Implement sensor failure detection – if a sensor returns -127C for 3 consecutive attempts, flag it as disconnected and continue reading the remaining sensors.

26.8 Knowledge Check

Not all temperature sensors are created equal. Use this framework to select the right sensor for your specific application.

Criteria DS18B20 DHT22 Thermistor (NTC) Thermocouple (K-Type) BME280
Temperature Range -55 to 125C -40 to 80C -55 to 150C -200 to 1250C -40 to 85C
Accuracy +/- 0.5C (-10 to 85C) +/- 0.5C +/- 0.2C (with calibration) +/- 2C +/- 0.5C (typical)
Interface 1-Wire digital Proprietary digital Analog (voltage divider) Analog (amplifier needed) I2C/SPI digital
Multi-Sensor Bus Yes (unique IDs) No (one per pin) No (one ADC channel each) No (one amplifier each) Yes (I2C, 2 addresses)
Humidity Included No Yes No No Yes (+ pressure)
Response Time 750ms (12-bit conv.) 2 sec (min interval) 0.5-5 sec (thermal mass) <1 sec ~1 sec
Cost $2-4 $4-6 $0.50-1 $5-10 (+ amplifier) $5-8
Power Consumption 1.5 mA active, 1 uA standby 1.5 mA (during read) <0.1 mA (passive divider) 0 mA (passive, amplifier draws power) 0.7 mA
Best For Multi-point monitoring Temp+humidity combo Battery-powered, low-cost Extreme temperatures Environmental stations

Decision Tree:

  1. Do you need to measure humidity too?
    • YES: DHT22 (budget) or BME280 (precision + pressure)
    • NO: Continue to step 2
  2. Do you need multiple sensors on one microcontroller?
    • YES: DS18B20 (1-Wire allows dozens on one pin)
    • NO: Continue to step 3
  3. What is your temperature range?
    • Normal environment (-10 to 50C): Any sensor works
    • Cold storage (-40 to 0C): DS18B20, DHT22, or BME280
    • Industrial ovens (100 to 300C): Thermocouple required
    • Extreme high (>500C): K-Type or J-Type thermocouple only
  4. What is your power budget?
    • Battery-powered (microamps matter): Thermistor (passive) or DS18B20 (1 uA standby with parasitic power)
    • Mains-powered: Any sensor works
  5. What is your accuracy requirement?
    • High precision (+/- 0.5C): DS18B20 or BME280
    • General purpose (+/- 1-2C): Thermistor or DHT22
    • Industrial monitoring (+/- 2C acceptable): Thermocouple

Example Use Cases:

Application Recommended Sensor Why?
Smart home thermostat BME280 Temp + humidity + pressure in one package; I2C interface
Freezer monitoring DS18B20 -55C capability; waterproof probe versions available
Food cooking probe K-Type thermocouple Fast response; handles up to 300C for ovens
Weather station BME280 Includes humidity and barometric pressure; I2C
Industrial boiler K-Type thermocouple Handles 500-1000C; probe can be remote from electronics
Battery-powered soil sensor Thermistor Ultra-low power; direct ADC reading; $0.50 per unit
Multi-room HVAC monitoring DS18B20 (x8 sensors) One 1-Wire bus for all rooms; unique addressing

Key Insight: For most IoT applications in normal environments (-10 to 50C), the DS18B20 is the best starting point due to its accuracy, digital interface, and multi-sensor capability. If you need humidity too, use a BME280 or DHT22. Reserve thermocouples for specialized high-temperature applications where no semiconductor sensor can survive.

26.9 Concept Relationships

Core Concept Related Concepts Why It Matters
1-Wire Protocol Unique Addressing, Multi-Drop Bus, Pull-up Resistors Enables dozens of sensors on a single GPIO pin
Conversion Time ADC Resolution, Blocking vs Non-Blocking 750ms at 12-bit; 93.75ms at 9-bit
CRC Error Detection Data Integrity, Cable Length, EMI -127C error code flags corrupt or missing data
Seebeck Effect Thermocouple Types, Cold Junction Compensation Voltage output proportional to temperature difference
Parasitic Power 2-Wire Operation, Strong Pull-up Sensor draws power from data line (no separate VDD wire needed)
Key Takeaway

Temperature sensors are the most common starting point for IoT projects. DS18B20 excels for multi-sensor networks (unique addressing on one wire), DHT22 combines temperature and humidity in one package (but reads slowly at 0.5 Hz), and thermocouples handle extreme temperatures using the Seebeck effect. Knowing the error signatures – 85C means conversion incomplete, -127C means wiring or CRC error, NaN means read failure – is essential for debugging any temperature monitoring system.

26.10 Summary

This chapter covered temperature sensor implementation fundamentals:

  • DS18B20 1-Wire sensors enable multi-sensor networks on a single GPIO pin with unique 64-bit addressing and +/-0.5C accuracy
  • DHT22 sensors provide combined temperature and humidity but require 2-second minimum intervals between reads
  • Thermocouples measure extreme temperatures (up to 1250C for K-Type) using the Seebeck effect with cold junction compensation
  • Proper pull-up resistors (4.7kOhm for 1-Wire, 4.7-10kOhm for DHT) ensure reliable communication
  • Common error values (85C = power-on default/conversion incomplete, -127C = CRC error/disconnected, NaN = DHT read failure) indicate specific failure modes that guide debugging
  • Sensor selection depends on temperature range, accuracy needs, power budget, and whether humidity measurement is also required

Common Pitfalls

Passing too much current through a thermistor or RTD causes it to heat itself, producing readings higher than ambient temperature. Keep excitation current below the manufacturer’s recommended maximum (typically under 1 mA for RTDs).

Thermocouples measure a temperature difference, not absolute temperature. Failing to measure and compensate for the cold-junction (reference) temperature introduces a constant offset error that changes with room temperature.

If the ADC reference voltage shifts with temperature or supply voltage, all readings shift proportionally. Use a stable voltage reference IC rather than the MCU supply rail for precision temperature measurement.

Using generic NTC coefficients instead of the specific A, B, C constants for your thermistor part number yields large nonlinearity errors especially at temperature extremes. Always use datasheet-specified coefficients.

26.11 What’s Next?

If you want to… Read this
Understand humidity sensing alongside temperature Sensor Types: Environmental Sensors
Add signal filtering to reduce noise Signal Processing for IoT Sensors
Integrate sensor readings into an IoT platform Sensor Applications Overview
Explore power-efficient sensor sampling Sensor Power Management

Now that you understand temperature sensors, continue to learn about motion and environmental sensors including accelerometers, gyroscopes, and barometric pressure sensors.

Continue to Motion & Environmental Sensors –>

Sammy the Sensor is a DS18B20 temperature sensor, and he has a superpower: a unique name! “Every DS18B20 in the world has a different 64-bit address,” Sammy explained. “So you can put 10 of us on the SAME wire, and Max the Microcontroller can ask each of us individually!”

Sammy’s friend Dee the DHT22 can measure two things: temperature AND humidity. “I am like a combo deal!” Dee laughed. But she has one rule: “You can only ask me once every 2 seconds. I need time to think!”

Lila the LED asked, “What if Sammy says 85 degrees right when he wakes up?” Max explained: “That is Sammy’s ‘I am not ready yet’ number. When he first powers on, he always says 85 until he finishes his first real measurement. Just wait 750 milliseconds!”

Bella the Battery added her tip: “If Sammy says -127 degrees, that means his wire came loose or the signal got scrambled. Check the connections and make sure the 4.7k pull-up resistor is in place!”

26.12 See Also