#include <Wire.h>
#include <RTClib.h>
#include <SD.h>
#include <EEPROM.h>
#include "EmonLib.h"
const int chipSelect = 10;
RTC_DS3231 rtc;
// Define the pin to which the current sensor is connected
const int pinSensorCorriente = A0;
bool monitorizar = true;
unsigned long intervaloLectura = 1000; // Default time interval in milliseconds
unsigned long ultimaLectura = 0; // Variable for interval handling
EnergyMonitor emon1;
void setup() {
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("RTC module not found. Please check the connection.");
while (1);
}
if (!SD.begin(chipSelect)) {
Serial.println("Couldn't initialize the SD card. Please check the connection.");
while (1);
}
// Initialize the current sensor
emon1.current(pinSensorCorriente, 30); // Calibration: 30 for ZHT103 sensor (adjust according to sensor specifications)
// Print the current time and the initial interval
imprimirHoraActual();
cargarIntervaloDesdeEEPROM();
imprimirIntervaloActual();
}
void loop() {
if (Serial.available() > 0) {
String instruccion = Serial.readStringUntil('\n');
ejecutarInstruccion(instruccion);
}
if (monitorizar && millis() - ultimaLectura >= intervaloLectura) {
ultimaLectura = millis(); // Update the time of the last reading
// Measure the current
double corriente = emon1.calcIrms(1480); // 1480 is the number of samples (adjust according to your needs)
DateTime now = rtc.now();
String datosCSV = construirDatosCSV(now, corriente);
Serial.println(datosCSV);
// Open or create the CSV file
File datosFile = SD.open("datos.csv", FILE_WRITE);
if (!datosFile) {
// If the file doesn't exist, try to create it
datosFile = SD.open("datos.csv", FILE_WRITE);
}
// Handle errors in file opening
if (datosFile) {
escribirEnArchivo(datosFile, datosCSV);
} else {
Serial.println("Error opening or creating the file.");
}
}
}
void ejecutarInstruccion(String instruccion) {
instruccion.trim();
if (instruccion == "STOP_MONITOR") {
Serial.println("Stopping monitoring.");
monitorizar = false;
} else if (instruccion == "EJECT_SD") {
Serial.println("Ejecting the SD card safely.");
SD.end();
} else if (instruccion.startsWith("SET_RTC")) {
instruccion.remove(0, 8); // Remove "SET_RTC" from the beginning
setearRTC(instruccion);
} else if (instruccion.startsWith("SET_INTERVAL")) {
instruccion.remove(0, 12); // Remove "SET_INTERVAL" from the beginning
intervaloLectura = instruccion.toInt() * 1000; // Convert to milliseconds
guardarIntervaloEnEEPROM();
Serial.println("Reading interval updated to " + String(intervaloLectura / 1000) + " seconds.");
} else if (instruccion == "RESUME_MONITOR") {
Serial.println("Resuming monitoring.");
monitorizar = true;
} else if (instruccion == "STATUS") {
mostrarStatus();
} else {
Serial.println("Unrecognized instruction.");
}
}
void setearRTC(String fechaHora) {
int day = fechaHora.substring(0, 2).toInt();
int month = fechaHora.substring(3, 5).toInt();
int year = fechaHora.substring(6, 10).toInt();
int hour = fechaHora.substring(11, 13).toInt();
int minute = fechaHora.substring(14, 16).toInt();
int second = fechaHora.substring(17, 19).toInt();
DateTime nuevaFechaHora(year, month, day, hour, minute, second);
rtc.adjust(nuevaFechaHora);
Serial.println("RTC date and time adjusted successfully.");
}
void mostrarStatus() {
Serial.println("Current configuration:");
imprimirHoraActual();
imprimirIntervaloActual();
Serial.println("STOP_MONITOR");
Serial.println("EJECT_SD");
Serial.println("SET_RTC DD MM YYYY HH:MM:SS");
Serial.println("SET_INTERVAL X");
Serial.println("RESUME_MONITOR");
Serial.println("STATUS");
}
void imprimirHoraActual() {
DateTime now = rtc.now();
Serial.print("Current time: ");
Serial.print(now.day());
Serial.print("/");
Serial.print(now.month());
Serial.print("/");
Serial.print(now.year());
Serial.print(" ");
Serial.print(now.hour());
Serial.print(":");
Serial.print(now.minute());
Serial.print(":");
Serial.println(now.second());
}
void imprimirIntervaloActual() {
Serial.print("Current reading interval: ");
Serial.println(intervaloLectura / 1000); // Convert to seconds
}
void escribirEnArchivo(File& datosFile, String datosCSV) {
// Write to the file and close it
datosFile.println(datosCSV);
datosFile.close();
}
String construirDatosCSV(DateTime now, double corriente) {
return String(now.day()) + "/" +
String(now.month()) + "/" +
String(now.year()) + "," +
String(now.hour()) + ":" +
String(now.minute()) + ":" +
String(now.second()) + "," +
String(corriente, 3); // Adjust the number of decimals as needed
}
void guardarIntervaloEnEEPROM() {
EEPROM.put(0, intervaloLectura);
}
void cargarIntervaloDesdeEEPROM() {
EEPROM.get(0, intervaloLectura);
}