linux中qt编写串口程序,在Linux下用QT5编写第一个串口调试程序

第一步:由于我们用的是第三方库文件,所以我们首先需要下载qextserialport-1.2win-alpha,下载地址:http://sourceforge.net/projects/qextserialport/files/,具体文件介绍可以参考yafeilinux的博客。

第二步:新建GUI工程,添加qextserialbase.cpp和qextserialbase.h 以及posix_qextserialport.cpp和posix_qextserialport.h四个文件到工程中。

第三步:绘制简单串口调试界面如下

0818b9ca8b590ca3270a3433284dd417.png

第四步:修改代码,实现串口调试功能

在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发送数据,运行结果如下:

0818b9ca8b590ca3270a3433284dd417.png

问题1:一开始时出现显示乱码问题

0818b9ca8b590ca3270a3433284dd417.png

原因:没有将接收到的数据以HEX格式显示,所以乱码,加以下语句:

temp=temp.toHex();

就可完美显示了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值