import http.client
import urllib.parse
import time
# Put your API Key here
key = "ABCD"
def read_cpu_temperature():
try:
# Calculate CPU temperature of Raspberry Pi in Degrees C
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
return temp
except Exception as e:
print("Failed to read CPU temperature:", e)
return None
def send_to_thingspeak(temp):
try:
params = urllib.parse.urlencode({'field1': temp, 'key': key})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = http.client.HTTPConnection("api.thingspeak.com", 80)
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print("Temperature:", temp)
print("Response:", response.status, response.reason)
data = response.read()
conn.close()
except Exception as e:
print("Failed to send data to ThingSpeak:", e)
if __name__ == "__main__":
while True:
temperature = read_cpu_temperature()
if temperature is not None:
send_to_thingspeak(temperature)
time.sleep(15) # Adjust the interval as needed