Enabling fan control on a Raspberry Pi

Hello everyone!

First post here, a few months after having started with NixOS (this is an indirect compliment to the documentation and the community content - searching through it was enough up to today :slight_smile: ).

I have installed and deployed NixOS on my RPI4, and I have the official RPI fan that is plugged on the GPIO pins. I’d like to control the fan speed based on the temperature of the CPU - the same way you can configure it in raspi-config in RaspiOS.

Is there something already packaged that I wouldn’t have found to do it already? And if not, how would you suggest I set this up?

Thanks a lot for your help :smiley:

1 Like

Hey! Did you figure out any solution to this? Im wondering the same thing.


I ended up with a working yet not super elegant solution :grimacing:

Here is the relevant part of my configuration file:

  environment.systemPackages = with pkgs; [
  # service to control the fan
  systemd.services.fan-control = {
    description = "Control the fan depending on the temperature";
    script = ''
      /run/current-system/sw/bin/gpio init 18 out
      temperature=$(/run/current-system/sw/bin/vcgencmd measure_temp | grep -oE '[0-9]+([.][0-9]+)?')
      if /run/current-system/sw/bin/awk -v temp="$temperature" -v threshold="$threshold" 'BEGIN { exit !(temp > threshold) }'; then
        /run/current-system/sw/bin/gpio write 18 hi
        /run/current-system/sw/bin/gpio write 18 lo
      /run/current-system/sw/bin/gpio close 18 out

  systemd.timers.fan-control-timer = {
    description = "Run control fan script regularly";
    timerConfig = {
      OnCalendar = "*-*-* *:0/1:00"; # Run every 10 minutes
      Persistent = true;
      Unit = "fan-control.service";
    wantedBy = [ "timers.target" ];

Hope this helps :slight_smile:

1 Like

Omg, i completely missed the notification on discourse. Im sorry for the late reply. Just tried it out and it works great! :smiley: Thanks a ton!

The only thing i needed to change was the pin from 18 to 14, due to how the fan i have is connected. Cheers!

1 Like

No worries, I’m glad it worked for you as well!

Enjoy a (mostly) silent and temperature-controlled raspberry pi :slight_smile:

1 Like