Make Serial.Print() and Client.Print() interchangeable

Hi all,

To give some context as to what I’m doing (if anyone’s interested I’ll publish all the code), I am writing a command line server for Arduino. This basically works as type thing and designed to establish a generic method for passing info in and out of a running arduino primarily via telnet but should work under serial too for debgugging.

I have this largely working for either Serial and over the network however what I would LOVE to do in order to either thin down my code or not have to maintain two libraries is to make Serial.print / println and Client.print / println totally interchangeable.

What I’d like to do is when I start up my CommandServer object it should take in a parameter which determines whether to use Serial.print() or Client.Print() (and ideally a reference to either one) and then in all of my functions I use this reference.

Serial and Client print functions are identical in function so for what I’m doing they are totally interchangeable so I’d like to be able to just use the defined one in all the functions which will then make that a lot more maintainable.

If anyone can give me any pointers or something in this respect I’d be greatly appreciated.


Serial is an instance of the HardwareSerial class, which derives from Stream. Client is also derived from Serial. So, by making the class take an instance of Stream as input, you could pass it any instance that derives from Stream, too.

Oh, and Stream derives from Print.

If all you need is a one-time flag to decide which print to use, how about a flag and then a function to wrap around a print():

int useClient=0;
void setup()
  // pick your destination
void Print2(char *text)
  if (useClient)
void loop()
  Print2("output"); // print to either depending on useClient

Of course, if you need a lot more shared functions, the inheritance solution already mentioned will make your code cleaner

@PaulS thanks for that - I was trying to figure out what the common parent object was. That should do nicely.

@David - thanks for that, yep that's pretty much what I was doing which works nicely but adds some weight to the whole thing.