Forum >How to inteface RS485 in the Edge101 IoT controller for ESP32 to connect wih an energy meter

How to inteface RS485 in the Edge101 IoT controller for ESP32 to connect wih an energy meter

userHead teamskrn2025 2025-07-16 21:36:25 280 Views2 Replies

I'm not able to communicate with energy meter using the in-built RS485 interface. The documentation says that Serial2 is used for RS485 interface to connect industrial sensors, actuators, and other devices. How to declare this in the Arduino IDE interface.

2025-07-16 23:11:32

In setup(), begin the Serial2 communication:

void setup() {
 Serial.begin(115200);       // For debug output to Serial Monitor
 Serial2.begin(9600);        // Start Serial2 at the baud rate used by your energy meter
}
Change the baud rate (9600) to match your energy meter's specification.

userHeadPic ahsrab.rifat
teamskrn2025 wrote:

"#include <ModbusRTU.h>
#include <WiFi.h>


ModbusRTU mb;

// Convert 2 x 16-bit register data into float
float InttoFloat(uint16_t Data0, uint16_t Data1) {
  float x;
  unsigned long *p = (unsigned long*)&x;
  *p = (unsigned long)Data0 << 16 | Data1;
  return x;
}

// Modbus result callback
bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) {
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Modbus error: 0x");
    Serial.println(event, HEX);
    return false;
  }
  return true;
}

void setup() {
  Serial.begin(115200);  // Serial monitor

  // Begin Modbus Serial  
  Serial2.begin(9600, SERIAL_8E1);  // 8 data bits, Even parity, 1 stop bit
  mb.begin(&Serial2);  
  mb.master();
}

void loop() {


  if (!mb.slave()) {
    uint16_t data[6];
   
    // Read 3-phase current from slave ID 1
    mb.readHreg(1, 2998, data, 6, cb);
    while (mb.slave()) {
      mb.task();
      delay(100);
    }

    float current_A = InttoFloat(data[1], data[0]);
    float current_B = InttoFloat(data[3], data[2]);
    float current_C = InttoFloat(data[5], data[4]);

  

    // Print values   
    Serial.print("Current A: "); Serial.print(current_A); Serial.println(" A");
    Serial.print("Current B: "); Serial.print(current_B); Serial.println(" A");
    Serial.print("Current C: "); Serial.print(current_C); Serial.println(" A");
   
  }

  delay(5000); // Wait before next read
}" this is the code. All connections are correct and the same code also worked with another gateway. Yet here I get a modbus error. Thanks for the earlier reply!

 

2025-07-21 15:10:43
1 Replies