Recipes for Splitting & Sharing Code in Arduino IDE
Multiple Files
In Arduino, splitting out functionality into multiple files is easy. Let's start by assuming we have a file Main.ino
. We can create other files in the format <name>.ino
and the Arduino IDE will pick up the files when compiling.
For instance:
// Main.Ino
void start() {
Serial.begin(9600);
doSomething(); // works without manually including it
}
void loop() {}
// Testing.Ino
void doSomething() {
Serial.println("Doing something");
}
The only caveat is that the extra files need to be in the same directory as Main.ino
.
Sharing Enums
When it comes to sharing enums, the above recipe will not work, as we need the enum defined before a file is compiled. But, if using an enum and the method above, when compiling an error will occur where the enum
will not be defined. So, we must create a header file and include it wherever it's used.
// Main.ino
#include "Types.h"
void start() {
Serial.begin(9600);
Serial.println(ButtonType::Solid);
}
void loop() {}
// Types.h
enum ButtonType
{
Solid,
Gradient,
Program,
None
};
There may be a better way to do this, but this works. I hope you found these helpful!