Communication timeout

Asked by solarwind

Hi all, for the following very simple code (just write data to two registers), for some reason, I need to put the sleep(2) before I call preset_multiple_registers, or I get the following error:

Starting...
Opening /dev/tty.usbserial-A700dYIj at 115200 bauds (even)
[01][10][00][00][00][01][02][00][01][67][90]
Waiting for a message (8 bytes)...

ERROR Communication time out (-12)
ret: -12

Why do I need to wait before I write into the registers?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "modbus.h"

#define SLAVE 1
#define START_ADDRESS 0
#define NB 1

int ret;
int addr;
int nb;

uint16_t val;

int main (int argc, const char * argv[]) {
    printf("Starting...\n\n");

 modbus_param_t mb_param;
 modbus_close(&mb_param);

 modbus_init_rtu(&mb_param, "/dev/tty.usbserial-A700dYIj", 115200, "even", 8, 1);

 modbus_set_debug(&mb_param, TRUE);
 if (modbus_connect(&mb_param) == -1) {
  printf("ERROR Connection failed\n");
  return 0;
 }

 sleep(2);

 val = 2;
 ret = preset_multiple_registers(&mb_param, SLAVE, 0, 1, &val);

 val = 100;
 ret = preset_multiple_registers(&mb_param, SLAVE, 1, 1, &val);

 printf("ret: %d\n", ret);

 printf("\n\n");

 sleep(4);

 modbus_close(&mb_param);

 return 0;

}

Question information

Language:
English Edit question
Status:
Answered
For:
libmodbus Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Stéphane Raimbault (sra) said :
#1

Certainly because your USB/Serial key is a bit slow to init (or buggy).
Your fist modbus_close is useless.

Can you help with this problem?

Provide an answer of your own, or ask solarwind for more information if necessary.

To post a message you must log in.