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
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);
}
-
Yes, thank you, this is exactly what I was looking formetichi– metichi10/19/2020 22:05:21Commented Oct 19, 2020 at 22:05
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:
-
1Gave 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 projectmetichi– metichi10/19/2020 22:06:27Commented Oct 19, 2020 at 22:06
-
4This is actually how libraries do it and I consider it superior to the preprocessor solution.AndreKR– AndreKR10/20/2020 09:36:13Commented Oct 20, 2020 at 9:36
-
3More importantly this can be leveraged at run time to switch between &Serial, &Serial2 etc. Macros are OK for compile time.mckenzm– mckenzm10/20/2020 21:27:51Commented Oct 20, 2020 at 21:27
-
this should be the accepted answer.Alnitak– Alnitak10/21/2020 07:01:06Commented Oct 21, 2020 at 7:01