IoT for Flood Detection & Early Warning System

Looking out for flood and early signs of it so you don’t have to

Muhammad Davin Dzimar
9 min readMar 25, 2023

During the 5th semester of my college, I took the newly opened Internet of Things class and included the course in my study plan. It was an elective and was mainly aimed towards final year students, but nonetheless I decided to take the class because I was interested. Fast forward about 2 months or so, after the midterms had passed, my classmates and I were tasked with developing an IoT-based system on our own as part of our final project. I was grouped with two other people in my class (shout out to Ima and Amel) to ideate and create the kind of system that needed to be built, at least up to producing a proof of concept that we can demonstrate.

And so, the three of us came up with a system that detects and raises a warning in the event of a flood or telltales signs of one, by implementing the concepts of IoT that we had learned so far.

The Problem

Flood is a pretty commonplace type of natural disasters, in fact, it is the most frequent one to happen around the world. With the potential to cause economic loss and loss of lives, it is a no brainer that technological efforts have been and should continue to be poured into forecasting these events better and ever faster. Even with the recorded incidents being increasingly frequent over the decades (perhaps due to climate change and increased human activities), technologies in aiding the prediction of and response to these incidents have also gotten increasingly more sophisticated. Thanks to that, we mostly were able to minimize the impacts as the years went by, especially in terms of fatalities.

With that said, Internet of Things is another piece of technology that we can fit into the picture of flood early warning and detection as well as, if not better suited than, any other kind of technology that has been put to use. Sensing, actuating, computing, and communicating among others, IoT possesses all these qualities that most definitely can be utilized in our particular predicament. So then, how exactly can we implement the concepts, principles, and ins-and-outs of IoT in the context of flood detection and early warning?

The Purpose

This final project was aimed and performed to fulfill these purposes:

  1. To develop a system that can detect an incoming flood by implementing IoT.
  2. To develop a system that can monitor the conditions of a body of water, especially a channel/stream, in the efforts of predicting the arrival of floods by implementing IoT.
  3. To develop a system that can communicate with other systems in the efforts of predicting the arrival of floods by implementing IoT.

The Requirement

My group defined the functional requirements that needed to be fulfilled by the system as follows:

  • it can measure the surface level of the water,
  • it can measure the flow rate of the water,
  • it can measure the temperature and humidity of the environment,
  • it can receive additional information about the weather from external source,
  • it can produce output that predicts whether a flood will happen or not,
  • it can re-route water in the event of clogging and potential overflowing but not so much as causing flood, and
  • it can raise an alert/warning in the event of imminent flood.

For the non-functional requirements, we defined them as follows:

  • it provides access 24/7,
  • it shall reliably measure temperature, humidity, water level, water flow rate and direction,
  • it shall never fail to alert users to the imminent occurrence of flood at the moment,
  • it can display the measurement values in no longer than 3 seconds,
  • it can be connected to using a smartphone, and
  • it shall guarantee the integrity of the data used and stored within.

The Design

Here are the core and necessary hardwares that we used to develop our system:

  1. ESP32 Microcontroller
  2. Ultrasonic sensor to measure water level.
  3. Potentiometer to serve as water flow sensor.
  4. Temperature & humidity sensor.
  5. Relay module connected to an AC water pump.
  6. Buzzer.
  7. LEDs.
  8. Power adapters.
  9. Wire connectors.

We then used a block diagram to model the conceptual hardware components and their relations in serving as the physical building blocks of our system.

Meanwhile for the software, we used Arduino as our main developing language and for the network standards, we used both Wi-Fi or IEEE 802.11n and Bluetooth Classic (as opposed to the Low-Energy variant). The Wi-Fi was used to publish the measurements taken to a ThingSpeak channel, while the Bluetooth was used to connect to another device using Serial Bluetooth Terminal.

ThingSpeak & Serial Bluetooth Terminal

For the proof-of-concept, we designed this sketch using Fritzing:

The Results

Here are some photos of the completed proof-of-concept of our system:

As you might have easily noticed, there are two ESP32 devices being used. The simple reason for that is the insufficiency of internal program memory that the microcontroller can hold. Too many peripherals that are connected to it proved to be too much for it to handle. That’s why we separated one function, that is to measure temperature and humidity, to a different ESP32 unit. The first ESP32 handled the brunt of the system’s functionalities and used the Bluetooth Classic as its mode of connectivity. Meanwhile the second ESP32 used Wi-Fi to connect to a ThingSpeak channel to publish its received measurements from the attached sensor.

Here is a link to a video demonstration for the first ESP32 in action:

For the second ESP32, I can only show screenshots of the dashboard containing the published data to the ThingSpeak platform:

The code sketch uploaded into the first ESP32 is as follows:

#include <BluetoothSerial.h>

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

String message = "";
char incomingChar;

const uint8_t trigPin = 26;
const uint8_t echoPin = 27;
const uint8_t relay = 18;
const uint8_t buzzer = 23;
const uint8_t potentio = 34;
const uint8_t led1 = 13;
const uint8_t led2 = 12;
const uint8_t led3 = 14;

#define SOUND_SPEED 0.03466 // speed of sound in air at around 26 degrees-Celsius

long duration;
float distanceCm;

uint16_t freq = 1000;
uint8_t channel0 = 0;
uint8_t channel1 = 1;
uint8_t channel2 = 2;
uint8_t channel3 = 3;
uint8_t resolution = 6;

String waterStatus;

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
SerialBT.begin("Weather Forecast Input ESP32");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relay, OUTPUT);
pinMode(buzzer, OUTPUT);
ledcSetup(channel0, freq, resolution);
ledcSetup(channel1, freq, resolution);
ledcSetup(channel2, freq, resolution);
ledcSetup(channel3, freq, resolution);
ledcAttachPin(buzzer, channel0);
ledcAttachPin(led1, channel1);
ledcAttachPin(led2, channel2);
ledcAttachPin(led3, channel3);
}

void loop() {
// put your main code here, to run repeatedly:
while (SerialBT.available()) {
char incomingChar = SerialBT.read();
if (incomingChar != '\n'){
message += String(incomingChar);
}
else{
message = "";
}
if (message == "hari_ini:cerah") {
ledcWrite(channel1, 63);
ledcWrite(channel2, 0);
ledcWrite(channel3, 0);
}
else if (message == "hari_ini:hujan_ringan_sedang") {
ledcWrite(channel2, 63);
ledcWrite(channel1, 0);
ledcWrite(channel3, 0);
}
else if (message == "hari_ini:hujan_deras_badai") {
ledcWrite(channel3, 63);
ledcWrite(channel1, 0);
ledcWrite(channel2, 0);
}
}

int flow = analogRead(potentio);
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;

Serial.println(flow);
Serial.print("Distance (cm): ");
Serial.println(distanceCm);

if (flow >= 1024 && distanceCm < 10){
String warning = "[WARNING: FLOOD INCOMING]";
Serial.println(warning);
SerialBT.println(warning);
while (flow >= 1024 && distanceCm < 10) {
digitalWrite(relay, HIGH);
for (int duty = 0; duty <= 63; duty++) {
ledcWrite(channel0, duty);
ledcWrite(channel1, duty);
ledcWrite(channel2, duty);
ledcWrite(channel3, duty);
delay(3);
}
for (int duty = 63; duty >= 0; duty--) {
ledcWrite(channel0, duty);
ledcWrite(channel1, duty);
ledcWrite(channel2, duty);
ledcWrite(channel3, duty);
delay(3);
}
flow = analogRead(potentio);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * SOUND_SPEED/2;
}
ledcWrite(channel1, 0);
ledcWrite(channel2, 0);
ledcWrite(channel3, 63);
}
else {
if (flow >= 1024 && distanceCm >= 10) {
waterStatus = "[NORMAL]";
ledcWrite(channel0, 0);
digitalWrite(relay, LOW);
}
else if (flow < 1024 && distanceCm < 10) {
waterStatus = "[POSSIBLE CLOGGING, WATER DUMPING IN PROGRESS...]";
digitalWrite(relay, HIGH);
ledcWrite(channel0, 0);
}
else if (flow < 1024 && distanceCm >= 10) {
waterStatus = "[NOTIFY CHECK FOR CLOGGING]";
digitalWrite(relay, LOW);
ledcWrite(channel0, 0);
}

Serial.print(F("Water Status -> "));
Serial.println(waterStatus);
SerialBT.println(waterStatus);
}

delay(1000);
}

Meanwhile, here is the code sketch that was uploaded to the second ESP32:

/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-temperature-humidity-sensor
*/

#include <DHT.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#define DHT_SENSOR_PIN 21 // ESP32 pin GIOP21 connected to DHT11 sensor
#define DHT_SENSOR_TYPE DHT11

DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);

const char* ssid = "CHANGE_TO_YOUR_SSID"; // your network SSID (name)
const char* password = "CHANGE_TO_YOUR_PASSWORD"; // your network password

WiFiClient client;

unsigned long myChannelNumber = CHANGE_TO_YOUR_CHANNEL_NUMBER;
const char * myWriteAPIKey = "CHANGE_TO_YOUR_CHANNEL_WRITE_API";

// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 20000;

void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
dht_sensor.begin(); // initialize the DHT sensor
Serial.println("Starting the BLE Server...");

if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
}

void loop() {
// read humidity
float humi = dht_sensor.readHumidity();
// read temperature in Celsius
float tempC = dht_sensor.readTemperature();
// read temperature in Fahrenheit
float tempF = dht_sensor.readTemperature(true);

// check whether the reading is successful or not
if ( isnan(tempC) || isnan(tempF) || isnan(humi)) {
Serial.println("Failed to read from DHT sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(humi);
Serial.print("%");

Serial.print(" | ");

Serial.print("Temperature: ");
Serial.print(tempC);
Serial.print("°C ~ ");
Serial.print(tempF);
Serial.println("°F");
}

if ((millis() - lastTime) > timerDelay) {
ThingSpeak.setField(1, tempC);
ThingSpeak.setField(2, tempF);
ThingSpeak.setField(3, humi);

int resp = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

if (resp == 200) {
Serial.println("OK");
}
else {
Serial.print("Error: ");
Serial.println(resp);
}

lastTime = millis();
}

// wait a 2 seconds between readings
delay(2000);
}

The Conclusion

It is possible to develop a flood detection and early warning system using the concepts found in IoT. Water flow rate, surface level, surrounding temperature and humidity are just examples of parameters that can be sensed in the efforts of determining whether a flood might take place. Of course, the project that my team and I undertook is far from perfect and many improvements can and should be made should this idea of ours be taken further, unto a more serious stage. Any criticism is welcomed, as long as it is constructive and contributes to the betterment of this proposed solution regarding the prediction and anticipation of flood using IoT.

References

https://www.who.int/health-topics/floods

https://www.bbc.com/indonesia/majalah-58498725

https://esp32io.com/tutorials/esp32-relay

https://esp32io.com/tutorials/esp32-temperature-humidity-sensor

https://randomnerdtutorials.com/esp32-thingspeak-publish-arduino/

--

--

Muhammad Davin Dzimar
0 Followers

Your average IT enjoyer looking for something meaningful to contribute to