#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define TRIG_PIN 5
#define ECHO_PIN 18
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const int tankHeight = 100; // Change this value based on your tank's height in cm
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
}
void loop() {
long duration;
float distance, waterLevel;
// Trigger Ultrasonic Sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure Echo Time
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration * 0.0343) / 2; // Convert time to distance (cm)
// Calculate Water Level
waterLevel = tankHeight - distance; // Assuming sensor is at top
if (waterLevel < 0) waterLevel = 0;
if (waterLevel > tankHeight) waterLevel = tankHeight;
// Display on OLED
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("Water Level:");
display.setCursor(0, 30);
display.print(waterLevel);
display.print(" cm");
display.display();
Serial.print("Water Level: ");
Serial.print(waterLevel);
Serial.println(" cm");
delay(1000);
}