#include <SD.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
File dataFile;
const int chipSelect = 10; // SD card chip select pin
const int primaryLED = 3;
const int secondaryLED = 4;
const int tertiaryLED = 5;
void setup() {
Serial.begin(9600);
// Set up LED pins as output
pinMode(primaryLED, OUTPUT);
pinMode(secondaryLED, OUTPUT);
pinMode(tertiaryLED, OUTPUT);
// Initialize the SD card
if (!SD.begin(chipSelect)) {
Serial.println("SD card initialization failed!");
return;
}
// Initialize the RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set to compile time
}
}
void loop() {
DateTime now = rtc.now();
char currentTime[20];
snprintf(currentTime, sizeof(currentTime), "%02d-%02d-%04d %02d:%02d:%02d",
now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
// Open the CSV file
dataFile = SD.open("schedule.csv");
if (!dataFile) {
Serial.println("Failed to open schedule file!");
return;
}
// Parse the CSV file line by line
while (dataFile.available()) {
String line = dataFile.readStringUntil('\n');
line.trim(); // Remove any newline or whitespace characters
// Skip empty lines
if (line.length() == 0) continue;
// Parse DateTime and load values from the line
int comma1 = line.indexOf(',');
int comma2 = line.indexOf(',', comma1 + 1);
int comma3 = line.indexOf(',', comma2 + 1);
String dateTime = line.substring(0, comma1);
int primaryLoad = line.substring(comma1 + 1, comma2).toInt();
int secondaryLoad = line.substring(comma2 + 1, comma3).toInt();
int tertiaryLoad = line.substring(comma3 + 1).toInt();
// Check if DateTime matches the current time
if (dateTime.equals(currentTime)) {
digitalWrite(primaryLED, primaryLoad);
digitalWrite(secondaryLED, secondaryLoad);
digitalWrite(tertiaryLED, tertiaryLoad);
Serial.print("Time: ");
Serial.print(currentTime);
Serial.print(" - Primary: ");
Serial.print(primaryLoad);
Serial.print(" - Secondary: ");
Serial.print(secondaryLoad);
Serial.print(" - Tertiary: ");
Serial.println(tertiaryLoad);
break; // Break once the line for the current time is found
}
}
dataFile.close(); // Close the CSV file
delay(1000); // Wait 1 second before checking again
}