Search code examples
esp32arduino-esp32

ESP32 load GPIOs via header files


I have a big school project with an ESP32. Almost all GPIOs are used in the project, so I want to have the whole thing a bit cleaner. If I declare all GPIOs in the main then it doesn't look so nice. Therefore I created a header file where all GPIOs are declared.

Here is an example:

//setPinConfig.h
const int start = 13;
const int stop = 9;    

void setPinConfig()
{
    pinMode(start, INPUT);
    pinMode(stop, INPUT);
}

Then I call this function in the setup of the Main function.

//main.cpp
#include "setPinConfig.h"
void setup()
{
    setPinConfig();
}

In the main, everything works the way I want it to. But if I now want to access the GPIOs in other header files, it comes to errors.

I work around this by using "#ifndef", #define, #endif in the header files in which I call the GPIO header file.

I am now wondering if this is a legitimate way to deklare and load the GPIOs. Or should I rather declare and load it classically in the main.


Solution

  • In short, you can't define functions in the header files (technically you can, but then you're in a world of pain). You define them in the .c or .cpp file, and declare in the .h file.

    If you wish to create a new module (pair of .h and .c files) for configuring GPIO pins, it would look something like so:

    Sample setPinConfig.h file:

    #ifndef _SET_PIN_CONFIG
    #define _SET_PIN_CONFIG
    
    const int start = 13;
    const int stop = 9;
    
    // This function sets the GPIO pins' configuration
    void setPinConfig();
    
    #endif // _SET_PIN_CONFIG
    

    Then sample setPinConfig.c

    #include "setPinConfig.h"
    
    void setPinConfig()
    {
        pinMode(start, INPUT);
        pinMode(stop, INPUT);
    }