ThingSpeak Temperature Sampling


Raspberry Pi Temperature Sampling using thinkspeak and a SHT31 Sensor

Scope: I work in a shop environment that gets to be pretty unbearable in the summertime. Hot machines, above 85 degree weather and Michigan humidity equals dehydration and heat stroke. There is a Union contract here that dictates and temp:humidity ratio on when we should be sent home, but it has only hit that twice since 2008 and no one was really monitoring those variables. I talked to our safety department and theie hands were kind of tied due to funding, the only repreive they could offer was putting a calibrated sensor on the shop floor nad having someone come down and read it everyday. That seemed like a great solution except the waterjet area was more humid than the machine shop, sheetmetal was cooler than the rest of the shop, and welding was the hottest area in the summer, for obvious reasons. Additionally, the temperature would spike at different times of the day. So the one sensor check per day, at the same time everyday, scenario did not work as well as intended when the temperature or humidity spiked after 1400 hours and the sample was already taken or the sensor was in a cooler part of the shop. After having a conversation, about our downfalls, with safety, we agreed that thier process was about as good as it was going to get with the resources available. I never took into consideration that there were other cells with the same issues and limited personel to check the readings.

Requirements: Obviously I have to automate the sampling procedure, it needs to sample as often as possible, there needs to be more than one location, and remotely viewable.

Solution: We decided on a Raspberry Pi 3b with a SHT31 sensor as we could use the Raspberry Pi for other purposes and the sensor was the most accurate for the cost out of pocket.

  • Below is the python code used to get information from the sensor and send it to ThingSpeak.com. The object was to get a sample every minute for 5 minutes, then add them up and divide by 5 for an average, then send the average to ThingSpeak. We did this for a few reasons;
  1. We are limited to the number of samples per hour we can send up on the free version.
  2. The bay door opens too often and would give extremly dynamic readings that caused the graph to show massive peaks and valleys. This left the more important data hard to visualize as the graph was now too small to see those numbers.
  3. I wanted to learn something a bit more complex.

So with a some help from the interwebs and a buddy I work with, we came up with this script.

#!/usr/bin/python
"""
MJRoBot Lab Temp Humidity Light RPi Station

Temperature/Humidity/Light monitor using Raspberry Pi, DHT11, and photosensor 
Data is displayed at thingspeak.com
2016/03/03
MJRoBot.org

Based on project by Mahesh Venkitachalam at electronut.in and SolderingSunday at Instructables.com

"""

# Import all the libraries we need to run
import sys
import RPi.GPIO as GPIO
import os
import time
from time import sleep
from Adafruit_SHT31 import *
import urllib2


#Setup our API and delay. 
myAPI = "XXXXXXXXXXXX" # Put your Thingspeak API here, leave the quotes.
myDelay = 60 #how many seconds between posting data

def GetSensorData():
    sensor = SHT31(address = 0x44)
    degrees = ((sensor.read_temperature()*1.8)+32)
    humidity = sensor.read_humidity()

    return degrees, humidity

def dataAverage():
    MeanDataTemp = []
    MeanDataHumid = []
    counter=0
    AveTemp=0
    
    while counter <= 4:
        GetSensorData()
        degrees, humidity = GetSensorData()
        #uncomment below for loop debugging in terminal
        #print degrees, humidity, counter
        MeanDataTemp.append(degrees)
        MeanDataHumid.append(humidity)
        sleep(int(myDelay))
        counter = counter + 1

    AveTemp = (MeanDataTemp[0] + MeanDataTemp[1] + MeanDataTemp[2] + MeanDataTemp[3] + MeanDataTemp[4])/5
    AveHumid = (MeanDataHumid[0] + MeanDataHumid[1] + MeanDataHumid[2] + MeanDataHumid[3] + MeanDataHumid[4])/5
    #Uncomment to see variables in terminal
    #print AveTemp, AveHumid
    return (round(AveTemp,3), round(AveHumid,2))

# main() function
def main():
    
    print 'starting...'
    
    baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
    print baseURL
    
    while True:
        try:
            AveTemp, AveHumid = dataAverage()
            f = urllib2.urlopen(baseURL + 
                                "&field1=%s&field2=%s" % (AveTemp, AveHumid)) #change these fields to accomodate your setup.
                              
            print f.read()
            
            print  '{0:0.3F} deg F'.format(AveTemp) + " " + '{0:0.2f} %'.format(AveHumid)
            f.close()
            
        except Exception ,e:
	    print e
            print 'Network Failure Retrying.'
	   
            time.sleep(60)
            main()

# call main"""
if __name__ == '__main__':
    main()

After we managed to get the python code to run exactly how we needed it to, we had to figure out how to get it to run on boot without us logging into the RPI, via ssh, and starting the code manually. Upon some research, the rc.local file seemed to be the legitimate way to start the code. I found an example online, copied it then added

/home/pi/CollectAndSendToThinkSpeak.py

after the code that was already there. Then I changed the rc.local file to be executable

chmod +x rc.local

and rebooted the RPI.

  • Here is the rc.local file
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi
/home/pi/CollectAndSendToThinkSpeak.py
exit 0

We ended up running the python code in 2 areas, one in the machine shop and the other down in waterjet. Unfortunatly at that time, the other supervisor thought we were trying to do some hacking and/or illegal stuff and did not want sampling in the areas of welding and assembly.

Here is the website if you want to see it yourself: ThingSpeak.