0

I have weird problem. I try to communicate with ifm AY1020 via modbusTCP using libmodbus from PC.

My code looks as follow:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus/modbus.h>

int main()
{
  modbus_t *ctx;
  uint16_t *tab_reg;
  int rc;
  int i;

  ctx = modbus_new_tcp("192.168.1.250", 502);
  modbus_set_debug(ctx, TRUE);


  tab_reg = (uint16_t *) malloc(5 * sizeof(uint16_t));
  memset(tab_reg, 0, 5 * sizeof(uint16_t));


  if (modbus_connect(ctx) == -1)
  {
    fprintf(stderr, "Connection failed: %s\n",modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
  }

  rc = modbus_read_registers(ctx, 3002, 2, tab_reg);

  if (rc == -1) 
  {
    fprintf(stderr, "%s\n", modbus_strerror(errno));
    return -1;
  }

  for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
   }

  modbus_close(ctx);
  modbus_free(ctx);
}

Thanks to debug I was able to get the frame that is generated in modbus_read_registers function:

[00][01][00][00][00][06][FF][03][0B][BA][00][02]

And I get this

ERROR Gateway path unavailable Gateway path unavailable

After analysis you can find that device id in that frame is FF, but according to this error PLC expects 1.

Going further if during debugging I force change this value from FF to 01 everything works fine. It looks like it assign wrong ID.

I would be grateful for any help, advice, solution.

Best,

Paweł

pzydziak
  • 89
  • 1
  • 2
  • 10

1 Answers1

0

Looking at the Man

You should call modbus_set_slave to set a specific destination device.

TCP

The slave number is only required in TCP if the message must reach a device on a serial network. The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to restore the default value.

Emphasis mine

Your code should be

modbus_set_slave(ctx, 1);
rc = modbus_read_registers(ctx, 3002, 2, tab_reg);
Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61