Connecting Elmeasure LG+5310 to Arduino Mega

Any one let you know if my code was correct plz

#include

// Define RS485 control pins
#define MAX485_DE 3
#define MAX485_RE_NEG 2

// Create ModbusMaster instance
ModbusMaster node;

// Function for enabling transmission mode
void preTransmission() {
digitalWrite(MAX485_RE_NEG, 1);
digitalWrite(MAX485_DE, 1);
}

// Function for enabling reception mode
void postTransmission() {
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
}

void setup() {
// Initialize control pins for RS485
pinMode(MAX485_RE_NEG, OUTPUT);
pinMode(MAX485_DE, OUTPUT);

// Set initial mode to receive
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);

// Initialize serial communication for Modbus
Serial.begin(9600); // Use your selected baud rate
Serial1.begin(9600, SERIAL_8E1); // Baud rate, Even parity, 1 stop bit

// Start Modbus communication with Slave ID 1
node.begin(1, Serial1);

// Set transmission and reception callback functions
node.preTransmission(preTransmission);
node.postTransmission(postTransmission);
}

void loop() {
uint8_t result;
float value;
uint32_t longValue;

// Array of register start addresses as per the communication map
uint16_t startAddress[] = {40101, 40103, 40105, 40107, 40109, 40111, 40113, 40115, 40117, 40119,
40121, 40123, 40125, 40127, 40129, 40131, 40133, 40135, 40137, 40139,
40141, 40143, 40145, 40147, 40149, 40151, 40153, 40155, 40157, 40159, 40217};
int numParameters = sizeof(startAddress) / sizeof(startAddress[0]);

for (int i = 0; i < numParameters; i++) {
if (i < 30) { // For float values (read 2 registers)
result = node.readHoldingRegisters(startAddress[i] - 40001, 2);
if (result == node.ku8MBSuccess) {
uint32_t rawData = ((uint32_t)node.getResponseBuffer(0) << 16) | node.getResponseBuffer(1);
memcpy(&value, &rawData, sizeof(value)); // Convert raw data to float
Serial.print("Parameter ");
Serial.print(i + 1);
Serial.print(": ");
Serial.println(value, 4); // Print float value with 4 decimal places
} else {
Serial.print("Read Error at parameter ");
Serial.print(i + 1);
Serial.print(", Error Code: ");
Serial.println(result);
}
} else { // For Unsigned long value (Load Hours Received)
result = node.readHoldingRegisters(startAddress[i] - 40001, 2);
if (result == node.ku8MBSuccess) {
longValue = ((uint32_t)node.getResponseBuffer(0) << 16) | node.getResponseBuffer(1);
Serial.print("Load Hours Received: ");
Serial.println(longValue);
} else {
Serial.print("Read Error at Load Hours Received, Error Code: ");
Serial.println(result);
}
}

delay(500);  // Delay between reading each parameter

}

delay(5000); // Delay before the next loop
}

I can try to get data from LG+5310 using Arduino

Please edit your post, select all code and click the <CODE/> button. Next save tour post.

This will apply code tags to the code which make the code easier to read, easier to copy and the forum software will display it correctly.

Do you have problems?