The DS18B20 is the most popular Raspberry Pi temperature sensor: one data wire, ±0.5°C accuracy, and as many sensors as you like on the same GPIO pin. But how does it work on the Raspberry Pi 5, where the 1-Wire bus is bit-banged by the kernel through the new RP1 chip, and how do you read it from both Python and C++?
This tutorial starts with a seven-step quick start that gets you a working temperature reading in about ten minutes. After that, you’ll find more in-depth information: the 1-Wire timing measured on an oscilloscope, the real read time at every resolution, how to read several sensors by their ROM IDs, how to check whether your DS18B20 is a clone, a CSV logger that starts at boot, and the fixes for the errors you’re most likely to meet. Without further ado, let’s get right into it!
Note: All steps in this tutorial are tested with a Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, and a DS18B20 (TO-92) with a 4.7kΩ pull-up resistor.
This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first.
Raspberry Pi DS18B20 Quick Start (1-Wire)
You need a Raspberry Pi, a DS18B20 (the 3-pin TO-92 chip or a waterproof probe), one 4.7kΩ resistor, a breadboard, and jumper wires:
| QTY. | Component Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 1+ | DS18B20 Temperature Sensor (TO-92) | Amazon | AliExpress |
| 1 | 4.7kΩ Resistor (Resistors Kit) | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires | Amazon | AliExpress |
#1
Wire the DS18B20 (3 wires and a 4.7kΩ pull-up)

Hold the sensor with its flat face toward you: GND goes to GND, DQ to GPIO4, and VDD to 3.3V. The 4.7kΩ resistor connects DQ to 3.3V. A waterproof probe has the same three wires: usually black = GND, yellow (or white) = DQ, red = VDD. Pin numbers are in the Raspberry Pi 5 pinout.
Note: Double-check VDD and GND before you power up. A DS18B20 wired backwards gets hot within seconds and can be damaged. If it feels warm, unplug it.
#2
Enable 1-Wire, then reboot
|
1 2 |
sudo raspi-config nonint do_onewire 0 sudo reboot |
This adds dtoverlay=w1-gpio to /boot/firmware/config.txt (1-Wire on GPIO4). The menu way is sudo raspi-config > Interface Options > 1-Wire. No modprobe is needed: the kernel loads the w1-gpio and w1-therm drivers by itself.
#3
Find the sensor in /sys/bus/w1/devices
|
1 |
ls /sys/bus/w1/devices/ |
Every DS18B20 gets a folder named after its ROM ID: 28- (the DS18B20 family code) plus 12 hex digits unique to that chip. No 28- folder? Jump to troubleshooting.
#4
Read the temperature with cat
|
1 |
cat /sys/bus/w1/devices/28-*/temperature |
The value is in millidegrees Celsius: 23937 = 23.937°C. The older w1_slave file shows the raw scratchpad bytes, the CRC check, and the same value after t=.
#5
Run the Python script
Python Code (ds18b20_read.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
''' * LAB Name: Raspberry Pi DS18B20 Temperature Read (Python, sysfs) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com ''' import glob, time sensor = glob.glob("/sys/bus/w1/devices/28-*/temperature")[0] # first DS18B20 on the bus try: while True: with open(sensor) as f: temp_c = int(f.read()) / 1000 # the file holds millidegrees Celsius print(f"Temperature: {temp_c:.3f} °C ({temp_c * 9 / 5 + 32:.2f} °F)") time.sleep(1) except KeyboardInterrupt: print("Stopped") |
|
1 |
python3 ds18b20_read.py |
#6
Run the C++ program
C++ Code (ds18b20_read.cpp)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/* * LAB Name: Raspberry Pi DS18B20 Temperature Read (C++, sysfs) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #include <chrono> #include <cstdio> #include <filesystem> #include <fstream> #include <thread> namespace fs = std::filesystem; int main() { std::setvbuf(stdout, nullptr, _IOLBF, 0); // print each line at once fs::path sensor; for (auto &d : fs::directory_iterator("/sys/bus/w1/devices")) // first DS18B20 on the bus if (d.path().filename().string().rfind("28-", 0) == 0) { sensor = d.path() / "temperature"; break; } if (sensor.empty()) { std::puts("No DS18B20 found"); return 1; } while (true) { std::ifstream f(sensor); long milli; if (f >> milli) // millidegrees Celsius std::printf("Temperature: %.3f °C (%.2f °F)\n", milli / 1000.0, milli / 1000.0 * 9 / 5 + 32); std::this_thread::sleep_for(std::chrono::seconds(1)); } } |
|
1 2 |
g++ -std=c++17 ds18b20_read.cpp -o ds18b20_read ./ds18b20_read |
Neither program needs a library or sudo: the kernel driver does the 1-Wire work, and both just read a file. g++ is on Raspberry Pi OS; if it’s missing, run sudo apt install build-essential.
#7
End result
That’s a working temperature reading in both languages. The rest of this tutorial explains the sensor and the bus, then covers multiple sensors, resolution and speed, fake sensors, a logger that starts at boot, and troubleshooting.
DS18B20 Temperature Sensor Explained
The DS18B20 (Analog Devices, formerly Maxim and Dallas) is a digital thermometer with its own ADC: it measures, converts, and sends the result as a number over the 1-Wire bus, so the Pi needs no analog input. The key specs, from the DS18B20 datasheet:
| Parameter | Value |
|---|---|
| Range | −55°C to +125°C |
| Accuracy | ±0.5°C from −10°C to +85°C (±2°C over the full range) |
| Resolution | 9 to 12 bits: 0.5, 0.25, 0.125, 0.0625°C (12-bit at power-up) |
| Conversion time (max) | 93.75 / 187.5 / 375 / 750ms at 9 / 10 / 11 / 12 bits |
| Supply | 3.0V to 5.5V, or parasite power from the data line |
| Current | 1mA typical (1.5mA max) while converting, 750nA standby |
| Address | 64-bit ROM: family code 0x28, 48-bit serial, 8-bit CRC |
DS18B20 Pinout
| Pin (flat face toward you) | Name | Waterproof probe wire | Connect to |
|---|---|---|---|
| 1 (left) | GND | black | GND (pin 6) |
| 2 (middle) | DQ (data) | yellow or white | GPIO4 (pin 7) + 4.7kΩ to 3.3V |
| 3 (right) | VDD | red | 3.3V (pin 1), or GND in parasite mode |
The 1-Wire Bus and ROM IDs

All sensors share the same three wires. The Pi tells them apart by their 64-bit ROM, which is lasered into each chip at the factory: Linux shows the family code and the 48-bit serial as the folder name ( 28-0120582962bc) and checks the CRC for you. So the folder name never changes, and you can label each sensor by it.
Raspberry Pi Temperature Sensor Options Compared
| Sensor | Measures | Interface | Accuracy | Best for |
|---|---|---|---|---|
| DS18B20 | Temperature | 1-Wire (1 GPIO for many sensors) | ±0.5°C | Liquids, outdoors (waterproof probe), many points, long wires |
| BME280 / BMP280 | Temp. + pressure (+ humidity on BME280) | I2C or SPI | ±1°C (BME280) | Weather stations, indoor climate |
| DHT22 (AM2302) | Temp. + humidity | Single-wire (not 1-Wire) | ±0.5°C | Humidity on a budget; slow (one read per 2s) |
| CPU temperature | SoC temperature | vcgencmd measure_temp | – | Cooling and throttling, not room temperature |
Pick the DS18B20 when you only need temperature and want several sensors or a probe on a cable. For humidity or pressure, use an I2C sensor on the bus from my Raspberry Pi I2C tutorial. The CPU temperature ( vcgencmd measure_temp) tells you how hot the chip is, not the room.
Raspberry Pi 1-Wire Protocol Explained
1-Wire uses one open-drain data line: the master and every sensor can only pull it low, and the pull-up resistor pulls it back high. Each transaction starts with a reset pulse from the master and a presence pulse from the sensors; then bits are sent in time slots, where the length of a low pulse means 0 or 1.

Here is the same bus on my oscilloscope (Siglent SDS1104X-E, CH1 on DQ) while the Pi 5 reads the sensor:
| 1-Wire timing | Datasheet | Measured on the Pi 5 |
|---|---|---|
| Reset pulse | ≥ 480µs | 505µs |
| Presence pulse (from the sensor) | 60–240µs | 124µs |
| Write 0, low time | 60–120µs | 66µs (driver asks 60) |
| Write 1, low time | 1–15µs | 11µs (driver asks 6) |
| Rising edge with 4.7kΩ | – | 1.4µs |
The kernel driver (w1_io.c) asks for 6µs and 60µs, and the Pi 5 adds about 5–6µs to each low pulse, because every GPIO change goes through the RP1 chip. That’s still inside the datasheet limits, but it shows why the Pi 5 has its own overlay, w1-gpio-pi5, which makes the driver poll a timer instead of using udelay() (overlay source).
Why the 4.7kΩ Pull-Up Resistor?
The Pi 5’s 1-Wire overlay turns the GPIO’s internal pull-up off ( pinctrl get 4 shows pn, pull none), so without an external resistor the line just sits at 0V: no presence pulse, no sensor. With the RP1’s internal pull-up switched on by hand ( pinctrl set 4 pu), my sensor still answered, but every rising edge took 9.8µs instead of 1.4µs:
With 11µs write-1 pulses and a 15µs read window, that leaves almost no margin, and it gets worse with longer wires. Use the external 4.7kΩ resistor (the datasheet value); 2.2kΩ to 4.7kΩ works for short runs, and lower values help long cables. One resistor for the whole bus, near the Pi.
Enable 1-Wire on the Raspberry Pi 5
| Method | How | Notes |
|---|---|---|
| raspi-config | sudo raspi-config nonint do_onewire 0 (or the menu) | Adds dtoverlay=w1-gpio; GPIO4 only |
| config.txt | dtoverlay=w1-gpio in /boot/firmware/config.txt | Edit with sudo nano; reboot |
| Another GPIO | dtoverlay=w1-gpio,gpiopin=17 | Any free GPIO; physical pin from the pinout |
| Two buses | Two lines: dtoverlay=w1-gpio,gpiopin=4 and dtoverlay=w1-gpio,gpiopin=17 | Shows up as w1_bus_master1 and w1_bus_master2 |
| Without a reboot | sudo dtoverlay w1-gpio | Loads the overlay now (until the next boot) |
On a Pi 5, w1-gpio is mapped to w1-gpio-pi5 automatically, as dtoverlay -l shows. The pullup parameter you’ll see in older tutorials is now ignored (overlay README), and /boot/config.txt moved to /boot/firmware/config.txt in Bookworm (config.txt documentation). On a Pi 4 the same dtoverlay=w1-gpio line loads the original overlay; everything else in this tutorial is the same.
Raspberry Pi 1-Wire sysfs Files (w1_therm)
| File | Read | Write (sudo) |
|---|---|---|
temperature | Temperature in m°C (starts a conversion) | – |
w1_slave | 9 scratchpad bytes, CRC YES/NO, t= value | 9–12 = resolution, 0 = save to EEPROM |
resolution | Current resolution (9–12) | New resolution (lost at power-off unless saved) |
conv_time | Wait time in ms | ms value, 1 = auto-measure, 0 = default |
features | Driver options | 1 = check conversion, 2 = poll for completion |
ext_power | 1 = VDD powered, 0 = parasite | – |
alarms | TL TH alarm thresholds (°C) | New thresholds |
w1_bus_master1/therm_bulk_read | 0 / −1 / 1 = conversion state | trigger = all sensors convert at once |
The full list is in the w1_therm kernel documentation. w1_master_slaves lists every device on the bus, and w1_master_slave_count counts them.
DS18B20 Resolution and Conversion Time (Measured)
A read of the temperature file starts a conversion, waits, then reads the result, so its duration is set by the resolution, not by your language. I timed it in Python and C++ on my Pi 5 (median of 5 reads; both languages gave the same times within 4ms):

| Resolution | Step | Datasheet max | Read time (default) | Read time (features=2) |
|---|---|---|---|---|
| 9-bit | 0.5°C | 93.75ms | 132ms | 140ms |
| 10-bit | 0.25°C | 187.5ms | 228ms | 212ms |
| 11-bit | 0.125°C | 375ms | 416ms | 392ms |
| 12-bit (default) | 0.0625°C | 750ms | 800ms | 752ms |
|
1 2 3 4 |
cd /sys/bus/w1/devices/28-*/ echo 9 | sudo tee resolution # 9-12, back to 12 at power-off echo 2 | sudo tee features # poll for the end of the conversion echo 0 | sudo tee w1_slave # optional: save the resolution to EEPROM |
About 40ms of each read is the bus traffic and the driver’s own waiting. With features=2 the driver polls the sensor and stops waiting as soon as the conversion is done, which saved 48ms at 12 bits on my sensor. For several sensors, write trigger to therm_bulk_read: they all convert at the same time, so ten sensors still take one conversion time, not ten.
Tip: Reading nonstop at 12 bits used 2.6% of one CPU core on my Pi 5 (0.78s of CPU in 30s, 38 reads), almost all in the kernel while it bit-bangs the bus. A one-second loop costs well under 1%.
Raspberry Pi DS18B20 Python Library (w1thermsensor)
| Option | Version | Install on Trixie | Use it for |
|---|---|---|---|
| Plain sysfs reads | – | Nothing | Quick scripts, services, no dependencies |
| w1thermsensor (PyPI) | 2.3.0 (2023) | venv + pip (not in apt) | Several sensors, units, error types, a CLI |
w1thermsensor wraps the same sysfs files with a sensor list, unit conversion, and clear exceptions; it worked on my Pi 5 without changes. It isn’t packaged in Raspberry Pi OS, and a plain pip install fails with externally-managed-environment (PEP 668), so install it in a virtual environment:
|
1 2 |
python3 -m venv --system-site-packages venv venv/bin/pip install w1thermsensor |
Multiple DS18B20 Sensors With Labels (Python)

Python Code (ds18b20_multi.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
''' * LAB Name: Raspberry Pi Multiple DS18B20 Sensors With Labels (Python, w1thermsensor) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com ''' import time from w1thermsensor import W1ThermSensor, Sensor from w1thermsensor.errors import SensorNotReadyError, NoSensorFoundError, ResetValueError # Give each sensor a name: copy the IDs from the first run's output LABELS = { # "0120582962bc": "Room", # w1thermsensor IDs have no "28-" } sensors = W1ThermSensor.get_available_sensors([Sensor.DS18B20]) if not sensors: raise SystemExit("No DS18B20 found: check 1-Wire, the wiring and the 4.7k pull-up") try: while True: for s in sensors: name = LABELS.get(s.id, s.id) try: print(f"{name:>14}: {s.get_temperature():7.3f} °C") except ResetValueError: # 85.000 °C power-on value: the conversion didn't run print(f"{name:>14}: power-on value (85 °C), ignored") except (SensorNotReadyError, NoSensorFoundError) as e: print(f"{name:>14}: read failed ({type(e).__name__})") print() time.sleep(2) except KeyboardInterrupt: print("Stopped") |
Run it once, copy the IDs it prints into LABELS, and every line gets a name. Example output with three sensors (illustrative values: my bench has one sensor, so this is not a capture):
|
1 2 3 |
Room: 23.937 °C Window: 21.812 °C 3c01d6071a2e: 24.125 °C |
Error Handling: CRC, Missing Sensor, 85°C (Python)
Python Code (ds18b20_robust.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
''' * LAB Name: Raspberry Pi DS18B20 Read With CRC Check and Error Handling (Python, sysfs) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com ''' import glob, os, time W1 = "/sys/bus/w1/devices" def read_ds18b20(rom, retries=3): """Return the temperature in °C, or raise OSError after `retries` bad reads.""" path = f"{W1}/{rom}/w1_slave" for _ in range(retries): try: with open(path) as f: crc_line, data_line = f.read().splitlines() except (FileNotFoundError, ValueError): # sensor gone, or empty read time.sleep(0.2) continue if not crc_line.endswith("YES"): # CRC mismatch: noise on the line continue raw = crc_line.split()[:9] if set(raw) == {"00"}: # DQ stuck low (no pull-up): zeros pass the CRC continue milli = int(data_line.split("t=")[1]) if milli == 85000 and raw[6] == "0c": # power-on value, no conversion done continue return milli / 1000 raise OSError(f"{rom}: no valid reading after {retries} tries") roms = sorted(os.path.basename(p) for p in glob.glob(f"{W1}/28-*")) print("Found:", ", ".join(roms) or "none") try: while True: for rom in roms: try: print(f"{rom}: {read_ds18b20(rom):.3f} °C") except OSError as e: print("ERROR", e) time.sleep(2) except KeyboardInterrupt: print("Stopped") |
It retries a read up to three times and rejects the four bad results you can get from the bus: a CRC mismatch ( NO), a missing sensor (the folder is gone), the 85.000°C power-on value (byte 6 = 0c), and all-zero bytes, which pass the CRC when the line is stuck low (see below).
Raspberry Pi DS18B20 C++ Example (sysfs)
C++ needs no library either: the program reads the same w1_slave files, with the same labels, retries, and checks as the Python version.
C++ Code (ds18b20_multi.cpp)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
/* * LAB Name: Raspberry Pi Multiple DS18B20 Sensors With Labels and Error Handling (C++, sysfs) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com */ #include <algorithm> #include <chrono> #include <cstdio> #include <filesystem> #include <fstream> #include <map> #include <optional> #include <sstream> #include <string> #include <thread> #include <vector> namespace fs = std::filesystem; const fs::path W1 = "/sys/bus/w1/devices"; // Give each sensor a name: copy the IDs from the first run's output const std::map<std::string, std::string> LABELS = { // {"28-0120582962bc", "Room"}, }; // One read of w1_slave: CRC, all-zero (stuck-low line) and 85 °C power-on checks. Empty = bad read. std::optional<double> readOnce(const std::string &rom) { std::ifstream f(W1 / rom / "w1_slave"); std::string crcLine, dataLine; if (!std::getline(f, crcLine) || !std::getline(f, dataLine)) return {}; // sensor gone if (crcLine.size() < 3 || crcLine.compare(crcLine.size() - 3, 3, "YES") != 0) return {}; std::istringstream bytes(crcLine); std::vector<std::string> raw(9); for (auto &b : raw) bytes >> b; if (std::all_of(raw.begin(), raw.end(), [](auto &b) { return b == "00"; })) return {}; // DQ stuck low auto pos = dataLine.find("t="); if (pos == std::string::npos) return {}; long milli = std::stol(dataLine.substr(pos + 2)); if (milli == 85000 && raw[6] == "0c") return {}; // power-on value, no conversion done return milli / 1000.0; } std::optional<double> readDS18B20(const std::string &rom, int retries = 3) { for (int i = 0; i < retries; i++) { if (auto t = readOnce(rom)) return t; std::this_thread::sleep_for(std::chrono::milliseconds(200)); } return {}; } int main() { std::setvbuf(stdout, nullptr, _IOLBF, 0); // print each line at once std::vector<std::string> roms; for (auto &d : fs::directory_iterator(W1)) if (d.path().filename().string().rfind("28-", 0) == 0) roms.push_back(d.path().filename()); if (roms.empty()) { std::puts("No DS18B20 found: check 1-Wire, the wiring and the 4.7k pull-up"); return 1; } std::sort(roms.begin(), roms.end()); while (true) { for (auto &rom : roms) { auto it = LABELS.find(rom); std::string name = (it != LABELS.end()) ? it->second : rom; if (auto t = readDS18B20(rom)) std::printf("%16s: %7.3f °C\n", name.c_str(), *t); else std::printf("%16s: read failed\n", name.c_str()); } std::puts(""); std::this_thread::sleep_for(std::chrono::seconds(2)); } } |
|
1 2 |
g++ -std=c++17 ds18b20_multi.cpp -o ds18b20_multi ./ds18b20_multi |
Why not bit-bang 1-Wire from your own program, as on a microcontroller? Because Linux can interrupt a user program at any moment, and a 1-Wire bit is only valid for 15µs. On my Pi 5, even the kernel driver needed about 6ms between the reset and the first command bit. The kernel driver disables interrupts while it times each bit (w1_io.c); a user program can’t. For timing-critical 1-Wire on a microcontroller, see my STM32 1-Wire DS18B20 tutorial.
Fake DS18B20: Check Your Sensor
Most DS18B20s sold online are clones. Chris Petrich’s study bought over 1,000 sensors and probes from more than 70 sellers in 2019, and almost all from eBay and AliExpress were counterfeit (counterfeit_DS18B20). Many work fine; some miss the ±0.5°C spec, don’t work in parasite mode, or are stuck at 12 bits. Three checks you can run from the Pi without risk:
| Check | Genuine DS18B20 | My sensor (28-0120582962bc) |
|---|---|---|
| ROM pattern (Linux name) | 28-0000xxxxxxxx (two zero bytes) | 28-0120… → clone |
| Scratchpad byte 6 after a config write | Follows 0x10 − (byte0 & 0x0F) | Copies the config byte (7f) → clone |
| Resolution 9 and 12 bit settable | Yes | Yes |
| 12-bit conversion (conv_time auto-measure) | ≈ 580–615ms (Petrich) | 864ms |
So my sensor is a clone; the byte-6 behaviour matches the GXCAS/UMW chips Petrich calls Family B. It still read sensibly and handled every resolution. If accuracy matters, buy from an authorized distributor (DigiKey, Mouser) and check the ROM pattern on arrival. The checks are in clone_check.py in the download.
Raspberry Pi Temperature Logger (CSV, systemd)
A logger that writes one CSV row every 10 seconds, starts at boot, and keeps running if a sensor drops out:
Python Code (ds18b20_logger.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
''' * LAB Name: Raspberry Pi DS18B20 Temperature Logger (CSV, Python) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com ''' import csv, datetime, glob, os, time PERIOD_S = 10 # one row every 10 seconds CSV_FILE = "temperature_log.csv" # created in WorkingDirectory W1 = "/sys/bus/w1/devices" def read_c(rom): """°C from w1_slave, or '' on a CRC error, a missing sensor, a stuck-low line (all zeros) or the 85 °C power-on value.""" try: with open(f"{W1}/{rom}/w1_slave") as f: crc_line, data_line = f.read().splitlines() except (OSError, ValueError): return "" raw = crc_line.split()[:9] milli = int(data_line.split("t=")[1]) if not crc_line.endswith("YES") or set(raw) == {"00"} or (milli == 85000 and raw[6] == "0c"): return "" return milli / 1000 roms = sorted(os.path.basename(p) for p in glob.glob(f"{W1}/28-*")) new_file = not os.path.exists(CSV_FILE) with open(CSV_FILE, "a", newline="") as f: log = csv.writer(f) if new_file: log.writerow(["time"] + roms) while True: t0 = time.monotonic() log.writerow([datetime.datetime.now().isoformat(timespec="seconds")] + [read_c(r) for r in roms]) f.flush() # the row is on disk even if the Pi loses power time.sleep(max(0, PERIOD_S - (time.monotonic() - t0))) |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[Unit] Description=DS18B20 temperature logger (CSV) After=multi-user.target [Service] User=pi WorkingDirectory=/home/pi/ds18b20/logger ExecStart=/usr/bin/python3 /home/pi/ds18b20/logger/ds18b20_logger.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target |
|
1 2 |
sudo cp ds18b20-logger.service /etc/systemd/system/ sudo systemctl enable --now ds18b20-logger |

The chart is 16 minutes of the real log from my desk (23.937–24.187°C). The drop to 0.000°C is the pull-up test from the troubleshooting section: my first logger version wrote those rows, which is why the listing above now rejects all-zero reads.
WorkingDirectory decides where temperature_log.csv goes, and f.flush() puts each row on the SD card at once, so a power cut loses at most one row. Copy the file to your PC with scp pi@pi5.local:ds18b20/logger/temperature_log.csv . and open it in any spreadsheet. To show the live value on a small screen, combine it with my Raspberry Pi OLED tutorial.
Raspberry Pi DS18B20 Troubleshooting
No 28-xxxxxxxxxxxx Folder
Check, in this order: 1-Wire enabled ( ls /sys/bus/w1/devices/ says No such file or directory when it’s off), the pull-up resistor in place, the data wire on the GPIO the overlay uses, and the legs in the right order. Here the overlay was on GPIO17 while the sensor was on GPIO4:
DS18B20 Reads 0.000°C, and Ghost 00- Devices
With the pull-up resistor out, DQ stays at 0V. The sensor folder that already existed kept returning 0.000°C in my logger: nine zero bytes have a valid CRC, so the driver accepted them. A 00-800000000000 ghost device appeared at the same time (the kernel log said Family 0 for 00.800000000000.8c is not registered, and w1_search: max_slave_count 64 reached before it):
Both mean the data line is held low: a missing pull-up, a short, or a wrong wire. The examples above reject an all-zero read.
DS18B20 Reads 85°C
85.000°C is the power-on value of the temperature register: the sensor was read before a conversion finished, usually after a brief power drop (a loose VDD wire) or with too short a conv_time. If it repeats, check VDD and write to conv_time. Byte 6 = 0c together with 85°C is the tell on genuine chips.
CRC Errors (crc=xx NO) or −127°C
NO in w1_slave means the bytes arrived corrupted: noise, a long or unshielded cable, a weak pull-up, or a loose breadboard contact. Retry the read (the robust examples do), shorten the wires, or lower the pull-up. −127°C is not a Linux value: it comes from Arduino code ( DEVICE_DISCONNECTED_C) and means the same thing there, a sensor that didn’t answer.
Sensors Drop Out on a Long Cable
Use twisted pair (Cat5: DQ and GND in one pair), a stronger pull-up (2.2kΩ–3.3kΩ), a daisy chain instead of a star, and 3.3V or 5V on VDD rather than parasite power. Analog Devices’ long-line 1-Wire guide covers runs of tens of meters. Keep DQ at 3.3V levels: the Pi’s GPIO isn’t 5V tolerant.
Parasite Mode Fails at 12 Bits

In parasite mode (VDD tied to GND), the sensor charges from DQ and needs up to 1.5mA during a conversion, more than a 4.7kΩ resistor supplies at 12 bits. The Linux driver handles this by driving the line high during the conversion (the strong_pullup module option, on by default, w1_therm docs); features=2 polling doesn’t work in this mode. Many clones don’t support parasite power at all, so use three wires when you can.
Raspberry Pi DS18B20 FAQ
Does the DS18B20 work with the Raspberry Pi 5?
Yes. Enable 1-Wire the usual way; the Pi 5 loads its own w1-gpio-pi5 overlay, and the sysfs files, Python, and C++ code are the same as on older models. Everything here was tested on a Pi 5.
Do I need modprobe w1-gpio and w1-therm?
No. That step is from the old kernels. With the overlay enabled, the drivers load at boot by themselves.
Can I power the DS18B20 from 5V?
The DS18B20 runs from 3.0V to 5.5V, but on a Raspberry Pi connect the pull-up to 3.3V, since the GPIO isn’t 5V tolerant. VDD at 3.3V is fine for normal cable lengths.
How many DS18B20 sensors can one GPIO handle?
The protocol has no practical limit, and the Linux driver searches for up to 64 devices per bus by default ( w1_master_max_slave_count). In practice the cable length and the pull-up set the limit; a second bus on another GPIO splits a big network.
Which GPIO pin is 1-Wire on the Raspberry Pi?
GPIO4 (physical pin 7) by default. Any other GPIO works with dtoverlay=w1-gpio,gpiopin=N.
Download Raspberry Pi DS18B20 Examples
The download has every Python and C++ example, the logger and its service file, the clone check, the resolution benchmark, and a README with the build and run commands.
Download Raspberry Pi DS18B20 Examples (Python, C++)
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
Wrap Up
To conclude this tutorial, we’ve wired a DS18B20 to the Raspberry Pi 5 with a 4.7kΩ pull-up, enabled 1-Wire, and read the temperature from the command line, Python, and C++, with several sensors, error handling, and a logger that starts at boot. The measurements show that the speed is set by the conversion time of the resolution you pick (800ms at 12 bits, 132ms at 9 bits), not the language.
The other buses on the Pi are covered in my I2C, SPI, and UART tutorials, the GPIO basics in the Raspberry Pi GPIO tutorial, and all the Raspberry Pi tutorials are listed on the Raspberry Pi tutorials page.