简体   繁体   English

带有Qt的Unix串行端口程序崩溃

[英]Unix serialport program with qt crashes

I am developing a simple serialport application with qt. 我正在用qt开发一个简单的串行端口应用程序。 I have configured the ttyUSB0 and i managed to open the port. 我已经配置了ttyUSB0,我设法打开了端口。 But when datareceived from serialport my application closes. 但是,当从串行端口接收到数据时,我的应用程序将关闭。 This is my code, Can anybody have an idea that what is wrong with this code ? 这是我的代码,有人可以知道此代码有什么问题吗?

Thanks in advance, 提前致谢,

    #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/ttyO1\n";
       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);
        }
    }
}

It is maybe better to use Qt 5.1 SerialPort support for this use case: 对于这种用例,最好使用Qt 5.1 SerialPort支持:
See further information on QSerialPort documentation with examples on Qt Project Homepage. 有关QSerialPort文档的更多信息,请参见Qt项目主页上的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM