Go Down

Topic: converting 2 variables into character array variable (Read 722 times) previous topic - next topic

Frisky

Hi
I have written some code that takes the amount on minutes called durationInMins.
durationInMins is converted to 2 byte variables named hours, and mins.

I don't know how to convert the byte variables hours, mins to a char array.
I'm trying to fill the character array with the data as follows "hh:mm" format.
Here is what I have so far I have it running on my Uno board.
Thank you
Don

Code: [Select]

#include <math.h>
void setup()
{
 Serial.begin(115200);
}

void loop()
{
 char duration[] = {"  :  "};
 int durationInMins = 490;
 byte hours = 0;
 byte mins = 0;
 double i, r;
 r = durationInMins * .01666;
 Serial.print("Durationin mins: ");
 Serial.println(durationInMins);
 r = modf(r, &i);
 r = r * 60;
 mins = byte(round(r));
 hours = byte(i);
 Serial.print("Hours: ");
 Serial.println(hours);
 Serial.print("Mins: ");
 Serial.println(mins);
 Serial.println();
 
 /*
   I now want to convert
   variable hours to a character array;
   and variable mins to a character array
   then put them in char array duration
   char duaration[] = {"hh:mm"};
 */
Serial.println(duration);
Serial.println();
 
for(;;){}  

}




holmes4

durationInMins/60 gets you the number of hours.

durationInMins%60 gets you the number on mins (see ref section).

Then use print an a print(0) in hours or mins is less than 10 to give the leading zero.

Mark


PeterH

Code: [Select]

hours = durationInMins / 60;
mins = durationInMins % 60;

sprintf(duration, "%02d:%02d", (int)hours, (int)mins);
I only provide help via the forum - please do not contact me for private consultancy.

Frisky

Ill give it a try much simpler that what I had lol thanks guys

holmes4

By the way if you want thing to happen just once put the code in setup(), don't use a forever loop as you do.

Mark

Go Up