Trivial code – strange behavior…..

Hi,

I've got some very basic coding here that isn't doing what I was expecting, have I missed something?

Here's the code, basically I'm displaying some error information after sending an SMS...

    Serial.print("sig_stren <");Serial.print(sig_stren);Serial.println(">.");
     sprintf(info,"CheckAndSendSMS. Sim SMS. FAIL <%d>ms. Sig str <%d>",duration_millis,sig_stren);
   Serial.println(info);
     sprintf(info,"CheckAndSendSMS. Sim SMS. FAIL <%d>ms. Sig str <%d>.<%d>",duration_millis,sig_stren,sig_stren);
   Serial.println(info);

And here's the output....

sig_stren <14>.
CheckAndSendSMS. Sim SMS. FAIL <2316>ms. Sig str <0>
CheckAndSendSMS. Sim SMS. FAIL <2316>ms. Sig str <0>.<14>

In the first use of sprintf I would expect sig_stren to be displayed within the 2nd set of chevrons, instead I get zero.
In the second use of sprintf I would expect in to be displayed twice, but it only gets displayed the 2nd time.

Whats going on?

How big is info?

What types are sig_stren and duration_millis?

The %d format specifier is for ints. You need to use %ld (that's the letter l, as in long, in front of the d) for signed or unsigned longs, which is the type that should be used for any kind of millis() output.

Thanks Paul - you got it! the definitions are...
int sig_stren = 0; // Signal strength before message sent
unsigned long duration_millis = 0; // Time (in milliseconds) to send SMS (irrespective of success or failure)

If I change the code to....

    sprintf(info,"CheckAndSendSMS. Sim SMS. FAIL <%ld>ms. Sig str <%d>.<%d>",duration_millis,sig_stren,sig_stren);
    Serial.println(info);
    sprintf(info,"CheckAndSendSMS. Sim SMS. FAIL <%ld>ms. Sig str <%d>",duration_millis,sig_stren);

It now works!

Since the error was with the display of sig_stren I assumed that this was where the problem lay. I figured (incorrectly) that since duration_millis was displaying OK the code for it must also be OK. That'll learn me!

Cheers

What was happening is that the first %d displayed the first 2 bytes of duration_millis, which happen to be the low order bytes. The 2nd %d was then printing the next two bytes - the high order bytes, which were 0 in your case, since the interval presumably is low. The 3rd %d in the 3rd statement was actually printing the first occurrence of sig_stren.