How to dynamically assign a serial print destination

I have a project that has two serial ports that are used for a type of management interface. What I would like to do is only code once when sending a block of print statements but dynamically direct it to one or both of the serial ports. One is a hardware Serial and the other is Software Serial.

This code gives you an idea of where things are not working. I'd probably put the target names in an array and iterate a counter to the next one for the next name. This may well be impossible but at least you have an idea of what I am trying to do.

void setup() {
  
  Serial.begin(9600);     // Open serial communications and wait for port to open:
  
  while (!Serial) { ; }   // wait for serial port to connect. Needed for native USB port only
  
  int target = Serial;
  target.println("Serial Started");

}

void loop(){}

You could use an array of pointers to Print objects:

Print *ports[] = {&Serial, &Serial1};

Hello,

Both HardwareSerial and SoftwareSerial inherits from the Stream class, so you can use something like this:

Stream * const target = &Serial;
...
target->println("Serial Started");

guix:
Both HardwareSerial and SoftwareSerial inherits from the Stream class

And Stream inherits from Print. So, if you're only sending output, the latter is preferable since it will also work with output-only devices like an LCD display.

I was just looking at it from the opposite end and just learned to create an array of pointers for the strings. which has also helped. So now I have 2 solutions!

Thank you very much for your help, it is really appreciated.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.