添加serialport模塊支持
QT += core gui serialport
添加頭文件
#include <QtSerialPort>
創建串口對象
private:
QSerialPort *serial;
創建必要的槽函數
private slots:
void getData(); // 串口數據接受的槽函數
void writeData(char *data, qint64 len); // 數據發送
void error(QSerialPort::SerialPortError serialPortError); // 操作錯誤槽函數
端口號獲取
QList<QString> portList;
portList.clear();
QList<QSerialPortInfo> serialPortInfo = QSerialPortInfo::availablePorts();
//搜索串口
for (int i=0;i<serialPortInfo.length();i++) {
qDebug() << "Name : " << serialPortInfo[i].portName();
qDebug() << "Description : " << serialPortInfo[i].description();
qDebug() << "Manufacturer: " << serialPortInfo[i].manufacturer();
portList.append(serialPortInfo[i].portName());
}
初始化串口參數連接相關槽函數
serial = new QSerialPort(this);
serial->setPortName("COM25"); // 設置端口
serial->setBaudRate(115200); // 波特率
serial->setDataBits(QSerialPort::Data8); // 數據位
serial->setParity(QSerialPort::NoParity); // 校驗位
serial->setStopBits(QSerialPort::OneStop); // 停止位
serial->setFlowControl(QSerialPort::NoFlowControl); // 無數據流控
// 綁定後信號槽函數:
connect(serial, SIGNAL(readyRead()), this, SLOT(getData()));
connect(serial, SIGNAL(errorOccurred(QSerialPort::SerialPortError)),this, SLOT(error(QSerialPort::SerialPortError)));
// 確認參數沒有問題過後就以可讀可寫方式打開串口
serial->open(QIODevice::ReadWrite);
槽函數
void MainWindow::getData()
{
char rebuf[1024]; // 數據接受緩存
int length = serial->read(rebuf, 1024);
// 打印接收到的內容,length是實際讀取的數量
for(int i=0; i<length; i++)
{
qDebug("%d",rebuf[i]);
}
}
// 可以當成普通函數來使用,根據需要來處理是否需要連接信號
void MainWindow::writeData(char *data, qint64 len)
{
if(serial->isOpen())
{
serial->write(data,len);
}
else
{
qDebug("端口未打開");
}
}
void MainWindow::error(QSerialPort::SerialPortError serialPortError)
{
}
上面具體serialPortError具體是什麼錯可以添加判斷根據情況處理,可能出現的錯誤類型如下
enum SerialPortError {
NoError,
DeviceNotFoundError,
PermissionError,
OpenError,
ParityError,
FramingError,
BreakConditionError,
WriteError,
ReadError,
ResourceError,
UnsupportedOperationError,
UnknownError,
TimeoutError,
NotOpenError
};
Q_ENUM(SerialPortError)
比較簡單適合初學者,可以直接下載demo。