【发布时间】:2013-12-18 03:38:42
【问题描述】:
我有一个 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;
}
【问题讨论】:
-
更详细地描述硬件可能很有用,因为它可能是一个特定设备的怪癖。什么是“IMU”?它是否唯一地描述了一种设备?
-
是的,IMU 是 CHR-UM6,chrobotics.com/shop/orientation-sensor-um6.
-
它处于广播模式,意味着它一直在发送数据。我用 JAVA 编写了一个程序,它完全符合我的要求,但是在 Raspberry PI 上运行速度很慢。因此,我将其重写为 C++,现在遇到了这种奇怪的不稳定性。覆盆子的原因是它必须在伐木时飞行。
标签: serial-port port communication