jpijnenburg
Posts: 12
Joined: Tue Feb 18, 2014 2:29 pm

differential of a temperature sensor curve

Tue Feb 18, 2014 2:35 pm

Hi guys!

added to my GPIO pins I have a temperature sensor (Ds18b20). Currently my program is just reading the temperature and printing it.

I would like to be able to measure if the curve is going up or going down, and posting it. So the delta of the curve.

Ideally i would like to measure how much the curve is going up or down, and then using 'if delta > 0' and 'if delta =< 0' something happens.

Before this post i did search the forums and google but i was unable to find something i could understand.

Thanks!

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: differential of a temperature sensor curve

Tue Feb 18, 2014 2:55 pm

You may want to consider using Google docs and load to a spreadsheet. You could get started here
http://learn.adafruit.com/dht-humidity- ... oogle-docs

I'm currently using Xively which is a service that graphs my DS18b20 sensors. This company was bought and sold 2 -3 times over the past three years and has changed quite a bit, I wouldn't necessarily recommend it.
https://xively.com/

I've read about other Python tools that can do graphing but haven't taken the time to try them out.
https://wiki.python.org/moin/NumericAnd ... c/Plotting

Here is my PI running a LAMP server
http://richpoints.x64.me

Good Luck!
Rich

tenochtitlanuk
Posts: 156
Joined: Fri Jul 06, 2012 8:51 pm
Location: Taunton, Somerset, UK
Contact: Website

Re: differential of a temperature sensor curve

Tue Feb 18, 2014 3:05 pm

Basically just keep updating a stored 'last value' as shown in the Python3 code here. I generate a sine wave- you'll have a routine reading the sensor.
Note that finding gradients very much emphasises random fluctuations. A smoothing routine ( see elsewhere on the forum) will help here.

Code: Select all

import math

readingOld =0
theta      =0

while theta <=4 *math.pi:
    readingNow = 50 +40 *math.sin( theta)
    delta_r =readingNow -readingOld
    print( "Currently =", readingNow, " which is up ", delta_r)
    readingOld =readingNow
    theta +=0.1

jpijnenburg
Posts: 12
Joined: Tue Feb 18, 2014 2:29 pm

Re: differential of a temperature sensor curve

Tue Feb 18, 2014 3:23 pm

Waw that is all very cool! Its cool to see how it works.

My question is a lot simpler though: I want to measure if the temperature is going up or going down, and print 'up' or 'down'.

Thanks,
Jonas

tenochtitlanuk
Posts: 156
Joined: Fri Jul 06, 2012 8:51 pm
Location: Taunton, Somerset, UK
Contact: Website

Re: differential of a temperature sensor curve

Tue Feb 18, 2014 3:31 pm

So just replace the print line with lines like

Code: Select all

    if delta_r >0.1:
        print( "Going up!")
    if delta_r <-0.1:
        print( "Going down!")
I've deliberately omitted cases where the change is between +/-0.1, because that allows for some 'noise' in the data.

achrn
Posts: 421
Joined: Wed Feb 13, 2013 1:22 pm

Re: differential of a temperature sensor curve

Tue Feb 18, 2014 8:27 pm

The case you actually ask about is trivial by simply remembering what teh last value was immediately before you get a new value, and comparing the two:

Code: Select all

last_temp=temperature
temperature=<<insert however it is you get a temperature value>>
if temperature<last_temp:
   print ("down")
if temperature>last_temp:
   print ("up")
However, you can be quite a lot cleverer than that with not a lot of effort if you keep an array of the last few readings (rather than just the last single value) and have the scipy package (sudo apt-get install python-scipy). Then, you can effectively draw a graph, put a best-fit straight line through the last few data points, and if it's heading downhill the trend is down, even if the last individual reading is above the one before that. This is better for values that are noisy (or jump around a bit), but it does slow down the responsiveness:

'slope, intercept, r_value, p_value, std_err = stats.linregress(readtimes,sensordata)' will give you the interesting values for the best fit straight line through the graph that you get by plotting the values in sensordata against the values in readtimes (those two being lists of floats). You can ignore all but slope if you don't know what they are.

Code: Select all

import time
from scipy import stats

# set this to over how long you want to check the trend
trend_time=60

# set this to the number of seconds between readings
sample_interval=6

# these arrays hold the readings and the time of the reading
sensordata=[]
readtimes=[]

while 1:
    # get the temperature and time 
    temperature=<<insert however it is you get a temperature value>>
    timenow=float(time.time())

    # record them
    sensordata.append(temperature)
    readtimes.append(timenow)

    # but we only want to keep data that's not too old
    # so discard any values older than trend_time value
    # but always keep at least three values
    while (len(readtimes)>3) and ((timenow-readtimes[0]) > trend_time):
        readtimes.pop(0)
        sensordata.pop(0)

    # print current temperature value
    print '  temperature: {:-6.2f}'.format(temperature)

    # if we have at least three values do statistical magic
    if len(readtimes) >= 3 and trend_time > 0:
        # abracadabra...
        slope, intercept, r_value, p_value, std_err = stats.linregress(readtimes,sensordata)
        
        # print interesting stuff
        print '     from {:d} samples over {:d} seconds :'.format(len(sensordata),int(max(readtimes)-min(readtimes)))
        print '     max {:-6.2f}, min {:-6.2f}, avg {:-6.2f}'.format(max(sensordata),min(sensordata),sum(sensordata)/len(sensordata))
        print '     trend {:-8.4f} per second'.format(slope)
        if (slope<0):
            print '       DOWN'
        if (slope>0):
            print '       UP  '

    # wait for next cycle
    time.sleep(sample_interval) 
Obviously you can just delete teh max / min / average / from x values over y seconds stuff if you want and just have teh 'UP' or 'DOWN'.

jpijnenburg
Posts: 12
Joined: Tue Feb 18, 2014 2:29 pm

Re: differential of a temperature sensor curve

Wed Feb 19, 2014 12:48 pm

Thank you all very much for the answers. I understand. This is how i coded it.

Code: Select all

import os
import glob
import time
import math

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c

ReadingOld=0

while True:
        ReadingNow = read_temp()
        delta_t = ReadingNow -ReadingOld
        print(ReadingNow, delta_t)
        if delta_t > 0
                print('up')
        else
                print('down')
        ReadingOld = ReadingNow
        time.sleep(1)
Before i tried to print 'up' and 'down' using If, everything worked perfectly. I could print ReadingNow and delta_t.

After i added this:

Code: Select all

        
if delta_t > 0
    print('up')
else
    print('down')
It gives a syntax error. How do i type this in correctly?

Again, thanks for the answers!
J

achrn
Posts: 421
Joined: Wed Feb 13, 2013 1:22 pm

Re: differential of a temperature sensor curve

Wed Feb 19, 2014 1:09 pm

jpijnenburg wrote: After i added this:

Code: Select all

        
if delta_t > 0
    print('up')
else
    print('down')
It gives a syntax error. How do i type this in correctly?
You're missing some ':' marks on the if and else lines:

Code: Select all

        
if delta_t > 0:
    print('up')
else:
    print('down')
It's a fallacy that python doesn't need line-end markers...

jpijnenburg
Posts: 12
Joined: Tue Feb 18, 2014 2:29 pm

Re: differential of a temperature sensor curve

Wed Feb 19, 2014 1:20 pm

Oops! Thank you very much!

Return to “Python”