#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

const int trigPin = 9;
const int echoPin = 10;

// Tank height in cm
const int TANK_HEIGHT_CM = 30;

// Variables 
long duration;
int distance;
int waterLevel;
int percentFull;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {

   if(!display.begin(SSD1306_I2C_ADDRESS, OLED_RESET)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }
  
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.display();
  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
 
  Serial.begin(9600); 
}

void loop() {
  
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
 
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  waterLevel = TANK_HEIGHT_CM - (distance + 5); //5cm for the gap between the water (when full) and the ultrasonic sensor

  waterLevel = waterLevel + 10;

  
  percentFull = (waterLevel * 100) / TANK_HEIGHT_CM;

 

  if(waterLevel < 1){
    waterLevel = 0;
  }

  if(percentFull < 1){
    percentFull = 0;
  }

 
 display.clearDisplay();
 display.setCursor(40, 10);
 display.setTextColor(SSD1306_WHITE);
 display.setTextSize(2);
 display.print("Water Level:");
 display.setCursor(40, 50);
 display.setTextSize(3);
 display.print(percentFull);
 display.println("%");
 display.display();
  //you can also add a snippet where if the water level is 100%, then the water pump is turned off
  //and back on when it is below a certain threshold (say 80%).
 
  delay(10);
}
