#include "widget.h" #include "ui_widget.h" #include #include #include #include #include "crc.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); serialPort = new QSerialPort(this); connect(serialPort,&QSerialPort::readyRead,this,&Widget::on_SerialData_ReadyToRead); ui->comboBox_baudRate->setCurrentIndex(3); ui->comboBox_dataBit->setCurrentIndex(3); ui->comboBox_xiaoyan->setCurrentIndex(2); QList serialList = QSerialPortInfo::availablePorts(); for(QSerialPortInfo serialInfo : serialList) { ui->comboBox_serialNum->addItem(serialInfo.portName()); } } Widget::~Widget() { delete ui; } void Widget::on_btnConnect_clicked() { if (ui->btnConnect->text() == "连接") { //配置串口号 serialPort->setPortName(ui->comboBox_serialNum->currentText()); //配置波特率 serialPort->setBaudRate(ui->comboBox_baudRate->currentText().toInt()); //配置数据位 serialPort->setDataBits(QSerialPort::DataBits(ui->comboBox_dataBit->currentText().toInt())); //配置校验位 switch (ui->comboBox_xiaoyan->currentIndex()) { case 0: serialPort->setParity(QSerialPort::NoParity); break; case 1: serialPort->setParity(QSerialPort::OddParity); break; case 2: serialPort->setParity(QSerialPort::EvenParity); } //配置停止位 serialPort->setStopBits(QSerialPort::StopBits(ui->comboBox_stopBit->currentText().toInt())); //打开串口 if (serialPort->open(QIODevice::ReadWrite)) { qDebug() << "Serial open success"; ui->btnConnect->setText("断开"); } else { qDebug() << "error"; } } else { serialPort->close(); ui->btnConnect->setText("连接"); } } void Widget::on_pushWrite_clicked() { const char *sendData = ui->lineEdit->text().toStdString().c_str(); serialPort->write(sendData); qDebug() << "SenOk" <readAll(); QString hexData = revMessage.toHex().toUpper(); qDebug() << hexData; ui->textEdit->append(hexData); } void Widget::on_btn_read_clicked() { QByteArray SendCommand; SendCommand.append(ui->comboBox_stationAddress->currentText().toInt()%256); if (ui->comboBox_gongnengma->currentIndex() == 0) { SendCommand.append(0x01); } else if(ui->comboBox_gongnengma->currentIndex() == 1) { SendCommand.append(0x03); } SendCommand.append(ui->lineEdit_stratAddress->text().toInt()/256); SendCommand.append(ui->lineEdit_stratAddress->text().toInt()%256); SendCommand.append(ui->lineEdit_length->text().toInt()/256); SendCommand.append(ui->lineEdit_length->text().toInt()%256); quint16 temp = calculateCrc(SendCommand); SendCommand.append(temp%256); SendCommand.append(temp/256); qDebug() << SendCommand.toHex(); serialPort->write(SendCommand); }