문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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:
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top