Ultrasonic Water Tank Level Monitor

So if anyone is interested… I have spent all morning on this - remember this is my first python program too !

I found such inconsistancies in reading - most likely the second read would be well out there - sometimes twice as big as it should be - once 10 times! Other times, it could be a lot lot smaller than it should be…

So it made me think - how to remove the outliers… If I could ignore the items that occurred at each extreme, and then looked at the average of ‘good’ data - would I then have some kind of consistency…

So here is my revised code - it works out the standard deviations, and removes things at both ends of the extreme - returning an array of potentially good data !!!

import RPi.GPIO as GPIO
import time
import numpy as np

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24

howmany = 50
soundspeed = 17550

a = np.zeros(shape=[howmany])

def outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/(mdev if mdev else 1.)
return data[s<m]

print (“Distance Measurement In Progress”)
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)

for n in range(1,howmany+1):
time.sleep(1)
GPIO.output(TRIG, True)
time.sleep(0.00003)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
a[n-1] = pulse_duration * soundspeed

print (“array -original”)
print(a)

print(“array - removed outliers”)
print(outliers(a))

print("Average - removed outliers: ",round(np.average(outliers(a)),1))

GPIO.cleanup()

Running this - it does not seem to matter if I do 20 Reads, 50 Reads, or even a 100 Reads - I end up with something that is now consistent… Each time I execute the code, I end up with .1cm consistency on each read… I have run at 20 times - and each time I got the same answer - so I am happy !!! Very happy !

Maybe this helps someone else ?