7

I am doing a project where, for troubleshooting reasons, I find myself often swapping components to different serial ports. Maybe one time it's in Serial, then in Serial1, maybe I need to try if software serial works.

But changing every line where Serial.print or Serial.write is written for the new port is a hassle and easy to screw up.

Would it be possible to either create a definition at the beginning of the code that lets me rename Serial to SensorSerial so just by changing that definition I am sure it will use the correct port?

2 Answers 2

14

Yes. The simplest way is with a preprocessor macro. Macros get replaced verbatim before compilation happens, so you can do something like:

#define MY_SERIAL Serial

void setup() {
    MY_SERIAL.begin(115200);
}

void loop() {
    MY_SERIAL.println(millis());
    delay(1000);
}
1
  • Yes, thank you, this is exactly what I was looking for
    – metichi
    Commented Oct 19, 2020 at 22:05
20

Majenko's answer is the right answer for your question. But to answer the title of the question, if you ever need to use different Arduino outputs and inputs as variable, most of them have common type Stream or Print. So it would be:

Stream& SensorSerial = Serial;

or

Stream* SensorSerial; 
SensorSerial = &Serial;

The Arduino Stream classes hierachy:

enter image description here

4
  • 1
    Gave the answer to the other person because it fit more precisely what I meant. But this is really helpful to know for another part of the same project
    – metichi
    Commented Oct 19, 2020 at 22:06
  • 4
    This is actually how libraries do it and I consider it superior to the preprocessor solution.
    – AndreKR
    Commented Oct 20, 2020 at 9:36
  • 3
    More importantly this can be leveraged at run time to switch between &Serial, &Serial2 etc. Macros are OK for compile time.
    – mckenzm
    Commented Oct 20, 2020 at 21:27
  • this should be the accepted answer.
    – Alnitak
    Commented Oct 21, 2020 at 7:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.