new to writing classes and a logic error I don't see

Status
Not open for further replies.

DaQue

Well-known member
I am trying to convert a working project over to a state machine layout that i hope will make it a bit more responsive but I also decided to do my first class at the same time. It was too much I fear. The code that follows compiles as is but has a logic error. It prints and then every time thru the loop. The problem is I want the msNow to be in the class and shared by each instance. If I comment out line one and uncomment it in the class I get an undefined reference to it. Anyone see my error? This is cut down as far as I can from about 200 lines of code. It gives errors for every line with msNow in it if I put it as a static class variable.

Code:
elapsedMillis msNow;
class uState {
  public:
    void setFlagWDelay(uint32_t msFromNow);
    void clrFlag();
    bool checkFlagWTmr(bool trigWhen);
  private:
    //static elapsedMillis msNow;
    bool flag;
    uint32_t tTime;
};
void uState::clrFlag() {
  flag = false;
}

void uState::setFlagWDelay(uint32_t msFromNow) {
  flag = true;
  tTime = msNow + msFromNow;
}

bool uState::checkFlagWTmr(bool trigWhen) {

  if ((flag == trigWhen) && (tTime > msNow)) {
    return true;
  }
  else {
    return false;
  }
}
uState test;

void setup() {
  Serial.begin(9600);
  test.setFlagWDelay(5000);
}
void loop() {
  Serial.println("now");
  if (test.checkFlagWTmr(true)) {
    test.clrFlag();
    Serial.println(" and then");
    test.setFlagWDelay(2000);
  }
}
 
Somewhere you need to allocate/define your static object
Example:
elapsedMillis uState::msNow;
 
Hmmm. Ok I will have to look over that part in my C++ books again. Thanks for the help.
 
Found it, "When we declare a static member variable inside a class, we’re simply telling the class that a static member variable exists (much like a forward declaration). Because static member variables are not part of the individual class objects (they get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope."

I would have sworn the examples I looked at (using int's) didn't do that.
 
Status
Not open for further replies.
Back
Top