Skip to content

Instantly share code, notes, and snippets.

@mrbalihai
Last active July 30, 2020 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrbalihai/71f0bb7683b6f8af2dda13aac9678586 to your computer and use it in GitHub Desktop.
Save mrbalihai/71f0bb7683b6f8af2dda13aac9678586 to your computer and use it in GitHub Desktop.
Triggering a Raspberry PI Fan via GPIO port in python or bash
#!/usr/bin/python3
import sys
import time
from gpiozero import LED # doc: https://gpiozero.readthedocs.io/
# define the GPIO to control the transistor's B pin
fan = LED(21)
def cpu_temp():
with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
return float(f.read())/1000
def main():
# close fan at begining
is_close = True
fan.off()
while True:
temp = cpu_temp()
if is_close:
if temp > 60.0: # upper bound to turn on the fan
print(time.ctime(), temp, 'Fan ON')
fan.on()
is_close = False
else:
if temp < 45.0: # lower bound to turn off the fan
print(time.ctime(), temp, 'Fan OFF')
fan.off()
is_close = True
time.sleep(5.0)
if __name__ == '__main__':
main()
[Unit]
Description=RPI Fan Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/rpi-fan.sh
[Install]
WantedBy=multi-user.target
#!/bin/bash
GPIO_EXPORT=/sys/class/gpio/export
if [ ! -f ${GPIO_EXPORT} ]; then
echo "21" > ${GPIO_EXPORT}
fi
echo "out" > /sys/class/gpio/gpio21/direction
while true; do
TEMP=$(cat /sys/class/thermal/thermal_zone0/temp)
if [ ${TEMP} -gt 60000 ]; then
echo "starting fan"
echo "1" > /sys/class/gpio/gpio21/value
elif [ ${TEMP} -lt 45000 ]; then
echo "stopping fan"
echo "0" > /sys/class/gpio/gpio21/value
fi
sleep 2
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment