Question

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. thanks

Was it helpful?

Solution

It appears that the usual C/C++ "extern" syntax works in Arduino as if the sketch file were a .cpp file:

Sketch:

int device = 123;

SomeClass.cpp:

extern int device;

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

   // will display "123" (or current value of device)
   // if serial output has been set up:
   Serial.println("device: " + String(device));
}

You may need to worry about startup and initialization order, depending on the complexity of your project.

OTHER TIPS

class Test
{
  public:
    int N = 0;

};

Test t;
int someNumber = t.N;

The best way to do this is to pass the value into the function as a parameter. Here's a simple example:

Class:

class Test
{
public:
    void doSomething(int v);

private:
    int myValue;
};

void Test::doSomething(int v)
{
     myValue = v;
}

Sketch:

Test t;
int someNumber;

void setup()
{
    someNumber = 27;
    t.doSomething(someNumber);
}

The setup() function here passes global variable someNumber into the class's member function. Inside the member function, it stores its own copy of the number.

It's important to note that it has a completely independent copy of the number. If the global variable changes, you'd need to pass it in again.

As much as Bloomfiled's answer is correct using the the more accepted practice of employing Getter and Setter functions. Below demonstrates this along with making the attribute public and directly accessing it.

class Test
{
public:
    void SetMyValue(int v);
    int  GetPublicValue();
    int  GetPrivateValue();
    int  myPublicValue;

private:
    int myPrivateValue;
};

void Test::SetMyValue(int v)
{
     myPublicValue = v;
     myPrivateValue = v;
}

int  Test::GetPublicValue()
{
     return myPublicValue;
}

int  Test::GetPrivateValue()
{
     return myPrivateValue;
}

Test t;
int someNumber;

void setup()
{
    someNumber = 27;
    t.SetMyValue(someNumber);         // set both private and public via Setter Function
    t.myPublicValue = someNumber;     // set public attribute directly.
    someNumber = t.GetPublicValue();  // read via Getter
    someNumber = t.GetPrivateValue();
    someNumber = t.myPublicValue;     // read attribute directly

}

void loop() {
  // put your main code here, to run repeatedly:
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top