usb_serial_class and HardwareSerial as class member

Status
Not open for further replies.
I've written a class that handles a serial-based menu and eeprom parameter storage. I would like to pass it a pointer to a serial port, so that I can decide later which port it'll be:
Code:
class EEPROMParams{
  HardwareSerial* p_serial;
  EEPROMParams(HardwareSerial* ser) : p_serial(ser) {};
  public:
    void write_something() { p_serial->println("Hello world"); };
};

Problem: teensy's usb serial is not a HardwareSerial; both only inherit from Stream.
Same issue was discussed in https://forum.pjrc.com/threads/3114...ial?highlight=hardwareserial+usb_serial_class and it was suggested to use Stream and call begin in the setup() function instead of in the class init.

I can live with that. However, I would like to make use of the print and println methods, which are not part of Stream.

I've thought about overloading my class's constructor to accept a HardwareSerial* and usb_serial_class*, have those set a member pointer and set a boolean to know which one was called:
Code:
class EEPROMParams{
  HardwareSerial* p_serial;
  usb_serial_class* teensy_serial;
  bool use_teensy_serial;
  EEPROMParams(HardwareSerial* ser) : p_serial(ser), use_teensy_serial(false) {};
  EEPROMParams(usb_serial_class* ser): teensy_serial(ser), use_teensy_serial(true) {};
  public:
    void write_something() { if(use_teensy_serial) teensy_serial->println("Hello world"); else p_serial->println("Hello world"); };
};
However, then I would have to replace all my p_serial->print statements… So I thought about making a helper method print() that would do this check, but then I have to define all overloaded print() methods (chars, ints, floats) and then might as well just stick with Stream and implement print() myself on that…

Any other suggestions?
 
Why do you think that stream does not support the print functions? I do this all the time and never had any issues?

Code:
 Stream* s = &Serial;
 s->println("test");

 Stream& s2 = Serial;
 s2.println("another test");

Compiles and works...
 
Huh. Because I read https://www.arduino.cc/en/Reference/Stream and there is no print on that page. And because I thought I had some "method not defined" errors when I had a Stream pointer in my class, but apparently that was not related to print, or I made a mistake.

I now see that I overlooked the last line on the Stream intro page of Arduino reference: "For functions like print(), Stream inherits from the Print class." My bad!

So. Thanks!
 
Status
Not open for further replies.
Back
Top