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?

metichi
  • 181
  • 1
  • 4

2 Answers2

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

Juraj
  • 18,264
  • 4
  • 31
  • 49
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); }

Majenko
  • 105,851
  • 5
  • 82
  • 139