I have my library that uses Serial, Serial1 and Serial2 to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.

Problem is, Serial1 and Serial2 are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error 'Serial1' was not declared in this scope.

So I figure I need to adjust my code with preprocessor directive like #if defined, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

  • Not sure if the SDK has particular hardware defines setup for things like a serial port. Most look at the SDK's processor defines and use conditional compilation directives such as "#ifdef ARDUINO_AVR_UNO".
    – st2000
    Jun 11, 2018 at 12:21
  • Also, I'm looking at the ArduinoBoardManager at github source code and do not see where they define hardware like serial port on a per processor bases. Maybe you could add that and re-use this code. But I still think the easiest way about this is pick what serial port code you want to compile based on the processor type. Look at the source code in this github project to see how they did this.
    – st2000
    Jun 11, 2018 at 12:26
  • Why not make the constructor take an object reference of type Serial (or HardwareSerial or even Print)? Jun 11, 2018 at 15:26

2 Answers 2


HardwareSerial.h in Arduino AVR boards core defines HAVE_HWSERIALX


#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX

Consider the approach used here in the ArduinoBoardManager project at github. The file ArduinoBoardManager.h uses conditional compiling to determine the correct code to compile based on processor type. A similar approach can be used to asses if certain hardware peripherals such as serial ports were available based on processor type.

#if defined(__AVR_ATmega328P__) // uno, fi
  // Code compatible with an Arduino Uno
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // Code compatible with an Arduino Mega
  • 1
    why do it, if HardwareSerial.h does it for you. and for example Uno Wifi has additional hw Serial1 (to connect onboard esp8266) even it is a 328p
    – Juraj
    Jun 11, 2018 at 16:05
  • Oh, I agree - I didn't know about the alternatives until posted here. I just knew how the ArduinoBoardManager project was handling it.
    – st2000
    Jun 12, 2018 at 0:05

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.