Hello,
You have a related post here already:
I have worked with stepper motors.
I provided a minimal example of an approach I took to this:
- Processing is sending integer “steps” and direction (this can be positive or negative) to the Arduino
- “Position” can be translated to steps and direction; you will have to do this correctly relative to the current initial and final position. I did not do this in this example.
- The Processing “simulation” should follow the expected motion of the stepper motor from the instructions you are sending.
- The motor must complete its motion (code is blocking on Arduino side) so that must also be given consideration. This is not in this code example.
I did this simulation (rotating line) using:
- A integer counter for steps.
- Drawing a line that was rotated by steps*angle/step
- Using modulo operator for the zero-crossing (0/360/720 deg… etc.) to determine the rotation and plot the line.
Examples:
4096%4096 = 0
(4096 + 1024)%4096 = 1024
And so on…
I left this uncommented and removed variable names so you can work through it:
float a;
int b, c;
void setup()
{
size(400, 400, P2D);
b = 32;
}
void draw()
{
background(64);
translate(width/2, height/2);
float d = TWO_PI/b;
a = (c%b)*d;
rotate(a);
strokeWeight(3);
stroke(255, 0, 0);
line(0, 0, 150, 0);
println(a, degrees(a));
}
void mousePressed()
{
if (mouseButton == LEFT) c++;
if (mouseButton == RIGHT) c--;
}
I used the modulo operator because floating point errors accumulated if I rotated the motor a few hundred thousand times; this kept the rotations to between 0 and 2π.
References:
’ ’