1. # -*- coding:utf-8 -*-
    2. """
    3. 根据CPU温度开启与关闭树莓派风扇
    4. """
    5. import time, os
    6. import RPi.GPIO as GPIO
    7. import logging
    8. GPIO_OUT = 14
    9. START_TEMP = 55
    10. CLOSE_TEMP = 45
    11. DELAY_TIME = 15
    12. LOG_PATH = '/var/log/fan_control.log'
    13. logging.basicConfig(level=logging.DEBUG,
    14. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', # 日志格式
    15. datefmt='%Y-%m-%d %H:%M:%S', # 时间格式
    16. filename=LOG_PATH, # 日志的输出路径
    17. filemode='a') # 追加模式
    18. def get_cpu_temperature():
    19. """
    20. 获取树莓派CPU温度, 读取/sys/class/thermal/thermal_zone0/temp内容, 除1000就是温度
    21. :return: float
    22. """
    23. with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
    24. temperature = float(f.read()) / 1000
    25. return temperature
    26. def start_fan(temp):
    27. """
    28. 开启风扇
    29. :param temp: 树莓派CPU温度
    30. :return:
    31. """
    32. logging.info('power on fan, temp is %s' % temp)
    33. # PNP型三极管基极施加低电平时才导通电路, NPN型三极管相反
    34. GPIO.output(GPIO_OUT, GPIO.LOW)
    35. def stop_fan(temp):
    36. """
    37. 关闭风扇
    38. :param temp: 树莓派CPU温度
    39. :return:
    40. """
    41. logging.info('power off fan, temp is %s' % temp)
    42. # 基级施加高电平
    43. GPIO.output(GPIO_OUT, GPIO.HIGH)
    44. def setup_GPIO():
    45. """
    46. GPIO初始化
    47. 风扇设置为关闭状态
    48. :return:
    49. """
    50. GPIO.setmode(GPIO.BCM)
    51. GPIO.setwarnings(False)
    52. GPIO.setup(GPIO_OUT, GPIO.OUT, initial=GPIO.HIGH)
    53. def control_fan():
    54. is_closed = True
    55. try:
    56. while True:
    57. temp = get_cpu_temperature()
    58. logging.debug("temperature: %s" % temp)
    59. # 温度大于START_TEMP开启风扇, 低于CLOSE_TEMP关闭风扇
    60. if (temp > START_TEMP and is_closed):
    61. start_fan(temp)
    62. is_closed = False
    63. elif (temp < CLOSE_TEMP and not is_closed):
    64. stop_fan(temp)
    65. is_closed = True
    66. else:
    67. pass
    68. time.sleep(DELAY_TIME)
    69. except Exception as e:
    70. GPIO.cleanup()
    71. logging.error(e)
    72. if __name__ == '__main__':
    73. os.environ["TZ"] = 'Asia/Shanghai'
    74. time.tzset()
    75. logging.info('started control fan...')
    76. setup_GPIO()
    77. control_fan()
    78. logging.info('quit started control fan...')