## Ultra Sonic Distance Measurement

To monitor the water storage in my cistern I decided for a HCSR04 sensor module.To avoid uncontrolled reflexes by the volume and the build in technique like pipes, I installed the sensor centrally of the manhole of the water reservoir anat a height, that it is safely over the maximal gauge. Following this tutorial, I run the following script to test my sensor:

```import numpy as np
import datetime
import time
import RPi.GPIO as GPIO
#GPIO mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 15
GPIO_ECHO = 14
DEPTH = 199.0 #cm
# my reservoir:
# D=2.1m; Hmax=1.7m; A=3.46m^2; V=5.89m^3

GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distance():
# set trigger HIGH
GPIO.output(GPIO_TRIGGER, GPIO.HIGH)
# set trigger LOW again to initiate measurement
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, GPIO.LOW)
start = time.time()
stop = time.time()
# measurement starts, once ECHO is set HIGH
while GPIO.input(GPIO_ECHO) == 0:
start = time.time()
# measurement ends, when ECHO is set LOW again
while GPIO.input(GPIO_ECHO) == 1:
stop = time.time()
# compute the distance, sound travels forth and back
elapsedTime = stop - start
distance = (elapsedTime * 34300) / 2.0
#print(distance)
return distance

level = []
for i in range(10):
level.append(distance())
time.sleep(1)

levelArr = np.array(level)
median = np.median(levelArr)
H2Oheight = (DEPTH - median)/DEPTH*100
today = datetime.date.today()
now = time.localtime(time.time())
f=open("/var/www/H2O.dat", "w+")
f.write("%st%3.1f" % (today,H2Oheight))
f.close()
```

This script is executed by cron deamon.

```# m h dom mon dow user  command
*/15 * * * *    www-data    /usr/bin/python /var/www/HV_H2Olevel.py
```

If you should have trouble to access /dev/mem as any user, try

```sudo adduser <user> gpio
sudo chown root.gpio /dev/gpiomem
sudo chmod g+rw /dev/gpiomem
```

If you use GPIO14 + GPIO15, then do

```sudo raspi-config > Advanced > Serial
```
to disable the serial port.

To execute this regularly, I created /etc/cron.hourly/getH2Olevel

```#!/bin/bash

/usr/bin/python /var/www/HV_H2Olevel.py > /dev/null 2>&1
```