1. 程式人生 > >Qt 5.7串列埠開發教程

Qt 5.7串列埠開發教程

     Qt5.7已經封裝了關於串列埠操作的類QSerialPort,QSerialPortInfo等,不需要再使用第三方串列埠類。串列埠應用程式的開發,包括查詢串列埠,開啟串列埠,傳送資料,讀取資料等。完整程式原始碼,請點選【串列埠助手原始碼下載】。

     介面如下:

     

     先看看類QSerialPortInfo, Qt的解釋如下:

   Provides information about existing serial ports.

Use the static functions to generate a list of QSerialPortInfo objects. Each QSerialPortInfo object in the list represents a single serial port and can be queried for the port name, system location, description, and manufacturer. The QSerialPortInfo class can also be used as an input parameter for the setPort() method of the QSerialPort

class.

英語差的沒關係,看看有道翻譯:

提供現有的串列埠的資訊。

使用靜態函式生成QSerialPortInfo物件的列表。列表中的每個QSerialPortInfo物件代表了一個串列埠和埠名稱,可以查詢系統位置、描述和製造商。QSerialPortInfo類也可以作為輸入引數用於setPort QSerialPort()方法的類。

一.  我們先來查詢系統可用的串列埠:

        //迴圈查詢串列埠
	foreach(const QSerialPortInfo &Info, QSerialPortInfo::availablePorts())
	{
		QSerialPort availablePort;
		QString str = Info.portName();  //除錯看串列埠的名字
		availablePort.setPortName(Info.portName());
		if (availablePort.open(QIODevice::ReadWrite))
		{
			int index = ui.COM->findText(Info.portName());
			ui.COM->setItemText(index, Info.portName() + QString::fromLocal8Bit("可用"));
			ui.COM->setCurrentIndex(index);
			m_iVec.push_back(index);
									
			availablePort.close();  //開啟後關閉
		}
	}

      二. 開啟串列埠

          QtSerialPort的成員函式已經有了該功能,如下:

bool open(OpenMode mode) Q_DECL_OVERRIDE;
void close() Q_DECL_OVERRIDE;

          具體程式碼如下:

//開啟串列埠
void MySerial::slotOpenSerialPort()
{
	if(ui.btn_OpenSerialPort->text() == QString::fromLocal8Bit("開啟串列埠"))
	{
		m_pSerialPort = new QSerialPort(this);
		QString tempStr = ui.COM->currentText();
		tempStr.remove(QString::fromLocal8Bit("可用"), Qt::CaseSensitive);  //去掉“可用”這兩個字
		//選擇串列埠號
		m_pSerialPort->setPortName(tempStr);
		if (m_pSerialPort->open(QIODevice::ReadWrite)) 
		{
			portIsOpen = true;
			
			//設定波特率,校驗位,資料位,停止位
			setBaudRate();
			setParity();
			setDataBits();
			setStopBits();
			setFlowCtrl();

			statusBar()->showMessage(m_pSerialPort->portName() + " is opened");
			
			connect(Timer_CP, SIGNAL(timeout()), this, SLOT(checkPort()));
			Timer_CP->start(1000);

			//接收資料時會觸發訊號readyRead()
			connect(m_pSerialPort, SIGNAL(readyRead()), this, SLOT(readMyCom()));
			ui.btn_OpenSerialPort->setText(QString::fromLocal8Bit("關閉串列埠"));
			ChangeLabelColor(0, 255, 0);
		}
		else
		{
			QMessageBox::warning(this, QString::fromLocal8Bit("串列埠開啟失敗"), QString::fromLocal8Bit("串列埠不存在或本串列埠已經被佔用,請重試!"), QMessageBox::Cancel);

			ui.btn_OpenSerialPort->setChecked(false);
			return;
		}
	}
	else
	{
		if (m_pTimer_AutoSend->isActive()) 
		{
			m_pTimer_AutoSend->stop();
		}

		if (Timer_CP->isActive()) 
			Timer_CP->stop();

		Timer_CP->disconnect();
		if (m_pSerialPort->isOpen()) m_pSerialPort->close();
		
		resetCnt();
		ui.btn_OpenSerialPort->setText(QString::fromLocal8Bit("開啟串列埠"));
		statusBar()->showMessage(m_pSerialPort->portName() + " is closed", 2000);
		portIsOpen = false;
		ChangeLabelColor(0, 0, 0);
	}
}

     具體程式碼請參考原始碼,上面有連結。

三.  傳送資料

     串列埠操作是對裝置的輸入輸出進行操作,可以知道QSerialPort是派生於QIODevice,發資料相當於給串列埠寫入資料,需要呼叫QIODevice的write方法。先連線【傳送】按鈕對應的槽;

connect(ui.sendButton_1, SIGNAL(clicked()), this, SLOT(writeToBuf()));  //傳送

   writeToBuf()的實現如下:

void MySerial::writeToBuf()
{
	QObject *signalSender = sender();
	if (signalSender->objectName() == "sendButton_1") 
	{
		if (ui.hexRB_1->isChecked()) 
		{
			writeHex(ui.senderTextEdit_1);
		}
		else 
		{
			writeChr(ui.senderTextEdit_1);
		}
	}

 四. 讀取串列埠的資料

      在開啟串列埠時,有一行程式碼如下:

//接收資料時會觸發訊號readyRead()
connect(m_pSerialPort, SIGNAL(readyRead()), this, SLOT(readMyCom()));

       觸發訊號readyRead()後,就會接受串列埠的資料,具體的實現請下載原始碼分析。

       介面我用qss做了優化,不會的可以百度自學。

       關於串列埠的程式碼分析就到此為止,請參考開頭的原始碼進行分析,有一定C++基礎的都可以看懂。