# Ultrasonic Water Tank Level Monitor

**URL:** <https://forum.core-electronics.com.au/t/ultrasonic-water-tank-level-monitor/5261>\
**Category:** Raspberry Pi\
**Created:** [3 May 2019 12:23 UTC](https://forum.core-electronics.com.au/t/ultrasonic-water-tank-level-monitor/5261 "2019-05-03T12:23:11Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![keith84844](https://avatars.discourse-cdn.com/v4/letter/k/ed655f/32.png) [@keith84844](https://forum.core-electronics.com.au/u/keith84844)\
**Post date:** [4 May 2019 03:59 UTC](https://forum.core-electronics.com.au/t/ultrasonic-water-tank-level-monitor/5261/2 "2019-05-04T03:59:11Z")

</div>

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 ?

---

_[View the full topic](https://forum.core-electronics.com.au/t/ultrasonic-water-tank-level-monitor/5261)._
