Software switch on Mega to switch between Serial and Serial1

Is there a way in software to switch the serial output between the main serial (usb) Portland serial1.

If I have connected my PC to the usb port I want the serial output to go to the pc, if no connection the serial output should go to serial1.

Is this possible?

Serial.print("this will go to Serial");
Serial1.print("this will go to Serial1");

If that does not provide an answer then you need to describe the problem more clearly.

...R
Serial Input Basics - simple reliable ways to receive data.

Some Serial ports Support additional Pins that indicate a physical Connection ("Terminal ready"). To Keep the number of Pins to a Minimum, the Arduino Serial port does NOT Support those Pins. Detecting if something is attached or not is therefore a function that Needs to be handled in the Software and is usually done by sending out a Signal and expecting a Response. Much like "Hi, how are you?" and if the guy wants to talk he'll answer with "Fine and yourself?"

Indeed, switching between Serial and Serial2 is the easy part. Something like

const byte SwitchPin = 5;

HardwareSerial *serialInUse;

void setup(){
  Serial.begin(115200);
  Serial1.begin(115200);

  pinMode(SwitchPin, INPUT_PULLUP);
}

void loop(){
  if(digitalRead(SwitchPin)){
    serialInUse = &Serial;
  }
  else{
    serialInUse = &Serial1;
  }

  serialInUse->println("Hello world!");
  delay(1000);
}

Detecting if the PC is connected is where you need to put in some thoughts :slight_smile:

@neiklot, see title :wink:

You would need a micro / Leonardo for that.

septillion:
@neiklot, see title :wink:

Saw title as I hit Post, alas too late, and deleted immediately. I'll wager it was gone before you posted :wink:

Maybe this would work:

HardwareSerial *SerialInUse;
void setup()
{
  Serial.begin(115200);

   while (!Serial && millis() < 5000);  // Give USB up to five seconds to connect

   if (!Serial)
  {
    Serial1.begin(115200);
    SerialInUse = Serial1;  // UART
  }
  else
    SerialInUse = Serial;  // USB

  SerialInUse->println(F("A serial port has been chosen!"));
}

johnwasser:
Maybe this would work:

Serial's always true except on micro and Leo

Not only Micro and Leonardo. You can do that on Due (native USB port), Zero (native USB port), and the MKR boards too.

neiklot:
Serial's always true except on micro and Leo

And on UNO/Nano/Mini there is no Serial1. On MEGA it will assume you always want to use Serial because there is no way to know if the PC is connected or not.