Stepper Motor - Quickest route

Hi All,

I need help.

I have a stepper motor, and for arguments sake, lets say a full revolution is 1000 steps.

If i'm at step position 100 , and i want to go to step position 900, I want to work out the quickest route, so rather than go anti clockwise to 900, i want to go past 0, clockwise to 900, in effect moving 200 steps rather than 700.

I am trying to figure out an algorithm for it, but failing....

I tried searching but could not find anything..

Anyone able to help ?

Here's something I wrote a long time ago to do this:

bool TurnRight(long CourseNow,long CourseNew)
// Should we turn left or right to make the move to new position shortest?
{
bool retval=true;  
if(CourseNew > CourseNow)
  {
  if((CourseNew-CourseNow) > (StepsPerQuarterRevolution*2))
    retval = false;
  }
else
  {
  if((CourseNow-CourseNew) < (StepsPerQuarterRevolution*2))
    retval=false;
  }
return retval;    
}

It takes two headings and returns a boolean determining whether to turn right to minimize the amount of rotation. Why the headings are long rather than int, I can no longer recall.

I too struggled with figuring out the perfect algorithm to start with. So much so that I figured I'd just brute force it and optimize later. A bit of coding later I was surprised to see how simple it turned out to be.

Here is my approach, which encodes both the number of steps to take and the direction, as the sign of the return argument.

It won't work properly if you want to move more than one revolution in either direction.

#define steps_per_revolution 200
// calculates number of steps and direction to rotate from old_pos to new_pos
int steps_to_go(int old_pos, int new_pos) {
 int half_rev = steps_per_revolution / 2;
 int diff = new_pos - old_pos; //if this is less than half a revolution, do this move. 
 // else
 if (diff > half_rev) diff = diff - steps_per_revolution;  //result negative, go the other way
 if (diff < -half_rev) diff = diff + steps_per_revolution; //result positive, go forward
 return diff;
}