Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import os
- import glob
- import datetime
- import time
- import RPi.GPIO as GPIO
- control_pin = 6 # broadcom pin 4
- def F_to_C(t):
- return (t-32)/1.8
- min_temperature = F_to_C(67.0)
- max_temperature = F_to_C(68.0)
- heater_on = False
- heater_change_ts = 0
- heater_hysteresis = 5 * 60 # five minutes
- os.system('modprobe w1-gpio')
- os.system('modprobe w1-therm')
- base_dir = '/sys/bus/w1/devices/'
- device_folder = glob.glob(base_dir + '28*')[0]
- device_file = device_folder + '/w1_slave'
- def update_setting(t):
- global heater_on, heater_change_ts, heater_hysteresis
- global min_temperature, max_temperature
- want_on = True if t <= min_temperature else heater_on
- if t >= max_temperature: want_on = False
- if want_on != heater_on:
- now = unix_ts()
- date_time = ymdhms(now)
- if now - heater_change_ts < heater_hysteresis:
- print(date_time, 'Heater changed too recently...not changing')
- else:
- heater_on = want_on
- heater_change_ts = now
- set_heater_on(heater_on)
- print(date_time, 'Heater on' if heater_on else 'Heater off')
- def read_temperature_raw():
- f = open(device_file, 'r')
- lines = f.readlines()
- f.close()
- return lines
- def read_temperature():
- lines = read_temperature_raw()
- while lines[0].strip()[-3:] != 'YES':
- time.sleep(0.2)
- lines = read_temperature_raw()
- equals_pos = lines[1].find('t=')
- if equals_pos != -1:
- temp_string = lines[1][equals_pos+2:]
- temp_c = float(temp_string) / 1000.0
- return temp_c, time.time()
- else:
- return 0, 0
- def unix_ts():
- return int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())
- def ymdhms(ts):
- return datetime.datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
- def init_control():
- global control_pin
- GPIO.setmode(GPIO.BCM)
- GPIO.setwarnings(False)
- GPIO.setup(control_pin, GPIO.OUT)
- GPIO.output(control_pin, GPIO.LOW)
- def set_heater_on(want_on):
- GPIO.output(control_pin, GPIO.HIGH if want_on else GPIO.LOW)
- def read_range():
- with open("range.txt") as f:
- low = (float(f.readline()) - 32)/1.8;
- high = (float(f.readline()) - 32)/1.8;
- return low, high
- def mainloop():
- global min_temperature, max_temperature, heater_on
- error_count = 0
- while True:
- temperature, temperature_ts = read_temperature()
- if temperature_ts == 0:
- error_count += 1
- if error_count > 20:
- set_heater_on(False)
- return
- time.sleep(60)
- else:
- error_count = 0
- print(temperature, temperature_ts, min_temperature, max_temperature, heater_on)
- update_setting(temperature)
- time.sleep(60)
- min_temperature, max_temperature = read_range()
- init_control()
- try:
- mainloop()
- except Exception as e:
- print('Exception', e)
- set_heater_on(False)
- GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment