当尝试单独打印变量时,Printf打印错误的值,在打印此变量和另一个变量时打印正确的值

时间:2014-03-27 23:29:50

标签: c printf stdout

我有一块嵌入式电路板和一个连接到它的相机。我试图在嵌入式主板的控制台输出上打印相机的时间戳。访问时间戳并将其加载到结构中,并使用printf打印,如下所示:

此代码处于循环中。

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

如果运行这些行,它总是打印“Timestamp is 77”。如果我这样做:

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

如果运行这些行,则会打印“第一个时间戳为”,时间戳每秒更新一次。我的问题是,如此微不足道的事情怎么会造成如此巨大的差异?是因为stdout缓冲区没有从一些旧的printf清除?此模块中没有其他打印语句。有没有人有任何想法?提前谢谢!

整个街区:

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

1 个答案:

答案 0 :(得分:5)

根据评论中的信息,f.timestamp的类型为uint64_t

除非uint64_tunsigned int的类型相同,否则

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

未定义。

标题<inttypes.h>定义了许多整数类型的格式宏,但我发现更容易转换为已知类型:

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

printf(" timestamp is %llu", (unsigned long long)f.timestamp);