ThingSpeak is an IoT analytics platform service that can process, visualize and live stream data in the cloud. In this tutorial, you are going to write a program to implement the following tasks simultaneously.
(1) Send CPU temperature data of Raspberry Pi 4B to ThingSpeak Cloud.
(2) Turn on cooling fan if the CPU temperature of Raspberry Pi 4B is higher than 46 degree Celcius.
https://thingspeak.com/pages/commercial_learn_more |
Step 1: Register account in ThingSpeak via https://thingspeak.com/login
Step 2: Create a new project and write down 'Channel ID'
Step 3: Write down the API keys that will be used in your python code in step 6
Step 4: Build a simple electronic circuit
Step 5: Install ThingSpeak in Raspberry Pi
Command: sudo pip install thingspeak
Here we do not need httplib and urllib because ThingSpeak has integrated them
Step 6: Store the following code as app.py
import thingspeak
import time
from time import sleep
import os
import signal
import sys
import RPi.GPIO as GPIO
channel_id=******** # Your channel ID
write_key = '********' # Your API Key
def thermometer(channel):
try:
#Calculate CPU temperature of Raspberry Pi in Degrees C
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
print(temp)
response = channel.update({'field1': temp})
read=channel.get({})
except:
print("connection failed")
pin = 16 # GPIO pin
max_temp = 46 # The threshold temperature in Celsius to turn on electric fan
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def getCPUtemperature():
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
print(temp)
return temp
def fanON():
setPin(True)
return()
def fanOFF():
setPin(False)
return()
def getTEMP():
CPU_temp = float(getCPUtemperature())
if CPU_temp>max_temp:
fanON()
else:
fanOFF()
return()
def setPin(mode):
GPIO.output(pin, mode)
return()
if __name__ == "__main__":
channel=thingspeak.Channel(id=channel_id,api_key=write_key)
try:
setup()
while True:
thermometer(channel) # communicate to ThingSpeak
getTEMP() # communicate to Raspberry Pi
sleep(10)
except KeyboardInterrupt:
GPIO.cleanup()
#The above code is modified from open-source platform
Step 7: Set the channel as private or public. Then observe the temperature data
When temperature exceed 46 Degree Celsius, the electric fan is turned on and then the CPU starts to cool down. Of course you can download the data from ThingSpeak Cloud
Comments
Post a Comment