Printf prints wrong value when trying to print the variable alone, prints the right value when printing this variable along with another variable

StackOverflow https://stackoverflow.com/questions/22701332

  •  22-06-2023
  •  | 
  •  

Question

I have an embedded board and a camera connected to it. I am trying to print the timestamp from the camera on the console output of the embedded board. The timestamp is accessed and loaded into a structure, and is printed using printf, as follows:

This code is in a loop.

f.timestamp = hrt_absolute_time(); // Inbuilt function
printf("Timestamp is %u",f.timestamp);

If these lines are run, it always prints "Timestamp is 77". If I do this instead:

counter = 1;
f.timestamp = hrt_absolute_time();
printf("The %d st timestamp is %u",counter,f.timestamp);

If these lines are run, it prints "The 1 st timestamp is " and the timestamp is updated every second. My question is, how can something so trivial cause such a huge difference? Is it because of the stdout buffer not cleared from some old printf? There are no other print statements in this module. Does anyone have any ideas? Thanks in advance!

Entire block:

if (msg->msgid == MAVLINK_MSG_ID_OPTICAL_FLOW) {
    mavlink_optical_flow_t flow;
    mavlink_msg_optical_flow_decode(msg, &flow);

    struct optical_flow_s f;

    f.timestamp = hrt_absolute_time();
    f.flow_raw_x = flow.flow_x;
    f.flow_raw_y = flow.flow_y;
    f.flow_comp_x_m = flow.flow_comp_m_x;
    f.flow_comp_y_m = flow.flow_comp_m_y;
    f.ground_distance_m = flow.ground_distance;
    f.quality = flow.quality;
    f.sensor_id = flow.sensor_id;

    printf("Timestamp is %u",f.timestamp);
            //OTHER CODE FOLLOWS
Was it helpful?

Solution

According to information in the comments, f.timestamp is of type uint64_t.

Unless uint64_t is the same type as unsigned int, the behavior of

printf(" timestamp is %u", f.timestamp);

is undefined.

The header <inttypes.h> defines format macros for a number of integer types, but I find it easier to cast to a known type:

printf(" timestamp is %ju", (uintmax_t)f.timestamp);

or

printf(" timestamp is %llu", (unsigned long long)f.timestamp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top