问题描述
我使用下面的 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 (将#修改为@)