tuxmartin

libmodbus rtu example

Nov 25th, 2014
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. #include <modbus.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4.  
  5. int main(void) {
  6.  
  7.     modbus_t *ctx;
  8.     uint16_t tab_reg[64];
  9.     int rc;
  10.     int i;
  11.  
  12.     ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
  13.  
  14.     if (ctx == NULL) {
  15.           fprintf(stderr, "Unable to create the libmodbus context\n");
  16.           return -1;
  17.     }
  18.     rc = modbus_read_registers(ctx, 2, 3, tab_reg);
  19.  
  20.     if (rc == -1) {
  21.           fprintf(stderr, "%s\n", modbus_strerror(errno));
  22.           return -1;
  23.     }
  24.  
  25.     for (i=0; i < rc; i++) {
  26.           printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
  27.     }
  28.  
  29.     modbus_close(ctx);
  30.     modbus_free(ctx);
  31.  
  32.     return 0;
  33. }
  34.  
  35. // # apt-get install libmodbus-dev libmodbus5
  36. // $ gcc -O2 -Wall -I /usr/include/modbus test.c -o test -L/usr/lib/modbus -lmodbus
Advertisement
Add Comment
Please, Sign In to add comment