Hello Everyone,
This is my first post here. Looking for some help.
I have a power meter and it uses MODBUS RTU for communication. I am trying to read data from it using sn65hvd75dr (RS485 transreceiver) breakout board and my Electron. Below is the code.
Problem is: I am able to read data from the power meter to Electron sometimes else it fails and gives error E0,E1,E3 and then all of a sudden it receives correct data and then fails again.
How should I make this reliable?
I tried the RS485 breakout board with arduino and it works fine all the time.
Thank you for the help
// This #include statement was automatically added by the Particle IDE.
#include <ModbusMaster.h>
#include <application.h>
ModbusMaster node(1);
char power_meter[]="";
void setup() {
// initialize Modbus communication baud rate
pinMode(D7, OUTPUT);
node.begin(19200);
node.enableTXpin(D7); //D7 is the pin used to control the TX enable pin of RS485 driver
Serial.begin(19200);
while(!Serial.available()) Particle.process();
Serial.println("Starting Modbus Transaction:");
}
void loop() {
static uint32_t i;
uint8_t j, result, cnt;
uint16_t data[50];
uint16_t datahex[50];
uint32_t out[25];
digitalWrite(D7, 0);
result = node.readHoldingRegisters(0x4000,50);
// do something with data if read is successful
if (result == node.ku8MBSuccess) {
Serial.print("Success, Received data: ");
for (j = 0; j <50; j++) {
data[j] = node.getResponseBuffer(j);
}
j=0;
for(cnt=0;cnt<25;cnt++)
{
out[cnt]= (data[j]<<16) | (data[j+1]);
float y = *(float*)&out[cnt];
sprintf(power_meter,"%3.4f",y);
Particle.publish(power_meter);
j=j+2;
}
Serial.println("");
} else {
Serial.print("Failed, Response Code: ");
Serial.print(result, HEX);
Serial.println("");
delay(5000); //if failed, wait for bit longer, before retrying!
}
delay(5000);
}