#include <LiquidCrystal_I2C.h>
// LCD
LiquidCrystal_I2C lcd(0x27,16,2);
// Ultrasonic sensor
const int trigPin = 5;
const int echoPin = 18;
// TDS potentiometer
const int tdsPin = 34;
// Tank height in cm
const float tankHeight = 400.0;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Ground Tank ESP");
delay(2000);
lcd.clear();
}
float getWaterLevel() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2.0; // cm
float levelPercent = constrain(100 - ((distance / tankHeight) * 100), 0, 100);
return levelPercent;
}
float getTDS() {
int val = analogRead(tdsPin);
return map(val, 0, 4095, 0, 1000); // ppm
}
void loop() {
float level = getWaterLevel();
float tds = getTDS();
// Display on LCD
lcd.setCursor(0,0);
lcd.print("Lvl: ");
lcd.print(level,1);
lcd.print("% ");
lcd.setCursor(0,1);
lcd.print("TDS: ");
lcd.print(tds,0);
lcd.print("ppm ");
// Serial output
Serial.print("Ground Tank Level: ");
Serial.print(level,1);
Serial.print("%, TDS: ");
Serial.println(tds,0);
delay(2000);
}