树莓派检测核心温度,自动运行风扇

需要准备的材料

1.带风扇的散热马甲一块,

2.S8550 三极管一颗

3.母口杜邦线一根

首先从中间剪断风扇的正极,把三级管的发射极和集电极分别接在正极两边,然后拿出杜邦线接到三极管的基极。如下图所示(水平有限将就看看)

 

 

然后正极连接树莓派第4脚,负极连接树莓派第6脚,蓝色杜邦线连接树莓派第8脚(如下图)

然后安装python RPi.GPIO库

sudo pip install RPi._GPIO

接下来执行代码就可以了:

sudo python3 rpi-gpio-fan.py

 

 

 

 

 

import RPi._GPIO as GPIO
import time


class RaspiFanControl:
    def __init__(self):
        self.max_temp = 45
        self.min_temp = 40
        self.run_time = 600  #  这里是运行时间,达到温度后运行10分钟,再停下来进入下一轮的检测
        self.gpio_ping = 14
        self.fan_status = 'Stop'
        self.temp_path = '/sys/class/thermal/thermal_zone0/temp'
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(self.gpio_ping, GPIO.IN)

    def check_cpu_temp(self):
        with open(self.temp_path, 'r') as tmp:
            cpu_temp = int(tmp.read()) / 1000
        if cpu_temp >= self.max_temp:
            self.raspi_fan_no(cpu_temp)
        elif self.fan_status == "Running":
            if cpu_temp <= self.min_temp:
                self.raspi_fan_off(cpu_temp)
        else:
            self.raspi_fan_between(cpu_temp)

    def raspi_fan_no(self, cpu_temp):
        ping_status = GPIO.input(self.gpio_ping)
        if ping_status == 1:
            GPIO.setup(self.gpio_ping, GPIO.OUT)
            GPIO.output(self.gpio_ping, True)
        self.fan_status = 'Running'
        print('.' * 40)
        print('Current temperature: %s' % cpu_temp)
        print('Fan status: %s' % self.fan_status)
        print('DateTime: %s' % time.ctime())
        print('.' * 40)
        time.sleep(self.run_time)

    def raspi_fan_off(self, cpu_temp):
        if GPIO.input(self.gpio_ping):
            GPIO.setup(self.gpio_ping, GPIO.IN)
        self.fan_status = 'Stop'
        print('.' * 40)
        print('Current temperature: %s' % cpu_temp)
        print('Fan status: %s' % self.fan_status)
        print('DateTime: %s' % time.ctime())
        print('.' * 40)
        time.sleep(self.run_time)

    def raspi_fan_between(self, cpu_temp):
        print('.' * 40)
        print('Current temperature: %s' % cpu_temp)
        print('Fan status: %s' % self.fan_status)
        print('DateTime: %s' % time.ctime())
        print('.' * 40)
        time.sleep(60)  # 这里是温度没有达到的话,就每分钟检测一次,


if __name__ == '__main__':
    raspi_fan = RaspiFanControl()
    while True:
        raspi_fan.check_cpu_temp()

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值