void WorkThread::sendSerialData(QByteArray data) { if (serialPort != nullptr) { serialPort->write(data); } }
时间: 2024-04-02 14:35:24 浏览: 25
这段代码是用来发送串口数据的,首先判断QSerialPort对象是否为nullptr,如果不是就调用QSerialPort的write()函数发送数据。write()函数会将指定的数据写入到串口缓冲区中,如果缓冲区已满,则write()函数可能会阻塞程序,直到缓冲区有足够的空间为止。需要注意的是,write()函数只是将数据写入缓冲区,并不保证数据已经成功发送到串口设备。
相关问题
bool WorkThread::openSerialPort(QString port) { this->serialPort = new QSerialPort(); int baudRate = QSerialPort::Baud115200; if(serialPort->isOpen()) { serialPort->close(); } serialPort->setPortName(port); if(!serialPort->open(QIODevice::ReadWrite)) { return false; } serialPort->setBaudRate(baudRate); serialPort->setParity(QSerialPort::NoParity); serialPort->setDataBits(QSerialPort::Data8); serialPort->setStopBits(QSerialPort::OneStop); serialPort->setFlowControl(QSerialPort::NoFlowControl); serialPort->setDataTerminalReady(true); serialPort->setRequestToSend(true); return true; }
这段代码实现了一个函数openSerialPort,作用是打开串口设备并进行设置,其中port是一个字符串,表示要打开的串口名称。具体实现步骤如下:
1. 创建一个串口对象serialPort,其类型为QSerialPort。
2. 设置串口波特率为115200,这里使用了QSerialPort类中的常量Baud115200。
3. 如果串口已经被打开,则先关闭串口。
4. 设置串口名称为port,并尝试打开串口设备。
5. 如果串口打开失败,则返回false,表示打开串口失败。
6. 设置串口的数据位、停止位、校验位、流控制等参数。
7. 将数据终端就绪(DTR)信号和请求发送(RTS)信号设置为true,表示串口已经准备好发送和接收数据。
8. 返回true,表示串口打开成功,并且已经设置好参数。
QByteArray WorkThread::readSerialPort() { if (nullptr == serialPort) {return "";} qint64 byteLen = serialPort->bytesAvailable(); if(byteLen < 0) { return ""; } return serialPort->readAll(); }
这段代码是用来读取串口数据的,先判断QSerialPort对象是否为nullptr,如果是就返回一个空的QByteArray。然后获取可用的字节数,如果小于0也返回一个空的QByteArray。最后调用QSerialPort的readAll()函数读取所有可用的数据,并将其封装到一个QByteArray对象中返回。这里需要注意,readAll()函数可能会阻塞程序,直到读取到数据为止。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)