gpt4 book ai didi

c++ - 检查串口是否有数据传入linux(cbInQue for linux)

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:20 25 4
gpt4 key购买 nike

我在管理从 Arduino 单元进入 linux 串行端口的数据时遇到了问题。

基本上,我有一个可以读取和打印(或只是存储)的工作代码,但它是为 Windows 平台编写的:

状态是 COMSTAT 类型

int SerialPort::readSerialPort(char *buffer, unsigned int buf_size)
{
DWORD bytesRead;
unsigned int toRead = 0;
Sleep(500);
ClearCommError(this->handler, &this->errors, &this->status);

if (this->status.cbInQue > 0) { //if there's something to read
if (this->status.cbInQue > buf_size) {//if there's something to read&bigger than buffer size
toRead = buf_size; //read as much as buffer alows
}
else toRead = this->status.cbInQue; //else just read as much as there is
}

if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL))
return bytesRead; //return read data


return 0;//return 0 if nothing is there.
}

除了 Windows 函数 Sleep() 之外,我想知道是否有一个等效的 linux 函数用于 status.cbInQue 以了解是否有任何数据可以在端口中读取。现在我只是继续阅读,没有检查,而且我经常在程序的后面没有打印任何东西。

TLDR:是否有适用于 Linux 的 cbInQue 等效项?

谢谢

最佳答案

是的,您将需要您的文件描述符,然后使用 FIONREAD 来查看是否有可用的内容。

像下面这样的东西应该可以工作:

int available;
if( ioctl( fd, FIONREAD, &available ) < 0 ) {
// Error handling here
}

关于c++ - 检查串口是否有数据传入linux(cbInQue for linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703828/

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