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'.