How to give reference of (Software)-Serial to library for logging?

Hi all,

I am using arduino pro mini in different projects. Hardware serial is now connected to a BLE module, so for debugging purpose I will use some kind of software serial (softwareSerial.h or NeoSWSerial or whatever).

I outsourced parts of my code to own libraries. In the past I had debug parts, where I just debugged via Serial.print(). Now I need to use a software serial class there.

How do I give the existing SoftwareSerial object from main code down to the library classes that I can write the debug logs there?

Can I do it somehow, that I just give a reference of the (Software)-Serial object to the library? How do I make it that it does not matter, if I defined Serial or SoftwareSerial? FunctionNames I am using are equal in both .

Or other approach: how can I create a static logger which all functions (of main code or libs) can call for logging? -> Should need as low resources as possible :wink:

Hope it is clear what I want. If not, pls ask for more details.

Thanks, Butch

You can pass either a pointer or a reference to a Stream object. I can think of 3 different variations (there may be more):

#include "SoftwareSerial.h"

class myClass1 {
  public:
    myClass1(Stream *streamPtr) : _ptr(streamPtr) {}
    void dataLog() {
      _ptr->println("Logging");
    }

  private:
    Stream *_ptr;
};

class myClass2 {
  public:
    myClass2(Stream &streamRef) : _ref(streamRef) {}
    void dataLog() {
      _ref.println("Logging");
    }

  private:
    Stream &_ref;
};


class myClass3 {
  public:
    myClass3(Stream &streamRef) : _ptr(&streamRef) {}
    void dataLog() {
      _ptr->println("Logging");
    }

  private:
    Stream *_ptr;
};


SoftwareSerial softSerial(4, 5);

myClass1 myObject1(&softSerial);
myClass2 myObject2(softSerial);
myClass3 myObject3(softSerial);

void setup() {
  softSerial.begin(9600);
  myObject1.dataLog();
  myObject2.dataLog();
  myObject3.dataLog();
}

void loop() {
}