Created
November 14, 2019 23:29
-
-
Save mvadu/9cfc55a41bc230e1c44a7ab17e64241d to your computer and use it in GitHub Desktop.
# This script is to control a fan via PWM signal on GPIO14. I have a MOSFET acting as a low side switch connected to this pin It measures the temperature, and if it corosses a set limit turns on the fan. The fan speed will be relative to temperature Once the temperature goes down fan will be turned off, it also logs it to a local influx DB
This file contains hidden or 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/env python | |
#~/.local/bin/cpuFanControl.py | |
################################################################################# | |
# This script is to control a fan via PWM signal on GPIO14 | |
# I have a MOSFET acting as a low side switch connected to this pin | |
# It measures the temperature, and if it corosses a set limit turns on the fan | |
# The fan speed will be relative to temperature | |
# Once the temperature goes down fan will be turned off | |
# it also logs it to a local influx DB | |
################################################################################# | |
import RPi.GPIO as GPIO | |
from gpiozero import CPUTemperature | |
from time import sleep, time | |
import requests | |
import psutil | |
fanControlPin = 14 | |
tempThreshold = 75 | |
maxFanTemp = tempThreshold * 0.9 | |
minFanTemp = 50 | |
minDutyCycle = 50 | |
maxDutyCycle = 100 | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(fanControlPin, GPIO.OUT) | |
GPIO.output(fanControlPin, 0) | |
#setup 100Hz PWM | |
pwmHandle = GPIO.PWM(fanControlPin, 100) | |
cpu = CPUTemperature() | |
fanRunning = False | |
while True: | |
temp = cpu.temperature | |
if temp >= maxFanTemp : delta = maxDutyCycle | |
elif temp < minFanTemp : delta = 0 | |
else: | |
delta = (temp-minFanTemp) / (maxFanTemp - minFanTemp) * 100 | |
#map 0-100 to min to max duty cycle | |
delta = delta * (maxDutyCycle- minDutyCycle) / 100 + minDutyCycle | |
if delta >= minDutyCycle: | |
if not(fanRunning): | |
pwmHandle.start(1) | |
fanRunning = True | |
pwmHandle.ChangeDutyCycle(delta) | |
elif fanRunning: | |
pwmHandle.stop() | |
fanRunning = False | |
sleep(60) | |
requests.post('http://localhost:8086/write?db=raspi_data&rp=one_month', "raspi_cpu,host=raspberrypi4 cpu_temp={0},fan_dc={1},cpu_load={2}".format(temp,delta,psutil.cpu_percent()).encode()) | |
pwmHandle.stop() | |
GPIO.cleanup() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment