Connection Timed Out

47 views
Skip to first unread message

Yiping Li

unread,
Jul 27, 2017, 6:31:24 AM7/27/17
to libmodbus

Hi,

 

We are using the modbus with RS485, connecting to Raspberry Pi 2. And we have used the library Libmodbus. But we are facing an issue:

 

When we start our program, we had a “Connection Timed Out” and the Bad File Descritptor.

 

What kind of problem can it be?

 

We need your help, thanks in advance.

Here is part of our code:


int read_registers(){

    int errMRR;
    int j;
    int nbReg, cptValue;
    int indexRegisterValues = 0;
    uint16_t tabRegister[2];

    for(j=0;j<deviceCfg[0].nbDevice;j++){

        if(!strcmp(deviceCfg[j].connected ,"Y")){

            usleep(20000);
            if (deviceCfg[j].deviceAddress!=currentDeviceAddress){

                modbus_close(ctx);
                currentDeviceAddress=deviceCfg[j].deviceAddress;
                modbus_set_slave(ctx, deviceCfg[j].deviceAddress);
                if (modbus_connect(ctx) == -1) {

                    fprintf(stderr, "Connexion failed: %s\n", modbus_strerror(errno));
                    modbus_free(ctx);
                    return -1;
                }
            }

            if (deviceCfg[j].registerAddressFormat == FORMAT32){

                nbReg=2;
            }
            else if (deviceCfg[j].registerAddressFormat == FORMAT16){

                nbReg=1;
            }

            errMRR = modbus_read_registers(ctx, (deviceCfg[j].registerAddress) - 1, nbReg, tabRegister);

            if(errMRR == -1){

                fprintf(stderr, "Modbus read register error : %s\n", modbus_strerror(errno));
                registerValues[indexRegisterValues] = -1;
                indexRegisterValues++;

            }else{

                if (deviceCfg[j].registerAddressFormat == FORMAT32) cptValue=tabRegister[0]*pow(2,16) + tabRegister[1];
                if (deviceCfg[j].registerAddressFormat == FORMAT16) cptValue=tabRegister[0];

                printf("cptValue = %d\n",cptValue);
                registerValues[indexRegisterValues]=cptValue;
                indexRegisterValues++;
            }
        }
    }

    printf("#communication : %d \n",nbCommunication);
    nbCommunication++;
}
Image Pasted at 2017-7-27 11-44.png

Mughil Arul

unread,
Feb 14, 2019, 8:16:15 AM2/14/19
to libmodbus
Hi,

You havent initialized a modbus_t structure ie ctx. use modbus_new_rtu() / modbus_new_tcp() function to initilize the  modbus_t structure.
Reply all
Reply to author
Forward
0 new messages