Last active
July 21, 2019 08:15
-
-
Save rogerlin0330/b935f1ac9db7f33db5defd716f3ecb5b to your computer and use it in GitHub Desktop.
CPU fan speed control settings for Raspberry Pi (fan_speed.py should be placed in /usr/bin, and fanctrl.service should be placed in /etc/systemd/system if the operating system is Raspbian); The dependency should be installed by pip install RPi.GPIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # -*- coding:utf-8 -*- | |
| import logging | |
| import RPi.GPIO | |
| import time | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format=( | |
| "[%(levelname)s]: %(message)s" | |
| ), | |
| ) | |
| RPi.GPIO.setwarnings(False) | |
| RPi.GPIO.setmode(RPi.GPIO.BCM) | |
| RPi.GPIO.setup(2, RPi.GPIO.OUT) | |
| pwm = RPi.GPIO.PWM(2, 100) | |
| RPi.GPIO.setwarnings(False) | |
| UPPER_THRESHOLD = 43 | |
| LOWER_THRESHOLD = 33 | |
| try: | |
| while True: | |
| with open( '/sys/class/thermal/thermal_zone0/temp' ) as f: | |
| cpu_temp = int(f.read()) / 1000 | |
| if cpu_temp >= LOWER_THRESHOLD: | |
| #启动时防止风扇卡死先全功率转0.1秒 | |
| pwm.start(0) | |
| pwm.ChangeDutyCycle(100) | |
| time.sleep(.1) | |
| slope = (100 - 0) / (UPPER_THRESHOLD - LOWER_THRESHOLD) | |
| speed_level = min(int(slope * (cpu_temp - LOWER_THRESHOLD)), 100) | |
| pwm.ChangeDutyCycle(speed_level) | |
| logging.info("cpu temp:{:.2f}'C - fan on (speed level:{:d}%)".format(cpu_temp, speed_level)) | |
| else: | |
| pwm.stop() | |
| logging.info("cpu temp:{:.2f}'C - fan off".format(cpu_temp)) | |
| time.sleep(5) | |
| except KeyboardInterrupt: | |
| pwm.stop() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [Unit] | |
| Description=A fan speed controlling service | |
| After=multi-user.target | |
| [Service] | |
| ExecStart=/usr/bin/fan_speed.py | |
| [Install] | |
| WantedBy=multi-user.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment