Skip to content

Instantly share code, notes, and snippets.

@James-Ansley
Last active May 27, 2024 10:21
Show Gist options
  • Save James-Ansley/32f72729487c8f287a801abcc7a54f38 to your computer and use it in GitHub Desktop.
Save James-Ansley/32f72729487c8f287a801abcc7a54f38 to your computer and use it in GitHub Desktop.
Raspberry Pi 5 Auto Fan Controller

Raspberry Pi 5 Auto Fan Controller

UPDATE: The fan is now controlled automatically in the latest updates (See this answer https://askubuntu.com/a/1497778/1746852). This cron job is no longer needed.

A quick hack to get around the fact Ubuntu for the Pi5 currently does not control the fan.

This needs to be run with sudo permissions:

sudo python3 pi5_fan_controller.py

And, by default, will monitor the Pi5's temperature for one minute every 2 seconds adjusting the fan based on some arbitrary boundaries I came up with on the spot :^)

This is intended to be set up as a system-wide cron job (system-wide because of the sudo privileges). To do this, edit this file:

sudo nano /etc/crontab

And add this cron job:

* * * * *  root  python3 /path/to/pi5_fan_controller.py

(with the updated path to the python file)

Many thanks to the following Ask Ubuntu answers:

from enum import Enum
import time
TEMP_PATH = "/sys/devices/virtual/thermal/thermal_zone0/temp"
FAN_PATH = "/sys/class/thermal/cooling_device0/cur_state"
class FanSpeed(Enum):
OFF = 0
LOW = 1
MEDIUM = 2
HIGH = 3
FULL = 4
def main():
start = time.time()
while time.time() - start < 59:
temp = get_temp()
if temp > 70:
speed = FanSpeed.FULL
elif temp > 65:
speed = FanSpeed.HIGH
elif temp > 60:
speed = FanSpeed.MEDIUM
elif temp > 50:
speed = FanSpeed.LOW
else:
speed = FanSpeed.OFF
set_fan_speed(speed)
time.sleep(2)
def get_temp() -> int:
with open(TEMP_PATH, "r") as f:
data = f.read()
return int(data) // 1000
def set_fan_speed(speed: FanSpeed):
with open(FAN_PATH, "w") as f:
f.write(str(speed.value))
if __name__ == "__main__":
main()
@13hakta
Copy link

13hakta commented Jan 21, 2024

You made a heavy work :) My RP4 has also 2-wired cooler, that is why I soldered couple components and made it PWM-compatible. My script above works as a service without cron.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment