modbus 用的是git上的開源代碼,位址:https://github.com/stephane/libmodbus
講一下基本使用(給指定位址發送 on/off指令以及讀取):
modbus_t *ctx = NULL;
ctx = modbus_new_tcp("127.0.0.1", 502);//填寫的是plc的ip、port
if (ctx == NULL)
{
cout << "Unable to allocate libmodbus context" << endl;
return -1;
}
//modbus_set_debug(ctx, TRUE);
if (modbus_connect(ctx) == -1)
{
cout << "Connection failed: " << modbus_strerror(errno) << endl;
modbus_free(ctx);
return -1;
}
int rc = modbus_write_bit(ctx, addr, value); //addr: 0x6000 value:true
if (rc != 1)
{
cout <<"ERROR modbus_write_bit "<< rc << endl;
}
uint8_t tab_rp_bits[4] = { 0 };
rc = modbus_read_bits(ctx, addr, 1, tab_rp_bits);
if (rc != 1)
{
cout <<"ERROR modbus_read_bits "<< rc << endl;
}
modbus_close(ctx);
modbus_free(ctx);