0

file0: Main.ino (it's arduino file):

#define AXIS_SERIAL Serial1
#include "header.h"
...
void setup(){...}
void loop() {...}
...

file1: header.h

...
#ifndef AXIS_SERIAL
#define AXIS_SERIAL Serial
#endif
...

file2: header.cpp

...
AXIS_SERIAL.print("Hello World")
...

Question: When I use function in header.cpp value inside of AXIS_SERIAL is still Serial (not Serial1). Is there a way to define a constant in main file, and use it in other header file(s)? If so, it will going to generalize my piece of code.

I do know that it's possible to declare a variable something like HardwareSerial Axis_serial = Serial1; but I may use Software Serial in the future. So I need a thing that works both Hardware & Software Serial classes.

Garid
  • 105
  • 1
  • 3

1 Answers1

-1

Yes, that should be possible, in the end the #define directive replaces your new "alias" with the string that you entered:

#define MY_DEFINE Serial

your code

void loop(){
   MY_DEFINE.println("Hello World!");
}

what your compiler sees:

void loop(){
   Serial.println("Hello World!");
}
Max Kofler
  • 86
  • 4
  • Yes, In main.ino file, AXIS_SERIAL is Serial1. However, when I use functions declared in header.cpp (which uses AXIS_SERIAL) AXIS_SERIAL is still Serial (not Serial1). – Garid Jan 04 '21 at 08:43
  • this is a wrong answer – Juraj Jan 04 '21 at 10:42