Raspberry pi 4 GPIO controlled cooling fan

Using some python, few electronics parts and a fan, I added a GPIO controlled fan to my RPI 4.

While working on the raspberry live video with tkinter I noticed that my rpi 4 (knows issue) tend to run really hot. When I ordered the rpi4, I also ordered a case and a cooling fan, I should have bought a heat sink as well, which I did later (after the video was done). If you want to watch the project you can see it here

Now I did not want it to run all the time, so I did 2 things.I create a PCB that move the control of the fan to a GPIO using a NPN transistor as a switch.And I wrote a little python script that takes the core temperature using this command : vcgencmd measure_temp. Once I get the temperature, I check if it’s over the threshold, if so I turn on the fan. If not turn it off. Pretty simple. I added the script to the rc.local file and it works on boot now. When I tested it later on (again after the video was out) I noticed that my code was not perfect for the job, and changed it to have a gap between the turn on to the turn off by temperature, not using the same one. I also printed a case for the camera The files can be found here (not mine!) https://www.thingiverse.com/thing:2746186I had a great time also creating the box and mount using fusion360.I did not publish the files, but if any one wants then will be more the happy to send it to him. Hope you will find it useful.

Schematics

Code

# code by [email protected]
# temp control with cooling fan.
# connect a fan via a npn transistor.
# power from the 5V of the rpi.

import os
import time
import RPi.GPIO as GPIO
fanPin = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(fanPin, GPIO.OUT)
threshHoldTempOn = 45
threshHoldTempOff = 40
pwmPrecentCycle = 75
p = GPIO.PWM(fanPin, 200)  # frequency=200Hz
p.start(0)

def measure_temp():
        temp = os.popen("vcgencmd measure_temp").readline()
        return float((temp.replace("temp=","").replace("\'C\n","")))

try:
    while True:
        currentTemp = measure_temp()
        if currentTemp >= threshHoldTempOn:
            p.ChangeDutyCycle(pwmPrecentCycle)
            #GPIO.output(fanPin, GPIO.HIGH)
            print ("hot")
        elif currentTemp <= threshHoldTempOff:
            p.ChangeDutyCycle(0)
            #p.stop()
            #GPIO.output(fanPin, GPIO.LOW)
            print ("ok")
        else:
            print ("no chnage")
        print(currentTemp)
        print("----------------")
        
        time.sleep(30)

except KeyboardInterrupt:
    GPIO.cleanup()
    print("Press Ctrl-C to terminate while statement")
    pass

Source: Raspberry pi 4 GPIO controlled cooling fan


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top