Raspberry Pi - DS18B20

Idea

  • Using python to periodically query several DS18B20 sensors
  • Write results to a logfile (no SQL database)
  • Webservice reads logfile to offer current data in JSON format


Install DS18B20 Sensor

Since the Raspbian operating system was updated end of January 2015 (kernel 3.18.8 and higher) an additional line in /boot/config.txt is required.

vi /boot/config.txt
dtoverlay=w1-gpio

Now reboot

reboot

Check if the sensors are here:

ls /sys/bus/w1/devices/
28-0000056a6f05  28-00000598caf1  w1_bus_master1

Quick test if sensors are working

cat /sys/bus/w1/devices/28-0000056a6f05/w1_slave | sed -n 's/^.*\(t=[^ ]*\).*/\1/p' | sed 's/t=//' | awk '{x=$1}END{print(x/1000)}'
38.125
cat /sys/bus/w1/devices/28-00000598caf1/w1_slave | sed -n 's/^.*\(t=[^ ]*\).*/\1/p' | sed 's/t=//' | awk '{x=$1}END{print(x/1000)}'
28.937

Install Webservice

apt-get install apache2
service apache2 restart
import time

device_file = []
device_file.append('/sys/bus/w1/devices/28-0000056a6f05/w1_slave')
device_file.append('/sys/bus/w1/devices/28-0114656186ff/w1_slave')
device_file.append('/sys/bus/w1/devices/28-0114657d02ff/w1_slave')
device_file.append('/sys/bus/w1/devices/28-0114653070ff/w1_slave')
device_file.append('/sys/bus/w1/devices/28-011465624bff/w1_slave')

def main():
    result = []

    for i in device_file:
        f = open(i, 'r')
        lines = f.readlines()
        f.close()

        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw(id)
        
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
            temp_string = lines[1][equals_pos+2:]
            temp_c = float(temp_string) / 1000.0
            result.append(temp_c)
        else:
            result.append('-')

    f = open('/var/www/html/sensorData','w')
    f.write(";".join(map(str,result)))
    f.close()


if __name__ == "__main__":
    main()