#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS_1 2 // DS18B20 temperature sensor CLT1
#define ONE_WIRE_BUS_2 3 // DS18B20 temperature sensor CLT2
#define FAN_PIN 11       // PWM output pin for FAN1
#define ANALOG_INPUT_PIN A0
#define ORS_PIN 19       // Input pin for fan control

#define FAN_ON 95        // Temperature threshold to turn on fan
#define FAN_OFF (FAN_ON - 10) // Temperature threshold to turn off fan
#define FAN_HIGH (FAN_ON + 10) // High temperature threshold for increased fan speed
#define FAN_HIGH_DUTY_CYCLE 95 // Duty cycle for increased fan speed
#define FAN_LOW_DUTY_CYCLE 40  // Duty cycle for normal fan speed

OneWire oneWire1(ONE_WIRE_BUS_1);
OneWire oneWire2(ONE_WIRE_BUS_2);
DallasTemperature sensor1(&oneWire1);
DallasTemperature sensor2(&oneWire2);

bool fanOverride = false;
int fanOverrideDutyCycle = 0;

void setup() {
  pinMode(ORS_PIN, INPUT_PULLUP);
  pinMode(FAN_PIN, OUTPUT);
  Serial.begin(9600);
  sensor1.begin();
  sensor2.begin();
}

void loop() {
  float temp1, temp2;
  bool validReading1 = false, validReading2 = false;

  // Read temperatures from sensors
  sensor1.requestTemperatures();
  sensor2.requestTemperatures();
  temp1 = sensor1.getTempCByIndex(0);
  temp2 = sensor2.getTempCByIndex(0);

  // Check if readings are valid
  if (temp1 >= -20 && temp1 <= 130) {
    validReading1 = true;
  }
  if (temp2 >= -20 && temp2 <= 130) {
    validReading2 = true;
  }

  // Calculate average temperature
  float avgTemp = -1;
  if (validReading1 && validReading2) {
    avgTemp = (temp1 + temp2) / 2;
  } else if (validReading1) {
    avgTemp = temp1;
  } else if (validReading2) {
    avgTemp = temp2;
  }

  // Check if fan should be controlled by temperature
  if (!fanOverride) {
    if (avgTemp >= FAN_ON) {
      analogWrite(FAN_PIN, FAN_LOW_DUTY_CYCLE);
    } else if (avgTemp <= FAN_OFF) {
      digitalWrite(FAN_PIN, LOW); // Fan should be off if temperature is below FAN_OFF threshold
    } else if (avgTemp >= FAN_HIGH) {
      analogWrite(FAN_PIN, FAN_HIGH_DUTY_CYCLE);
    } else {
      analogWrite(FAN_PIN, FAN_LOW_DUTY_CYCLE);
    }
  } else {
    analogWrite(FAN_PIN, fanOverrideDutyCycle);
  }

  // Check if fan control pin is pulled low
  if (digitalRead(ORS_PIN) == LOW) {
    int potValue = analogRead(ANALOG_INPUT_PIN);
    fanOverrideDutyCycle = map(potValue, 0, 1023, 0, 255);
    fanOverride = true;
  } else {
    fanOverride = false;
  }

  // Output to serial monitor
  Serial.print("Average Temperature: ");
  if (avgTemp != -1) {
    Serial.print(avgTemp);
    Serial.println(" C");
  } else {
    Serial.println("Invalid reading");
  }
  Serial.print("Fan Duty Cycle: ");
  if (fanOverride) {
    Serial.print(map(fanOverrideDutyCycle, 0, 255, 0, 100));
  } else {
    Serial.print(map(analogRead(FAN_PIN), 0, 1023, 0, 100));
  }
  Serial.println("%");
  delay(1000);
}
