The DS18b20 is a digital temperature sensor. The datasheet can be found here. It has three connections: data, power, ground (although it can work in parasite mode). I have the waterproof version to stick in the soil.
The sensor uses the 1-wire protocol.
This needs to be enabled on the pi in order for the sensor to be read.
There are several ways to achieve this, but the easiest is probably via the raspi-config
:
raspi-config > 5 Interfacing Options > P7 1-Wire > Yes
By default (at the time of writing), only gpio pin 4 is enabled to read 1-wire.
Wiring
The diagram I followed is here.
The data pin requires pin 4 (see above), and a 4.7k pull up resistor. Apparently, each DS18B20 has a unique 64-bit serial code, and so multiple DS18B20s can function on the same 1-Wire bus. I haven’t tried.
Software
The interface is a bit, ummm, unrobust.
You try to read and parse the file that, provided the sensor is connected properly,
appears in /sys/bus/w1/devices
with a filename beginning with 28
.
Often it would just not appear as and when expected.
class DS18B20:
def __init__(self):
pass
def read_temp_raw(self):
= '/sys/bus/w1/devices/'
base_dir = glob.glob(base_dir + '28*')[0]
device_folder = device_folder + '/w1_slave'
device_file with open(device_file, 'r') as fh:
= fh.readlines()
lines return lines
def poll(self):
= self.read_temp_raw()
lines while lines[0].strip()[-3:] != 'YES':
0.2)
time.sleep(= self.read_temp_raw()
lines = lines[1].find('t=')
equals_pos if equals_pos != -1:
= lines[1][equals_pos+2:]
temp_string = float(temp_string) / 1000.0
temp_c return temp_c