两个串口如何分别使用QSerialport :: readyRead()接收数据,槽函数分别怎么写
时间: 2024-05-19 21:17:54 浏览: 12
对于两个串口分别接收数据,可以创建两个 QSerialPort 对象,并分别为它们绑定 readyRead() 信号,示例代码如下:
QSerialPort serialPort1;
QSerialPort serialPort2;
//设置串口1的端口号、波特率等参数
serialPort1.setPortName("COM1");
serialPort1.setBaudRate(QSerialPort::Baud9600);
serialPort1.setDataBits(QSerialPort::Data8);
serialPort1.setFlowControl(QSerialPort::NoFlowControl);
serialPort1.setParity(QSerialPort::NoParity);
serialPort1.setStopBits(QSerialPort::OneStop);
//设置串口2的端口号、波特率等参数
serialPort2.setPortName("COM2");
serialPort2.setBaudRate(QSerialPort::Baud9600);
serialPort2.setDataBits(QSerialPort::Data8);
serialPort2.setFlowControl(QSerialPort::NoFlowControl);
serialPort2.setParity(QSerialPort::NoParity);
serialPort2.setStopBits(QSerialPort::OneStop);
//分别为两个串口绑定 readyRead() 信号
connect(&serialPort1, SIGNAL(readyRead()), this, SLOT(serialPort1ReadyRead()));
connect(&serialPort2, SIGNAL(readyRead()), this, SLOT(serialPort2ReadyRead()));
然后,分别编写两个槽函数 serialPort1ReadyRead() 和 serialPort2ReadyRead(),来实现数据的接收处理,示例代码如下:
void MyClass::serialPort1ReadyRead()
{
QByteArray data = serialPort1.readAll();
// 处理接收到的数据 ...
}
void MyClass::serialPort2ReadyRead()
{
QByteArray data = serialPort2.readAll();
// 处理接收到的数据 ...
}
在两个槽函数中,可以用 readAll() 函数读取收到的数据,并在函数中进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)