I have developed a MEGA2560 custom circuit board. On it are 3 FT232-RL chips feeding TX/RX0, 1 and 2 on the 2560. All ports are working as expected. I can send data from three PCs connected to the 3 USB ports. Using the Serial, Serial1, Serial2 method I can receive data knowing which port sent a message. I've created 3 separate buffers that store the received data; one from each port. I can also Serial1.print Serial2.print etc.. to each serial port monitor. All three USB ports support can send the exact same commands. The MEGA2560 will also reply exactly the same way to each command.
I created a function - DoSomethingWith - that determines what to do with the incoming message based on the first char received. Through a switch and series of "case" statements, a case is selected and a response is returned using a "Serial.print" function. However this function uses the hardcoded Serial.print and Serial.println functions to respond (USB port 0) but I need to respond to the serial port that sent the command (could be USB1 or USB2).
Now I realized I could just copy the original DoSomethingWith and create a DoSomethingWith_1 and DoSomethingWith_2... but that would seem to me very poor programming practice. I then tried creating a custom functions; sPrint and sPrintln function that would reply to a corresponding port (see below). This works except the value I need to print to the serial port is not always a "String" type. I could cast all sPrint value to "String" when executing the function or create separate sPrintInt, sPrintLong, etc... but that again seems like poor programming practice.
I considered modifying the HardwareSerial.cpp and HardwareSerail.h but it's been a long time since I've programmed "c" to go down that path - (last coding I did was on a 8085 microprocessor - yes I'm old!) . I thought I try you folks on this forum who have yet to steer me in the wrong direction. There must be a more common sense way to approach coding for this problem.
void sPrint(byte port, String val)
{
switch (port)
{
case 0:
Serial.print(val);
break;
case 1:
Serial1.print(val);
break;
case 2:
Serial2.print(val);
break;
case 3:
Serial3.print(val);
break;
default:
break;
}
}
void sPrintln(byte port, String val)
{
switch (port)
{
case 0:
Serial.println(val);
break;
case 1:
Serial1.println(val);
break;
case 2:
Serial2.println(val);
break;
case 3:
Serial3.println(val);
break;
default:
break;
}
}