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;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...