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
Sensor lab implementation workflow
Figure 26.1: Sensor lab workflow showing the complete implementation process from planning through deployment
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.
Figure 26.2: Sensor Implementation Workflow: From Research to Deployment with Debug Loops
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// GPIO4OneWire oneWire(ONE_WIRE_BUS);DallasTemperature sensors(&oneWire);// Store number of devicesint 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 addressesfor(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 printingif(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);}}
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.
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.
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.
Show code
viewof rawDecimal = Inputs.range([-2048,2047], {value:464,step:1,label:"Raw Value (decimal, signed 16-bit)"})viewof resolutionBits = Inputs.select([9,10,11,12], {value:12,label:"Resolution (bits)"})// DS18B20 always divides by 16 regardless of resolution.// Lower resolutions leave the least-significant bits undefined.undefinedBits =12- resolutionBitsstepSizeC =Math.pow(2, undefinedBits) /16tempFromRaw = rawDecimal /16rawHex = rawDecimal >=0?"0x"+ rawDecimal.toString(16).toUpperCase().padStart(4,'0') :"0x"+ ((rawDecimal +65536) >>>0).toString(16).toUpperCase().padStart(4,'0')conversionTime = resolutionBits ===9?93.75: resolutionBits ===10?187.5: resolutionBits ===11?375:750isErrorValue = rawDecimal ===1360isCrcError = rawDecimal <=-2032html`<div style="background: var(--bs-light, #f8f9fa); padding: 15px; border-radius: 8px; border-left: 4px solid #16A085; margin-top: 10px;"> <h4 style="margin-top: 0; color: #2C3E50;">DS18B20 Raw-to-Temperature Converter</h4> <p style="font-size: 14px; line-height: 1.8; margin: 8px 0;"> <strong>Raw hex:</strong> ${rawHex} <br><strong>Temperature:</strong> ${tempFromRaw.toFixed(4)}°C <br><strong>Resolution step:</strong> ${stepSizeC.toFixed(4)}°C (${resolutionBits}-bit mode; ${undefinedBits} LSB${undefinedBits >1?'s':''} undefined) <br><strong>Conversion time:</strong> ${conversionTime} ms${isErrorValue ?'<br><span style="color: #E74C3C; font-weight: bold;">Warning: This is the power-on reset value (85°C). The sensor may not have completed conversion yet.</span>':''}${isCrcError ?'<br><span style="color: #E74C3C; font-weight: bold;">Warning: This value is at or below -127°C, which typically indicates a CRC error or disconnected sensor.</span>':''} </p> <p style="font-size: 13px; color: #7F8C8D; margin: 8px 0; font-style: italic;"> Formula: T = raw_value / 16 = ${rawDecimal} / 16 = ${tempFromRaw.toFixed(4)}°C </p></div>`
How It Works: DS18B20 1-Wire Communication
The DS18B20 uses a single data line for bidirectional communication with strict timing requirements:
Initialization – Master pulls line LOW for 480us minimum, then releases. The bus pull-up resistor returns the line HIGH.
Presence pulse – Sensor responds by pulling the line LOW for 60-240us, signalling “I am here.”
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).
Function command – Master sends 0x44 (Convert T) to start temperature conversion.
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.
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.
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
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
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
Interactive: Thermocouple Voltage Calculator
Estimate the output voltage of a thermocouple given the junction temperatures and type.
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
Figure 26.5: Comparison of relative humidity sensors
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.
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:
Install the OneWire and DallasTemperature libraries from the Arduino Library Manager
Upload the ESP32 Implementation code from the DS18B20 section above
Open Serial Monitor at 115200 baud
Verify the sensor is detected (should print “Found 1 temperature sensors”)
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
Intermediate Level: Multi-Sensor 1-Wire Bus
Goal: Read 3 DS18B20 sensors on one GPIO pin, identify each by address.
Challenge:
Connect all 3 sensors to the same GPIO pin (parallel wiring – all VDD to VDD, all GND to GND, all DATA to GPIO4)
Use a single 4.7kOhm pull-up resistor shared by all sensors
Use getDeviceCount() to verify all 3 sensors are detected
Read each sensor by its unique address using getTempC(address)
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.
Advanced Level: Temperature Data 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.
26.8 Knowledge Check
Decision Framework: Choosing a Temperature Sensor for Your IoT Project
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:
Do you need to measure humidity too?
YES: DHT22 (budget) or BME280 (precision + pressure)
NO: Continue to step 2
Do you need multiple sensors on one microcontroller?
YES: DS18B20 (1-Wire allows dozens on one pin)
NO: Continue to step 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
What is your power budget?
Battery-powered (microamps matter): Thermistor (passive) or DS18B20 (1 uA standby with parasitic power)
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.
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.
🏷️ Label the Diagram
Code Challenge
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
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).
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.
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.
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.
Now that you understand temperature sensors, continue to learn about motion and environmental sensors including accelerometers, gyroscopes, and barometric pressure 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!”