【问题标题】:Read Register via Modbus通过 Modbus 读取寄存器
【发布时间】:2013-08-08 22:47:55
【问题描述】:

我正在尝试编写一个 c 程序来读取 Morningstar sunsaver MPPT 的数据。

这是我在net中找到的简单程序。但是我的程序无法从寄存器中读取数据。

#include <stdlib.h>
#include <errno.h>
#include "src/modbus.h"
int main(void)
{
    modbus_t *ctx;
    uint16_t tab_reg[64];
    int rc;
    int i;

    ctx = modbus_new_rtu("/dev/ttyS0", 115200, 'N',8,1);
    if (ctx == NULL) {
       fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
       modbus_free(ctx);
       return -1;
    }

    rc = modbus_read_registers(ctx, 0, 10, tab_reg);
    if (rc == -1) {
      fprintf(stderr, "%s\n", modbus_strerror(errno));
      return -1;
    }

    for (i=0; i < rc; i++) {
      printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
    }

    modbus_close(ctx);
    modbus_free(ctx);
}

它对我不起作用。我收到以下错误消息:

错误的文件描述符

【问题讨论】:

  • 您的系统上是否存在/dev/ttyS0 文件?

标签: c modbus


【解决方案1】:

通过阅读documentation from LibModBus,我认为您错过了对modbus_connect 的呼叫。

在读取寄存器之前尝试连接:

ctx = modbus_new_rtu("/dev/ttyS0", 115200, 'N',8,1);
if (ctx == NULL) {
   fprintf(stderr, "Creation failed: %s\n", modbus_strerror(errno));
   return -1;
}

if (modbus_connect(ctx) == -1) {
    fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}

另外,由于进一步的错误情况,请记住在退出之前modbus_closemodbus_free 您的上下文。例如:

rc = modbus_read_registers(ctx, 0, 10, tab_reg);
if (rc == -1) {
  fprintf(stderr, "%s\n", modbus_strerror(errno));
  modbus_close(ctx);
  modbus_free(ctx);
  return -1;
}

【讨论】:

    【解决方案2】:

    原来是尝试从错误的串行端口读取。

    从 /dev/ttyS3 读取有效。

    我后来意识到串口来自 /dev/ttyS0 .. /dev/ttyS9

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2019-01-20
      • 2018-12-15
      • 2015-03-08
      • 2022-07-04
      • 2022-01-06
      相关资源
      最近更新 更多