Skip to content

Instantly share code, notes, and snippets.

@thelabcat
Created July 4, 2026 18:15
Show Gist options
  • Select an option

  • Save thelabcat/f936fde85825bdbf482e27ea9a1ef063 to your computer and use it in GitHub Desktop.

Select an option

Save thelabcat/f936fde85825bdbf482e27ea9a1ef063 to your computer and use it in GitHub Desktop.
Dallas DS18B20 temperature sensor reading utility for the Raspberry Pi
#!/usr/bin/env python3
"""Dallas DS18B20 temperature sensor reader
Provide a simple utility function to read the temperature on a Raspberry Pi.
Sensor should be wired as follows:
+------+
| FLAT |---[3v3]
| SIDE |---[GPIO BCM pin 4]--&--[4.7 kOhm (Yellow violet Red) pull-up resistor]---[3v3]
| UP |---[Ground]
+------+
In other words, the middle pin of the sensor should be connected directly to GPIO BCM pin 4,
and also pulled up to 3v3 with a 4.7 kOhm resistor.
The file /boot/firmware/config.txt should contain the line 'dtoverlay=w1-gpio` before boot.
Kernel modules w1-gpio and w1-therm must be "probed" (loaded) using 'sudo modprobe [module]'
Reference material used:
https://thepihut.com/blogs/raspberry-pi-tutorials/18095732-sensors-temperature-with-the-1-wire-interface-and-the-ds18b20
Copyright 2026 Wilbur Jaywright dba Marswide BGL
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
S.D.G.
"""
import glob
from os import path as op
from warnings import warn
# What we expect text files to be encoded in
FILE_ENC = "utf-8"
# Folder where 1-Wire Interface devices live
DEVICES_PATH = "/sys/bus/w1/devices"
# How the temperature sensor's folder should start
TEMP_SENSOR_PREFIX = "28-"
def read(units: str = "F"):
"""
Read the Dallas DS18B20 temperature sensor
Args:
units (str): Either C for celcius or F for farenheit.
Defaults to F.
Returns:
temperature (float): The read temperature.
"""
# The units might be an object with a __str__ method, let's give 'em that chance
units = str(units).upper()
assert len(units) == 1 and units in "CF", f"Units as string must be C or F, not '{units}'"
# Look for any temperature sensors
sensor_folders = glob.glob(op.join(DEVICES_PATH, TEMP_SENSOR_PREFIX) + "*")
# We need at least one!
assert sensor_folders, "No sensors found at " + DEVICES_PATH
# We'll use the first one in the list regardless, but if there's more than one we should warn the user
if (num_sensors := len(sensor_folders)) > 1:
warn(f"Found {num_sensors} sensors instead of just one. Using the first, {op.basename(sensor_folders[0])}.")
sensor_folder = sensor_folders[0]
# Finally, the reading
with open(op.join(sensor_folder, "temperature"), encoding=FILE_ENC) as f:
# The file shows only the temperature in millidegrees celcius
c_temp = float(f.read().strip()) / 1000
# The user wanted farenheit
if units == "F":
return c_temp * 1.8 + 32
# The user wanted Celcius
# No else clause needed because the previous one contains a return statement
return c_temp
if __name__ == "__main__":
print("Dallas DS18B20 temperature sensor reader")
print("\nImport `read()` from this module to use in your own projects.")
print(f"\nIt is currently {read():.03f} F.")
print("S.D.G")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment