I am working on a project where when the device will record the time it is "turned on", via an on/off button, where there is a loopRunning variable that is toggled so that on the first press, the device turns off, and on the next press, it turns off and so on. Hence, there are two if statements: one of them gathers the time when the device first turns on, and the other is for all the things the Arduino will do after it is "turned on".
In the first if statement, I record startTime and the subsequent print statements show that this startTime is indeed the time when the device was first turned on. However, as soon as I step out of the if statement or into another if statement, I am getting completely incorrect values for startTime--no matter what startTime actually was, startTime.minutes(), DEC was always 28, and for day it was always 6.
So, is there a way I can get the correct values for startTime outside of the if statement? Below is the code I am using:
#include <RTClib.h>
#include <Wire.h>
#include <Adafruit_I2CDevice.h>
RTC_DS1307 rtc;
boolean loopRunning = false;
int onoffState = 0;
int prevOnoff = 0;
//pausing intervals - minutes
const int timeWater = 10;
//Define blank variables
DateTime startTime = (0,0,0,0,0,0);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(onoff, INPUT);
if(! rtc.begin()){
Serial.println("Couldnt find RTC");
while(1);
}
if(! rtc.isrunning()){
Serial.println("RTC is NOT running!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
// put your main code here, to run repeatedly:
onoffState = digitalRead(onoff);
//When device is turned on - gets correct startTime values
if((onoffState==HIGH)&&(loopRunning==false)) {
DateTime startTime = rtc.now();
Serial.println(startTime.month(), DEC);
Serial.print('/');
Serial.print(startTime.day(), DEC);
Serial.print('/');
Serial.print(startTime.minute());
}
//Everything below returns incorrect values for startTime
Serial.println(startTime.day(), DEC);
//Running everything else once device is on
if (loopRunning) {
Serial.println(startTime.minute(), DEC);
}
Serial.println(onoffState);
//Turning on and off
if((onoffState==LOW)&&(prevOnoff==HIGH)) {
loopRunning = !loopRunning;
Serial.println(loopRunning);
}
prevOnoff = onoffState;
}
Any help would be much appreciated, thanks!