A Python script monitors CPU temperature and controls the fan using On-Off control with temperature hysteresis. 

A Python script monitors CPU temperature and controls the fan using On-Off control with temperature hysteresis.

Brief overview

By default, the fan is directly connected to the GPIO - this implies its constant operation. Despite the relative quiet operation of the fan, its continuous operation is not an effective use of an active cooling system. At the same time, the constant operation of a fan can just be annoying. Also, if Raspberry Pi is turned off, the fan will still work if the power is connected.

This article will show how, using simple and not complicated manipulations, turn an existing cooling system into a smart one, which will only be turned on when the processor really needs it. The fan would be turned on only when there is heavy usage, thus reducing fan power consumption and noise. Also extending fan life by keeping it off when not needed.

Items for Getting Started

The components you will be required for this project are as follows

  1. Raspberry Pi 4 Computer Model B 4GB
  2. NPN transistor S8050
  3. 330ohms resistor
  4. Armor Aluminum Metal Case with Dual Fans for Raspberry Pi
  5. Jumper cables
  6. Breadboard

Building the circuit

The circuit is pretty simple. The power to the fan is cut off using NPN transistor. In this configuration, the transistor is acting as a low-side switch. Resistor is only required to limit the current through GPIO. The Raspberry Pi’s GPIO has a maximum current output of 16mA. I used 330 ohms which gives us a base current of about (5-0.7)/330 = 13mA. I selected a NPN transistor S8050, so switching a 400mA load from both fans is no problem.

Untitled Sketch_bb.jpg

Perform connections as shown in the following schematic diagram above.

IMG_4019.JPG

Log CPU temperature with ThingSpeak

ThingSpeak is a platform for projects based on the Internet of Things concept. This platform allows you to build applications based on data collected from sensors. The main features of ThingSpeak include: real-time data collection, data processing and visualization. ThingSpeak API not only allows you to send, store and access data, but also provides various statistical methods for processing them.

Screen Shot 2019-11-06 at 10.57.45 PM.png

ThingSpeak can integrate popular devices and services such as:

  • Arduino
  • Raspberry pi
  • ioBridge / RealTime.io
  • Electric imp
  • Mobile and Web applications
  • Social networks
  • Data Analysis in MATLAB

Before we start, you need an account at ThingSpeak.

  1. Go to the following link and sign up to ThingSpeak.
  2. After your account activation, sign in.
  3. Go to Channels -> My Channels
Screen Shot 2019-11-06 at 11.00.06 PM.png

Click on New Channel button.

Screen Shot 2019-11-06 at 11.03.35 PM.png

Enter the name, description and fields of the data you want to upload

Screen Shot 2019-11-06 at 11.16.14 PM.png

Click on Save Channel button to save all of your settings.

We need an API key, which we will later add to python code in order to upload our CPU temperature to Thingspeak cloud.

Click on API Keys tab to get the Write API Key.

Screen Shot 2019-11-06 at 11.34.25 PM.png

Once you have the Write API Key, we are almost ready to upload our data.

Getting the CPU temperature from a Raspberry Pi using Python

The script is based on a retrieving the processor temperature, which occurs every second. It can be obtained from the terminal by running the vcgencmd command with the measure_temp parameter.

        vcgencmd measure_temp
    

Subprocess.check_output() library was used to execute the command and then using regular expression to extract the actual value from the returned string.

        from subprocess import check_output
from re import findall
def get_temp():
    temp = check_output(["vcgencmd","measure_temp"]).decode()    
    temp = float(findall('\d+\.\d+', temp)[0])                   
    return(temp)

print(get_temp())
    

After the temperature value is fetched, data needs to be sent to ThingSpeak cloud. Use your Write API Key to change the myApi variable in the below Python code.

Controlling the Fan Based on Temperature

Python script shown below implements logic that turns on the fan when the temperature rises above the tempOn and off only when the temperature drops down below the threshold. This way, the fan won’t turn on and off rapidly.

Final Python code

The main python code can be found on my GitHub account in the following link. Remember to put your own Write API Key.

  1. Log into your Raspberry PI board
  2. Run the following command on terminal
        python3 cpu.py
    

After a while, open your channel on ThingSpeak and you should see the temperature uploading into Thingspeak cloud in a real-time.

Screen Shot 2019-11-06 at 11.41.54 PM.png

Run the Python script at Startup

To do this, at the end of the /etc/rc.local file:

        sudo nano /etc/rc.local
    

You need to place the script start command in front of the line exit 0:

        sudo python /home/pi/cpu.py &
    

The presence of the & symbol at the end of the command is mandatory, since it is a flag to start the process in the background.

After the reboot, the script will automatically run and the fan will turn on when the specified conditions are met.