Linux c++串口读写

Linux C++ Serial Port Reading/Writing

本文关键字:读写 串口 c++ Linux      更新时间:2023-10-16

我正试图读取我已写入串行端口/tty/USBS0的数据。我已经通过serial_fd = open(serialport.str().c_str(), O_RDWR | O_NOCTTY | O_NDELAY);打开端口,我正在通过retVal2 = write(serial_fd, (void *)&msg, length);写入数据。

然而,我遇到了一个问题,当我调用read()时,它停在那里;换句话说,它无限地继续读取。

void cmgGSP::read_thread(){ 
unsigned char msg[256];
unsigned char messagelength;
msg_header msgHeader; //msg_header is defined in cmgCOM.h
msgHeader.startByte = 0;
msgHeader.length = 0;
msgHeader.ID = 0;
int totalBytes;
int retVal;
cout<<"Scope Test -- In Read Thread"<<endl;
while(1) //infinte loop, since we're going to want to always be reading command data
{
cout<<"Scope Test -- In While(1)"<< endl;
    totalBytes = 0;
    while (totalBytes == 0) {
        cout<<"Scope Test -- First While Loop"<<endl;
        retVal = read(serial_fd, (unsigned char*)&msgHeader, 1);
        cout<<"retVal: "<<retVal <<endl; //This does not get printed
        if (retVal == -1)
        {
            printf("read() message failed: %sn", strerror(errno));
        }
        if (msgHeader.startByte != FROM_CMG) {
            printf("Bad start byte on read()n");
            totalBytes = 0;
        } else {
            cout<<"scope test 2"<<endl;
            totalBytes+=retVal;
        }
    }

    while (totalBytes < sizeof(msgHeader)) {
retVal = read(serial_fd, (unsigned char*)&msgHeader+totalBytes, sizeof(msgHeader)-totalBytes);
        cout<< "in second while"<<endl;         
        if (retVal == -1){
            printf("read() message failed: %sn", strerror(errno));
        }
        totalBytes+=retVal;
    }
    if (msgHeader.startByte != START_BYTE) {
        printf("Bad start byte on messagen");
        continue;
    }
    else
    {
        printf("MSG RCV: StartByte=0x%X, Length=0x%X, ID=0x%Xn", msgHeader.startByte, msgHeader.ID, msgHeader.length);
        break;
    }
}
}

上面是我创建的线程;然而,输出从来没有通过"Scope Test—First While循环"。即使在写入数据后显式地调用线程,结果也是一样的:它无限地读取。我知道它实际上正在阅读,因为如果我断开电路板,而它卡住了,它开始打印"read()消息失败……"

任何帮助是感激-谢谢!

您可能需要在开放系统调用中设置O_NONBLOCK标志;这样,根据写入端口的数据,您将退出read()并错误输出/获得已填满的缓冲区。

"如果某个进程打开了用于写的管道并且O_NONBLOCK被清除,read()将阻塞调用线程,直到一些数据被写入或管道被所有打开管道用于写的进程关闭。"

在这里阅读O_NONBLOCK标志:http://pubs.opengroup.org/onlinepubs/7908799/xsh/read.html