Stepper Motor Shortest Path Whilst Keeping Positional Data

Hi guys,
I have an algorithm/logic based issue I am struggling to solve. I have created the below image to try and explain the issue clearer:

The marker has 10 sequential positions to follow and I need an algorithm to move the stepper to positions in the sequence following the shortest path.The stepper motor is at position 30, the next position is 330. Currently the stepper moves clockwise a full 300 steps instead of moving 60 steps anti-clockwise.

I have drafted up the following code:

fullRev = 360
halfRev = 180
currentPos = 30
nextPos = 330
diff = nextPos - currentPos #300
if diff > halfRev:
	result = diff - fullRev #-60
if diff <= halfRev:
	result = nextPos

However I need to keep the steppers positional data for the next position in the sequence. So if I use my code above and move the stepper -60 steps as calculated then it has kind of lost the fact that it is actually sitting at position 330 (i assume the stepper thinks it is at position -30 instead). This makes it troublesome calculating the next sequential positions and the shortest path.

I also don't want to power down the stepper at each position to reset it’s 0 position as it may lose steps.

Can anyone think of any solutions? I am using Python to serial to Arduino and accelStepper library’s stepper.moveTo function.

That's the new position in either case :slight_smile:

Compute the number of steps in positive or negative direction.

1 Like

Assume positive rotation. If the number of steps N to the next position is greater than 180, change direction and take 360-N steps.

1 Like

Thank you both,
I after some testing I believe the following code works well:

def shortestPath(oldPos, newPos):
	stepsPerRev = 360
	halfRev = 180
	difference = newPos - oldPos

	if difference > halfRev:
		result = str(difference-stepsPerRev)
		return result

	if difference <= -halfRev:
		result = str(difference+stepsPerRev)
		return result

	else:
		result = str(difference)
		return result

print(shortestPath(330, 180))

Unreachable code

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.