#include <LiquidCrystal_I2C.h> 
LiquidCrystal_I2C lcd(0x27,16,2);
int aVal=0,tempaVal=0;
const int SW_ON = 2; 
const int led_ON =  13; int CSW_ON = 0; int C_CSW_ON =0;
int Relay1=12,Relay2=11,Relay3=10,Relay4=9;
int sensorPin = A0;
int sensorValue = 0;
void setup() {
  lcd.backlight();
  lcd.begin();
  Serial.begin(9600);
  pinMode(led_ON, OUTPUT);pinMode(SW_ON, INPUT);
  pinMode(Relay1,OUTPUT);pinMode(Relay2,OUTPUT);
  pinMode(Relay3,OUTPUT);pinMode(Relay4,OUTPUT);
//
  digitalWrite(Relay1,HIGH);digitalWrite(Relay2,HIGH);
  digitalWrite(Relay3,HIGH);digitalWrite(Relay4,HIGH);
  lcd.setCursor(0,0);
  lcd.print("Project2017");
  lcd.setCursor(0,1);
  lcd.print("standby");
}
//END Setup
void loop() {
  CSW_ON = digitalRead(SW_ON);
  sensorValue = analogRead(sensorPin);//Serial.println(sensorValue);
  //=======================================================================
  int c_sensorValue1 = map(sensorValue,0,1023,0,255);
  //Serial.print("c_sensorValue1 = ");Serial.println(c_sensorValue1);
  int c_sensorValue2 = map(sensorValue,0,1023,255,0);
  //Serial.print("c_sensorValue2 = ");Serial.println(c_sensorValue2);
  //=======================================================================
  //check SW_ON
  if (CSW_ON == LOW) { delay(1000);
    lcd.clear();
    C_CSW_ON++;
      Serial.print("C_CSW_ON = ");Serial.println(C_CSW_ON);
    //OPEN Project
    digitalWrite(led_ON, HIGH);
  //END check SW_ON
    if(C_CSW_ON == 1){
    lcd.setCursor(0,0);
    lcd.print("Power On ");
    delay(1000);
    lcd.clear();
    lcd.print("Power On ");
    delay(1000);
    lcd.clear();
    }
  }
  if(C_CSW_ON == 1){//OPEN PROJECT
    digitalWrite(led_ON, HIGH);
    //delay(1000);
    digitalWrite(Relay1, HIGH);
    //ตรวจสอบค่า VR================
      //lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(c_sensorValue1);
      lcd.print(" ");
      //==============================
      if(c_sensorValue1 >= 150){
      digitalWrite(Relay2, LOW);
      }else{
        digitalWrite(Relay2, HIGH);
        }
      //=============================
    //RelaySTART();
    }else{//OFF PROJECT
    lcd.setCursor(0,0);
    //lcd.print("Power Off");
    lcd.setCursor(0,1);
    lcd.print("standby");
    digitalWrite(led_ON, LOW); C_CSW_ON = 0;
    RelaySTOP();
    }
  }//END Loop
//======โปรแกรมย่อย==========
void RelaySTOP(){
digitalWrite(Relay1,HIGH);digitalWrite(Relay2,HIGH);
digitalWrite(Relay3,HIGH);digitalWrite(Relay4,HIGH);  
  }
void RelaySTART(){
digitalWrite(Relay1,LOW);digitalWrite(Relay2,LOW);
digitalWrite(Relay3,LOW);digitalWrite(Relay4,LOW); 
}  


