#include <Adafruit_CircuitPlayground.h>
#include <Adafruit_Circuit_Playground.h>
#include <Adafruit_PCT2075.h>

#define RELAY_PIN A2               // Relay pin that controls the heating pad
const int motorPin = A1;           //Define motor control pins
const float alertTempHigh = 22;  // High Temp
const float alertTempLow = 20;   // Low Temp

Adafruit_PCT2075 PCT2075;
bool heatPadActive = false;

void setup() {
  Serial.begin(9600);
  PCT2075 = Adafruit_PCT2075();
  if (!PCT2075.begin()) {
    Serial.println("Couldn't find PCT2075 chip");
    while (1);
  }
  CircuitPlayground.begin();
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(motorPin, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  digitalWrite(motorPin, LOW);  //Initialization state
  Serial.println("ready");
}

void loop() {
  float internalTemp = CircuitPlayground.temperature();  // Read the temperature of the built-in temperature sensor
  float heatPadTemp = PCT2075.getTemperature();          // Read the temperature from PCT2075

  Serial.print("Internal Temperature: ");
  Serial.print(internalTemp);
  Serial.print(" °C, Heat Pad Temperature: ");
  Serial.print(heatPadTemp);
  Serial.println(" °C");

  if (internalTemp < alertTempLow && !heatPadActive) {
    Serial.println("heating");
    digitalWrite(RELAY_PIN, HIGH);  // heat pad turn on
    heatPadActive = true;
  } else if (heatPadTemp >= 30 && heatPadActive) {
    Serial.println("Heating pad turning OFF");
    digitalWrite(RELAY_PIN, LOW);// heat pad turn off
    heatPadActive = false;

  }

  if (internalTemp > alertTempHigh) {
    Serial.println("Fan: ON");
    digitalWrite(motorPin, HIGH);// If the temperature is above 22°C, the motor starts to turn.
  } else if (internalTemp < alertTempLow) {
    Serial.println("Fan: OFF");
    digitalWrite(motorPin, LOW);// If the temperature is below 20°C, the motor stops running.
  }
  
  delay(1000);  // Update once per second
}
