Advertisement
Guest User

Untitled

a guest
Jul 21st, 2015
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5.  
  6. #include <modbus.h>
  7.  
  8. int main (void) {
  9. modbus_t *ctx;
  10. uint16_t tab_reg[64];
  11. int rc;
  12. int i;
  13.  
  14. ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);
  15. if (ctx == NULL ) {
  16. fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
  17. modbus_free(ctx);
  18. return -1;
  19. } else {
  20. fprintf(stderr, "Connected to /dev/ttyUSB0\n");
  21. }
  22.  
  23. modbus_set_debug(ctx, 0x01);
  24.  
  25. rc = modbus_set_slave(ctx, 0x01);
  26. if (rc == -1) {
  27. fprintf(stderr, "Set slave error: %s\n", modbus_strerror(errno));
  28. return -1;
  29. } else {
  30. fprintf(stderr, "Slave set to 0x01\n");
  31. }
  32.  
  33.  
  34. rc = modbus_read_registers(ctx, 0, 1, tab_reg);
  35. if (rc == -1) {
  36. fprintf(stderr, "%s\n", modbus_strerror(errno));
  37. return -1;
  38. } else {
  39. fprintf(stderr, "Called Modbus function code 0x03 (read holding registers) = %d\n", rc);
  40. }
  41. for (i=0; i < rc; i++) {
  42. printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
  43. }
  44.  
  45. modbus_close(ctx);
  46. modbus_free(ctx);
  47.  
  48. return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement