#include "ESP32Servo.h"

Servo myservo;  
#define Servo1Pin     19
#define ledWatringOn  2
#define ledEmg        15
#define button        12
#define speaker1      4


#define WaterOpen 180
#define WaterClose 0


int buttonState;
int IsEmg=0;

void setup() {
  // put your setup code here, to run once:
   myservo.attach(Servo1Pin); 
  
 
  pinMode(ledWatringOn,OUTPUT);
  pinMode(ledEmg,OUTPUT);
  
  pinMode(button, INPUT_PULLUP);
  pinMode(speaker1, OUTPUT);

  Serial.begin(115200);
  Serial.println("start program");

  digitalWrite(ledWatringOn, LOW);
  digitalWrite(ledEmg, LOW);


/*
  myservo.write(0); 
   Serial.println("Servo 0");  // close
  delay(3000);
   Serial.println("Servo 180");  // open
  myservo.write(180); 
  */

}

void loop() {


if (IsEmg!=1)
{
          digitalWrite(ledWatringOn, LOW);
          myservo.write(WaterClose);

          for(int i=0;i<10;i++)
          {
          Serial.println("Not watering");   
          buttonState = digitalRead(button);
                  if ( buttonState==0)
                  {
                  //Serial.println("Emg pressed");  
                  Serial.println("Stop"); 
                  myservo.write(WaterClose);
                  digitalWrite(ledWatringOn, LOW);
                  digitalWrite(ledEmg, HIGH);
                  IsEmg=1;
                  break;
                  }
                  if ( buttonState==1)
                  {
                    digitalWrite(ledEmg, LOW);
                  // Serial.println("Emg not pressed ");  
                    
                  }  
          delay(1000);
          }
}


if (IsEmg!=1)
{
digitalWrite(ledWatringOn, HIGH);
  myservo.write(WaterOpen);
 
  for(int i=0;i<5;i++)
  {
  Serial.println("watering");    
  buttonState = digitalRead(button);
          if ( buttonState==0)
          {
           //Serial.println("Emg pressed");  
           Serial.println("Stop"); 
           myservo.write(WaterClose);
           digitalWrite(ledWatringOn, LOW);
           digitalWrite(ledEmg, HIGH);
           IsEmg=1;
            break;
          }
           if ( buttonState==1)
          {
             digitalWrite(ledEmg, LOW);
           // Serial.println("Emg not pressed ");  
             
          }  
  delay(1000);
  }

} // if Emg=1

if (IsEmg==1)
    {

    Serial.println("System Stoped : Emg button pressed "); 
    for(;;)
      {
        tone(speaker1, 1700); // Send 1200KHz sound signal, which is a G tone
        delay(50);
        noTone(speaker1); // Stop sound
        delay(500);
      }
    }

  // put your main code here, to run repeatedly:
  delay(1000); // this speeds up the simulation
}