首页 > 解决方案 > libmodbus 库的 modbus_read_registers() 无法在 Raspbian GNU/Linux 10 (buster) 上读取 RS485 数据,但能够在 Yocto Dizzy Release 上读取

问题描述

我正在使用下面的 c\c++ 示例代码来使用 libmodbus 读取 Modbus RTU 数据。我有两个不同的基于 linux 的网关,一个有 Raspbian GNU/Linux 10 (buster),另一个有 Yocto Dizzy Release。使用 libmodbus lib,我能够读取两个网关上的 modbus tcp 数据。但是对于 modbus rtu (RS485) 的 Raspbian GNU/Linux 10 (buster),我在读取缓冲区时遇到连接超时。两种网关还有一个区别,即 Raspbian GNU/Linux 10 (buster) 使用 ttyUSB0 端口,而 Yocto Dizzy Release 使用 linux 的 ttymxc2 端口。

但是当我在 Raspbian GNU/Linux 10 (buster) 上使用 pymodbus 在 python 中尝试示例代码时,我能够读取数据。

有人可以帮助确定在 c++ 中使用 libmodbus for Raspbian GNU/Linux 10 (buster) 的 modbus rtu (RS485) 出了什么问题。

//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;

标签: c++modbusraspbian-busterlibmodbus

解决方案


推荐阅读