串口案例
111204
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSerialPort>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void spReadyRead();
private:
Ui::MainWindow *ui;
QSerialPort sp;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// sp=new QSerialPort();
sp.setPortName("COM3");
sp.setBaudRate(QSerialPort::Baud9600);
sp.setDataBits(QSerialPort::Data8);
sp.setParity(QSerialPort::NoParity);
sp.setStopBits(QSerialPort::OneStop);
connect(&sp,QSerialPort::readyRead,this,MainWindow::spReadyRead);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString str=ui->lineEdit->text();
if(!sp.isOpen())
{
sp.open(QSerialPort::ReadWrite);
}
sp.write(str.toLatin1());
}
void MainWindow::spReadyRead()
{
ui->lineEdit_2->setText(sp.readAll());
}