# Understanding bresenham's line algorithm to move stepper motors

Hello,
I’ve been using 3D printers for a while, and I always wondered how the firmware works. I have come across this topic on MarginallyClever. I was able to compile the code from his GitHub repository named GcodeCNCDemo4AxisRAMPS sice I use Arduino Mega and RMPS1.4 shield.

I have been trying to understand the code used to draw lines and Acrs, but I couldn’t completely understand it so far.

``````/**
* Uses bresenham's line algorithm to move both motors
* @input newx the destination x position
* @input newy the destination y position
**/
void line(float newx,float newy,float newz,float newe) {
a[0].delta = (newx-px)*STEPS_PER_MM;
a[1].delta = (newy-py)*STEPS_PER_MM;
a[2].delta = (newz-pz)*STEPS_PER_MM;
a[3].delta = (newe-pe)*STEPS_PER_MM;

long i,j,maxsteps=0;

for(i=0;i<NUM_AXIES;++i) {
a[i].absdelta = abs(a[i].delta);
if( maxsteps < a[i].absdelta ) maxsteps = a[i].absdelta;
// set the direction once per movement
Dio_ChannelWrite((DioChannel_t)motors[i].dir_pin,a[i].delta>0?DIO_HIGH:DIO_LOW);
}
for(i=0;i<NUM_AXIES;++i) {
a[i].over= maxsteps/2;
}

long dt = MAX_FEEDRATE/5000;
long accel = 1;
long steps_to_accel = dt - step_delay;
if(steps_to_accel > maxsteps/2 )
steps_to_accel = maxsteps/2;

long steps_to_decel = maxsteps - steps_to_accel;

Serial.print("START ");
Serial.println(dt);
Serial.print("TOP ");
Serial.println(step_delay);

Serial.print("accel until ");
Serial.println(steps_to_accel);
Serial.print("decel after ");
Serial.println(steps_to_decel);
Serial.print("total ");
Serial.println(maxsteps);
#ifdef VERBOSE
Serial.println(F("Start >"));
#endif

for( i=0; i<maxsteps; ++i ) {
for(j=0;j<NUM_AXIES;++j) {
a[j].over += a[j].absdelta;
if(a[j].over >= maxsteps) {
a[j].over -= maxsteps;

//digitalWrite(motors[j].step_pin,HIGH);
//digitalWrite(motors[j].step_pin,LOW);
Dio_ChannelWrite((DioChannel_t)motors[j].step_pin, DIO_HIGH);
Dio_ChannelWrite((DioChannel_t)motors[j].step_pin, DIO_LOW);
}
}

if(i<steps_to_accel) {
dt -= accel;
}
if(i>=steps_to_decel) {
dt += accel;
}
delayMicroseconds(dt);
}

#ifdef VERBOSE
Serial.println(F("< Done."));
#endif

position(newx,newy,newz,newe);

where();
}
``````

Can someone explain to me how this algorithm works. ?
I read about bresenham’s line algorithm from different sources, most of them only explains about slope less than 1. But the code used here is quite different from what I have seen in those explanations

Thanks

The original paper by Bresenham is completely straightforward, referenced in Wikipedia here, which also provides a clear explanation.