/*
Wokwi | questions
can someone help me with this project please?
Lach$ff — 6/20/24 at 11:44 AM
https://wokwi.com/projects/401226418170277889
*/

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

#define TEMP_SENSOR_PIN A0
#define LDR_SENSOR_PIN A1
#define LED_RED_PIN 3
#define BEEP_PIN 2
#define NUM_LEDS 10
#define EEPROM_SIZE 900

LiquidCrystal_I2C lcd(0x27, 16, 2);
int ledPins[NUM_LEDS] = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4};
float temperatureSum = 0;
int lightSum = 0;
int readCount = 0;
int eepromIndex = 0;

void setup() {
  Serial.begin(115200);
  //pinMode(TEMP_SENSOR_PIN, INPUT);
  //pinMode(LDR_SENSOR_PIN, INPUT);
  pinMode(LED_RED_PIN, OUTPUT);
  pinMode(BEEP_PIN, OUTPUT);
  
  for (int i = 0; i < NUM_LEDS; i++) {
    pinMode(ledPins[i], OUTPUT);
  }

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("BlueShield");
  lcd.setCursor(0, 1);
  lcd.print("Inicializando...");
  delay(2000);
  lcd.clear();
}

void loop() {
  float temperature = readTemperature();
  int light = analogRead(LDR_SENSOR_PIN);

  Serial.print("Temp: ");
  Serial.println(temperature);
  Serial.print("Light: ");
  Serial.println(light);

  temperatureSum += temperature;
  lightSum += light;
  readCount++;
  
  if (readCount == 30) {
    float avgTemp = temperatureSum / 30.0;
    float avgLight = (lightSum / 30.0) / 10.23;
    
    if (avgTemp > 23.0) {
      digitalWrite(LED_RED_PIN, HIGH);
      tone(BEEP_PIN, 1000, 500);
      storeData(avgTemp, avgLight);
    } else {
      digitalWrite(LED_RED_PIN, LOW);
      noTone(BEEP_PIN);
    }
    
    updateDisplay(avgTemp, avgLight);
    updateLedBar(avgLight);
    
    temperatureSum = 0;
    lightSum = 0;
    readCount = 0;
  }
  
  delay(2000);
}

float readTemperature() {
  int analogValue = analogRead(TEMP_SENSOR_PIN);
  float voltage = analogValue * (5.0 / 1023.0);
  float temperature = (voltage - 0.5) * 100.0;
  return temperature;
}

void storeData(float temp, float light) {
  if (eepromIndex + 4 > EEPROM_SIZE) {
    eepromIndex = 0;
  }
  
  EEPROM.put(eepromIndex, temp);
  EEPROM.put(eepromIndex + 2, light);
  eepromIndex += 4;
}

void updateDisplay(float temp, float light) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temp: ");
  lcd.print(temp);
  lcd.print(" C");
  lcd.setCursor(0, 1);
  lcd.print("Luz: ");
  lcd.print(light);
  lcd.print(" %");
}

void updateLedBar(float light) {
  int numLedsOn = (light / 100.0) * NUM_LEDS;
  
  for (int i = 0; i < NUM_LEDS; i++) {
    if (i < numLedsOn) {
      digitalWrite(ledPins[i], HIGH);
    } else {
      digitalWrite(ledPins[i], LOW);
    }
  }
}
$abcdeabcde151015202530354045505560fghijfghij