I want to read a modbus device.
My program crashes or, sometimes, reboot with this piece of code:
#include <ModbusMaster.h>
void setup()
{
Serial.begin(9600);
newReadingMB(5,222,"float32","false","hr","abc");
newReadingMB(3,4,"float32","false","hr","abc");
}
void newReadingMB(uint8_t id, uint16_t address,char *format, char *inversion, char *method, char *uuid)
{
uint8_t j = 0;
uint16_t data[6];
uint8_t result;
ModbusMaster node(2,id);
node.begin(9600);
Serial.println(address,DEC);
result = node.readInputRegisters(address,2);
Serial.println(result,HEX);
for (j=0;j<2;j++)
{
data[j] = node.getResponseBuffer(j);
Serial.println(data[j],HEX);
}
}
When I declare node as a global variable I receive the value but, of course, I am not able to choose other device to read.
Is there any way to destruct the ModbusMaster object so I can declare another? Or, how can I declare multiple ModbusMaster instances? If I have 3 Modbus devices do I need to have 3 different ModbusMaster instances?
As an update, I declared a global ModbusMaster variable, MBnode, and changed ModbusMaster library. I declared _u8SerialPort and _u8MBSlave as public instead of private variables. Now, when I want to change the slave ID e repeat this steps:
MBnode._u8SerialPort = 2;
MBnode._u8MBSlave = atoi(id);
MBnode.begin(9600);
Maybe it’s not the prettiest thing to do but now it works .