Water level measurement

Water level measurement

In this article, you can find how to indicate water level in the reservoir (e.g. rainwater tank). The values are converted into the volume in liters. This feature enables you to automatically fill the tank when needed or predict any other situations (e.g. irrigation volume).


Ultrasonic waterproof distance sensor JSN-SR04T

Pi-Home - if you don't have it, see How to section




Sensor JSN-SR04T consists of two parts, an electronic board and a water-resistant sensor. The electronic part must be near the tank stored in a water-resistant case. The sensor is operating based on acoustic waves. For more information see for example this link: https://www.electronicwings.com/sensors-modules/ultrasonic-module-hc-sr04. The sensor can measure from about 20 cm to 450 cm at an angle of about 45°. It is therefore very important that there are no obstacles near the sensor and also on the sides. It is ideal to have your own sensor in a plastic tube and place it about 25 cm above the maximum water level in the middle of the tank.

Senzor hladiny vodni nadrze

How to

We can fit the sensor in any tube. The sensor head is 25 mm in diameter so use tube with same or larger internal diameter and attach sensor on one end. Fix the tube to the reservoir. Connect cable to an electronic board. We are using 3D printed case for electronic board. Electronic board is connected to the Arduino board. We are using CAT6 UTP cable. You will need to use four wires. Plug in four wires depending on how it looks on the Arduino plate of the sketch, see below.

Next, we'll upload a sketch to Arduino. Sketch load and send distance values from the sensor. Then there is the conversion into tank volume. Focus and edit this part of the sketch according to your tank. The code can, of course, be combined to collect distance, temperature, PIR and other useful sensors on one Arduino board.

Výpočet objedmu nádrže dešťové vody

Full sketch:

Script to read volume of liquid medium in water tank

- connect to MQTT server
- publishes "Hello world - Arduino XYZ" to the topic
- read sensor value, calculate volume and filter results
- multiple arduino's with same generic sketch can run parallel to each other
- multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID
- tested on arduino-mega with W5100 ethernet shield


#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
//Tank level
#include <NewPing.h>
#include <MedianFilter.h>
#include <Wire.h>

//Tank Level
#define TRIGGER_PIN 3
#define ECHO_PIN 4
#define MAX_DISTANCE 200 // (in centimeters). Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
MedianFilter filter(31,0);

//Time variable
unsigned long time_now = 0;

//Char strings for MQTT
char tankDV[10];


// Arduino MAC address must be unique for every node in same network
byte mac[] = { 0xCC, 0xFA, 0x00, 0x1B, 0x19, 0x77 };

// Unique static IP address of Arduino
IPAddress ip(192,168,4,101);

// IP Address of your MQTT broker (OpenHAB server)
byte server[] = { 192,168,4,30 };

// Handle and convert incoming MQTT messages ----------------------------------------
void callback(char* topic, byte * payload, unsigned int length) {


// Initiate instances -----------------------------------
EthernetClient arduino_XYZ;
PubSubClient client(server, 1883, callback, arduino_XYZ);

void setup()

// Setup ethernet connection to MQTT broker
Ethernet.begin(mac, ip);
if (client.connect("arduino_XYZ", "openhabian", "openhabian")) { // change as desired - clientname must be unique for MQTT broker
client.publish("sensors","Hello world - here Arduino XYZ with IP");

long lastReconnectAttempt = 0;

boolean reconnect() {
if (client.connect("arduino_XYZ", "openhabian", "openhabian")) {
// Once connected, publish an announcement...
client.publish("sensors","Arduino XYZ - reconnected");
// ... and resubscribe
return client.connected();

void loop()

if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
} else {
// Client connected


// Collect sensor data every 30 seconds. Change value 30000 ms to another if you want
if(millis() >= time_now + 30000){
time_now += 30000;

//============TANK LEVEL SENSOR============================
unsigned int otank1,uStank1 = sonar.ping(); // Send ping, get ping time in microseconds (uStank1).
otank1 = filter.out();
//Calculate volume in litres (add values in centimeters): ((sensor height from bottom - sensor value) * pi * r2)/1000
float cmtank1 = ((160-(otank1 / US_ROUNDTRIP_CM))*3.14*6400)/1000;
//Filter value - we should get only values between maximum volume of tank and minimum volume
if ((cmtank1 <=2700) && (cmtank1 >= 50)){
dtostrf(cmtank1,3, 0, tankDV);
client.publish("pihome/sensor/water/rain", tankDV);


// End of sketch ---------------------------------



We can easily get the values into OpenHAB 3 by creating Thing (type MQTT). Then add Channel to listen MQTT topic "pihome/sensor/water/rain". My tab "Code" under Thing looks like below:

UID: mqtt:topic:pihome:sensors-other
label: Sensors other
thingTypeUID: mqtt:topic
configuration: {}
bridgeUID: mqtt:broker:pihome
  - id: SW101
    channelTypeUID: mqtt:number
    label: WaterTank Litres Rain
    description: null
      stateTopic: pihome/sensor/water/rain

Then create Item from the Channel. If you have an item, let's show the number of litres in reservoir on our Overview page.

PiHome - OpenHAB 3 Overview water tank

PiHome - OpenHAB 3 Overview water tank label

PiHome - OpenHAB 3 UI Water reserviour liters

PiHome - OpenHAB 3 UI Water tank graph

PS: If you looking for value SW101p - it is a percentage of total volume. How to get? Simply add empty number type item "SW101p" and add Rule which calculate the percentage. Current value divided by one percent (for me, 2700 litres / 100 = 27) See rule below:

configuration: {}
  - id: "1"
      itemName: SW101
      state: ""
      previousState: ""
    type: core.ItemStateChangeTrigger
conditions: []
  - inputs: {}
    id: "2"
      type: application/vnd.openhab.dsl.rule
      script: "

        \   sendCommand(SW101p, (SW101.state as Number)/27)

        \   "
    type: script.ScriptAction

What else?

You can add more rules for your home automation e.g.:

  • if below 300, add water from water pipe
  • if more than 2,500, pump into the next tank
  • if less than 1,000, do not use for irrigation etc.



Rate the article:

Average: 3.5 (2 votes)

Support Us:

Add comment:

Add comment

Newest articles in blog

MikroTik - Winbox, DHCP, Ranges
Basics - Winbox, DHCPRating: 

In this series, we will look at the step-by-step setup of MikroTik devices for home users or a small business (up to 25 people). In the first article, we will focus on the initial setup - we will download Winbox and set up DHCP for the primary network and guest network. Similarly, we will also adjust the WiFi settings.

Alarm Smart Home PIR
Alarm from existing PIR sensors in a smart home.Rating: 

In a your smart home, PIR sensors may not only be used to switch lights on and off based on motion, it is possible to utilize these sensors to detect the presence of motion in a particular room. This information can be used to create a relatively reliable uncertified home security system. In this guide, you will find the logic for how this can work in the OpenHAB software in our model smart home.

NFC Tag Example in Smart Home
NFC tags in smart homeRating: 

NFC (Near Field Communication) tags are small plastic or paper stickers that can be used to automate various functions in the smart home. In this article, we will show you examples of use and a guide on how to write an action on an NFC tag using a mobile phone.

WireGuard iOS
WireGuard on iOS devicesRating: 

In this article, you will find a detailed guide on how to connect to WireGuard VPN from iOS.

WireGuard on Android device
WireGuard on Android devicesRating: 

In this article, you will find a detailed guide on how to connect to WireGuard VPN from Android.

WireGuard on MikroTikRating: 

This article describes the self setup of the WireGuard VPN protocol on MikroTik devices with RouterOS version 7 and higher. This phenomenal VPN is very fast, secure, and easily configurable in a home environment. It can be said that it is currently the best VPN for home use available.

Nilan VP18 vs OpenHABRating: 

We provide tutorial for the connection of the active Nilan recuperation unit, in our case the VP18 K WT type with OpenHAB 3. By communicating via Modbus it is possible to read the whole range of values, but mainly also to control the unit through OpenHAB. This allows us to remotely or programmatically change the performance and ventilation settings depending on the mode (night, cooking, etc.)

PiHome - Chytry dum mereni spotreby elektriny
Energy meter in smart homeRating: 

We are providing a simple step-by-step tutorial how to install home energy meter. We did not find any MQTT device, so we buy Aeotec Home Energy Meter as we are already have a Z-Wave controlller in our smart home.

Centrální tablet pro chytrý dům
Wall tablet to controll your smart homeRating: 

Wall tablet or older smartphone is perfectly suited as a central indicator of the state of the home, as well as controlling it. It usually replaces the video doorbell and as example, you can play your favorite music or read recipes on it during cooking in your kitchen. In the article, we describe a functional example of such a "wall" tablet and its settings in so-called kiosk mode so, display doesn't run at night and only reacts when someone is nearby.

Jablotron and smarthome synchronization
Connecting Jablotron with OpenHABRating: 

In this article we will show you how to install Jablotron binding in OpenHAB. This binding helps us to synchronize states from Jablotron alarm to OpenHAB. Typically, you can force to switch off lights, close water pipe and circulation, switch off sockets or whatever you want to do when you leave home and set alarm.