Advertisement
pleasedontcode

**Modbus Communication** rev_01

Nov 27th, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: **Modbus Communication**
  13.     - Source Code NOT compiled for: ESP8266 NodeMCU V1.0
  14.     - Source Code created on: 2024-11-28 05:25:27
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* Implement a Modbus communication protocol to */
  21.     /* enable data exchange between Arduino and Modbus- */
  22.     /* compatible devices, ensuring reliable and */
  23.     /* efficient control of connected components. */
  24. /****** END SYSTEM REQUIREMENTS *****/
  25.  
  26. /* START CODE */
  27.  
  28. /****** DEFINITION OF LIBRARIES *****/
  29. #include <ModbusMaster.h>   //https://github.com/4-20ma/ModbusMaster
  30. //#include <SoftwareSerial.h> // SoftwareSerial is not compatible with ESP8266 as it doesn't support multiple serial ports like Arduino
  31.  
  32. /****** FUNCTION PROTOTYPES *****/
  33. void setup(void);
  34. void loop(void);
  35.  
  36. /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
  37. ModbusMaster node;
  38.  
  39. // Define MODBUS_SERIAL to use the default Serial for ESP8266
  40. #define MODBUS_SERIAL Serial
  41.  
  42. void setup(void)
  43. {
  44.     Serial.begin(115200);  
  45.     MODBUS_SERIAL.begin(115200, SERIAL_8N1, 14, 27);  // IO14: RX, IO27: TX
  46.     node.begin(1, MODBUS_SERIAL); // Initialize Modbus master with slave ID of 1
  47. }
  48.  
  49. void loop(void)
  50. {
  51.     uint8_t result; // Variable to hold the result of the Modbus request
  52.     uint16_t data[10]; // Buffer to hold the data
  53.  
  54.     result = node.readHoldingRegisters(0, 1); // Read one holding register from address 0
  55.     if (result == node.ku8MBSuccess) { // Check if the read was successful
  56.         Serial.print("Flow Rate: ");
  57.         Serial.println(node.getResponseBuffer(0)); // Print the value of the first holding register
  58.     } else {
  59.         Serial.print("Error reading Flow Rate: ");
  60.         Serial.println(result); // Print the error code
  61.     }
  62.  
  63.     delay(2000);  // Wait for 2 seconds before the next loop iteration
  64. }
  65.  
  66. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement