34  Lab: Temperature Sensors

sensors
sensor
temperature

34.1 Start With the Measurement Story

A temperature lab is not just a wiring exercise. The useful story is heat moving through the sensor package, the reading lagging behind reality, and calibration evidence showing when the number can be trusted.

34.2 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).

Chapter Roadmap

This lab moves from dependable first readings to field-ready evidence:

  1. First you compare the major sensor families and set up a safe DS18B20 measurement path.
  2. Then you decode 1-Wire raw values, timing, pull-ups, and the 85C and -127C failure signatures.
  3. Next you contrast thermocouples, DHT22 timing, humidity behavior, and multi-sensor lab exercises.
  4. Finally you choose a sensor for the application, test yourself with quizzes, and carry the thermistor/RTD material into the next chapter.

Checkpoints recap the operational decisions; deeper calculators and audits are support material when you need the arithmetic.

34.3 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

Phoebe the physics guide

34.3.1 Phoebe’s Why

A thermistor and an RTD both turn heat into resistance, but the physics is different. In an NTC thermistor, warming gives charge carriers enough thermal energy to cross a material barrier, so resistance falls steeply and nonlinearly. In a platinum RTD, warming makes the metal lattice vibrate more, so electrons scatter more often and resistance rises almost linearly. The ADC never measures temperature directly; it measures a voltage made from that changing resistance, then the firmware inverts the sensor law.

34.3.2 The Derivation

For an NTC thermistor, the carrier population follows a Boltzmann factor, so resistance can be written as the Beta law:

\[R(T) = R_0 e^{B(1/T - 1/T_0)}\]

Invert it to recover temperature from resistance:

\[\ln(R/R_0) = B(1/T - 1/T_0)\]

\[\frac{1}{T} = \frac{1}{T_0} + \frac{1}{B}\ln(R/R_0)\]

A fuller Steinhart-Hart fit uses measured calibration constants:

\[\frac{1}{T} = A + B_s\ln R + C_s(\ln R)^3\]

An RTD uses a first-order metal law over modest spans:

\[R(T) = R_0(1 + \alpha T)\]

Self-heating comes from the same excitation current used to read the resistor:

\[P = I^2R\]

\[\Delta T_{self} = P\theta\]

34.3.3 Worked Numbers: This Chapter’s Lab Limits

The chapter uses a 12-bit ADC reference of \(3.3\) V in the thermocouple calculator, so one ADC count is

\[q = 3.3/4096 = 0.000806 \text{ V}\]

For a balanced thermistor divider, the midpoint is

\[V_{out} = 3.3/2 = 1.65 \text{ V}\]

For a standard Pt100, \(R_0 = 100\) ohm at \(0\) C and \(\alpha = 0.00385/\text{C}\). At the chapter’s “under 1 mA” excitation limit:

  • Pt100 sensitivity: \(1.00\text{ mA} \times 0.385\text{ ohm/C} = 0.385\text{ mV/C}\)
  • 12-bit count size: \(0.806/0.385 = 2.09\) C per count before amplification
  • Pt1000 sensitivity: \(1.00\text{ mA} \times 3.85\text{ ohm/C} = 3.85\text{ mV/C}\), so \(0.806/3.85 = 0.209\) C per count
  • Self-heating power at 1 mA is \(1.00^2\text{ mA}^2 \times 100\text{ ohm} = 0.100\text{ mW}\) for Pt100 and \(1.00\text{ mW}\) for Pt1000

That is why precision RTD circuits usually amplify the small voltage, use a stable reference, and keep excitation current low enough that the sensor does not warm itself.

34.4 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

34.5 Prerequisites

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:

34.6 For Beginners: Temperature Sensor Basics

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!

34.7 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 34.1 illustrates this complete pipeline, and Figure 34.2 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 34.1: 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 means wiring issue, wrong values indicate voltage or timing problems, unstable readings need filtering, and drift requires calibration.
Figure 34.2: 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.

The overview gives you the workflow. The first detailed device is the DS18B20 because it turns wiring, addressing, timing, and error handling into one compact lab.

34.8 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

What to Observe Before Coding:

The DS18B20 is useful because many sensors can share one GPIO pin. The first behavior to check is discovery: how many devices are on the 1-Wire bus, and does each one have a unique address?

34.8.1 1-Wire Discovery Flow

  1. Start the 1-Wire bus.
  2. Count connected temperature sensors.
  3. Print each unique sensor address.
  4. Request temperatures.
  5. Reject disconnected-sensor error values.

34.8.2 Optional 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);
  }
}

34.8.3 Putting Numbers to It

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.

34.8.4 Interactive: DS18B20 Raw Value Converter

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

34.8.5 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.

34.8.6 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

Physics PhoebeCheckpoint: DS18B20 Measurement Path

You now know:

  • A single GPIO pin can host many DS18B20 sensors because each device has a unique 64-bit address.
  • The 12-bit conversion can take 750ms, and the raw register still divides by 16 when you decode it.
  • 85C means conversion is not ready; -127C points to a CRC or disconnection fault.

34.9 Thermocouple-Based Temperature Sensors

Diagram showing thermocouple-based temperature sensors with junction points and voltage output circuitry for measuring temperature differences
Figure 34.3: 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

34.9.1 Thermocouple Voltage Calculator

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.

Physics PhoebeCheckpoint: High-Temperature Sensing

You now know:

  • Thermocouples measure a temperature difference, so cold-junction compensation is part of the measurement, not an optional extra.
  • A K-Type probe covers -200 to 1250C, which is why it fits the 600C oven case later in the quiz.
  • The calculator shows why tiny uV/C signals need amplification before a 12-bit ADC can use them.

34.10 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 34.4: Comparison of relative humidity sensors

34.10.1 DHT Setup Resource

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 34.5: 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) Behavior:

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

34.10.2 DHT22 Timing Requirement

The DHT22 requires a minimum 2-second interval between readings. Reading faster causes the sensor to return stale data or errors. The important rule is simple: validate the reading, then wait at least 2 seconds before asking again.

34.10.3 Optional DHT22 Read Loop

#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
}

34.11 Lab Exercises

The sensor sections told you what can go wrong. The labs now turn those rules into checks you can perform at the bench.

34.11.1 Beginner Level: Read a Single DS18B20

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

Wiring:

Wiring path:

  • DS18B20 red/VDD -> ESP32 3.3V
  • DS18B20 black/GND -> ESP32 GND
  • DS18B20 yellow/DATA -> ESP32 GPIO4
  • 4.7kOhm pull-up resistor between DATA and VDD

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

34.11.2 Multi-Sensor 1-Wire Bus

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.

34.11.3 Temperature Logger with Alarms

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.

Physics PhoebeCheckpoint: Lab Readiness

You now know:

  • The beginner lab should find 1 temperature sensor before you trust the readings.
  • A multi-sensor bus still uses one shared 4.7kOhm pull-up resistor.
  • The logger moves from readings to evidence by storing CSV data, hourly averages, and alarms above 30C.

34.12 Knowledge Check

34.13 IoT Temp Sensor Choice

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.

Physics PhoebeCheckpoint: Sensor Choice

You now know:

  • DS18B20 fits multi-point temperature monitoring; DHT22 or BME280 fits temperature plus humidity.
  • Thermistors suit low-cost battery designs, while thermocouples are reserved for high-temperature work.
  • Selection depends on range, accuracy, power budget, humidity needs, and whether multiple sensors share one controller.

34.14 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)

34.15 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.

34.16 Label the Diagram

34.17 Code Challenge

34.18 Thermistor Linear Fit

The lab above covers DS18B20, DHT22, thermocouple, and humidity-sensor workflows. Continue to Thermistor Linearization and Temperature Calibration when the measurement path uses a thermistor or RTD analog front end. That page separates the deeper material: divider-to-resistance conversion, Beta-equation math, Steinhart-Hart fitting, RTD curve limits, self-heating, lead resistance, and calibration records.

34.19 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

34.19.1 1. Self-heating errors

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).

34.19.2 2. Cold-junction compensation omitted

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.

34.19.3 3. Ignoring ADC reference voltage drift

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.

34.19.4 4. Incorrect Steinhart-Hart coefficients

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.

34.20 What’s Next?

If you want to… Read this
Linearize thermistors and RTDs Thermistor Linearization and Temperature Calibration
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 –>

34.20.1 For Kids: Meet the Sensor Squad!

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!”

34.21 See Also