/*
Smart Water Tank Management System
Working Principle:
This program uses an ultrasonic sensor to measure water level in a tank.
The ESP32 sends data to ThingSpeak using its Wi-Fi capability.
The data is visualized in a line chart on ThingSpeak.
Hardware Required:
- ESP32
- HC-SR04 ultrasonic sensor
- Jumper wires
- Breadboard
*/
// Include necessary libraries
#include <WiFi.h>
#include <HTTPClient.h>
// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
const char* password = ""; // Replace with your Wi-Fi password
// ThingSpeak settings
const char* server = "http://api.thingspeak.com/update";
String apiKey = "NX09U7D677P2EDJS"; // Replace with your ThingSpeak Write API Key
// Ultrasonic sensor pins
const int trigPin = 13; // Trigger pin connected to GPIO 5
const int echoPin = 12; // Echo pin connected to GPIO 18
// Tank dimensions (in cm)
const int tankHeight = 400; // Maximum height of the tank in cm
void setup() {
Serial.begin(115200); // Start serial communication for debugging
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
// Connect to Wi-Fi
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
}
void loop() {
// Measure water level
float waterLevel = getWaterLevel();
Serial.print("Water Level: ");
Serial.print(waterLevel);
Serial.println(" cm");
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey + "&field1=" + String(waterLevel);
http.begin(url); // Start connection
int httpCode = http.GET(); // Send HTTP GET request
if (httpCode > 0) {
Serial.println("Data sent to ThingSpeak");
} else {
Serial.println("Error sending data");
}
http.end(); // End connection
} else {
Serial.println("Wi-Fi Disconnected");
}
delay(15000); // Send data every 15 seconds
}
// Function to calculate water level
float getWaterLevel() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
float distance = (duration * 0.0343) / 2;
// Calculate water level
float waterLevel = tankHeight - distance;
if (waterLevel < 0) {
waterLevel = 0; // Ensure water level doesn't go below zero
} else if (waterLevel > tankHeight) {
waterLevel = tankHeight; // Ensure water level doesn't exceed the tank height
}
return waterLevel;
}