第一步:由于我们用的是第三方库文件,所以我们首先需要下载qextserialport-1.2win-alpha,下载地址:http://sourceforge.net/projects/qextserialport/files/,具体文件介绍可以参考yafeilinux的博客。
第二步:新建GUI工程,添加qextserialbase.cpp和qextserialbase.h 以及posix_qextserialport.cpp和posix_qextserialport.h四个文件到工程中。
第三步:绘制简单串口调试界面如下
第四步:修改代码,实现串口调试功能
在mainwindow.h中添加:Posix_QextSerialPort *myCom;以及定义槽函数:
void readMyCom();
void on_pushButton_clicked();
在mainwindow.cpp中添加代码如下
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//this->setWindowFlags(Qt::FramelessWindowHint); //加这句可以可以让对话框的控制台不显示。
// struct PortSettings myComSetting={BAUD115200,DATA_8,PAR_NONE,STOP_1,FLOW_OFF,500};
//declear a struct for cortain the member of mycom;
myCom = new Posix_QextSerialPort("/dev/ttyUSB0",QextSerialBase::Polling);
//define the member of serial ,and sen the number ,declear for it in the constructor
myCom->setBaudRate(BAUD9600); //波特率设置,我们设置为9600,这个值是我在用MSP430传数时用的最合适的波特率。
myCom->setDataBits(DATA_8); //数据位设置,我们设置为8位数据位
myCom->setParity(PAR_NONE); //奇偶校验设置,我们设置为无校验
myCom->setStopBits(STOP_1); //停止位设置,我们设置为1位停止位
myCom->setFlowControl(FLOW_OFF); //数据流控制设置,我们设置为无数据流控制
myCom->open(QIODevice::ReadWrite); //open the serial with the style of ReadWrite.
//connect(myCom,SIGNAL(readyRead()),this,SLOT(readMyCom())); //这个为中断方式,但linux下只能用查询方式
//conect the SLOT and SIGNAL,when there are data in the serial buffer,it will read the serial
myCom->setTimeout(100);
QTimer *readTimer = new QTimer(this);
readTimer->start(100);
connect(readTimer,SIGNAL(timeout()),this,SLOT(readMyCom()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::readMyCom() //The function for read
{
QByteArray temp = myCom->readAll();
//read all data int the buffer ,and send it to the temporary variable "temp"
temp=temp.toHex();
ui->textBrowser->insertPlainText(temp);
//show the data of serial int the texBrowser
}
void MainWindow::on_pushButton_clicked()//发送数据
{
myCom->write(ui->lineEdit->text().toLatin1().data()); //以ASCII码形式将数据写入串口
}
连上msp430的串口线,并向PC发送数据,运行结果如下:
问题1:一开始时出现显示乱码问题
原因:没有将接收到的数据以HEX格式显示,所以乱码,加以下语句:
temp=temp.toHex();
就可完美显示了。