/*
  Automatic watering system
 
 created 30 Sep. 2017
 by Piotr Trembecki
 http://pino-tech.eu/
 
 This example code is in the public domain.
 
 */
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>


#define SOILWATCH_PIN             A0  //connect output of Soilwatch 10 to this analog pin (deafult A0)
#define PUMP_PIN                  2   //connect to pump mosfet
#define DOWN_PIN                  4   //Swap this two if buttons work in reverse
#define UP_PIN                    3   //Swap this two if buttons work in reverse
#define MIN_TIME_BETWEEN_WATERING 2   //minimum time between watering plant in seconds
#define MOISTURE_SET              0   //Set desired moisture level
#define WATER_FOR_SEC             5   //Set time for single watering in seconds


LiquidCrystal_I2C lcd(0x27, 16, 2);   // Set the LCD I2C address


void setup()
{

  pinMode ( UP_PIN, INPUT );
  pinMode ( DOWN_PIN, INPUT );

  //Set analog reference to internal 1.1V
  analogReference(INTERNAL);
  
  lcd.init();                      // initialize the lcd 
    // Print a message to the LCD.
  lcd.backlight();
  lcd.home ();                   // go home
  lcd.print("");  
  lcd.setCursor ( 0, 1 );        // go to the next line
  lcd.print ("  pino-tech.eu  ");
  delay ( 1000 );
}

void loop()
{
   lcd.home ();
   static int dontwaterfor = MIN_TIME_BETWEEN_WATERING*10;
   static int moistureSet = MOISTURE_SET;
   static int watering = 0;
   int analogValue = analogRead(SOILWATCH_PIN);
   int moisture = map(analogValue, 0, 1023, 0, 100);

   lcd.print("Moisture: ");
   lcd.print(moisture);
   lcd.print("%   ");


   int downButton = digitalRead(DOWN_PIN);
   int upButton = digitalRead(UP_PIN);
   if(downButton == HIGH)
   {
    if(moistureSet != 0) moistureSet--;
    delay(50);
   }

   if(upButton)
   {
    if(moistureSet != 100) moistureSet++;
    delay(50);
   }


  lcd.setCursor ( 0, 1 );        // go to the next line
  lcd.print ("MoistureSet: ");
  lcd.print (moistureSet);
  lcd.print ("     "); //space characters to erase previous characters from lcd
  
   

   if(dontwaterfor >= 1)dontwaterfor--;
   
   if(((moisture < moistureSet) && (!dontwaterfor)) || (watering))
   {

      if(watering == 0)watering = WATER_FOR_SEC*10;
      if(watering > 1){

        digitalWrite(PUMP_PIN, HIGH);
                
      }
      else
      { 
        digitalWrite(PUMP_PIN, LOW);
        dontwaterfor = MIN_TIME_BETWEEN_WATERING*10;
      }

      watering--;
   }
 
   delay (100);
}

