Skip to content

Instantly share code, notes, and snippets.

@s-geissler
Last active January 7, 2024 11:04
Show Gist options
  • Save s-geissler/89d2dbe8ee75e67aaadf5c870cf9291e to your computer and use it in GitHub Desktop.
Save s-geissler/89d2dbe8ee75e67aaadf5c870cf9291e to your computer and use it in GitHub Desktop.
Manual fancontrol on Raspberry Pi 5 for Ubuntu 23.10 64bit
#!/bin/bash
round() {
printf "%.${2}f" "${1}"
}
debug() {
if [[ $debug -eq 1 ]]; then
echo "[$(date)] [DEBUG] $1" >> "$2"
fi
}
log() {
echo "[$(date)] [LOG] $1" >> "$2"
}
# Default values
speed0=0.25
temp0=68
speed1=0.4
temp1=75
speed2=0.75
temp2=80
debug=0
logfile=/var/log/fancontrol
if [ "$EUID" -ne 0 ]
then
echo "Please run as root"
exit
fi
# Parse parameters
while [[ $# -gt 0 ]]; do
case "$1" in
-s0 | --speed0 )
speed0="$2"
shift 2
;;
-t0 | --temp0 )
temp0="$2"
shift 2
;;
-s1 | --speed1 )
speed1="$2"
shift 2
;;
-t1 | --temp1 )
temp1="$2"
shift 2
;;
-s2 | --speed2 )
speed2="$2"
shift 2
;;
-t2 | --temp2 )
temp2="$2"
shift 2
;;
-d | --debug )
debug=1
shift
;;
* )
echo "Unknown parameter: $1"
exit 1
;;
esac
done
# Main script logic using the parsed parameters
debug "Temps: $temp0,$temp1,$temp2" $logfile
debug "Speeds: $speed0,$speed1,$speed2" $logfile
if lsmod | grep -wq "pwm_fan"; then
debug "pwm_fan module found. Unloading." $logfile
rmmod pwm_fan
else
debug "pwm_fan module not loaded. Doing nothing." $logfile
fi
if [[ -d "/sys/class/pwm/pwmchip0/pwm3" ]]; then
debug "pwm3 already exported. Doing nothing." $logfile
else
debug "Exporting pwm3." $logfile
echo 3 > /sys/class/pwm/pwmchip0/export
fi
cur_temp=$(round $(vcgencmd measure_temp | cut -d'=' -f2 | cut -d"'" -f1) 0)
period=$(cat /sys/class/pwm/pwmchip0/pwm3/period)
speed=$speed3
if [[ $cur_temp -le $temp0 ]]; then
speed=$speed0
elif [[ $cur_temp -le $temp1 ]]; then
speed=$speed1
else
speed=$speed2
fi
tmp=$(echo "$speed*$period" | bc)
duty_cycle=$(round $tmp 0)
log "temp: $cur_temp - speed: $speed - duty_cycle: $duty_cycle." $logfile
echo 1 > /sys/class/pwm/pwmchip0/pwm3/enable
echo $duty_cycle > /sys/class/pwm/pwmchip0/pwm3/duty_cycle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment