Newer
Older
devtimer / ds18b20.py
#!/usr/bin/env python3

import globals

import sys
from time import sleep, time
from threading import Thread

DEBUG = False

'''
  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.

class read_temp(Thread):

    def run(self):
        probe = open("/sys/bus/w1/devices/%s/w1_slave" % DS18B20_ID)
        temp = float(probe.readlines()[-1].split()[-1].split("=")[-1])/1000         # Parse probe output
        globals.CURRENT_TEMP = int(round((temp * 9/5) +32))                         # Convert C-F and round into an integer
        probe.close()


def read_temp_probe():

    while True:
        read_temp().start()

        if DEBUG:
            sys.stdout.write("Temp: %sF\n" % globals.CURRENT_TEMP)

        sleep(1)


# Run this from the command line

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