Advertisement
Guest User

modbus

a guest
Jul 21st, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  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. /* Read register at address 30005 */
  34.  
  35. rc = modbus_read_registers(ctx, 30005, 1, tab_reg);
  36. if (rc == -1) {
  37. fprintf(stderr, "%s\n", modbus_strerror(errno));
  38. return -1;
  39. } else {
  40. fprintf(stderr, "Called Modbus function code 0x03 (read holding registers) = %d\n", rc);
  41. }
  42.  
  43. for (i=0; i < rc; i++) {
  44. printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
  45. }
  46.  
  47. modbus_close(ctx);
  48. modbus_free(ctx);
  49.  
  50. return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement