Qt Modbus在QtCreator的示例里面有例子,直接搜modbus就可以看到了,简单学一下就能学会了。
QModbusClient *modbusDevice;
1、删除modbus设备对象
if (modbusDevice) modbusDevice->disconnectDevice();
delete modbusDevice;
modbusDevice = nullptr;
2、创建modbus对象
modbusDevice = new QModbusRtuSerialMaster(this);
connect(modbusDevice, &QModbusClient::errorOccurred, [this](QModbusClient::Error){
statusBar()->showMessage(modbusDevice->errorString(), 5000);
});
//检查是否创建modbus master成功
if(!modbusDevice){
ui->btn_connect->setDisabled(true);
statusBar()->showMessage(tr("不能创建Modbus Master。"), 5000);
}else{
//当连接状态出现改变
connect(modbusDevice, &QModbusClient::stateChanged, this, &MainWindow::modbusStateChanged);
}
qDebug() << "创建ModbusDevice成功!";
/**********************modbusStateChanged****************************/
void MainWindow::modbusStateChanged(int state){
if(state == QModbusDevice::UnconnectedState){
ui->btn_connect->setText("连接");
}else{
ui->btn_connect->setText("断开");
}
}
/**************************************************************/
3、配置modbus设备参数
//需要先检查modbus设备是否存在
if (!modbusDevice) return;
if(modbusDevice->state() != QModbusDevice::ConnectedState){
modbusDevice->setConnectionParameter(
QModbusDevice::SerialPortNameParameter, ui->lineEdit_port->text());
modbusDevice->setConnectionParameter(
QModbusDevice::SerialParityParameter, serial_cfig.serial_settings.parity);
modbusDevice->setConnectionParameter(
QModbusDevice::SerialBaudRateParameter, serial_cfig.serial_settings.baud);
modbusDevice->setConnectionParameter(
QModbusDevice::SerialDataBitsParameter, serial_cfig.serial_settings.dataBits);
modbusDevice->setConnectionParameter(
QModbusDevice::SerialStopBitsParameter, serial_cfig.serial_settings.stopBits);
modbusDevice->setTimeout(serial_cfig.serial_settings.responseTime);
modbusDevice->setNumberOfRetries(serial_cfig.serial_settings.numberOfRetries);
//检查modbusDevice是否连接成功
if(!modbusDevice->connectDevice()){
statusBar()->showMessage(tr("连接失败:") + modbusDevice->errorString(), 5000);
qDebug() << "连接失败!";
}else{
ui->btn_connect->setText("断开");
qDebug() << "连接成功!";
}
}else{
modbusDevice->disconnectDevice();
ui->btn_connect->setText("连接");
qDebug() << "断开成功";
}
/**********************************************************************************/
//这里是读写操作
void MainWindow::read_button_clicked()
{
statusBar()->clearMessage();
if(!modbusDevice || modbusDevice->state() != QModbusDevice::ConnectedState) {
statusBar()->showMessage(tr("Modbus Device is not connected!"), 5000);
return;
}
//table
const auto table = static_cast (ui->comboBox_table->currentData().toInt());
//读取modbus变量起始地址
int startAddress = ui->lineEdit_address->text().toInt()-1;
//读取modbus变量的数量
int numOfEntries = ui->lineEdit_length->text().toInt();
//QModbusDataUnit
QModbusDataUnit dataunit = QModbusDataUnit(table, startAddress, numOfEntries);
if(auto *reply = modbusDevice->sendReadRequest( dataunit, ui->spinBox_server_address->value())){
if(!reply->isFinished()) {
connect(reply, &QModbusReply::finished, this, &MainWindow::read_ready);
} else {
delete reply;
}
}else{
statusBar()->showMessage(tr("Read Error:")+modbusDevice->errorString(), 5000);
}
}
void MainWindow::read_ready()
{
auto reply = qobject_cast (sender());
if (!reply) return;
if (reply->error() == QModbusDevice::NoError) {
const QModbusDataUnit unit = reply->result();
ui->textEdit->clear();
for (uint i = 0; i < unit.valueCount(); i++) {
const QString entry = tr("Address: %1, Value: %2")
.arg(unit.startAddress() + i + 1)
.arg(QString::number(unit.value(i)));
ui->textEdit->append(entry);
}
} else if (reply->error() == QModbusDevice::ProtocolError) {
statusBar()->showMessage(tr("Read response error: %1 (Mobus exception: 0x%2)")
.arg(reply->errorString())
.arg(reply->rawResult().exceptionCode(), -1, 16), 5000);
} else {
statusBar()->showMessage(tr("Read response error: %1 (code: 0x%2)")
.arg(reply->errorString())
.arg(reply->error(), -1, 16), 5000);
}
reply->deleteLater();
}
void MainWindow::write_button_clicked()
{
statusBar()->clearMessage();
if(!modbusDevice || modbusDevice->state() != QModbusDevice::ConnectedState) {
statusBar()->showMessage(tr("Modbus Device is not connected!"), 5000);
return;
}
//table
const auto table = static_cast (ui->comboBox_table->currentData().toInt());
//读取modbus变量起始地址
int startAddress = ui->lineEdit_address->text().toInt()-1;
//读取modbus变量的数量
int numOfEntries = ui->lineEdit_length->text().toInt();
//QModbusDataUnit
QModbusDataUnit dataunit = QModbusDataUnit(table, startAddress, numOfEntries);
for(uint i = 0; i < dataunit.valueCount(); i++){
dataunit.setValue( i, ui->lineEdit_data->text().toUShort());
}
if(auto *reply = modbusDevice->sendWriteRequest(dataunit, ui->spinBox_server_address->value())){
if(!reply->isFinished()){
connect(reply, &QModbusReply::finished, this, [this, reply](){
if(reply->error() == QModbusDevice::ProtocolError){
statusBar()->showMessage(tr("Write response error: %1 (Modbus exception:0x%2)")
.arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16), 5000);
}else if(reply->error() != QModbusDevice::NoError){
statusBar()->showMessage(tr("Write response error: %1 (code: 0x%2)")
.arg(reply->errorString(), -1, 16), 5000);
}
reply->deleteLater();
});
}else{
statusBar()->showMessage(tr("Write error:") + modbusDevice->errorString(), 5000);
}
}
}