gpt4 book ai didi

c++ - 在串行端口上读取返回我刚写的内容

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:11 24 4
gpt4 key购买 nike

我刚刚开始了一个项目,从现在开始我就在为串行端口而苦苦挣扎。我写了一个静态库,它可以处理所有的串行例程,并提供一个带有“readLine()”和“writeLine()”函数的接口(interface)。写入和读取(顺便说一下,它们是线程化的)一切都完美无缺,除非奴隶在获取数据后没有回答,然后,数据被发回给我,我读取了它。

我使用 O_NDELAY 打开我的 fd,并使用 fcntl 将我的读取系统调用配置为非阻塞。

这里有两个线程循环与之完美配合。

void *Serial_Port::readLoop(void *param)
{
Serial_Port *sp = static_cast<Serial_Port*>(param);
std::string *line = NULL;
char buffer[128];

while (1)
{
line = new std::string();
while ((line->find("\r\n")) == std::string::npos)
{
usleep(100);
bzero(buffer, 128);
pthread_mutex_lock(sp->getRLock());
if (read(sp->getDescriptor(), buffer, 127) > 0)
*line += buffer;
pthread_mutex_unlock(sp->getRLock());
}
pthread_mutex_lock(sp->getRLock());
sp->getRStack()->push(line->substr(0, line->find("\r\n")));
pthread_mutex_unlock(sp->getRLock());
delete (line);
}
return (param);
}

void *Serial_Port::writeLoop(void *param)
{
Serial_Port *sp = static_cast<Serial_Port*>(param);
std::string *line;

while (1)
{
line = NULL;
pthread_mutex_lock(sp->getWLock());
if (!sp->getWStack()->empty())
{
line = new std::string(sp->getWStack()->front());
sp->getWStack()->pop();
}
pthread_mutex_unlock(sp->getWLock());
if (line != NULL)
{
pthread_mutex_lock(sp->getWLock());
write(sp->getDescriptor(), line->c_str(), line->length());
// fsync(sp->getDescriptor());
pthread_mutex_unlock(sp->getWLock());
}
usleep(100);
}
return (param);
}

我尝试刷新文件描述符,但之后我无法接收到任何数据。我怎样才能摆脱那些重复的、不必要的数据?

谢谢。

最佳答案

经过多次测试和行为分析,我发现是“Pulsar3”(我在串口上使用的设备)不断返回我作为“确认”发送的内容。很高兴知道!

关于c++ - 在串行端口上读取返回我刚写的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36869981/

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