读取具有不同数据类型的二进制数据

时间:2017-01-30 15:20:52

标签: c++ c embedded microcontroller sd-card

我正在制作一个数据记录器项目。在我的数据记录器中,我有5个传感器,如:温度,湿度,加速度计,光和气压计。 在这里,我将数据以二进制格式存储到SD卡中。我在1HZ存储加速度计@ 3200HZ和所有其他传感器。

在写作的时候,我正在添加一个特殊字符,如$,&每个传感器测量值,以在读取时识别数据。我没有为加速度计数据添加任何spl字符。加速度计数据是3200HZ的巨大数据,因此我不会添加spl字符,因为它会占用一些内存,而且写入会导致错过一些样本,并且只能为2600HZ的3200HZ。

我的阅读数据代码如下所示:

while((nr = fgetc(logFile)) != EOF)
{
    if (nr == '$')
    {      // read temp data if nr = $
        fread(&temp_read,sizeof(float),1,logFile);
        pc.printf("\r\n %f",temp_read);
    }
    if (nr == '&')
    {    // read humidity data if nr = &
        fread(&Humidity_read,sizeof(float),1,logFile);
        pc.printf("\r\n %f",Humidity_read);
    }
    else
    {           // if nr is not a spl character
        data1 = nr;// send nr to a variable.
        nr = fgetc(logFile);// read next byte and save it in nr
        data2 = nr;// send nr to another variable
        int16_t temp = (data1 | (data2 << 8));// club both bytes to form                   int16_t data 
        pc.printf("\r\n %i",temp);// print the one axis 
    }
}

不幸的是这个程序提供了错误的数据。有很大的不同。有没有其他方法可以解决这个问题。我在哪里犯错误。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可能会因为尝试通过修改数据格式来持续捕获高速采样而冒汗。问题几乎肯定与SD卡中的块延迟有关(超过闪存页面或扇区边界时需要额外的写入时间)。

您可能需要结合使用多种方法:

  • 使用RTOS,在高优先级任务中执行采样,并将日志记录延迟到低优先级任务
  • 将样本发送到足够长的队列中的日志记录任务,以涵盖在最大SD延迟期间获取的样本数。
  • 小心选择SD卡;特别是如果使用SPI而不是SDIO接口。我发现卡的持续写入速度在每秒32k到800k字节之间,块延迟超过400ms。

请参阅How can I use an SD card for logging 16-bit data at 48 ksamples/s?