我试图连接到PLC设备。我正确设置了设备中的所有配置,我成功连接并通过ModbusSlave软件测试了PC和PLC设备之间的通信。
我的QT代码是:
PLC = new QModbusTcpClient();
m_port = 502;
m_host = "10.100.101.2"; //PLC IP
PLC->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->m_port);
PLC->setConnectionParameter(QModbusDevice::NetworkAddressParameter, this->m_host);
PLC->setTimeout(5000);
PLC->setNumberOfRetries(10);
qDebug()<<"State: " << PLC->state();
qDebug()<<"Try to connect...";
if(!PLC->connectDevice()){
qDebug()<<"Not connected to PLC: " << PLC->errorString();
}
else{
qDebug()<<"State: " << PLC->state();
while(PLC->state()!=QModbusDevice::ConnectedState){
QThread::msleep(5);
}
qDebug()<<"Connection to PLC succesed" << PLC->state();
emit PLCConnected();
}
输出为:
状态:QModbus设备::未连接状态 尝试连接... 状态:QModbus设备::连接状态
首先,PLC->connectDevice((是做什么的?
其次,您不能在同一线程中等待连接,只需订阅QModbusDevice::stateChanged 信号并查找状态更改