Linux 虛擬串口及 Qt 串口通信實(shí)例
Linux下的虛擬終端
由于手上沒(méi)有可以測(cè)試的串口設(shè)備,因此發(fā)了點(diǎn)時(shí)間找了一個(gè)Linux下的虛擬串口工具:http://fayaa.com/code/view/8500/ ,這個(gè)工具打開(kāi)了兩個(gè)偽終端,然后讀兩個(gè)口子的數(shù)據(jù),如果是從1號(hào)口來(lái)的,就往2號(hào)口寫(xiě)入數(shù)據(jù),從2號(hào)口來(lái)的就寫(xiě)到1號(hào)口。
經(jīng)過(guò)我的修改后變成了這個(gè)樣子:
- #! /usr/bin/env python
- #coding=utf-8
- import pty
- import os
- import select
- def mkpty():
- #
- master1, slave = pty.openpty()
- slaveName1 = os.ttyname(slave)
- master2, slave = pty.openpty()
- slaveName2 = os.ttyname(slave)
- print '\nslave device names: ', slaveName1, slaveName2
- return master1, master2
- if __name__ == "__main__":
- master1, master2 = mkpty()
- while True:
- rl, wl, el = select.select([master1,master2], [], [], 1)
- for master in rl:
- data = os.read(master, 128)
- if master==master1:
- print "read %d data:" % len(data)
- print data
- #os.write(master2, data)
- else:
- print "to write %d data:" % len(data)
- print data.strip()
- os.write(master1, data.strip())
改變后 我們讓1號(hào)口為讀入口(串口設(shè)備讀入數(shù)據(jù)的口子),2號(hào)口為寫(xiě)出口(串口向外面寫(xiě)數(shù)據(jù)),將其保存為com.py
- #python com.py
- slave device names: /dev/pts/1 /dev/pts/2
意思是pts/1為1號(hào)口 pts/2為2號(hào)口
另建一個(gè)終端 #cd /dev/pts/
- #echo 456 > 2
就會(huì)向2號(hào)口寫(xiě)數(shù)據(jù),如果我們沒(méi)有其他程序讀串口的數(shù)據(jù)的話,那么就會(huì)出現(xiàn)4行數(shù):
- to write 5 data:
- 456
- read 3 data:
- 456
那么我們只要用程序讀/dev/pts/1就可以模擬串口通信了
Qt下的串口通訊
Qt沒(méi)有自帶串口模塊,只有第三方庫(kù) http://wenku.baidu.com/view/55849f4ffe4733687e21aa99.html,這篇文章介紹了簡(jiǎn)單的Qt串口通信
學(xué)著他的例子也做了一個(gè)程序,核心代碼:
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- com = new QextSerialPort("/dev/pts/1", QextSerialPort::Polling);
- com->open(QextSerialPort::ReadWrite);
- com->setBaudRate(BAUD9600);
- com->setDataBits(DATA_8);
- com->setParity(PAR_NONE);
- com->setStopBits(STOP_1);
- com->setFlowControl(FLOW_OFF);
- com->setTimeout(10);
- QTimer *timer = new QTimer(this);
- connect(timer, SIGNAL(timeout()), this, SLOT(readCOM()));
- timer->start(20);
- }
- void MainWindow::readCOM()
- {
- if (com->bytesAvailable() > 1)
- ui->showText->insertPlainText(com->readAll());
- }
- void MainWindow::on_btnSend_clicked()
- {
- com->write(ui->edit->text().toAscii().data());
- }
運(yùn)行結(jié)果:Qt向串口寫(xiě)數(shù)據(jù)
收到數(shù)據(jù):
串口向Qt寫(xiě)數(shù)據(jù)(下面那個(gè)終端控制)
注意:1號(hào)口和2號(hào)口的方向問(wèn)題很難分清楚,暫時(shí)這樣理解了沒(méi)必要深究 windows下的虛擬串口工具為VSPM,是Telnet管理的,建議先研究這個(gè)。
小結(jié):Linux 虛擬串口及 Qt 串口通信實(shí)例的內(nèi)容介紹完了,希望本文對(duì)你 有所幫助!