#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>

const int fanPin = 9;  
const int heaterPin = 10; 
const int tempSensorPin = A0; 

const int upperTempDefault = 25;
const int lowerTempDefault = 20;
const int hysteresis = 2;
const int tempDifference = 3; 

int upperTemp = upperTempDefault;
int lowerTemp = lowerTempDefault;

const byte ROW_NUM    = 4;
const byte COLUMN_NUM = 4;
char keys[ROW_NUM][COLUMN_NUM] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte pin_rows[ROW_NUM] = {2, 3, 4, 5}; 
byte pin_column[COLUMN_NUM] = {6, 7, 8, 9};

Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
LiquidCrystal_I2C lcd(0x27, 16, 2); 

void setup() {
  pinMode(fanPin, OUTPUT);
  pinMode(heaterPin, OUTPUT);
  
  lcd.begin(16, 2);
  lcd.print("Sicaklik Gir:");
  
  loadSettings();
}

void loop() {
  char key = keypad.getKey();
  
  if (key) {
    lcd.clear();
    lcd.print("Sicaklik Gir:");
    lcd.setCursor(0, 1);
    
    switch (key) {
      case 'A':
        lcd.print("Fan Sicakligi: ");
        upperTemp = readTemperature();
        break;
      case 'B':
        lcd.print("Isitici Sicakligi: ");
        lowerTemp = readTemperature();
        break;
      case '#':
        saveSettings();
        lcd.print("Saved!");
        delay(1000);
        lcd.clear();
        lcd.print("Sicaklik Gir:");
        break;
      default:
        break;
    }
    
    lcd.print(upperTemp);
    lcd.print("C - ");
    lcd.print(lowerTemp);
    lcd.print("C");
  }
  
  int currentTemp = readTemperature();
  
  if (currentTemp >= (upperTemp + hysteresis)) {
    digitalWrite(fanPin, HIGH);
  } else if (currentTemp <= (lowerTemp - hysteresis)) {
    digitalWrite(heaterPin, HIGH);
  }
  
  if (currentTemp <= (lowerTemp - tempDifference)) {
    digitalWrite(fanPin, LOW);
  }
  
  if (currentTemp >= (upperTemp + tempDifference)) {
    digitalWrite(heaterPin, LOW);
  }
}

int readTemperature() {
  int sensorValue = analogRead(tempSensorPin);
  float voltage = sensorValue * 5.0 / 1024.0;
  float temperatureC = (voltage - 0.5) * 100.0;
  return temperatureC;
}

void saveSettings() {
  EEPROM.put(0, upperTemp);
  EEPROM.put(sizeof(int), lowerTemp);
}

void loadSettings() {
  EEPROM.get(0, upperTemp);
  EEPROM.get(sizeof(int), lowerTemp);
}