#include <EEPROM.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,14,27,26,25,33);

long duration, inches;
int set_val,percentage;
bool state,pump;

void setup() {
  lcd.begin(20, 4);
  lcd.print("NAVANATH ELECTRICAL:");
  lcd.setCursor(0, 1);
  lcd.print("WATER LEVEL:");
  lcd.setCursor(0, 2);
  lcd.print("PUMP:OFF MANUAL");
  
  pinMode(21, OUTPUT);
  pinMode(22, INPUT);
  pinMode(23, INPUT_PULLUP);
  pinMode(19, INPUT_PULLUP);
  pinMode(5, OUTPUT);
  set_val=EEPROM.read(0);
  if(set_val>150)set_val=150;
}
   void loop() {
     digitalWrite(14, LOW);
     delayMicroseconds(2);
     digitalWrite(21, HIGH);
   delayMicroseconds(10);
   digitalWrite(21, LOW);
   duration = pulseIn(22, HIGH);
   inches = microsecondsToInches(duration);
   percentage=(set_val-inches)*100/set_val;
   lcd.setCursor(12, 1);
   if(percentage<0)percentage=0;
   lcd.print(percentage);
   lcd.print("%   ");
   if(percentage<30&digitalRead(19))pump=1;
   if(percentage>90)pump=0;
   digitalWrite(5,!pump);
   
   lcd.setCursor(5, 2);
   if(pump==1)lcd.print("ON ");
   else if(pump==0) lcd.print("OFF");
   lcd.setCursor(9, 2);
   if(!digitalRead(19))lcd.print("MANUAL");
   else lcd.print("AUTO   ");
   
   if(!digitalRead(23)&!state&digitalRead(19)){
     state=1;
     set_val=inches;
     EEPROM.write(0, set_val);
     }
     
     if(!digitalRead(23)&!state&!digitalRead(19)){
       state=1;
       pump=!pump;
       }
       if(digitalRead(23))state=0;
       delay(500);
       }
       long microsecondsToInches(long microseconds) {
         return microseconds / 74 / 2;
         }