The bresenham algorithm used in computer graphics to draw a straight line was originally used to control two motors on the X axis and Y axis on a plotter. Recently, a very similar stepping motor control problem was encountered, the bresenham algorithm can be used to solve the problem.
Problem description: There are two identical stepper motors, with 8051 Single Chip Microcomputer to control the L297 + L298 chip drive, they need to rotate at the same time (start at the same time, stop at the same time), but the speed is different. For example, the motor on the left is turning to step 2, and the motor on the right is reversing step 97. This is like drawing a straight line from the origin point (180,-97.
The interface with the motor has been abstracted into four functions:
Void motorleftshrink (); // tighten ropes on the left Motor
Void motorleftloose (); // The left-side motor to relax the rope
Void motorrightshrink (); // tighten the rope with the right Motor
Void motorrightloose (); // The right motor to relax the rope
There are two auxiliary functions to control the Left and Right Motors respectively:
Void motorleftstep (INT direct)
{
If (direct = 1)
Motorleftloose ();
Else if (direct =-1)
Motorleftshrink ();
}
Void motorrightstep (INT direct)
{
If (direct = 1)
Motorrightloose ();
Else if (direct =-1)
Motorrightshrink ();
}
The current task is to write a function movemotor (), which has four parameters, namely the number and direction of the two motors to control the simultaneous operation of the two motors. I am using the integer version of the line bresenham algorithm, taken from the book "Computer Graphics algorithm basics.
// Parameters: absdl and absdr are the steps in which the left and right Motors rotate.
// SDL and SDR are respectively the orientation of the left and right motor Rotation
Void movemotor3 (INT absdl, int absdr, int SDL, int SDR)
{
Int steps = max (absdl, absdr );
Int El = 2 * absdl-steps; // error accumulation item
Int ER = 2 * absdr-steps; // error accumulation item
Int cntl = 0;
Int cntr = 0;
For (INT I = 0; I <steps; ++ I) {// It is dominated by a large number of rotating steps.
While (El> 0 ){
++ Cntl;
Motorleftstep (SDL );
El-= 2 * steps;
}
El + = 2 * absdl;
While (ER> 0 ){
++ Cntr;
Motorrightstep (SDR );
Er-= 2 * steps;
}
Er + = 2 * absdr;
Wait_ms (15); // wait
}
Assert (cntl = absdl );
Assert (cntr = absdr );
}
After the program is slightly modified, it is compiled on Keil C51, and the motor runs well :)