diff --git a/ds18b20.py b/ds18b20.py index e67cae2..e5d08c1 100755 --- a/ds18b20.py +++ b/ds18b20.py @@ -1,9 +1,12 @@ #!/usr/bin/env python3 -import sys -from time import sleep, time 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. @@ -30,35 +33,34 @@ 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(): - 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 - globals.CURRENT_TEMP = int(round((temp * 9/5) +32)) # Convert C-F and round into an integer + while True: + read_temp().start() - if DEBUG: - sys.stdout.write("Temp: %sF\n" % globals.CURRENT_TEMP) + if DEBUG: + sys.stdout.write("Temp: %sF\n" % globals.CURRENT_TEMP) - except: - pass + sleep(1) - finally: - probe.close() # Run this from the command line if __name__ == "__main__": - DEBUG = 1 + DEBUG = True read_temp_probe()