Ultra Sonic Distance Measurement

1Set up the Raspberry Pi
2Electrical Connection of Sensores and Actuators
2.1AD Converters connected via SPI
2.2Relay on GPIO via Opto-Coupler
2.3PWM Control of Ventilation via i2c
2.4OneWire Temperature Sensor
2.5Ultra-sonic Distrance Measurement
2.6Serial RS232 connection
2.7Stepper Motor Control
3Heating Control
4Ventilation Control (Paul Lüftung, Thermos 200)
5 z-wave


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 an additional 70 mm pipe vertically in the water reservoir and mounted the sensor at the top, such that it is safely over the maximal gauge.

showHouse_H2Olevel.svg

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
Login
Valid HTML 4.01!