This is a simple question that goes like this:
Is the code for variables declared (and instantiated) in libraries executed after or before setup() is called?
And here’s the longer version:
So, I have this code with tact switches. Simple stuff, pinMode with INPUT_PULLUP. They way it works, the buttons are initialized (ie call pinMode) directly from code like this:
Buttons.cpp:
// The buttons class goes like this (heavely simplified to just show how it works):
#include "Buttons.h"
TButtons ButtonsHandler(PIN_B1, PIN_B2, PIN_B3, 3); //where PIN_B# is a pin number of course
TButtons::TButtons(byte ButtonPins[], byte ButtonCount){
for (byte i= 0; i < ButtonCount; i++){
pinMode(ButtonPins[i], INPUT_PULLUP);
}
}
byte TButtons::GetButton(){
for(byte i= 0; i < ButtonCount; i++)
if (digitalRead(ButtonPins[i]) == LOW)
return i;
return 0;
}
Now here’s the problem. In my contraption, I’d like to be able to enter a special mode that should happen before anything else. For that I decided to check if a button was pressed or not from startup. So I did this:
In main.ino:
#include "Buttons.h"
void setup(){
if (ButtonsHandler.GetButton() == PIN_B1)
GoSpecialMode();
else
DoTheRestOfTheStuff();
}
void loop(){
and the rest of things.
}
But it doesn’t work, it ignores the button being pressed. My guess is that the pin is not yet “functional” when I try to digitalRead() it.
If I do this:
void setup(){
pinMode(Pin_B1, INPUT_PULLUP); //This should have been done already by TButtons' constructor at this time
delay(50);
if (ButtonsHandler.GetButton() == PIN_B1)
GoSpecialMode()
}
it works perfectly. I did check that the object is being instantiated before setup() and it does and sets up everything as it should.
So it got my thinking. What is going on?
I’d imagine that setup() is called AFTER all the code from libraries is executed, so ButtonHandler should have been initialized by then. Which it does (I logged the order of execution in EEPROM and then checked).