#define BLYNK_TEMPLATE_ID "YOUR_TEMPLATE_ID"
#define BLYNK_DEVICE_NAME "Ultrasonic Water System"
#define BLYNK_AUTH_TOKEN "YOUR_AUTH_TOKEN"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#define TRIG_PIN 5
#define ECHO_PIN 18
#define RELAY_PIN 26
char ssid[] = "YOUR_WIFI_NAME";
char pass[] = "YOUR_WIFI_PASSWORD";
float tankHeight = 30.0;
long duration;
float distance;
float waterLevel;
float percentage;
bool autoMode = true;
bool motorState = false;
BLYNK_WRITE(V0) {
autoMode = param.asInt();
}
BLYNK_WRITE(V1) {
if (!autoMode) {
int value = param.asInt();
if (value == 1) turnMotorOn();
else turnMotorOff();
}
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH);
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
}
void loop() {
Blynk.run();
// Ultrasonic measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
waterLevel = tankHeight - distance;
if (waterLevel < 0) waterLevel = 0;
if (waterLevel > tankHeight) waterLevel = tankHeight;
percentage = (waterLevel / tankHeight) * 100;
Blynk.virtualWrite(V2, percentage);
if (autoMode) {
if (percentage < 20 && !motorState) {
turnMotorOn();
}
if (percentage > 90 && motorState) {
turnMotorOff();
Blynk.virtualWrite(V3, 1);
} else {
Blynk.virtualWrite(V3, 0);
}
}
}
void turnMotorOn() {
digitalWrite(RELAY_PIN, LOW);
motorState = true;
Blynk.virtualWrite(V1, 1);
}
void turnMotorOff() {
digitalWrite(RELAY_PIN, HIGH);
motorState = false;
Blynk.virtualWrite(V1, 0);
}
🧠 Code Explanation
1️⃣ BLYNK_WRITE(V0)
Controls Auto/Manual mode from dashboard.
If:
-
1 → Auto Mode
-
0 → Manual Mode
2️⃣ BLYNK_WRITE(V1)
Controls motor manually only when Auto mode is OFF.
3️⃣ Ultrasonic Measurement
distance = duration × 0.034 / 2
Converts echo time into distance.
4️⃣ Tank Percentage Calculation
percentage = (waterLevel / tankHeight) × 100
Calculates water percentage.
5️⃣ Dashboard Updates
Blynk.virtualWrite(V2, percentage);
Updates tank percentage display.
Blynk.virtualWrite(V3, 1);
Turns ON tank FULL LED.
6️⃣ Auto Mode Logic
If tank < 20%
→ Motor ON
If tank > 90%
→ Motor OFF + LED ON
📟 System Working Flow
-
ESP32 connects to WiFi
-
Connects to Blynk Cloud
-
Reads ultrasonic sensor
-
Calculates tank percentage
-
Checks mode
-
Controls motor
-
Updates dashboard
🎯 What Students Learn
-
Cloud-based IoT architecture
-
Virtual pin concept
-
Ultrasonic measurement logic
-
Remote automation system
-
Auto + Manual design
-
Real-world IoT implementation