This is a common issue I keep running into. When I call a function which calulates a value using a changing variable for example:
void operateMotor(int move2percent) {
int endCount = closePercent - move2percent;
if (oldCurtainState == open) {
myStepper.step(-10);
}
else if (oldCurtainState == closed) {
myStepper.step(10);
}
counter = counter + 10;
if (counter >= (endCount)) {
endOfMovement();
}
}
I only want to calculate the first line
int endCount = closePercent - move2percent;
on the first instance that the function is called.
I have previously used a simple bool called first which is reset on the completion of the movement but I wondered if there was a more elegant way?
static int endCount = closePercent - move2percent;
gcjr
May 18, 2020, 9:07pm
3
static int endCount = 0;
if (0 == endCount)
endCount = closePercent - move2percent;
No need for the if() statement. Local static variables are only initialized the first time control passes through the point were they are defined.
Sorry I don't think I've made it quite clear. The function is called to rotate a stepper motor and therefore a curtain to a location. To make the stopper non blocking it moves 10 steps at a time. When it gets to the end it stops until another command is sent. When the new command is sent I want to recalculate the value
gcjr:
static int endCount = 0;
if (0 == endCount)
endCount = closePercent - move2percent;
Actually think about it more I think this would work for my solution. I will give it a go a let you know