03. 串口打开和关闭按钮操作//串口打开和关闭按钮
void MainWindow::on_pushButton_Open_clicked()
{
//设置串口号;也就是说打开的是当前显示的串口
if(ui->comboBox_Port->currentText().isEmpty())
{
QMessageBox::information(this,"提示","没有可用的串口");
return;
}
Serial.setPortName(ui->comboBox_Port->currentText());
if(ui->pushButton_Open->text() == "打开串口")
{
if(Serial.open(QIODevice::ReadWrite))//读写方式打开,成功后设置串口
{
//设置波特率
Serial.setBaudRate(ui->comboBox_Baud->currentText().toInt());
//设置数据位
switch(ui->comboBox_DataBit->currentText().toInt())
{
case 5:
Serial.setDataBits(QSerialPort::Data5);
break;
case 6:
Serial.setDataBits(QSerialPort::Data6);
break;
case 7:
Serial.setDataBits(QSerialPort::Data7);
break;
case 8:
Serial.setDataBits(QSerialPort::Data8);
break;
default:
QMessageBox::information(this,"提示","数据位配置出错");
return;
break;
}
//设置校验位
if (ui->comboBox_CheckBit->currentText() == "奇效验")
{
Serial.setParity(QSerialPort::OddParity);
}
else if (ui->comboBox_CheckBit->currentText() == "偶效验")
{
Serial.setParity(QSerialPort::EvenParity);
}
else if (ui->comboBox_CheckBit->currentText() == "无")
{
Serial.setParity(QSerialPort::NoParity);
}
//设置停止位
if (ui->comboBox_StopBit->currentText().toFloat() == 1)
{
Serial.setStopBits(QSerialPort::OneStop);
}
else if(ui->comboBox_StopBit->currentText().toFloat() == 1.5)
{
Serial.setStopBits(QSerialPort::OneAndHalfStop);
}
else if(ui->comboBox_StopBit->currentText().toFloat() == 2)
{
Serial.setStopBits(QSerialPort::TwoStop);
}
//设置流控制
Serial.setFlowControl(QSerialPort::NoFlowControl);
ui->pushButton_Open->setText("关闭串口");
//建立串口接收的槽函数
connect(&Serial,&QSerialPort::readyRead ,this,&MainWindow::ReadRecData);
// timer0->start(100);
}
else//串口打开失败
{
QMessageBox::about(NULL, "提示", "打开出错,串口被占用!");
return ;
}
}
else if(ui->pushButton_Open->text() == "关闭串口")
{
Serial.close();//关串口
//timer0->stop();
ui->pushButton_Open->setText("打开串口");
}
}
|