A "pointer" to either Serial1 or Serial2 ?

Hello out there,

I have a project with two arduino megas sending and receiving serial data over two xbee modules, and it is working perfectly well. Now I had the idea to extend the system with a wired mode over one of the other serial interfaces.

So basicly, when the wired connection is plugged in at power-up, a pin in the plug is tied to GND, read in setup(), and wired mode instead of xbee-mode is chosen. Can I create a variable or pointer to use it in the program, so that I can direct every Serial.read and Serial.write to the desired pin? And if so, could anyone point me in the right direction?

In pseudocode:

boolean mode;
int modePin;

Serial selectedSerial;

void setup() {
  mode=digitalRead(modePin);
  if (mode) {
    selectedSerial=Serial1;
  } 
  else {
    selectedSerial=Serial2;
  }
  selectedSerial.begin(9600);
}

void loop() {
  //write example
  selectedSerial.write("whatsoever");

  //read epample
  while (selectedSerial.available() > 0) {
    input=selectedSerial.read();
  }

}

Serial and Serial1 are both instances of the HardwareSerial class. A pointer, of type HardwareSerial, can point to either one.

Then, use pointer notation (->) rather than instance notation (.) to access the methods.

This should help http://arduino.cc/en/Serial/IfSerial

I usually use their parent class Stream instead of HardwareSerial. This way I can use software serial if I have to, or write to files using Print class.

Stream * myPort=&Serial1; // Or assign software serial port address to it myPort->println("Hello world!");

Thank you so much, that was exactly what I was looking for but couldn't figure out by myself (especially the -> part). I rewrote the code according to your replies, and it compiles without problems in both of the alternatives (HardwareSerial and Stream classes). Thanks to all of you.

boolean mode;
int modePin;
byte input, output;

//both variants will compile
HardwareSerial *selectedSerial;
//Stream *selectedSerial;

void setup() {
  mode=digitalRead(modePin);
  if (mode) {
    selectedSerial=&Serial1;
    Serial1.begin(9600);
  } 
  else {
    selectedSerial=&Serial2;
    Serial2.begin(9600);
  }
}

void loop() {
  //write example
  selectedSerial->write(output);

  //read epample
  while (selectedSerial->available() > 0) {
    input=selectedSerial->read();
  }
}

You are welcome! It's neat to have this flexibility, isn't it?