Hello everyone, I would like to make the arduino MEGA communicate with 2 modbus masters, I think it is possible since it has more than one USART, but how could I manage the library to create 2 networks? tks
In case you are using my modbus server library you can create two modbus server objects
for example
ModbusServer modbusServerA(42, Serial2);
ModbusServer modbusServerB(24, Serial3);
Tank you,
actually i was using ArduinoModbus, but I will study that library.
I think Nick Gammon's non-blocking rs485 library should also work nicely.
I have just tried to test this functionality on an ESP32, using 2 of its additional UART ports.
This is a loopback test, in which an ESP32 sends and receives data to and from itself, using 2 of its additional UART ports. So you connect a wire from pin 13 (RX1) to pin 14(TX1), and another wire from pin 27 (RX2) to pin 12(TX2) . You just need to adjust the code slightly to fit your mega.
Obviously, you also need to add additional code when using RS485, so that you don't have 2 nodes sending data to each other at the exact same time.
#include <RS485_non_blocking.h>
HardwareSerial Node_One(1);
HardwareSerial Node_Two(2);
//Node_One callbacks
size_t Node_One_write (const byte what)
{
return Node_One.write (what);
}
int Node_One_Available ()
{
return Node_One.available ();
}
int Node_One_Read ()
{
return Node_One.read ();
}
RS485 Node_OneChannel (Node_One_Read, Node_One_Available, Node_One_write, 20);
//Node_Two callbacks
size_t Node_Two_write (const byte what)
{
return Node_Two.write (what);
}
int Node_Two_Available ()
{
return Node_Two.available ();
}
int Node_Two_read ()
{
return Node_Two.read ();
}
RS485 Node_TwoChannel (Node_Two_read, Node_Two_Available, Node_Two_write, 20);
unsigned long previousMillis = 0;
const byte msg1 [] = "N1 --> N2"; //node 1 to node 2
const byte msg2 [] = "N2 --> N1"; //node 2 to node 1
void setup ()
{
Serial.begin (115200);
Node_One.begin(115200, SERIAL_8N1, 13, 12); //Baud Rate, Data Protocol, SERIAL_8N1, RXD2, TXD2
Node_Two.begin(115200, SERIAL_8N1, 27, 14);
Node_OneChannel.begin ();
Node_TwoChannel.begin ();
} // end of setup
void loop ()
{
if (millis() - previousMillis >= 1000) {
previousMillis = millis();
Node_OneChannel.sendMsg (msg1, sizeof (msg1)); //node one TX pin sends data to node two RX pin
Node_TwoChannel.sendMsg (msg2, sizeof (msg2)); //node two TX pin sends data to node one RX pin
}
if (Node_TwoChannel.update ()) //check node 2 receive buffer
{
//receive message from Node_One
Serial.write (Node_TwoChannel.getData (), Node_TwoChannel.getLength ()); //parse and print message to serial monitor
Serial.println ();
}
if (Node_OneChannel.update ()) //check node 1 receive buffer
{
//receive message from Node_Two
Serial.write (Node_OneChannel.getData (), Node_OneChannel.getLength ()); //parse and print message to serial monitor
Serial.println ();
}
} // end of loop