-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraspi3b_fan.py
executable file
·108 lines (81 loc) · 2.46 KB
/
raspi3b_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
"""
This script is used to start/start the fan when
the configured temperature threshold is reached.
Author: Matei Ciobotaru
Raspberry 3B+ SBC implementation
"""
import logging
from time import sleep
import RPi.GPIO as GPIO
# Set up logging
LOG_FILE = '/var/log/fan.log'
logging.basicConfig(filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s [%(levelname)s]: %(message)s')
# Fan switch is on BCM pin 18, change this value according to your setup
PIN = 12
# Maximum temperature threshold ['C] (fan will start)
MAX_TEMP = 65
# Mininum temperature threshold ['C] (fan swill stop)
MIN_TEMP = 45
def setup(pin):
"""
Setup GPIO pin
"""
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
def get_temp():
"""
Get current temperature
"""
try:
with open('/sys/class/thermal/thermal_zone0/temp', 'r') as fhandle:
temp = int(fhandle.read())/1000.0
return round(temp, 1)
except IOError as io_err:
logging.error('Can\'t read temp file: %s', io_err)
def fan_switch(state):
"""
Switch fan ON or OFF
"""
try:
fan_state = int(GPIO.input(PIN))
# Check if fan is already in the desired state
if fan_state != state:
GPIO.output(PIN, state)
except Exception as gpio_err:
logging.error('GPIO exception: %s', gpio_err)
def check_temp(current_temp, min_temp, max_temp):
"""
Compare CPU temp to max threshold and start fan if exceeded
Stop fan only when temperature is 15'C under max threshold
"""
if current_temp >= max_temp:
fan_switch(1)
logging.info('Started fan, CPU temperature is: %.1f\'C, '
'max threshold is: %.1f\'C', current_temp, max_temp)
else:
fan_switch(0)
logging.info('Stopped fan, CPU temperature is: %.1f\'C, '
'min threshold is: %.1f\'C', current_temp, min_temp)
def main():
"""
Run temperature check every 3 seconds untill stopped by user
"""
try:
logging.info('Started fan service...')
setup(PIN)
while True:
temp = get_temp()
check_temp(temp, MIN_TEMP, MAX_TEMP)
sleep(2)
except KeyboardInterrupt:
logging.info('Stopped fan service...')
finally:
fan_switch(GPIO.LOW)
GPIO.cleanup(PIN)
if __name__ == '__main__':
main()