Code running correctly only when variables defined outside of class in Arduino IDE

29 views Asked by At

I'm very new to C++, I'm writing a code to control stepper motors using the micros() function on Arduino IDE. When I run the code as is, the stepper motor does not turn. While the motor runs expectedly when I assign the variables outside the class instead of in the class.

NON-WORKING CODE:

const int DIR_PIN = 5; // direction
const int STEP_PIN = 2; // step

class steppercontrol {
private:
  unsigned long currenttime;
  unsigned long prevtime;
  int pulsecount;
  int stepcount;
  int delaytime;
  bool pulse;

public:
  void setspeed(int speed){ 
    delaytime = speed;
  }
  void run(int targetstep){
    while (stepcount < targetstep){
      currenttime = micros();
      if (currenttime - prevtime > delaytime){ // compare time passed to desired delay
        pulsecount ++; 
        if(pulsecount % 2 == 0){stepcount++;} // 2 pulses in 1 step

        pulse = pulse == LOW ? HIGH : LOW;
        digitalWrite(STEP_PIN, pulse);
        prevtime = currenttime;
      }
    }
  }
};

void setup() {
  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
  digitalWrite(DIR_PIN, HIGH);
  steppercontrol stepper;

  stepper.setspeed(1000);
  stepper.run(1600);
}

void loop() {
}

CODE WITH VARIABLES OUTSIDE CLASS, WORKING:

const int DIR_PIN = 5; // direction
const int STEP_PIN = 2; // step

unsigned long currenttime;
unsigned long prevtime;
int pulsecount;
int stepcount;
int delaytime;
bool pulse;

class steppercontrol {
public:
  void setspeed(int speed){ 
    delaytime = speed;
  }
  void run(int targetstep){
    while (stepcount < targetstep){
      currenttime = micros();
      if (currenttime - prevtime > delaytime){ // compare time passed to desired delay
        pulsecount ++; 
        if(pulsecount % 2 == 0){stepcount++;} // 2 pulses in 1 step

        pulse = pulse == LOW ? HIGH : LOW;
        digitalWrite(STEP_PIN, pulse);
        prevtime = currenttime;
      }
    }
  }
};

void setup() {
  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
  digitalWrite(DIR_PIN, HIGH);
  steppercontrol stepper;

  stepper.setspeed(1000);
  stepper.run(1600);
}

void loop() {
}
0

There are 0 answers