Arduino myFile.write(buff,len)不能工作

时间:2016-03-24 02:08:10

标签: c arduino arduino-uno

我最近写了一些关于获取IMU数据并将其保存到SD卡的代码。为了提高写入数据的速度,我需要使用二进制格式来保存它,这是我的代码:

byte myData[20];

((long int*)myData)[0] = count;
((long int*)myData)[4] = microSec;
((short int*)myData)[8] = ax;
((short int*)myData)[10] = ay;
((short int*)myData)[12] = az;
((short int*)myData)[14] = gx;
((short int*)myData)[16] = gy;
((short int*)myData)[18] = gz;

myFile3.write(myData, sizeof(myData));

但它完全不起作用。(但编译可以,我真的很困惑......)

有没有人遇到这个问题......?

2 个答案:

答案 0 :(得分:0)

尝试这个怎么样:

    byte myData[20];

((long int*)myData)[0] = count;
((long int*)myData)[1] = microSec;
((short int*)myData)[4] = ax;
((short int*)myData)[5] = ay;
((short int*)myData)[6] = az;
((short int*)myData)[7] = gx;
((short int*)myData)[8] = gy;
((short int*)myData)[9] = gz;

myFile3.write(myData, sizeof(myData));

答案 1 :(得分:0)

谢谢你们!这个问题通过数百次测试得以解决(缺乏C编码技能水平让我对Arduino编码感到困扰......)

这是新代码(由@ frarugi87的建议编辑)

byte myData[20];
  *((long int *)(myData+0)) = count;
  *((long int *)(myData+4)) = microSec;
  *((short int *)(myData+8)) = ax;
  *((short int *)(myData+10)) = ay;
  *((short int *)(myData+12)) = az;
  *((short int *)(myData+14)) = gx;
  *((short int *)(myData+16)) = gy;
  *((short int *)(myData+18)) = gz;

它确实有效,数据是正确的,例如

数据:0C 6A 30 00

答案:3172876

我还找到另一种方法:

  myFile3.write( (byte*)&count, sizeof(long));
  myFile3.write( (byte*)&microSec, sizeof(long));
  myFile3.write( (byte*)&ax, sizeof(short));
  myFile3.write( (byte*)&ay, sizeof(short));
  myFile3.write( (byte*)&az, sizeof(short));
  myFile3.write( (byte*)&gx, sizeof(short));
  myFile3.write( (byte*)&gy, sizeof(short));
  myFile3.write( (byte*)&gz, sizeof(short));

它也有效,数据格式与第一种编码方式相同。

问候!