Skip to content

Instantly share code, notes, and snippets.

@Eminlin
Created November 21, 2020 10:33
Show Gist options
  • Save Eminlin/85094e3bef83208471fbfdc5368b0315 to your computer and use it in GitHub Desktop.
Save Eminlin/85094e3bef83208471fbfdc5368b0315 to your computer and use it in GitHub Desktop.
树莓派风扇散热
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os
import time
import RPi.GPIO as GPIO
# GPIO14 08号引脚
GPIO_OUT = 14
# 日志位置
LOG_PATH = '/tmp/fan_control.log'
# 调试模式
IS_DEBUG = False
class Fan:
def __init__(self):
# BOARD编号方式,基于插座引脚编号
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# 设置08号引脚为输出模式
GPIO.setup(GPIO_OUT, GPIO.OUT)
"""
读取 CPU 温度
"""
def read_cpu_temperature(self):
with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
temperature = float(f.read()) / 1000
log('DEBUG', 'Current CPU temperature is {}'.format(temperature))
return temperature
"""
启动风扇
"""
def start_fan(self):
log('INFO', 'Power on')
GPIO.output(GPIO_OUT, GPIO.HIGH)
"""
停止风扇
"""
def stop_fan(self):
log('INFO', 'Power off')
GPIO.output(GPIO_OUT, GPIO.LOW)
"""
控制风扇
"""
def control_fan(self):
# 标记风扇开关状态
is_closed = True
try:
while True:
temperature = self.read_cpu_temperature()
if is_closed:
# 温度高于50°即启动风扇
if temperature >= 50:
self.start_fan()
is_closed = False
else:
# 温度低于45°即停止风扇
if temperature <= 43:
self.stop_fan()
is_closed = True
# 每10s检查一次
time.sleep(10)
except Exception as e:
GPIO.cleanup()
log('ERROR', e)
"""
日志
:param level 级别
:param msg 消息
"""
def log(level, msg):
log_msg = '{} [{}] {}'.format(datetime.datetime.now(), level, msg)
if not IS_DEBUG and level == 'DEBUG':
return
try:
with open(LOG_PATH, 'a') as f:
f.write(log_msg + '\n')
except Exception as e:
print("Unable to log: {}".format(e))
if __name__ == '__main__':
os.environ["TZ"] = 'Asia/Shanghai'
time.tzset()
log('INFO', '[*] Started')
Fan().control_fan()
log('INFO', '[*] Quit')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment