Im using the esp32s, an rtc3231 and an sd card
The overview of the project is:
I have 8 valves which i want to time for how long they have been on and save the times of each valve in an sd card. But how can I make it so that it writes in a different file for every valve.
The code is probably horrible sorry for that, but it is as follows
I've declared the pins in an array
int valvePins[8] = {0, 4, 15, 16, 17, 32, 34, 35};
int lastValveState[8];
then I set them as inputs and get their state in a forloop inside the void setup()
for (int i = 0; i < 8; i++) {
pinMode(valvePins[i], INPUT);
lastValveState[i] = digitalRead(valvePins[i]);
}
and in the void loop I use another for loop to go trough each pin and check if the state has changed, if it has then the code checks which valve its reading and writes it to the sd card and the time when the state has changed when it turns off then the time is also written to it.
void loop()
{
//RTC start
for (int i = 0; i < 8; i++)
{
int currentValveState = digitalRead(valvePins[i]);
if (currentValveState != lastValveState[i])
{
DateTime now = rtc.now();
if (currentValveState == HIGH){
myFile = SD.open("times.txt", FILE_WRITE);
if (myFile)
{
myFile.print("valve: ");
myFile.print(valvePins[i]);
// Format the time using sprintf
char timeBuffer[12];
sprintf(firsttimeBuffer, " %02u:%02u:%02u", now.hour(), now.minute(), now.second());
myFile.print(" ");
myFile.print(now.day());
myFile.print("/");
myFile.print(now.month());
myFile.print(" from ");
myFile.print(timeBuffer);
} else { Serial.println("error opening times.txt");}
}
else{
if (myFile) {
// Format the start time using sprintf
char startTimeBuffer[12];
sprintf(lastTimeBuffer, " %02u:%02u:%02u", now.hour(), now.minute(), now.second());
myFile.print(" to ");
myFile.println(startTimeBuffer);
myFile.close();
} else { Serial.println("error opening times.txt"); }
}
delay(100);
lastValveState[i] = currentValveState;
}
}
It is currently writing everything in the same file. To make it write in different ones i thought of just checking with if which valve it is and write in the file for that valve. Is there a shorter way of doing it?
Thanks in advance to everyone who is going to help! I'll be happy to explain further if i have missed somthing.