Share/pass value from .ino to .cpp?

Hi there,

I am using a library and would like to pass a variable (like a button state, on/off) to a library. This state would change based on an ISR using an interrupt.

I am using this library: Adafruit FONA Library

Basically I want my ISR in my .ino to update the shared variable ("buttonPressed") whenever the ISR is triggered. However, I couldn't quite figure out where to put everything to make it compile properly. I tried adding a function like this in the .cpp file:

void Adafruit_FONA_3G::setButtonState(bool buttonState) {
  buttonPressed = buttonState;
}

and initializing the variable in the .h file at line 67 with this:

volatile bool buttonPressed = false;

but I couldn't get it to work. It keeps saying there are multiple definitions of "buttonPressed" even though in the .ino I don't declare it.

What's the proper way of sharing a variable between the .ino and library?

Put that definition for buttonPressed in the .cpp and not in the .h. Give the .ino an extern declaration for it so the .ino knows it exists.

Thanks, it compiles now! So I don't need the function that toggles the variable? Does declaring it as extern in the .ino and putting the main declaration in the .cpp automatically share it so that I don't have to do anything special? (I.e, can I just change the variable state directly in the .ino with something like "buttonPressed = true" and it will update in the .cpp?)

Yes. Go google extern.

Awesome, thanks!

OK,now here's my real question: how do I share a function in my .in with my .cpp so that I can call that function in my .cpp?

Thanks!

Extern. Did you read up about it yet?

I put this in my .ccp file and it didn't compile.

extern void MCU_powerDown(void);

The function in my .ino blinks an LED and tells the MCU to go to sleep and I want to call it in my .cpp. Am I missing something here? Thanks!

Never mind, it compiles! I made some other change that broke it haha.

Glad it compiles. Although if the cpp needs a function from the ino I worry a little about the program structure.