class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pbConnect_clicked();
void readData();
private:
Ui::MainWindow *ui;
QSerialPort *serial; // 私有QSerialPort成员
};
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
const auto infos = QSerialPortInfo::availablePorts();
for(const QSerialPortInfo &info : infos){
ui->cbCom->addItem(info.portName());
}
serial = new QSerialPort; //实例化 serial
connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
}
void MainWindow::on_pbConnect_clicked()
{
if(ui->pbConnect->text()==QString("连接")){
serial->setPortName(ui->cbCom->currentText());
serial->setBaudRate(QSerialPort::Baud115200);
serial->setDataBits(QSerialPort::Data8);
serial->setStopBits(QSerialPort::OneStop);
serial->setParity(QSerialPort::NoParity);
if(!serial->open(QIODevice::ReadWrite)){
QMessageBox::information(this,"错误提示","不能打开串口",QMessageBox::Ok);
}
else{
ui->cbCom->setEnabled(false);
ui->pbConnect->setText("关闭");
}
}
else{
serial->close();
ui->cbCom->setEnabled(true);
ui->pbConnect->setText("连接");
}
}
const auto infos = QSerialPortInfo::availablePorts();
for(const QSerialPortInfo &info : infos){
ui->cbCom->addItem(info.portName());
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pbConnect_clicked();
void readData();
private:
Ui::MainWindow *ui;
QSerialPort *serial;
};
void MainWindow::readData()
{
QString data = serial->readAll();
QStringList datlist = data.split(",",QString::SkipEmptyParts);
ui->lineEdit->setText(data);
ui->lcdNumber1->display(datlist[0]);
ui->lcdNumber2->display(datlist[1]);
}
作者:southcreek
来源:面包板社区
https://mbb.eet-china.com/blog/408807-441193.html
本文为面包板社区原创打赏文章,点击阅读原文,发表原创文章,获得打赏奖励!
↓↓ 点击阅读原文,参加活动