Advertisement
Nusa_Techno

Untitled

Jun 5th, 2024
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <ModbusMaster.h>
  2. #define MAX485_DE      3
  3. #define MAX485_RE_NEG  2
  4.  
  5. // instantiate ModbusMaster object
  6. ModbusMaster node;
  7.  
  8. void preTransmission()
  9. {
  10.   digitalWrite(MAX485_RE_NEG, 1);
  11.   digitalWrite(MAX485_DE, 1);
  12. }
  13.  
  14. void postTransmission()
  15. {
  16.   digitalWrite(MAX485_RE_NEG, 0);
  17.   digitalWrite(MAX485_DE, 0);
  18. }
  19.  
  20. void setup()
  21. {
  22.   pinMode(MAX485_RE_NEG, OUTPUT);
  23.   pinMode(MAX485_DE, OUTPUT);
  24.   // Init in receive mode
  25.   digitalWrite(MAX485_RE_NEG, 0);
  26.   digitalWrite(MAX485_DE, 0);
  27.  
  28.   // Modbus communication runs at 115200 baud
  29.   Serial.begin(115200);
  30.  
  31.   // Modbus slave ID 1
  32.   node.begin(1, Serial);
  33.   // Callbacks allow us to configure the RS485 transceiver correctly
  34.   node.preTransmission(preTransmission);
  35.   node.postTransmission(postTransmission);
  36. }
  37.  
  38. bool state = true;
  39.  
  40. void loop()
  41. {
  42.   uint8_t result;
  43.   uint16_t data[6];
  44.  
  45.   // Toggle the coil at address 0x0002 (Manual Load Control)
  46.   result = node.writeSingleCoil(0x0002, state);
  47.   state = !state;
  48.  
  49.   // Read 16 registers starting at 0x3100)
  50.   result = node.readInputRegisters(0x3100, 16);
  51.   if (result == node.ku8MBSuccess)
  52.   {
  53.     Serial.print("Vbatt: ");
  54.     Serial.println(node.getResponseBuffer(0x04)/100.0f);
  55.     Serial.print("Vload: ");
  56.     Serial.println(node.getResponseBuffer(0xC0)/100.0f);
  57.     Serial.print("Pload: ");
  58.     Serial.println((node.getResponseBuffer(0x0D) +
  59.                     node.getResponseBuffer(0x0E) << 16)/100.0f);
  60.   }
  61.  
  62.   delay(1000);
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement