Binary reading and writing in C++

2019-07-23 08:59发布

问题:

I am making an data logger project. In my data logger, I have 5 sensors like: temperature, humidity, accelerometer, light and barometer.

Here, I am storing the data in to SD card in binary format. I'm storing accelerometer @3200HZ and all other sensors at 1HZ.

While writing, I'm adding a special character to each measurements like below.

 if(DRDY)
  { 
    fwrite(&accdata,sizeof(char),1,logFile);  // accelerometer special char         
    accelerometer.getOutput(readings);
    int16_t store[3] = {(int16_t)readings[0],(int16_t)readings[1],(int16_t)readings[2]};  // accelerometer data
    fwrite((store),sizeof(int16_t),3,logFile);

   } 


    if(flag_humi)
  { 
    flag_humi = 0;
   fwrite(humidata,sizeof(char),1,logFile); // humidity character
   float store2[1] = {sht.readHumidity()};  // humidity data
   fwrite(store2,sizeof(float),1,logFile);
   }
    if(flag_temp)
  { 
   flag_temp = 0;
   fwrite(tempdata,sizeof(char),1,logFile);  // temp character
   float store1[1] = { sht.readTemp()};   // temp data
   fwrite(store1,sizeof(float),1,logFile);
  }

While reading, it separates the data according to the special character.

   while ((nr = fgetc(logFile)) != EOF){
       if (nr == 5){    // 5 is special character  for accelerometer
         fread(read,sizeof(int16_t),3,logFile);
          pc.printf("\r\n %i, %i, %i ",read[0],read[1],read[2]);
              }


    else if(nr == 10){  // 10 is char for temp
           fread(temp_read,sizeof(float),1,logFile); 
           pc.printf("\r\n %f",temp_read[0]);
                     }
    else  if(nr ==15)   // 15 is character for humidity
                    { 
          fread(humi_read,sizeof(float),1,logFile); 
          pc.printf("\r\n %f",humi_read[0]);
                   }

Everything is fine. Now I would like to remove a special character for the accelerometer since writing special character makes loss of some samples.

I tried once by writing accelerometer without spl.character and other sensors with spl.character.

While reading, I thought I could keep only else to read accelerometer since other have else if anyway.

   while ((nr = fgetc(logFile)) != EOF){
    if(nr == 10){  // 10 is char for temp
           fread(temp_read,sizeof(float),1,logFile); 
           pc.printf("\r\n %f",temp_read[0]);
                     }
    else  if(nr ==15)   // 15 is character for humidity
                    { 
          fread(humi_read,sizeof(float),1,logFile); 
          pc.printf("\r\n %f",humi_read[0]);
                   }
    else  {    // 5 is special character  for accelerometer
         fread(read,sizeof(int16_t),3,logFile);
          pc.printf("\r\n %i, %i, %i ",read[0],read[1],read[2]);
              }

But it is showing all wrong values and it is unstoppable. How can I achive this?