DS18B20 Temperature Sensor

Posted on 2019-11-16 by me

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):
        base_dir = '/sys/bus/w1/devices/'
        device_folder = glob.glob(base_dir + '28*')[0]
        device_file = device_folder + '/w1_slave'
        with open(device_file, 'r') as fh:
            lines = fh.readlines()
        return lines

    def poll(self):
        lines = self.read_temp_raw()
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = self.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
            return temp_c