Unix 串行端口程序与 qt 崩溃

Unix serialport program with qt crashes

本文关键字:qt 崩溃 程序 串行端口 Unix      更新时间:2023-10-16

我正在使用qt开发一个简单的串行端口应用程序。我已经配置了ttyUSB0,并设法打开了端口。但是当从串行端口接收的数据时,我的应用程序关闭了。这是我的代码,任何人都可以知道这段代码有什么问题吗?

提前感谢,

    #include "linkasunixserialport.h"
LinkasUnixSerialPort::LinkasUnixSerialPort()
{
    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
       qDebug()<<"open_port: Unable to open /dev/ttyO1n";
       exit(1);
    }
    qDebug()<<"devttyUSB0 opened";
    fcntl(fd, F_SETFL, FNDELAY);
    fcntl(fd, F_SETOWN, getpid());
    fcntl(fd, F_SETFL,  O_ASYNC );
    tcgetattr(fd,&termAttr);
    cfsetispeed(&termAttr,B115200);
    cfsetospeed(&termAttr,B115200);
    termAttr.c_cflag &= ~PARENB;
    termAttr.c_cflag &= ~CSTOPB;
    termAttr.c_cflag &= ~CSIZE;
    termAttr.c_cflag |= CS8;
    termAttr.c_cflag |= (CLOCAL | CREAD);
    termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
    termAttr.c_oflag &= ~OPOST;
    tcsetattr(fd,TCSANOW,&termAttr);
    qDebug()<<"UART1 configured....n";
    this->start();
}
int LinkasUnixSerialPort::bytes_available()
{
    int bytesQueued;
    if (::ioctl(fd, FIONREAD, &bytesQueued) == -1) {
        return -1;
    }
    qDebug()<<bytesQueued;
    return bytesQueued;
}
void LinkasUnixSerialPort::run()
{
    char receive_data[2];
    forever
    {
        int bytes_read = bytes_available();
        if(bytes_read > -1)
        {
            int retVal = ::read(fd, receive_data, 1);
            if(retVal != -1)
            {
                emit dataReceived(QChar(receive_data[0]));
            }
        }
        else
        {
            this->msleep(1);
        }
    }
}
对于

此用例,最好使用 Qt 5.1 SerialPort 支持:
有关QSerialPort文档的更多信息,请参阅Qt项目主页上的示例。