Hello Everyone, I Start my first industrial project based on Modbus communication but stuck very badly. I tried a lot to rectify the error and for that read many blogs and tried in different way but i do not find any solution.
I have one analyzer which communicate on modbus protocol.
I tried some code file and successfully communicate with the analyzer but after few week later when i start testing again i got only 0 value on my serial monitor then i tried to debug the code and find some error.
Here i am going to paste my code and looking for a support.
// This #include statement was automatically added by the Particle IDE.
#include <ModbusMaster.h>
// ****** DEFINES ******
#define MAX485_DE 3
#define MAX485_RE_NEG 2
//instantiate ModbusMaster object as slave ID 1
ModbusMaster node;
unsigned long interval = 0;
unsigned long base_T = 1000;
// ****** SUPPORT FUNCTIONS ******
void preTransmission()
{
digitalWrite(MAX485_RE_NEG, 1);
digitalWrite(MAX485_DE, 1);
}
void postTransmission()
{
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
}
void setup() {
// initialize Modbus communication baud rate
// make pins 2 and 3 output pins for Max485 flow control
pinMode(MAX485_RE_NEG, OUTPUT);
pinMode(MAX485_DE, OUTPUT);
// Init in receive mode
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
// Baudrate for serial monitor if you want to see responses
while (!Serial);
Serial.begin(9600);
//Baudrate of modbus device is 9600
while (!Serial1);
Serial1.begin(9600, SERIAL_8N1);
//
// Serial.begin(9600); // TX0/RX0 serial monitor
// Serial1.begin(9600); // TX1/RX1 Modbus comms
// Modbus slave ID = 254
node.begin(1, Serial1);
// Callbacks allow us to configure the RS485 transceiver correctly
node.preTransmission(preTransmission);
node.postTransmission(postTransmission);
Serial.println("Starting Modbus Transaction:");
}
void loop() {
uint8_t i, result;
uint16_t data[8];
union
{
uint32_t j;
float f;
} u;
if (millis() - interval > base_T) {
interval = millis();
result = node.readHoldingRegisters(23, 8);
// do something with data if read is successful
if (result == node.ku8MBSuccess) {
Serial.print("Success, Received data: ");
for (i = 0; i < 8; i++) {
data[i] = node.getResponseBuffer(i);
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.println("");
base_T = 1000;
u.j = ((unsigned long)data[1] << 16 | data[2]);
Serial.print("TSS:");
Serial.println(String(u.f));
u.j = ((unsigned long)data[3] << 16 | data[4]);
Serial.print("BOD:");
Serial.println(String(u.f));
u.j = ((unsigned long)data[5] << 16 | data[6]);
Serial.print("COD:");
Serial.println(String(u.f));
u.j = ((unsigned long)data[7] << 16 | data[8]);
Serial.print("pH:");
Serial.println(String(u.f));
}
else {
Serial.print("Failed, Response Code: ");
Serial.print(result);
Serial.print(" - ");
Serial.print(result, HEX);
Serial.println("");
base_T = 5000; //if failed, wait for bit longer, before retrying!
}
}
}
Here i am attaching the output on serial monitor.
Thank You for response.