To learn and understand the Modbus comminication with Arduino mega I use a 2 way RTU relay module (link). As a firts excercise I just want to switch on and off the two relays. This works fine when I use the Serial (standard RX/TX). It does not work when I use the Serial1 (or Serial2 or Serial3).
Below the code I'm using:
// ############################### includes ################################
#include <stdlib.h>
#include <string.h>
#include <ModbusMaster.h> // Modbus communication to converter and energiemonitor
// ######################### create classes ################################
ModbusMaster RelayBoard; // instantiate ModbusMaster object
// #########################################################################
// ######################## i n i t ################################
// #########################################################################
void setup() {
Serial.begin(9600); // Monitor
Serial2.begin(9600); // Modbus
RelayBoard.begin(255, Serial2);
Serial.println("init finished");
}
// #########################################################################
// ######################## l o o p ################################
// #########################################################################
void loop() {
if (Serial2)
{
Serial.println("Serial2 found");
auto tmp = Serial2.available();
Serial.print("Available(read): ");
Serial.println(tmp);
tmp = Serial2.availableForWrite();
Serial.print("Available(write): ");
Serial.println(tmp);
}
else
{
Serial.println("Serial2 NOT found");
}
auto tmp = RelayBoard.writeSingleCoil(0x0000, 0xFF); // switch ON (0xFF) relay 1 (0x0000);
Serial.print("Modbus relay 1 ON (return value): ");
Serial.println(tmp);
delay(500);
tmp = RelayBoard.writeSingleCoil(0x0001, 0xFF); // switch ON (0xFF) relay 2 (0x0001);
Serial.print("Modbus relay 2 ON (return value): ");
Serial.println(tmp);
delay(500);
tmp = RelayBoard.writeSingleCoil(0x0000, 0x00); // switch OFF (0x00) relay 1 (0x0000);
Serial.print("Modbus relay 1 OFF (return value): ");
Serial.println(tmp);
delay(1000);
tmp = RelayBoard.writeSingleCoil(0x0001, 0x00); // switch OFF (0x00) relay 2 (0x0001);
Serial.print("Modbus relay 2 OFF (return value): ");
Serial.println(tmp);
delay(1000);
Serial.println("loop finished");
}
This is my hardware setup:
Please help, I did spent several hours, but I can only use Serial, but not Serial1, Serial2, or Serial3. What is wrong?
thanks Martin