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
import json

device_file = [
    {'addr':'28-0000056a6f05','pos':'heizung_in'},
    {'addr':'28-0114656186ff','pos':'heizung_out'},
    {'addr':'28-0114657d02ff','pos':'wasser_in'},
    {'addr':'28-0114653070ff','pos':'wasser_out'},
    {'addr':'28-01146537e8ff','pos':'solar_out'},
    {'addr':'28-011465624bff','pos':'solar_in'},
    {'addr':'28-011465624bff','pos':'raum'}
]

W1_PATH = '/sys/bus/w1/devices'
OUTPUT = '/var/www/html/sensorData'


def main():
    result = {}

    for i in device_file:
        with open(f"{W1_PATH}/{i['addr']}/w1_slave") as f:
            lines = f.readlines()
            f.close()

        if lines[0].strip()[-3:] == 'YES':        
            equals_pos = lines[1].find('t=')
            if equals_pos != -1:
                result[i['pos']] = float(lines[1][equals_pos+2:]) / 1000.0   
                print(f"{i['pos']} with {result[i['pos']]}°C")

    with open(OUTPUT, 'w') as f:
        f.write(json.dumps(result))

if __name__ == "__main__":
    main()