Newer
Older
devtimer / db18b20.py
from time import sleep, time
from devtimer import CURRENT_TEMP

'''
  This is based on the widely available DS18B20 temperature probe.
  It is a 1-wire protocol device that returns temperature directly
  degrees C.  The dataline must go on the Pi GPIO 4 (pin 7) which
  should be pulled up to VCC with a 4.7K resistor.

  You have to do several thingsto make this work:

    1) Enable 1-wire support in the Pi:

        edit /boot/config.txt set: dtoverlay=w1-gpio
        reboot

    2) Each 1-wire device is connected to the same pin (7)
       on the Pi.  It distinguishes between them by a uniq
       address.  You have to find that address *for your specific
       device*.  You do this by looking at:

         ls -l /sys/bus/w1/devices

       You'll see the ID of your device there.  That needs to
       be set in the line below for this code to work with
       your device.
'''



DS18B20_ID = "28-0416840ac6ff"


# This function is called on it's own thread by __main__
# so that it runs continuously in background.

def read_temp_probe():

    try:
        probe = open("/sys/bus/w1/devices/%s/w1_slave" % DS18B20_ID)
        while True:
            probe.seek(0)    # Ensure we are at beginning-of-file to read latest probe sample
            temp = float(probe.readlines()[-1].split()[-1].split("=")[-1])/1000 # Parse probe output
            CURRENT_TEMP = int(round((temp * 9/5) +32))                         # Convert C-F and round into an integer
            if DEBUG:
                print(CURRENT_TEMP)
    except:
        pass

    finally:
        probe.close()

if __name__ == "__main__":
    DEBUG = 1
    read_temp_probe()