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.

Hey!

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; [
    haskellPackages.gpio
    libraspberrypi
  ];
  # 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]+)?')
      threshold=65
      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
      else
        /run/current-system/sw/bin/gpio write 18 lo
      fi
      /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

Hey! I have the same issue and stumbled across this thread. The solution sadly doesn’t work for me, so I’m wondering if you also got the “No such file or directory” exception. When I run /run/current-system/sw/bin/gpio init 18 out in the terminal I get

gpio: InitPinException P18 "/sys/class/gpio/export: withFile: does not exist (No such file or directory)"

and if I check the /sys/class/ there is no gpio directory present. Is there some other setup needed for it to be created?