QT 串口 windows下

http://blog.csdn.net/yafeilinux/article/details/5741706

用widget类新建一个窗口

其中的TextBrowser 部件用来显示接收到的数据,

Line Edit部件用来输入要发送的数据,

Push Button按钮用来发送数据。我们保持各部件的属性为默认值即可。


引入第三方的类 qextserialport-1.2win-alpha.zip

加入

qextserialbase.cpp和qextserialbase.h以及win_qextserialport.cpp和win_qextserialport.h

 

 

myCom.h

#ifndef MYCOM_H

#define MYCOM_H

 

#include <QWidget>

#include "win_qextserialport.h"

namespace Ui {

    classmyCom;

}

 

class myCom : public QWidget

{

    Q_OBJECT

 

public:

    explicitmyCom(QWidget *parent = 0);

    ~myCom();

 

private:

    Ui::myCom*ui;

   Win_QextSerialPort *myCom1;

 

private slots:

    voidon_pushButton_clicked(); //”发送数据”按钮槽函数

    voidreadMyCom();  //读取串口

};

 

#endif // MYCOM_H

myCom.cpp

#include "mycom.h"

#include "ui_mycom.h"

 

myCom::myCom(QWidget *parent) :

    QWidget(parent),

    ui(newUi::myCom)

{

   ui->setupUi(this);

    myCom1 =new Win_QextSerialPort("COM1",QextSerialBase::EventDriven);

        //定义串口对象,指定串口名和查询模式,这里使用事件驱动EventDriven

        myCom1->open(QIODevice::ReadWrite);

        //以读写方式打开串口

        myCom1->setBaudRate(BAUD9600);

        //波特率设置,我们设置为9600

       myCom1->setDataBits(DATA_8);

        //数据位设置,我们设置为8位数据位

       myCom1->setParity(PAR_NONE);

        //奇偶校验设置,我们设置为无校验

        myCom1->setStopBits(STOP_1);

        //停止位设置,我们设置为1位停止位

        myCom1->setFlowControl(FLOW_OFF);

        //数据流控制设置,我们设置为无数据流控制

        myCom1->setTimeout(500);

        //延时设置,我们设置为延时500ms,这个在Windows下好像不起作用

       connect(myCom1,SIGNAL(readyRead()),this,SLOT(readMyCom()));

        //信号和槽函数关联,当串口缓冲区有数据时,进行读串口操作

}

 

myCom::~myCom()

{

    delete ui;

}

 

void myCom::readMyCom() //读取串口数据并显示出来

{

    QByteArraytemp = myCom1->readAll();

    //读取串口缓冲区的所有数据给临时变量temp

    ui->textBrowser->insertPlainText(temp);

    //将串口的数据显示在窗口的文本浏览器中

}

void myCom::on_pushButton_clicked()  //发送数据

{

   myCom1->write(ui->lineEdit->text().toAscii());

    //以ASCII码形式将数据写入串口

}

 

main.cpp

#include <QtGui/QApplication>

#include "mycom.h"

 

int main(int argc, char *argv[])

{

   QApplication a(argc, argv);

    myCom w;

    w.show();

 

    returna.exec();

}

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值