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.



# 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.setup(fanPin, GPIO.OUT)
threshHoldTempOn = 45
threshHoldTempOff = 40
pwmPrecentCycle = 75
p = GPIO.PWM(fanPin, 200)  # frequency=200Hz

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

    while True:
        currentTemp = measure_temp()
        if currentTemp >= threshHoldTempOn:
            #GPIO.output(fanPin, GPIO.HIGH)
            print ("hot")
        elif currentTemp <= threshHoldTempOff:
            #GPIO.output(fanPin, GPIO.LOW)
            print ("ok")
            print ("no chnage")

except KeyboardInterrupt:
    print("Press Ctrl-C to terminate while statement")

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.

Scroll to Top