carduinoarduino-uno

Creating a time based system—hours minutes seconds


I'm currently trying Arduino C and trying to figure out the best way to convert the given added values into the correct seconds, minutes, and hours. I'm aware this needs division and modulo; it's just that I'm not sure where. How would I go about doing this?

This is my code:

void setup() {

int swimhours=0;
int swimmins=50;
int swimsecs=59;
int bikehours=2;
int bikemins=50;
int bikesecs=59;
int runhours=1;
int runmins=50;
int runsecs=59;

int totalhours=swimhours+bikehours+runhours;
int totalmins=swimmins+bikemins+runmins;
int totalsecs=swimsecs+runsecs+bikesecs;`

int completehours
int completemins
int completesecs

serial.print
}

void loop() {

}

I need the values of the above to be added (which is the total) and then I need the conversion in the complete variables.


Solution

  • The "trick" is to work in seconds.


    These are durations, so we don't have to worry about time zones or Daylight-Savings Time, etc. Good.

    First, convert everything to seconds.

    swimmins += swimhours * 60u;
    swimsecs += swimmins * 60u;
    
    bikemins += bikehours * 60u;
    bikesecs += bikemins * 60u;
    
    runmins += runhours * 60u;
    runsecs += runmins * 60u;
    

    Then, find the total number of seconds.

    uint16_t totalsecs = swimsecs + bikesecs + runsecs;
    

    Finally, find convert back to hours, minutes and seconds.

    uint16_t totalmins = totalsecs / 60u;
    totalsecs %= 60u;
    
    uint16_t totalhours = totalmins / 60u;
    totalmins %= 60u;