I am using below c\c++ sample code to read Modbus RTU data using libmodbus. I have two different linux based gateways one has Raspbian GNU/Linux 10 (buster) while other has Yocto Dizzy Release. Using libmodbus lib, I am able to read modbus tcp data on both gateways. But in case of Raspbian GNU/Linux 10 (buster) for modbus rtu (RS485), I am getting connection timeout while reading buffer. There is one more difference in both gateways, i.e, Raspbian GNU/Linux 10 (buster) uses ttyUSB0 port while Yocto Dizzy Release uses ttymxc2 port of linux.

But when I tried a sample code in python using pymodbus on Raspbian GNU/Linux 10 (buster), I was able to read data.

Can someone help to identify what's going wrong for modbus rtu (RS485) using libmodbus for Raspbian GNU/Linux 10 (buster) in c++.

//Create a new RTU context with proper serial parameters (in this example,
//device name /dev/ttyUSB0, baud rate 9600, no parity bit, 8 data bits, 1 stop bit)
modbus_t *ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);

if (!ctx) {
    printf("Failed to create the context: %s\n", modbus_strerror(errno));
    //exit(1);
}

if (modbus_connect(ctx) == -1) {
    printf("Unable to connect: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    //exit(1);
}

//Set the Modbus address of the remote slave (to 1)
modbus_set_slave(ctx, 1);


uint16_t reg[5];// will store read registers values

//Read 5 holding registers starting from address 10
int num = modbus_read_registers(ctx, 50001, 5, reg);
if (num != 5) {// number of read registers is not the one expected
    printf("Failed to read: %s\n", modbus_strerror(errno));
}
else
{
    for(int i=0; i < 5; i++)
    {
        printf("reg %d: %d\n", i,reg[i]);
    }
}
modbus_close(ctx);
modbus_free(ctx);
return 0;
0

There are 0 best solutions below