So you have an Arduino program (or sketch) and it’s getting a bit cumbersome and messy. Now could be the time to start breaking your program up into smaller more manageable chunks.
A basic solution (see code below) for breaking the program into more managable chunks is to put the common variables declarations into a shared file that gets included into each program file (shared.h here) and the implementation into a source file (Shared.cpp here). Use #include “Shared.h” to get access to the globals for each source file (.cpp or .ino) that needs them.
Shared.h
1 2 3 4 5 6 |
// The Panel object is declared external so that all who include this file know about it. // This doesn't actually make an InterfacePanel it just lets everyone know what Panel is. extern InterfacePanel Panel; // This is the declaration for a function that we want to make available to multiple files. void MyFunction(int p); |
Shared.cpp
1 2 3 4 5 6 7 8 9 |
// This is the actual instance of the object. It sets aside the memory and other things for the panel. InterfacePanel Panel; // Here's the definition of the function. Notice it is using Panel void MyFunction(int p) { Panel.SetProgress("Progress", p); Panel.SetNumber("Current", p); } |
MainProgram.ino
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include "Shared.h" // so we know what Panel is. void loop() { // The panel can be used here because there is a declaration for it in Shared.h (which got included above) Panel.SetProgress("Progress", Progress); Panel.SetNumber("Current", Progress); // Also, we can use the function we declared in Shared.h MyFunction(Progress); //etc. } |
A more complex solution is to use classes. Adafruit have a good example where they transfer a basic program into a class.
You might also want to move to a more powerful integrated development invironment (IDE) such as Visual Studio (with Visual Micro plugin) or Eclipse and start useing some more advanced approaches to coding.