-
Notifications
You must be signed in to change notification settings - Fork 7
/
run-fan.py
81 lines (66 loc) · 1.99 KB
/
run-fan.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
import os
import re
from time import sleep
import RPi.GPIO as GPIO
pin = 18 # The pin ID, edit here to change it
maxTMP = 70 # The maximum temperature in Celsius after which we trigger the fan
stopTMP = maxTMP - 10
def setup() -> tuple:
"""
Sets the mode and warnings for the GPIO setup.
:return: An empty tuple.
"""
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return ()
def get_cpu_temperature() -> float:
"""
Retrieves the CPU temperature of the Raspberry Pi using vcgencmd.
:return: A float value which indicates the CPU temperature.
"""
res = os.popen("vcgencmd measure_temp").readline()
temp = re.findall("\d+\.\d+", res)[0]
print("temp is {0}".format(temp)) # Uncomment here for testing
return temp
def fan_on() -> tuple:
"""
Turns the fan on by setting the GPIO pin mode.
:return: An empty tuple.
"""
set_pin(True)
return ()
def fan_off() -> tuple:
"""
Turns the fan off by setting the GPIO pin mode.
:return: An empty tuple.
"""
set_pin(False)
return ()
def get_temp() -> tuple:
"""
Retrieves the CPU temperature of the Raspberry Pi and turns the fan
on or off based on the read value.
:return: An empty tuple.
"""
cpu_temp = float(get_cpu_temperature())
if cpu_temp > maxTMP:
fan_on()
elif cpu_temp < stopTMP:
fan_off()
return ()
def set_pin(mode: bool) -> tuple: # A little redundant function but useful if you want to add logging
"""
Sets the GPIO pin to the mode needed depending on the CPU temperature.
:param mode: A boolean, True or False.
:return: An empty tuple.
"""
GPIO.output(pin, mode)
return ()
try:
setup()
while True:
get_temp()
sleep(5) # Read the temperature every 5 sec, increase or decrease this limit if you want
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
GPIO.cleanup() # resets all GPIO ports used by this program