gpt4 book ai didi

c++ - 串口通讯崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:43 27 4
gpt4 key购买 nike

我正在使用 radio 模块 XBee pro 并记录一些 radio 数据。

我使用 FTDI 串口转 USB 转换器,因此该模块出现在 /dev/ttyUSB0 下。

我写了这段代码:

void TsToCoord::serialConfig()
{
// Open Serial Port
cout << "Opening serial port..." << endl;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);

if (fd < 0 )
{
cout << "Error " << errno << " opening /dev/ttyUSB0: " << strerror(errno) << endl;
}
else
{
//Configure Serial Port
cout << "Configuring serial port..." << endl;
struct termios tty;
memset (&tty, 0, sizeof tty);

if (tcgetattr (fd, &tty) != 0)
{
cout << "Error " << errno << " from tcgetattr: " << strerror (errno) << endl;
}

cfsetispeed(&tty, B57600);
cfsetospeed(&tty, B57600);

tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS;
tty.c_lflag = 0;
tty.c_oflag = 0;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 50;

tty.c_cflag |= CREAD | CLOCAL;

cfmakeraw(&tty);

tcflush(fd, TCIFLUSH);

if (tcsetattr(fd, TCSANOW, &tty) != 0)
{
cout << "Error " << errno << " from tcsetattr" << endl;
}
}
}


void TsToCoord::listenPort()
{
// Creation of a buffer to store data from radio module
fill_n(buff, 2048, '\0');
this-> ind = 0;

while(true)
{
char mes[1024];
fill_n(mes, 1024, '0');
//cout << "Blocking read" << endl;
int rd = read(fd, &mes, sizeof(mes));

if (rd > 0)
{
//cout << "Storing in buffer" << endl;
storeInBuff(mes, rd);
fill_n(mes, 1024, '0');

struct pollfd fds;
fds.fd = fd;
fds.events = POLLIN | POLLPRI;
int slct = 1;

/*
int slct = 1;
fd_set rdfds;
FD_ZERO(&rdfds);
FD_SET(fd, &rdfds);
struct timeval to;
to.tv_sec = 0;
to.tv_usec = 100000;
*/
//fd_set rdfdsCopy = rdfds;
//cout << "Entering second while loop" << endl;
while (slct > 0)
{
//cout << "Call to select" << endl;
//slct = select((fd+1), &rdfdsCopy, NULL, NULL, &to);
slct = poll(&fds, 1, 100);
if (slct > 0)
{
//cout << "Next call to read, would not block" << endl;
rd = read(fd, &mes, sizeof(mes));
storeInBuff(mes, rd);
//rdfdsCopy = rdfds;
}
}
findFrame(0);
ind = 0;
fill_n(buff, 2048, '\0');
}
}
}

我的问题是,当它启动时,它运行得很好。但是大约 20 分钟后,它就不再工作了。 CPU 使用率接近 100%,因此读取调用似乎不再阻塞。就像文件描述符不再链接到设备...

因为我完全不知道原因和错误,而且它在崩溃之前需要随机的时间,所以我不能只是取消守护进程并在我的终端中观察输出...

所以我想问:

  • 代码中是否存在我没​​有发现的大错误。
  • 导致它崩溃的原因是什么?我想到了另一个试图使用同一设备的软件,但似乎并非如此。我也不认为这是波特率问题。

我添加了一个检查 radio 被拔掉的情况,所以程序不能自己退出。我很确定这不是问题,因为模块在发生崩溃后仍位于 /dev/ttyUSB0 下。

我使用的是 Debian 3.2.57-3 i686。

将其他软件与我的 radio 模块一起使用时,我没有遇到任何问题。

我在另一台类似的计算机上使用这段代码似乎没有问题......

感谢阅读,抱歉英语不太好。

编辑:更准确地说我想从这篇文章和这个程序中得到什么:在某些时候,程序无法阻止读取,并且每次对读取的调用都不会阻止并且不会读取任何内容,因此程序不会执行其创建的目的:记录来自 radio 模块的数据。我只是想避免它,因为如果没有它,它会工作得很好,并且可能会对硬件造成损害。

最佳答案

快速查看您的代码——如果您在读取时遇到 EOF 或错误(即 read() 返回零或 -1),您将永远循环。我可以看到您处于原始模式,但我看到 FTDI 驱动程序和固件中的各种错误可能会导致这种情况发生,而您正在处理的不是这种情况。

关于c++ - 串口通讯崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com