#include <LiquidCrystal_I2C.h> // Biblioteca para LCD I2C
#include <RTClib.h> // Biblioteca para Relógio em Tempo Real
#include <Wire.h> // Biblioteca para comunicação I2C
#include <EEPROM.h>
#include "DHT.h"
#define LOG_OPTION 1 // Opção para ativar a leitura do log
#define SERIAL_OPTION 0 // Opção de comunicação serial: 0 para desligado, 1 para ligado
#define UTC_OFFSET -3 // Ajuste de fuso horário para UTC-3
// Configurações do DHT22
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Endereço de acesso: 0x3F ou 0x27
RTC_DS1307 RTC;
// Configurações da EEPROM
const int maxRecords = 100;
const int recordSize = 8; // Tamanho de cada registro em bytes
int startAddress = 0;
int endAddress = maxRecords * recordSize;
int currentAddress = 0;
int lastLoggedMinute = -1;
// Triggers de temperatura e umidade
float trigger_t_min = 20.0; // Exemplo: valor mínimo de temperatura
float trigger_t_max = 30.0; // Exemplo: valor máximo de temperatura
float trigger_u_min = 30.0; // Exemplo: valor mínimo de umidade
float trigger_u_max = 60.0; // Exemplo: valor máximo de umidade
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
dht.begin();
Serial.begin(9600);
lcd.init(); // Inicialização do LCD
lcd.backlight(); // Ligando o backlight do LCD
RTC.begin(); // Inicialização do Relógio em Tempo Real
RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
// RTC.adjust(DateTime(2024, 5, 6, 08, 15, 00)); // Ajustar a data e hora apropriadas uma vez inicialmente, depois comentar
EEPROM.begin();
}
void loop() {
DateTime now = RTC.now();
// Calculando o deslocamento do fuso horário
int offsetSeconds = UTC_OFFSET * 3600; // Convertendo horas para segundos
now = now.unixtime() + offsetSeconds; // Adicionando o deslocamento ao tempo atual
// Convertendo o novo tempo para DateTime
DateTime adjustedTime = DateTime(now);
if (LOG_OPTION) get_log();
// Verifica se o minuto atual é diferente do minuto do último registro
if (adjustedTime.minute() != lastLoggedMinute) {
lastLoggedMinute = adjustedTime.minute();
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
// Ler os valores de temperatura e umidade
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Verificar se os valores estão fora dos triggers
if (temperature < trigger_t_min || temperature > trigger_t_max || humidity < trigger_u_min || humidity > trigger_u_max) {
// Converter valores para int para armazenamento
int tempInt = (int)(temperature * 100);
int humiInt = (int)(humidity * 100);
// Escrever dados na EEPROM
EEPROM.put(currentAddress, now.unixtime());
EEPROM.put(currentAddress + 4, tempInt);
EEPROM.put(currentAddress + 6, humiInt);
// Atualiza o endereço para o próximo registro
getNextAddress();
}
}
if (SERIAL_OPTION) {
Serial.print(adjustedTime.day());
Serial.print("/");
Serial.print(adjustedTime.month());
Serial.print("/");
Serial.print(adjustedTime.year());
Serial.print(" ");
Serial.print(adjustedTime.hour() < 10 ? "0" : ""); // Adiciona zero à esquerda se hora for menor que 10
Serial.print(adjustedTime.hour());
Serial.print(":");
Serial.print(adjustedTime.minute() < 10 ? "0" : ""); // Adiciona zero à esquerda se minuto for menor que 10
Serial.print(adjustedTime.minute());
Serial.print(":");
Serial.print(adjustedTime.second() < 10 ? "0" : ""); // Adiciona zero à esquerda se segundo for menor que 10
Serial.print(adjustedTime.second());
Serial.print("\n");
}
lcd.setCursor(0, 0);
lcd.print("DATA: ");
lcd.print(adjustedTime.day() < 10 ? "0" : ""); // Adiciona zero à esquerda se dia for menor que 10
lcd.print(adjustedTime.day());
lcd.print("/");
lcd.print(adjustedTime.month() < 10 ? "0" : ""); // Adiciona zero à esquerda se mês for menor que 10
lcd.print(adjustedTime.month());
lcd.print("/");
lcd.print(adjustedTime.year());
lcd.setCursor(0, 1);
lcd.print("HORA: ");
lcd.print(adjustedTime.hour() < 10 ? "0" : ""); // Adiciona zero à esquerda se hora for menor que 10
lcd.print(adjustedTime.hour());
lcd.print(":");
lcd.print(adjustedTime.minute() < 10 ? "0" : ""); // Adiciona zero à esquerda se minuto for menor que 10
lcd.print(adjustedTime.minute());
lcd.print(":");
lcd.print(adjustedTime.second() < 10 ? "0" : ""); // Adiciona zero à esquerda se segundo for menor que 10
lcd.print(adjustedTime.second());
delay(1000);
}
void getNextAddress() {
currentAddress += recordSize;
if (currentAddress >= endAddress) {
currentAddress = 0; // Volta para o começo se atingir o limite
}
}
void get_log() {
Serial.println("Data stored in EEPROM:");
Serial.println("Timestamp\t\tTemperature\tHumidity");
for (int address = startAddress; address < endAddress; address += recordSize) {
long timeStamp;
int tempInt, humiInt;
// Ler dados da EEPROM
EEPROM.get(address, timeStamp);
EEPROM.get(address + 4, tempInt);
EEPROM.get(address + 6, humiInt);
// Converter valores
float temperature = tempInt / 100.0;
float humidity = humiInt / 100.0;
// Verificar se os dados são válidos antes de imprimir
if (timeStamp != 0xFFFFFFFF) { // 0xFFFFFFFF é o valor padrão de uma EEPROM não inicializada
//Serial.print(timeStamp);
DateTime dt = DateTime(timeStamp);
Serial.print(dt.timestamp(DateTime::TIMESTAMP_FULL));
Serial.print("\t");
Serial.print(temperature);
Serial.print(" C\t\t");
Serial.print(humidity);
Serial.println(" %");
}
}
}