数据解析可以参考(写脉冲信号时:应先清零,再写0xff00,在清零):Ubuntu C++ Modbus Rtu 伪代码_yuchunhai321的博客-CSDN博客
modbus 网络通信(伪代码):
void init(std::string ip, uint16_t port)
{
modbus_t *m_sensor_ctx = modbus_new_tcp(ip.c_str(), port);
if(m_sensor_ctx == NULL) {
printf("sensor modbus connet ip: %s faild", ip.c_str());
return;
}
modbus_set_slave(m_sensor_ctx, 1);
if((m_modbusIsConnect = modbus_connect(m_sensor_ctx)) == -1) {
printf("modbus tcp connect failed: %s", modbus_strerror(errno));
return ;
}
}
void close()
{
modbus_close(m_sensor_ctx);
modbus_free(m_sensor_ctx);
}
void write()
{
uint16_t write_regs[3] = {0};
write_regs[0] = 0x01;
write_regs[1] = 0x02;
write_regs[2] = 0x03;
modbus_write_registers(m_sensor_ctx, 25, 3, write_regs);
return true;
}
void read()
{
uint16_t reg_value[12] = {0};
int reconnect_times = 0;
while(true){
memset(reg_value, 0, sizeof(reg_value));
modbus_flush(m_sensor_ctx);
int ret = modbus_read_registers(m_sensor_ctx, 0, 12, reg_value); //返回接收到得数据长度 第一次返回-1, 第二次开始返回接收到得数据长度
if(ret < 0){
printf("Sensor board : read_holding_registers error! ret = %d \n",ret);
sleep(1);
if(++reconnect_times > 10)
{
printf("Sensor board : disconnected,reconnecting... ret = %d \n",ret);
modbus_close(m_sensor_ctx);
modbus_free(m_sensor_ctx);
reconnect_times = 0;
m_sensor_ctx = modbus_new_tcp(ip.c_str(), port);
modbus_set_slave(m_sensor_ctx, 1);
if((m_modbusIsConnect = modbus_connect(m_sensor_ctx)) == -1) {
printf("modbus tcp connect failed: %s", modbus_strerror(errno));
}
}
} else if(ret >= 0) {
reconnect_times = 0;
for(int i = 0 ; i < 12; i++)
printf("sensor reg_value[%d] = 0x%04x\n",i,reg_value[i]);
sensor_data.forward_avoidance_sensor = reg_value[0];
sensor_data.backward_avoidance_sensor = reg_value[1];
LOG_INFO("recv data 0 = %d 1 = %d", reg_value[0], reg_value[1]);
}
usleep(500*1000)
}
}