sprintf .... why it does not work?

Hello,

I'm trying this:

char buffer[50];
unsigned long tempo = 0;

.....

void loop(void) {
.......
tempo = millis();
sprintf( buffer , "%01d:%02d.%02d", tempo / 60000 , tempo / 1000 % 60, tempo % 1000 / 10 );
Serial.println(buffer);
.....
}

I see this on the serial monitor:

for example
2:00.23
2 is minute and is correct
:
00 is always zero, is not correct
.
23 is second, the position is not correct, must before the dot

Instead I should see this:

M:SS.MS

%01d = M one char minute with zero
:
%02d = SS two char Second with zero
.
%02d = MS two char MilliSecond with zero

Why? Can someone help me?

%d expects an int parameter, you need %ld for a long.

Hy oqibidipo,

YES super Thank You :slight_smile:

The sprintf() function is very powerful, but rarely does an app use all of that power. In the code below, the sprintf() version uses 3450 bytes while the non-sprintf() version uses 2136 bytes.

char buffer[50];
unsigned long tempo = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop(void) {

  tempo = millis();
  //sprintf( buffer , "%01d:%02ld.%02ld", tempo / 60000L , tempo / 1000L % 60L, tempo % 1000L / 10L);
  //Serial.println(buffer);
  Serial.print(ltoa(tempo / 60000L, buffer, 10));
  Serial.print(":");
  Serial.print(ltoa(tempo / 1000L % 60L, buffer, 10));
  Serial.print(".");
  Serial.println(ltoa(tempo % 1000L / 10L, buffer, 10));

}

While the savings makes no difference in this test, if you find yourself up against memory limits down the road, try the simpler functions.

Hi econjack,

very interesting, thank you so much 8)