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).


 

Hardware

Ultrasonic waterproof distance sensor JSN-SR04T

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

Software

OpenHAB

 

Application

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

*/


//MQTT
#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.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
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 192.168.4.101");
}
}


//-----------------------------------------------
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
client.subscribe("sensors");
}
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

client.loop();
}

// 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).
filter.in(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);
}
}
delay(1000);

}

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

 

OpenHAB

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
channels:
  - id: SW101
    channelTypeUID: mqtt:number
    label: WaterTank Litres Rain
    description: null
    configuration:
      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

Water Tank Level Measurement in your smartphone

 

 

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: {}
triggers:
  - id: "1"
    configuration:
      itemName: SW101
      state: ""
      previousState: ""
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      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: 4 (4 votes)

Support Us:

Add comment:

Add comment

Newest articles in blog

Tailscale - remote access without public IP
Tailscale - remote access without public IPRating: 
90%

The Tailscale service solves access between individual devices if you don't have a public IP address. It's free for one user with support for up to 100 devices. We'll show you how to install Tailscale on a Raspberry Pi that you'll have at home and on a client (Android, iPhone) from which you'll want to access the home Raspberry Pi. Our example will be remote access to OpenHAB running on a Raspberry Pi. However, the same setup applies to many other applications - home NAS, PiHole, Home Assistant, Domoticz, NextCloud, and others.

Shelly OpenHAB MQTT
Shelly vs OpenHABRating: 
90%

The Shelly brand is known for its products that primarily communicate over WiFi, including smart plugs, relay switches, blinds control relays, and many other devices. One of the advantages for deployment is the ability to both read and control these devices using the universal MQTT protocol. Across existing add-ons for both OpenHAB and Home Assistant, we will demonstrate how to use Shelly devices without installing any additional extensions.

Victron & OpenHAB
Victron vs Smart HomeRating: 
0%

In this post, we will show you how to retrieve information from a photovoltaic power plant by Victron. We will connect to the Cerbo unit via MQTT. Based on these values, we can control various appliances (heating, boiler, etc.) and prevent the battery from being drained when they don't need to be.

Smart Home GoodWe inverter
Smart Home vs GoodWeRating: 
50%

In the post, we will demonstrate step by step how to communicate directly with the GoodWe inverter in a smart home setup and obtain real-time information (unlike the SEMS portal). This information is essential if we want to react to current parameters in a smart home, such as activating additional cooling or controlling a socket with a various load.

Voice control smart home
Voice control of the houseRating: 
60%

In this article, we will connect the Amazon Echo Dot voice assistant with open source home automation. We won't be using OpenHAB Cloud, so everything runs locally. In this case, a few additional settings are necessary, but the result is worth it!

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

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: 
0%

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: 
80%

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: 
88%

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: 
50%

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