I have need to measure temperature in upcoming projects. It should be configurable and be made to log data data. I have some of the DS18B20 1-wire digital thermometer devices in the TO-92 packages. So the idea was to set up a Pi 4 that is accessible from my PC over the network. This way there is no additional keyboard and monitor to unnecessarily clutter up my limited space.
I used this tutorial on the Circuit Basics website.
DS18B20 pinouts from datasheet (I'm using the TO-92 package device).
Raspberry Pi 4 GPIO pinouts from the Raspberry Pi Spy website.
I've made a 1m long three wire cable. This will allow for keeping the Pi well out of the way while easily getting the termometer where I need it to go.
Pi pin | Pi function | DS18B20 pin | DS18B20 function |
---|---|---|---|
1 | 3V3 | 3 | Vdd |
7 | GPIO4 1-wire | 2 | DQ data |
6 | Ground | 1 | GND |
I'm running a headless version of Raspberry Pi OS. Used code from tutorial as a starting point.
The code below is taken from the tutorial and slightly modified to only print out temperature in Celsius.
#!/usr/bin/python3 import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 # temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c while True: print(read_temp()) time.sleep(1)