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– metichi2020年10月19日 22:05:21 +00:00Commented 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– metichi2020年10月19日 22:06:27 +00:00Commented Oct 19, 2020 at 22:06
-
4This is actually how libraries do it and I consider it superior to the preprocessor solution.AndreKR– AndreKR2020年10月20日 09:36:13 +00:00Commented 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– mckenzm2020年10月20日 21:27:51 +00:00Commented Oct 20, 2020 at 21:27
-
this should be the accepted answer.Alnitak– Alnitak2020年10月21日 07:01:06 +00:00Commented Oct 21, 2020 at 7:01