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);
}
2 Answers 2
Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.
The line:
int ctr = 0;
literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens every time loop()
is executed.
Instead making it static will change it so that it only happens the first time loop()
is executed so it retains its value across successive executions of loop()
.
static int ctr = 0;
-
Agreed. A declaration
int ctr = 0;
inside a function tells the compiler to assign0
toctr
every time it passes that line.2017年03月15日 06:59:03 +00:00Commented Mar 15, 2017 at 6:59
loop() != main()
when declaring a variable inside a function, it is cleaned up when returning from the function.
if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.
Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).
void backMotion...
andvoid forthMotion...
beforevoid loop()
? When you declare a function likeforthMotion
orbackMotion
, it should be before you call the function.