Select serial port programmatically

Hi,

I am attempting to write a library for communicating with a piece of lab equipment and I would like to be able to select, in the constructor, which serial port on an arduino mega to use for the communication. I can certainly hard code it, but hopefully someone knows a nice way to do this.

Thanks!

Select how?

You could make a reference to the serial object. Without seeing your code it is hard to give better advice.

You could make a reference to the serial object

Sorry I don't know what you mean by reference.

Without seeing your code it is hard to give better advice.

Right now I have the serial port hard coded in the constructor:

Wavemeter::Wavemeter(int baud) {
  Serial.begin(baud);
  Serial.write("Power On\n");

  // initialization of values removed
}

What I would like to do it be able to select an arbitrary port in the constructor like so:

Wavemeter::Wavemeter(int port, baud) {
  Serial.begin(port,baud);
  Serial.write(port,"Power On\n");

  // initialization of values removed
}

But it seems like in order to use the other serial ports the syntax is:
Serial1, Serial2 ...
which I don't know how to deal with

Like this:

class Wavemeter
  {
  public:
  
    Wavemeter(HardwareSerial & port, const unsigned long baud) : port_ (port), baud_ (baud) {}
    
    void begin ();
    
  private:
  
    HardwareSerial & port_;
    const unsigned long baud_;
    
  };  // end of class Wavemeter
 
void Wavemeter::begin ()
  {
  port_.begin (baud_);
  port_.write("Power On\n");
  }  // end of Wavemeter::begin 

Wavemeter foo (Serial1, 9600);

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop () {}

I was able to successfully create a test library based on your example code, thank you! The error messages I generated by playing with it also led me to some information on references.