## Calculating Distance

- Basicmicro Support
**Posts:**1594**Joined:**Thu Feb 26, 2015 9:45 pm

##### Calculating Distance

This is a post to describe how to calculate the distance of a movement for the SpeedAccelDistance commands.

The simple distance formula is d = (V*V)/(2*a). This assumes starting or ending with a velocity of 0.

First you need to calculate the distance needed to accelerate to you speed and then to decelerate back to 0. We'll call those d1 and d2.

If d1+d2 is less than or equal to the distance you want to travel then subtract d2 from the distance you want to move(we'll call that D) and use that for the first SpeedAccelDistance command distance. Then send a second SpeedAccelDistance command to decelerate to 0 speed. The distance it takes to decel to 0 will be equal to d2 as calculated.

If d1+d2 is greater than the distance you want to travel you have to calculate things differently. You need to recalculate d1 and d2 using the ratio of the distances first calculated with the distance you want to move. The formulas are simple enough.

//Here is some psuedo code

//D, speed, accel and decel are defined by you

float d1 = (speed*speed)/(2*accel)

float d2 = (speed*speed)/(2*decel)

uint32_t dT = d1+d2

if(dT>D) {

d1 = d1/dT * D;

d2 = d2/dT * D;

}

else{

d1 = D-d2;

}

SpeedAccelDistanceM1(0x80, accel, speed, d1, 0);

SpeedAccelDistanceM1(0x80, decel, speed, d2, 0);

The simple distance formula is d = (V*V)/(2*a). This assumes starting or ending with a velocity of 0.

First you need to calculate the distance needed to accelerate to you speed and then to decelerate back to 0. We'll call those d1 and d2.

If d1+d2 is less than or equal to the distance you want to travel then subtract d2 from the distance you want to move(we'll call that D) and use that for the first SpeedAccelDistance command distance. Then send a second SpeedAccelDistance command to decelerate to 0 speed. The distance it takes to decel to 0 will be equal to d2 as calculated.

If d1+d2 is greater than the distance you want to travel you have to calculate things differently. You need to recalculate d1 and d2 using the ratio of the distances first calculated with the distance you want to move. The formulas are simple enough.

//Here is some psuedo code

//D, speed, accel and decel are defined by you

float d1 = (speed*speed)/(2*accel)

float d2 = (speed*speed)/(2*decel)

uint32_t dT = d1+d2

if(dT>D) {

d1 = d1/dT * D;

d2 = d2/dT * D;

}

else{

d1 = D-d2;

}

SpeedAccelDistanceM1(0x80, accel, speed, d1, 0);

SpeedAccelDistanceM1(0x80, decel, speed, d2, 0);