Last active
July 30, 2020 08:24
-
-
Save mrbalihai/71f0bb7683b6f8af2dda13aac9678586 to your computer and use it in GitHub Desktop.
Triggering a Raspberry PI Fan via GPIO port in python or bash
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
#!/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() |
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
[Unit] | |
Description=RPI Fan Service | |
After=multi-user.target | |
[Service] | |
Type=idle | |
ExecStart=/usr/bin/rpi-fan.sh | |
[Install] | |
WantedBy=multi-user.target |
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 | |
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