Two thermometers on one wire (DS18B20)
Find two DS18B20 temperature sensors on a single 1-Wire pin by their addresses and read both.
Sensors · Intermediate
In a real product: Cold-chain truck monitor (Rail and transport): Several probes on one wire log the temperature in each part of the cargo.
The DS18B20 is a digital thermometer with a unique 64-bit address burned into it. Because each one has its own address, any number of them can share one data pin: a room, a fridge and a freezer, all on pin 2.
What you'll learn
- The 1-Wire bus: one data line, a pull-up resistor and timed slots
- Finding devices by searching their ROM addresses
- Starting a conversion and reading the result with DallasTemperature
How it works
The data line (DQ) is open drain: the board and the sensors only ever pull it LOW, and the 4.7 kΩ resistor pulls it back HIGH. Without that resistor the line never rises, and no sensor is found.
sensors.begin() resets the bus (a 480 µs LOW, answered by each sensor's presence pulse) and runs the search algorithm: it reads each address bit and its complement from all sensors at once, and where they disagree it picks one branch, then comes back for the other. getDeviceCount() is the result.
requestTemperatures() sends CONVERT T to every sensor and waits for them to finish (750 ms at 12-bit resolution); getTempCByIndex(i) then reads sensor i's scratchpad and checks its CRC.
Try this
- Click a sensor while it runs and change its temperature: the reading follows at the next conversion.
- Remove the resistor's wire and restart: "Found 0 sensors".
- Use
sensors.setResolution(9)and see the readings change in half-degree steps, and the conversion get 8 times faster.
sketch.ino
// Two DS18B20 sensors share pin 2. The sketch finds them by address and prints both temperatures every second.
#include <OneWire.h>
#include <DallasTemperature.h>
OneWire bus(2);
DallasTemperature sensors(&bus);
int count = 0;
void printAddress(DeviceAddress address) {
for (int i = 0; i < 8; i++) {
if (address[i] < 16) Serial.print('0');
Serial.print(address[i], HEX);
}
}
void setup() {
Serial.begin(9600);
sensors.begin();
count = sensors.getDeviceCount();
Serial.print("Found ");
Serial.print(count);
Serial.println(" sensors");
for (int i = 0; i < count; i++) {
DeviceAddress address;
if (sensors.getAddress(address, i)) {
Serial.print(" sensor ");
Serial.print(i);
Serial.print(": ");
printAddress(address);
Serial.println();
}
}
}
void loop() {
sensors.requestTemperatures();
for (int i = 0; i < count; i++) {
Serial.print("Sensor ");
Serial.print(i);
Serial.print(": ");
Serial.print(sensors.getTempCByIndex(i), 1);
Serial.print(" C ");
}
Serial.println();
delay(1000);
}