Is it possible to access a variable in a sketch from a class?

Say I want to get a value of a variable in a sketch from a class I wrote like:

sketch

int device;
void setUp() {
   device = 1;
}

And I have a class SomeClass.cpp

void Device::checkTimedEvent() {
   someDevice = device; //variable from sketch
}

I know it's possible to access members from another class where I can include the class and use the :: scope operator but not sure how the sketch relates to classes. I might have to stick the device variable in its own class or typedef?

thanks

Yes, it is possible, but it’s not advised.

Far better is to pass the device number as a parameter.

void Device::checkTimedEvent(int dev) {
  someDevice = dev;
}

myDevice.checkTimedEvent(1);

Even better is to pass the device ID to the constructor:

Device::Device(int devID) {
  myDeviceID = devID;
}

void Device::checkTimedEvent() {
  // Do something with myDeviceID
}

//...

Device myDevice(1);

myDevice.checkTimedEvent();

Hmm, something to thing about. I can't pass it to the constructor because the variable changes.

Just curious, how would you get the value of a variable in a sketch besides passing in into a setter method.

Assuming your class is (as it should be) in a different set of files:

extern int device;

void Device::checkTimedEvent() {
  somedevice = device;
}
int device;

void setUp() {
   device = 1;
}

Ahh, thanks. I've seen 'extern' a bit in libraries where that make the instance exposed to the sketch.

I've decided to use an in-between class (delegate) where the sketch & classes can access values. My example is a simple one but there are other complicated methods I'll need as well so a delegate class is good.

The "extern" keyword tells the compiler "The variable or function I am defining here is actually located in a different file. Look for it elsewhere."

majenko:
The “extern” keyword tells the compiler “The variable or function I am defining here is actually located in a different file. Look for it elsewhere.”

wow - a week earlier and that explanation would’ve saved me “slumming” (!!) :stuck_out_tongue: through the cplusplus reference pages trying to find a page that explained the ‘extern’ keyword !