我不熟悉Modbus协议。我想从RS485中读取数据。我已经使用Libmodbus库编写了C代码,但无法读取连接超时的错误数据。我在这里使用运行在windows机器上的modbus从属设备,从这里我从windows机器的COM端口将USB连接到串行电缆。到Linux机器的RS485端口,我在那里运行下面的C代码。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <modbus.h>
int main()
{
modbus_t *ctx = 0;
//
// create a libmodbus context for RTU
// doesn't check if the serial is really there
//
ctx = modbus_new_rtu("/dev/ttyS2", 115200, 'N', 8, 1);
if (ctx == 0) {
fprintf(stderr, "Unable to create the libmodbus context\n");
return -1;
} else {
struct timeval old_response_timeout;
struct timeval response_timeout;
// enable debug
modbus_set_debug(ctx, true);
// initialize timeouts with default
modbus_get_response_timeout(ctx, &old_response_timeout);
response_timeout = old_response_timeout;
// set the message and charcater timeout to 2 seconds
response_timeout.tv_sec = 2;
modbus_set_response_timeout(ctx, &response_timeout);
modbus_set_byte_timeout(ctx, &response_timeout);
}
// try to connet to the first DZT on the line
// assume that line address is 1, the default
// send nothing on the line, just set the address in the context
if(modbus_set_slave(ctx, 1) == -1) {
fprintf(stderr, "Didn't connect to slave/n");
return -1;
}
// establish a Modbus connection
// in a RS-485 context that means the serial interface is opened
// but nothing is yet sent on the line
if(modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
} else {
int nreg = 0;
uint16_t tab_reg[32];
// uint16_t
fprintf(stderr, "Connected\n");
//
// read all registers in DVT 6001
// the function uses the Modbus function code 0x03 (read holding registers).
//
nreg = modbus_read_registers(ctx,0,5,tab_reg);
//printf(tab_reg);
if (nreg == -1) {
fprintf(stderr, "Error reading registers: %s\n", modbus_strerror(errno));
modbus_close(ctx);
modbus_free(ctx);
return -1;
} else {
int i;
// dump all registers content
fprintf (stderr, "Register dump:\n");
for(i=0; i < nreg; i++)
printf("reg #%d: %d\n", i, tab_reg[i]);
modbus_close(ctx);
modbus_free(ctx);
return 0;
}
}
}错误如下
Opening /dev/ttyS2 at 115200 bauds (N, 8, 1)
Connected
[01][03][00][00][00][05][85][C9]
Waiting for a confirmation...
ERROR Connection timed out: select
Error reading registers: Connection timed out发布于 2018-10-24 20:47:24
我要检查的第一件事是串行通信硬件。是否有任何其他设备可以尝试连接到这两台计算机,以确保每台计算机的串行端口都正常工作?这将有助于验证每台计算机上是否正确安装和配置了串行端口。USB到串行的转换是出了名的挑剔和困难的工作。
我要检查的下一件事是每台机器的波特率和串口设置。RS-232和RS-485串行通信协议不会自动协商/自动检测连接速度,因此两台设备需要具有相同的连接设置。
您可能还想尝试使用低于115200的波特率。虽然更高的波特率允许更多的带宽和吞吐量,但也有更大的机会出错。我会从19200波特率开始,一旦你让它正常工作,我就会从那里开始。
另外,您在哪个用户下运行此程序?您可能需要通过sudo或以提升权限的用户身份执行该程序。
https://stackoverflow.com/questions/52967306
复制相似问题