// Perfect Thermostate with setpoint Push Buttons

// http://basicarduinotutorial.blogspot.com/2017/08/project-iii-7-thermostat-with-lcd-and-3.html

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

byte derajat[8] = {
0b01100,
0b10010,
0b10010,
0b01100,
0b00000,
0b00000,
0b00000,
0b00000
};

int adc,T,setPoint;
byte setSP, f_awal;
long lastButton = 0;
long delayAntiBouncing = 50;

void setup(){

pinMode(8,OUTPUT);              // Relay
pinMode(9,INPUT_PULLUP);        // Set Button
pinMode(10,INPUT_PULLUP);       // Up Button
pinMode(11,INPUT_PULLUP);       // Down Button

digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);

lcd.createChar(1, derajat);
lcd.init();
lcd.backlight();
lcd.print("T/C Controller");
lcd.setCursor(0, 1);
lcd.print("K-Type");
delay(2000);
lcd.clear();
//*******************************
setPoint=70;   //40      // By Defualt,that can be changed using push button
//******************************

}
void loop(){
lcd.setCursor(0,0);
lcd.print("SP=");
lcd.print(setPoint);
lcd.write(1);
lcd.setCursor(6,0);
lcd.print("*C");

//**********************************************
adc = analogRead(0);
T=(adc*5)/10;
//**********************************************

lcd.setCursor(8, 0);
lcd.print(" T=");
lcd.print(T);
lcd.write(1);
lcd.setCursor(14, 0);
lcd.print("*C");

if(T<(setPoint-1) || f_awal==0){
lcd.setCursor(0,1);
lcd.print("Device ON ");
digitalWrite(8,HIGH);
f_awal=1;

}

else if(T>=setPoint){
lcd.setCursor(0,1);
lcd.print("Device OFF");
digitalWrite(8,LOW);
}
tombol();
delay(100);
}
void tombol(){
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
if(digitalRead(9)==0){
lcd.clear();
lcd.print("New Set Point");
lcd.setCursor(9,0);
delay(1000);
lcd.clear();
setSP++;
//-----------------program looping seting set point
do{
if(digitalRead(9)==0){
if ((millis() - lastButton) > delayAntiBouncing){
setSP++;
}
lastButton = millis();
}
else if(digitalRead(10)==0){
if ((millis() - lastButton) > delayAntiBouncing){
setPoint++;
}
lastButton = millis();
}
else if(digitalRead(11)==0){
if ((millis() - lastButton) > delayAntiBouncing){
if (setPoint>0){
setPoint--;
}
}
lastButton = millis();
}
lcd.setCursor(0,0);
lcd.print("SP=");
lcd.print(setPoint);
lcd.write(1);
lcd.setCursor(6,0);
lcd.print(" *C");
}
while (setSP<2);
setSP=0;
f_awal=0;
lcd.clear();
lcd.print("Setpoint Saved!");
delay(1000);
lcd.clear();
}
}