#include <M2M_LM75A.h>

M2M_LM75A lm75a;

unsigned long previousTime = 0; // Variable to store the previous time
const unsigned long interval = 600000; // Interval in milliseconds (10 minutes)

float highestTemperature = -999; // Initialize highest temperature with a low value
float lowestTemperature = 999; // Initialize lowest temperature with a high value
float totalTemperature = 0; // Accumulator for calculating average
int temperatureCount = 0; // Counter for calculating average

bool inputAvailable = false; // Flag to indicate if user input is available
char userInput; // Variable to store user input

void setup() {
  lm75a.begin();
  Serial.begin(9600);
}

void loop() {
  // Check if user input is available
  if (Serial.available()) {
    userInput = Serial.read();
    inputAvailable = true;
  }

  unsigned long currentTime = millis(); // Get the current time

  // Check if it's time to record temperature
  if (currentTime - previousTime >= interval) {
    previousTime = currentTime; // Update the previous time

    float temperature = lm75a.getTemperature();
    updateStatistics(temperature);

    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
  }

  // Process user input if available
  if (inputAvailable) {
    processUserInput(userInput);
    inputAvailable = false; // Reset the flag
  }
}

void updateStatistics(float temperature) {
  // Update highest temperature
  if (temperature > highestTemperature) {
    highestTemperature = temperature;
  }

  // Update lowest temperature
  if (temperature < lowestTemperature) {
    lowestTemperature = temperature;
  }

  // Update total temperature and count
  totalTemperature += temperature;
  temperatureCount++;
}

void processUserInput(char input) {
  switch (input) {
    case 'H':
      Serial.print("Highest Temperature: ");
      Serial.print(highestTemperature);
      Serial.println(" °C");
      break;
    case 'L':
      Serial.print("Lowest Temperature: ");
      Serial.print(lowestTemperature);
      Serial.println(" °C");
      break;
    case 'A':
      if (temperatureCount > 0) {
        float overallAverageTemperature = totalTemperature / temperatureCount;
        Serial.print("Overall Average Temperature: ");
        Serial.print(overallAverageTemperature);
        Serial.println(" °C");
      } else {
        Serial.println("No temperature data available.");
      }
      break;
  }
}
