Go Down

Topic: Stepper motor feedback with optical encoder (Read 33 times) previous topic - next topic


What I'm trying to achieve is to control a stepper motor with user defined number of steps, through the use of an optical encoder that is mechanically linked to the stepper motor.

The motor should rotate until the encoder reads the number of steps is equal to the user defined number of steps

I'm aware that stepper motors, if run within rated values should not slip and thus do not need feedback - even for precise stepping

I've written some simple code, speed is not an issue - thus pulsing outpin directly in a while loop- but it seems to be flawed

Looking forward to a reply

The code

#include <Encoder.h>

Encoder knobLeft(2, 3);

int counter=0;
int stepPin=5;
int dirPin=4;
int rev=1000;

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  digitalWrite(dirPin, LOW);

long positionLeft  = -999;

void loop() {
  long newLeft;
  newLeft = knobLeft.read();
  if (newLeft != positionLeft ) {
   // Serial.print("Left = ");
    //Serial.print(newLeft);    //Serial.println();
    positionLeft = newLeft;





Aug 23, 2016, 10:00 pm Last Edit: Aug 23, 2016, 10:00 pm by Robin2
"it seems to be flawed" does not give any idea of how the program actually behaves or what you would like it to do.

What happens if you make your stepper move very much slower - like 2 steps every second?

I find it easier to manage the step timing like this
Code: [Select]

with all the step interval in one place.

For a practical program delayMicroseconds() is unsuitable beacuse it blocks the Arduino from doing other stuff - such as reading the encoder. See the second example in this Simple Stepper Code

Actually, that may be your problem. You are using the blocking WHILE when you probably should move the motor just one step between readings of the encoder.

Two or three hours spent thinking and reading documentation solves most programming problems.


Hi, thanks for the reply

Sorry, my problem description seems to be flawed  :)

When the encoder turns the full number of specified steps, the motor simply slows down slightly and then continues to rotate.

If I rotate the encoder by hand, whilst the motor is rotating, a full of rotation which should stop the motor, the motor again simply slows down when the encoder is turning and then when the I stop rotating the encoder it speeds up again and continues to run.

It seems as though the encoder is interrupting the pulsing of the motor, hence the decrease in motor speed.

I will try implement your method to delay the pulsing of the motor

Thanks for your insight


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131