我正在用 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/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);
}
}
}