Select which serial port to use in library

Hi,

I have a question for all you seasoned programmers.

I made a library that writes data to serial ports depending on which chip I'm using sometimes I use a ATM328p sometimes ATM2560 sometimes others. Since the 328P has only one serial this isn't a problem but when I use the 2560 I have 4 serial ports and sometimes my projects use all 4 of them.

The solution I found was to define something like this:

#ifdef USE_SERIAL0
Serial.print (data);
#else
Serial1.print(data);
#endif

I can always use #else if for additional ports.

My question, is there another method to accomplish the same task like passing a variable with the function or something that doesn't require code duplication? Something like this (I know this doesn't work) SerialX.print(data);

Thx and happy new year.
rob

Hello,

You can use #define's

#ifdef USE_SERIAL0
  #define SERIAL Serial
#else
  #define SERIAL Serial1
#endif

...

SERIAL.print(data);

You could also make a "reference" variable which will behave the same.

#include <Arduino.h>

#ifdef USE_SERIAL0
HardwareSerial & output (Serial);
#else
HardwareSerial & output (Serial1);
#endif

void setup() 
{
  output.begin (115200);
  output.println ("hi there");
}

void loop() 
{
 
}

Nice, never thought of those answers. Using your and guix solution can reduce the code size significantly, just declare it once and use it anywhere.

Thanks

Your class constructor or begin() method should take a Stream parameter. Stream is the class that sits behind Serial. It also sits behind most LCD libraries, software serial and I2C so your class could possibly talk to those devices as well.

#include <MyClass.h>

MyClass MyObject;

setup() {
  //SERIAL_PORT_MONITOR is a constant defined by Arduino to refer to whatever serial port is connected to the serial monitor
  SERIAL_PORT_MONITOR.begin(9600);
  MyObject.begin(SERIAL_PORT_MONITOR);  
}

loop() {
  MyObject.doSomething();
}

Stream doesn't have begin however.