Last active
March 20, 2018 13:36
-
-
Save satori99/812d55afb79f5bbf156ef268237e43d2 to your computer and use it in GitHub Desktop.
Raspberry Pi Cooling Fan Control via GPIO
This file contains 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
#!/bin/bash | |
# | |
# Raspberry Pi Fan Control Script | |
# | |
# This script toggles a GPIO output pin when a system temperature limit is exceed to control a cooling fan. | |
# | |
# usage: | |
# | |
# $ ./fancontrol.sh | |
# | |
# $ # show temp readings and fan state | |
# $ DEBUG=1 ./fancontrol.sh | |
# | |
# $ # set monitor freq to 2s and temp threshold to 55 degrees | |
# $ FREQ=2 THRESHOLD=55000 ./fancontrol.sh | |
# | |
# The GPIO Pin number to use for switching the fan. Default = 18 | |
PIN=${PIN:-18} | |
# Temp monitoring frequency (in seconds). Default = 5 | |
FREQ=${FREQ:-5} | |
# Temp threshold. Fan will turn on when the temperature exceeds this value (in millidegrees). Default = 70000 | |
THRESHOLD=${THRESHOLD:-70000} | |
function init { | |
echo $PIN > /sys/class/gpio/export 2> /dev/null | |
if [ $? != 0 ]; then | |
>&2 echo "$(date): fan control failed to start" | |
exit 1 | |
fi | |
sleep 0.25 | |
echo "out" > "/sys/class/gpio/gpio$PIN/direction" | |
echo "$(date): fan control started ($THRESHOLD/$FREQ)" | |
[ ! -f $DEBUG ] && echo "$(date): debug: exported GPIO Pin $PIN -> /sys/class/gpio/gpio$PIN" | |
} | |
function cleanup { | |
echo "$PIN" > /sys/class/gpio/unexport 2> /dev/null | |
[ ! -f $DEBUG ] && echo "$(date): debug: unexported GPIO Pin $PIN" | |
echo "$(date): fan control stopped" | |
} | |
function fan_on { | |
[ $FAN_STATE = 0 ] && echo "1" > "/sys/class/gpio/gpio$PIN/value" | |
FAN_STATE=1 | |
} | |
function fan_off { | |
[ $FAN_STATE = 1 ] && echo "0" > "/sys/class/gpio/gpio$PIN/value" | |
FAN_STATE=0 | |
} | |
FAN_STATE=0 | |
CURR_TEMP=0 | |
init | |
trap cleanup EXIT | |
set -e | |
while true | |
do | |
CURR_TEMP=$(cat /sys/class/thermal/thermal_zone0/temp) | |
[ ! -f $DEBUG ] && echo "$(date): debug: Temp=$CURR_TEMP, Fan=$FAN_STATE" | |
if [ $CURR_TEMP -gt $THRESHOLD ]; then | |
fan_on | |
else | |
fan_off | |
fi | |
sleep $FREQ | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment