Smart Control of Raspberry Pi Fan Using Python & Thingspeak
by shahizat in Circuits > Raspberry Pi
3832 Views, 3 Favorites, 0 Comments
Smart Control of Raspberry Pi Fan Using Python & Thingspeak
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.
What You Will Learn
How to implement a Python script to control a fan based on the current temperature of Raspberry CPU using On-Off control with temperature hysteresis.How to transport data from your RaspberryPi to Things Speak Cloud.
Supplies
The components you will be required for this project are as follows
- Raspberry Pi 4 Computer Model B 4GB
- NPN transistor S8050330ohms resistor
- Armor Aluminum Metal Case with Dual Fans for Raspberry Pi
- Jumper cables
- 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.
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.
ThingSpeak can integrate popular devices and services such as:
- Arduino
- Raspberry pii
- oBridge / RealTime.io
- Electric imp
- Mobile and Web applications
- Social networks
- Data Analysis in MATLAB
Before we start, you need an account at ThingSpeak.
- Go to the following link and sign up to ThingSpeak.
- After your account activation, sign in.
- Go to Channels -> My Channels
- Click on New Channel button.
- Enter the name, description and fields of the data you want to upload
- 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
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 findalldef 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.
from urllib import request from re import findall from time import sleep from subprocess import check_output myAPI = '################' baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPIdef get_temp(): temp = check_output(["vcgencmd","measure_temp"]).decode() temp = float(findall('\d+\.\d+', temp)[0]) return(temp) try: while True: temp = get_temp() conn = request.urlopen(baseURL + '&field1=%s' % (temp)) print(str(temp)) conn.close() sleep(1) except KeyboardInterrupt: print("Exit pressed Ctrl+C")
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.
import RPi.GPIO as GPIO import sys from re import findall from time import sleep from subprocess import check_output def get_temp(): temp = check_output(["vcgencmd","measure_temp"]).decode() temp = float(findall('\d+\.\d+', temp)[0]) return(temp) try: GPIO.setwarnings(False) tempOn = 50 threshold = 10 controlPin = 14 pinState = False GPIO.setmode(GPIO.BCM) GPIO.setup(controlPin, GPIO.OUT, initial=0) while True: temp = get_temp() if temp > tempOn and not pinState or temp < tempOn - threshold and pinState: pinState = not pinState GPIO.output(controlPin, pinState) print(str(temp) + " " + str(pinState)) sleep(1) except KeyboardInterrupt: print("Exit pressed Ctrl+C") except: print("Other Exception") print("--- Start Exception Data:") traceback.print_exc(limit=2, file=sys.stdout) print("--- End Exception Data:") finally: print("CleanUp") GPIO.cleanup() print("End of program")
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.
- Log into your Raspberry PI board
- Run the following command on terminal
python3 cpu.py
Monitoring Data Via Thingspeak Cloud
After a while, open your channel on ThingSpeak and you should see the temperature uploading into Thingspeak cloud in a real-time.
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.