三极管控制散热风扇

前言

风扇直接连阵脚会一直转,加个三极管,可以通过脚本控制开关。

GPIO 针脚定义

硬件准备

散热风扇、三极管(S8050)、母对母杜邦线

风扇:风扇红线接5V、黑线接地。

三极管:把平的那面对准自己,三个引脚分别是 E、B、C。分别是E发射机、B基极、C集电极。可以理解为E极是正极、C极是负极、B极是信号极控制是否通电。和二极管一样,正极接电源正极,负极接电源的负极。

S8050 引脚

接线方式

  1. 风扇红线 接 树莓派5V,比如:04号引脚。
  2. 风扇黑线 接 三极管C。
  3. 三极管E极 接 树莓派0V,比如:06号引脚。
  4. 三极管B极 接 GPIO,比如:08号引脚。

Python 控制脚本

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
#!/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 <= 45:
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')

为了实现开机自动运行,可以把启动脚本写在rc.local中

Author

Zoctan

Posted on

2018-07-21

Updated on

2023-03-14

Licensed under