-
Notifications
You must be signed in to change notification settings - Fork 0
/
Thermostat.py
executable file
·96 lines (84 loc) · 3.01 KB
/
Thermostat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/python
from pydispatch import dispatcher
from decimal import *
from threading import Timer
import RPi.GPIO as GPIO
import time
import math
class ThermostatSensor:
"""Class that manages temperature readings"""
# uF - Tweek this value around 0.33 to improve accuracy
C = 0.33
R1 = 1000 # Ohms
# The thermistor constant - change this for a different thermistor
B = 3800.0
# The resistance of the thermistor at 25C -change for different thermistor
R0 = 1000.0
updateInterval = 5 # seconds
THERMOSTAT_TO_CONTROLLER_SIG = "HELLO-CONTROLLER-IM-THERMOSTAT"
THERMOSTAT_TO_DISPLAY_SIG = "HELLO-DISPLAY-IM-THERMOSTAT"
def __init__(self, chargePin, dischargePin, readingNum=100):
GPIO.setmode(GPIO.BCM)
self.chargePin = chargePin
self.dischargePin = dischargePin
self.n = readingNum
self.readTemp = Timer(self.updateInterval, self._getTemp)
def close(self):
GPIO.cleanup()
def _getTemp(self):
"""
This method is in charge of taking the temperature of the environment
and send it to the controller
"""
temp = Decimal(self._read_temp_c())
.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
# Send the temp to the controller
dispatcher.send(signal=self.THERMOSTAT_TO_CONTROLLER_SIG,
sender=self, param={'temp': float(temp)})
# Send the temp to the display
dispatcher.send(signal=self.THERMOSTAT_TO_DISPLAY_SIG, sender=self,
param=float(temp))
self.readTemp = Timer(self.updateInterval, self._getTemp).start()
def _read_temp_c(self):
R = self._read_resistance()
t0 = 273.15 # 0 degrees C in K
t25 = t0 + 25.0
invT = 1 / t25 + 1 / self.B * math.log(R / self.R0)
T = (1 / invT - t0)
return T
def _read_resistance(self):
total = 0
for i in range(0, self.n):
total += self._analog_read()
total /= float(self.n)
T = total * 0.632 * 3.3
r = (T / self.C) - self.R1
return r
def _analog_read(self):
"""
Take an analog reading as the time taken to charge after first
discharging the capacitor
"""
self._discharge()
t = self._charge_time()
self._discharge()
return t
def _discharge(self):
GPIO.setup(self.chargePin, GPIO.IN)
GPIO.setup(self.dischargePin, GPIO.OUT)
GPIO.output(self.dischargePin, False)
time.sleep(0.01)
def _charge_time(self):
"""
Return the time taken for the voltage on the capacitor to count as a
digital input HIGH than means around 1.65V
"""
GPIO.setup(self.dischargePin, GPIO.IN)
GPIO.setup(self.chargePin, GPIO.OUT)
GPIO.output(self.chargePin, True)
t1 = time.time()
# While input is LOW
while not GPIO.input(self.dischargePin):
pass
t2 = time.time()
return (t2 - t1) * 1000000 # uS