我有一个C ++程序,它读取IMU设备并将一些处理后的数据写入文件。 率高,每秒500线。该程序似乎工作正常,但它随机停止读取串口。
经过一些研究后,它似乎陷入了读取命令:
while((res += read(IMU, header, 3)) != 3).
这怎么可能发生?如何防止这种情况发生?
如果您需要任何其他信息,请与我们联系。
void* imuLogger(void* arg) {
IMU = initSerial("/dev/ttyUSB0", B115200);
openLog("logIMU", IMUfile);
int res;
char tmp;
char header[3];
while(true)
{
gettimeofday(&ts, NULL);
timeLog = (ts.tv_sec * 1000000 + ts.tv_usec) - timeStart;
/**** READ IMU ****/
res = 0;
cout << indexLog << "-"<< IMU<< endl;
while((res += read(IMU, header, 3)) != 3);
cout << indexLog << "entered loop"<< endl;
string head(header, 3);
if(head.compare("snp") == 0 || head.substr(1, 2).compare("np") == 0 || head.substr(0, 2).compare("sn") == 0 || (header[0] == 's' && header[2] == 'p'))
{
buf[0] = 's';
buf[1] = 'n';
buf[2] = 'p';
while((res = read(IMU, &tmp, 1)) != 1);
buf[3] = tmp;
res = 4;
while(res < sizeof(buf))
res += read(IMU, buf + res, sizeof(buf) - res);
parseData();
}
else if(head.substr(0, 2).compare("np") == 0)
{
buf[0] = 's';
buf[1] = 'n';
buf[3] = buf[2];
buf[2] = 'p';
res = 4;
while(res < sizeof(buf))
res += read(IMU, buf + res, sizeof(buf) - res);
parseData();
}
else if(head.substr(1,2).compare("sn") == 0)
{
buf[0] = 's';
buf[1] = 'n';
buf[2] = 'p';
while((res = read(IMU, &tmp, 1)) != 1);
while((res = read(IMU, &tmp, 1)) != 1);
buf[3] = tmp;
res = 4;
while(res < sizeof(buf))
res += read(IMU, buf + res, sizeof(buf) - res);
parseData();
}
else
{
//tcflush(IMU, TCIOFLUSH);
//while((res = read(IMU, header, 1)) != 1)
// cout <<
cout << "Error parser\n";
}
//parseData();
//gettimeofday(&ts, NULL);
//timeEnd = (ts.tv_sec * 1000000 + ts.tv_usec) - time - timeStart;
//cout << "Length:" << res << " Time:" << timeEnd << " Address:" << (int)packet.Address << endl;
//usleep(10000 - timeEnd);
//cout <<"entered"<< endl;
}
return 0;
}
int main() {
signal(SIGINT, exit_handler);
gettimeofday(&ts, NULL);
timeStart = ts.tv_sec * 1000000 + ts.tv_usec;
pthread_create(&imuThread, NULL, imuLogger, NULL);
pthread_create(&rpmThread, NULL, rpmLogger, NULL);
//pthread_create(&baroThread, NULL, baroLogger, NULL);
while(true)
{
gettimeofday(&ts4, NULL);
timeLog_main = (ts4.tv_sec * 1000000 + ts4.tv_usec) - timeStart;
cout << timeLog_main/1e6 << endl;
sleep(1);
}
return 0;
}
答案 0 :(得分:0)
如果read()
第一次返回1个字节,第二次返回3个字节,那么res
永远不会是3。