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"


# Read the current temp returned by the probe

def read_probe():

    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()


# Update the store temperature every second or so

def monitor_temps():

    while True:
        update_temp = Thread(name="Update Temp", target=read_probe)
        update_temp.start()
        sleep(1)

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


# Run this from the command line
if __name__ == "__main__":
    DEBUG = True
    monitor_temps()