modbus_read_register - Error connection timed out(no hardware problem)

159 Views Asked by At

I am new to Modbus protocol. I want to read data from RS485. I have written C code using Libmodbus library on Linux board but unable to read data getting error connection timed out.

timeout error

I connect the LInux board to my PC through a 485-to-USB module, and use the modbus slave software on my PC for modbus testing. To the RS485 port of Linux machine where I run the below C code there.

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "modbus-rtu.h"  //modbus动态库文件
 
int main(int argc, char *argv[])
{
    uint16_t buffer[10];
    modbus_t *ctx = NULL;
 
    int rc;
    int i;
    
    //以串口的方式创建libmobus实例,并设置参数
    ctx = modbus_new_rtu("/dev/ttyS7", 115200, 'N', 8, 1);
    modbus_rtu_set_serial_mode(ctx, 1);
                    
    if (ctx == NULL)
    {
        fprintf(stderr, "Unable to allocate libmodbus contex\n");
        return -1;
    }
    
    modbus_set_debug(ctx, 1);      //设置1可看到调试信息
    modbus_set_slave(ctx, 1);      //设置slave ID
    
    if (modbus_connect(ctx) == -1) //等待连接设备
    {
        fprintf(stderr, "Connection failed:%s\n", modbus_strerror(errno));
        return -1;
    }
    
    while (1)
    {
        printf("\n----------------\n");
        rc = modbus_read_registers(ctx, 0, 10, buffer);
        if (rc == -1)                   //读取保持寄存器的值,可读取多个连续输入保持寄存器
        {
            fprintf(stderr,"%s\n", modbus_strerror(errno));
            return -1;
        }
        for (i=0; i<10; i++)
        {
            printf("reg[%d] = %d(0x%x)\n", i, buffer[i], buffer[i]);
        }
        
        usleep(100000);
    }
    modbus_close(ctx);  //关闭modbus连接
    modbus_free(ctx);   //释放modbus资源,使用完libmodbus需要释放掉
 
    return 0;
}

I have checked the communication on the modbus slave, the sending and receiving have no problem, as shown in the following picture:

communication on modbus slave

Since I reserved more than one RS485 interface on the Linux board, I connected another RS485 interface to the PC through another 485-to-USB module, and checked the communication on the 485 bus with the serial port debugging assistant.

communition on serial port debugging

I also wrote a set of custom protocols for RS485 communication between Linux board and raspbery pico board before, and the communication have no problem, so there should be no problem with the hardware.

I have checked the previous post on stackoverflow, and one suggested to start the test from 19200 baud rate, but I adjusted the baud rate of both Linux board and modbus slave to 19200, the error is the same, still timeout error.

0

There are 0 best solutions below