Mistergreen Mistergreen - 3 months ago 24
C++ Question

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

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

Answer

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:
}