So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.
I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.
The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.
Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?
void loop()
{
stepper1.run();
int ctr = 0; //counter value to store how many times the back and forth motion has occured
if(stepper1.currentPosition() == 1024){
backMotion(stepper1.currentPosition());
ctr++;
Serial.println(ctr);
}
Serial.println(ctr);
if(stepper1.currentPosition() == 824 && ctr > 0){
forthMotion(stepper1.currentPosition());
}
}
void backMotion(int value){
int current = value;
int back_distance = current - 200; //distance to move back by
stepper1.moveTo(back_distance);
}
void forthMotion(int value) {
int current = value;
int forth_distance = current+200;
stepper1.moveTo(forth_distance);
}
void backMotion...
andvoid forthMotion...
beforevoid loop()
? When you declare a function likeforthMotion
orbackMotion
, it should be before you call the function.