// Include necessary libraries
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define pin connections
#define TRIGGER_PIN 32
#define ECHO_PIN 33
#define RELAY_PIN 3
#define BUZZER_PIN 18
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// OLED display setup
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Blynk authentication token
char auth[] = "YourAuthToken";
// Your WiFi credentials
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";
// Variables to store water level and distance
long duration;
float distance;
float waterLevel;
const float maxDistance = 200.0; // Maximum distance your sensor can measure
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Initialize the OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 10);
display.println(F("Water Level Monitoring"));
display.display();
// Initialize pin modes
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Ensure pump is off initially
// Connect to WiFi and Blynk
WiFi.begin(ssid, pass);
Blynk.begin(auth, ssid, pass);
}
void loop() {
// Measure water level
measureWaterLevel();
// Display water level on OLED
displayWaterLevel();
// Send water level to Blynk app
Blynk.virtualWrite(V1, waterLevel);
// Control water pump based on water level
controlPump();
// Run Blynk
Blynk.run();
}
void measureWaterLevel() {
// Clear the trigger pin
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
// Sets the trigger pin on HIGH state for 10 microseconds
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Reads the echo pin, returns the sound wave travel time in microseconds
duration = pulseIn(ECHO_PIN, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
waterLevel = maxDistance - distance;
}
void displayWaterLevel() {
display.clearDisplay();
display.setCursor(0, 0);
display.print(F("Water Level: "));
display.print(waterLevel);
display.println(F(" cm"));
if (digitalRead(RELAY_PIN) == HIGH) {
display.println(F("Pump: ON"));
} else {
display.println(F("Pump: OFF"));
}
display.display();
}
void controlPump() {
// Thresholds for turning the pump on/off
const float upperThreshold = 180.0; // cm
const float lowerThreshold = 20.0; // cm
if (waterLevel < lowerThreshold) {
digitalWrite(RELAY_PIN, HIGH); // Turn pump on
} else if (waterLevel > upperThreshold) {
digitalWrite(RELAY_PIN, LOW); // Turn pump off
tone(BUZZER_PIN, 1000); // Alert with buzzer
delay(1000);
noTone(BUZZER_PIN);
}
}