const int startTime = 1211;
const unsigned long startMillis = 1547;
int millisToHourMin(int startTime, unsigned long startMillis=0){
//since millis() returns an unsigned long, it will roll over in about 90 days
//by defining nextMillis as unsigned long also, it should roll over 1 second in advance of millis() rollover
static unsigned long nextMillis;
if (nextMillis == 0){ //initializer nextMillis
nextMillis = millis();
}
static int time; //will hold the number of seconds since reset (corrected for start without reset using startMillis)
int seconds; //hold intermediate results of calculation
int sec; //seconds since startMillis
int min; //minutes since startMillis
int hrs; //hours since startMillis
int startSeconds; //derived from startTime
int startHours; //derived from startTime
int startMin; //derived from startTime
int newMin; //new minutes, corrected for startTime
int newHours; //new hours, corrected for startTime
static int newTime; //time to return, in format newHours * 100 + newMin
const int SECONDS_PER_MINUTE = 60;
const int MINUTES_PER_HOUR = 60;
const int HOURS_PER_DAY = 24;
const int MILLIS_PER_SECOND = 1000;
if(millis() >= nextMillis) {
nextMillis += MILLIS_PER_SECOND; //execute this if once per second
time++; //number of seconds since reset
startSeconds = startMillis / MILLIS_PER_SECOND; //allow for non-reset time setting
seconds = time - startSeconds; // this should never go negative, corrected for time setting without reset
sec = seconds % SECONDS_PER_MINUTE;
seconds /= SECONDS_PER_MINUTE;
min = seconds % MINUTES_PER_HOUR;
seconds /= MINUTES_PER_HOUR;
hrs = seconds % HOURS_PER_DAY;
seconds /= HOURS_PER_DAY;
//Serial.println(time);
startHours = startTime / 100; // startTime is formatted as an integer = hours * 100 + minutes, so 1:51 pm is 1351
startMin = startTime % 100;
newMin = min + startMin;
if (newMin >= MINUTES_PER_HOUR){
newMin = newMin - MINUTES_PER_HOUR;
hrs++;
}
newHours = hrs + startHours;
if (newHours >= HOURS_PER_DAY){
newHours = newHours - HOURS_PER_DAY;
}
newTime = newHours * 100 + newMin;
}
return newTime;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int myTime = millisToHourMin(startTime, startMillis);
Serial.print("calculated time =");
Serial.println(myTime);
delay(1000);
}