I'm creating an Arduino library and have 3 files - a "test.ino" program, and two library/class files: "testLibrary.h" and a "testLibrary.cpp".
The library makes use of some hardware-specific resources such as registers and ISRs that depend upon which I/O pin is used, and this should be done at compile time.
I would like to #define a pin number in the main program which, at compile time, is used in the library to determine which code sections are activated. Since this will be a standard Arduino library for use by others, it should compile and run without users having to change their compiler or #include path to make it work.
But it seems that the scope of #define in the main program/sketch does not extend to the library.
test.ino
#define PIN_NUMBER 3
#include "testLibrary.h"
void setup() {}
void loop() {}
testLibrary.h
#ifndef _TESTLIBRARY_h
#define _TESTLIBRARY_h
#ifndef PIN_NUMBER
#error PIN is not defined
#endif
class test {
public:
test();
~test();
};
#endif
testLibrary.cpp
#include "testLibrary.h"
test::test(){}*
test::~test(){}
Compiling the above branches to "#error" using the Arduino IDE 1.8.13 and also using Visual Studio with Visual Micro.
Is there a way for me to have an Arduino library use a "#define" from the main sketch?
PIN_NUMBER
in your code. Or is that a copy&paste error?#endif
but only one#if
in testLibrary.h. This will cause a compilation error if you definePIN_NUMBER
in your main code (test.ino) when it skips the#error
in testLibrary.h. Maybe you did not notice the#endif without #if
error? You can fix it by inserting#define _TESTLIBRARY_h
as the first line of testLibrary.h. I.o.w. the scope ofPIN_NUMBER
will be global if you define it in test.ino. Try it.begin()
method.