Skip to main content
2 of 2
+ answer to comment
Edgar Bonet
  • 45.2k
  • 4
  • 42
  • 81

You can create a class derived from Print that forwards its output to either or both Serial and Serial1. The only method you need to implement for this to work is write(uint8_t):

class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

You would use it like this:

out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format them as text only once, and the underlying Serial and Serial1 will only handle the resulting characters.


Edit: To answer the question in OP's comment, the construct

class ClassName
{
    ...definition...
} classInstace;

is a shotcut for

class ClassName
{
    ...definition...
};
ClassName classInstace;

A very similar construct exists in plain C:

struct struct_name {
    ...the struct fields...
} struct_instance;
Edgar Bonet
  • 45.2k
  • 4
  • 42
  • 81