Sub topic 16
Beyond open-loop control: encoders and closed-loop steppers
This chapter assumes you have read the earlier chapters on torque versus speed, acceleration ramps, and the STEP/DIR interface. You should be comfortable with the AccelStepper library and with the idea that a stepper moves one fixed angle per pulse.
What "open loop" means
Everything so far has been open-loop control. The Arduino sends pulses and trusts that the rotor followed each one. It never measures where the shaft actually is. The position it reports, such as stepper.currentPosition(), is a count of pulses sent, not a measurement.
That trust is usually justified. A hybrid stepper has no accumulating error as long as it keeps up. If it moves 1000 steps, it ends at the same angle as 1000 steps from any other start. The trouble comes when it does not keep up.
How open-loop steppers lose position
A stepper loses steps when the load or the speed demands more torque than the motor can make at that moment. Causes you have already met:
- Starting or accelerating faster than the torque-speed curve allows.
- Running at a step rate where torque has fallen below the load.
- A current limit set too low for the load.
- A mechanical jam, a collision, or a belt that slips.
- Resonance at certain speeds, which can make the rotor skip.
When the rotor skips, the driver and the Arduino do not know. The software count says 5000. The shaft is somewhere else. Every later move is offset by the lost amount, and the error never corrects itself.
Open-loop control is still the right choice for many jobs: 3D printer axes with sensible limits, light camera sliders, and dispensers with a known light load. It is simple, cheap, and quiet in software. You need more only when a lost step has a real cost, or when you push the motor hard enough that you cannot be sure it keeps up.
Ways to know the real position
You can add information in several ways, from cheap to complete.
| Approach | What it tells you | Cost and effort |
|---|---|---|
| Limit switch homing | Position at one known point | Very low |
| Stall detection in the driver | That the motor stalled, not where | Low, needs a capable driver |
| Encoder on the shaft, read by the Arduino | Actual position, so you can detect and correct errors | Medium |
| Closed-loop stepper (motor, encoder, and controller) | Actual position, corrected automatically | Higher |
Homing with a limit switch
Homing moves an axis until it presses a switch, then declares that point to be position zero. It fixes the offset that lost steps built up, but only when you home. It does not detect a loss during a move. Many machines home at power-up and periodically after that.
Stall detection
Some drivers, such as Trinamic's TMC2209, can report a stall by sensing the back-EMF (the voltage the spinning rotor induces in the coils). This tells you the motor stopped following the pulses, which is useful for sensorless homing. It does not give you a measured angle, and it works only within a certain speed range. Treat it as an alarm, not a position sensor.
Encoders
An encoder is a sensor that turns shaft rotation into electrical signals. Two kinds are common with steppers:
- Incremental encoders output two square waves, called A and B, that are 90 degrees out of phase. Counting the edges gives movement, and the order of A and B gives direction. A typical optical encoder gives 600 pulses per revolution, and counting every edge of both channels (quadrature decoding) gives four times that, 2400 counts per revolution.
- Absolute encoders report the actual angle at power-up, for example through SPI or a magnetic sensor such as the AS5600. They need no homing, but they cost more and use a communication protocol.
How a closed loop works
In closed-loop control, a sensor measures the result and the controller adjusts its output to reduce the difference between target and actual. For a stepper, the loop compares the commanded position with the encoder position. The difference is the following error.
The diagram below shows the loop.
There are two broad ways to build this.
- Monitor and correct with your own code. The Arduino sends pulses as before and also reads an encoder. If the following error exceeds a threshold, it stops, flags a fault, or issues extra steps. The motor and driver stay standard.
- Use an integrated closed-loop stepper. The motor ships with an encoder and a controller or driver that also adjusts the coil current to match the load. These accept the same STEP and DIR signals, so your Arduino code barely changes.
Reading an encoder on the Arduino
The example below counts quadrature edges on an Arduino Uno using the two external-interrupt pins, 2 and 3. It uses a simple state-table decoder: each change in the A/B pair adds or subtracts one count.
const int ENC_A = 2;
const int ENC_B = 3;
volatile long encoderCount = 0;
volatile uint8_t lastState = 0;
// Index is (previous state << 2) | new state.
// Values are the count change for each transition. Invalid jumps give 0.
const int8_t TRANSITION[16] = {
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0
};
void onEncoderChange() {
uint8_t state = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
encoderCount += TRANSITION[(lastState << 2) | state];
lastState = state;
}
void setup() {
Serial.begin(115200);
pinMode(ENC_A, INPUT_PULLUP);
pinMode(ENC_B, INPUT_PULLUP);
lastState = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
attachInterrupt(digitalPinToInterrupt(ENC_A), onEncoderChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_B), onEncoderChange, CHANGE);
}
void loop() {
noInterrupts();
long count = encoderCount;
interrupts();
Serial.println(count);
delay(200);
}Copying encoderCount with interrupts disabled matters. It is a 4-byte value on an 8-bit chip, so a read can be torn if an interrupt fires halfway through.
Comparing steps with encoder counts
To compare, convert both to the same unit. Suppose the motor is 200 full steps per revolution, the driver uses 16 microsteps, and the encoder gives 2400 counts per revolution after quadrature decoding.
- Pulses per revolution: 200 × 16 = 3200.
- Encoder counts per revolution: 2400.
- Ratio: 2400 / 3200 = 0.75 counts per pulse.
const float COUNTS_PER_STEP = 2400.0f / 3200.0f; // 0.75
const long MAX_ERROR_COUNTS = 60; // about 9 degrees
// commandedSteps comes from AccelStepper's currentPosition().
// encoderCounts is a snapshot of encoderCount taken with interrupts off.
long followingError(long commandedSteps, long encoderCounts) {
long expectedCounts = (long)(commandedSteps * COUNTS_PER_STEP);
return expectedCounts - encoderCounts;
}
bool positionLost(long commandedSteps, long encoderCounts) {
long err = followingError(commandedSteps, encoderCounts);
return err > MAX_ERROR_COUNTS || err < -MAX_ERROR_COUNTS;
}Choose the threshold with care. At 2400 counts per revolution, 60 counts is 9 degrees, which is five full steps of 1.8 degrees. A tighter limit catches problems sooner but can trigger false alarms because the rotor naturally lags the commanded position under load, and more so during acceleration. A good starting point is a threshold of a few full steps, then tune it by running the machine normally and watching the largest error you see.
When the check fails, the safest default response is to stop, report a fault, and re-home. Silently adding correction steps can hide a mechanical problem and may drive the load into a hard stop.
Gotchas with your own feedback loop
- Interrupt load. A fast encoder on a Uno can produce tens of thousands of edges per second. Each interrupt takes time away from your step generation, which can cause pulse jitter. Use a hardware counter, an encoder-reading chip, or a board with hardware quadrature support if rates are high.
- Backlash and compliance. If the encoder is on the load side of a belt or gearbox, the gap and stretch appear as error. Mount it on the motor shaft to monitor the motor, or on the load to monitor the result, and know which you chose.
- Noise. Motor wires radiate switching noise. Use shielded or twisted encoder cables, keep them away from motor wires, and share a ground reference.
- Resolution mismatch. If the encoder has fewer counts than your microsteps, you cannot see sub-step errors. That is fine for loss detection but not for fine positioning.
What an integrated closed-loop stepper does differently
A basic open-loop driver pushes the full set current all the time, so the motor runs warm even when idle. A closed-loop driver measures the rotor angle and applies current only as needed to keep the rotor at its target. This changes behavior in useful ways:
- The motor does not lose steps within its torque limit, because the controller advances the field to match the rotor.
- Current falls when the load is light, so the motor runs cooler and quieter.
- Overload becomes a reported fault instead of silent position loss.
The limit is torque. A closed-loop stepper is not stronger than the same motor open loop at its peak. It uses its torque more efficiently, and it tells you when that torque is not enough. If you need much more speed or force, a larger motor or a servo is the answer.
Choosing between the options
- Light load, modest speed, homing available: stay open loop with ramps.
- Occasional loss would be costly, but the budget is tight: add an encoder and a following-error check.
- Hard-driven axis, varying load, or unattended machine: use a closed-loop stepper or a servo.
Exercise
A motor has 200 full steps per revolution and the driver is set to 8 microsteps. An encoder gives 1000 pulses per revolution on each channel, and you decode all four edges. After a move, AccelStepper reports a position of 8000 steps and the encoder count is 4600. How many counts of following error are there, and in which direction did the shaft fall short?
Show answer
Pulses per revolution are 200 × 8 = 1600. Encoder counts per revolution are 1000 × 4 = 4000, so there are 2.5 counts per pulse. Expected counts are 8000 × 2.5 = 20000? No: 8000 steps is 5 revolutions, which is 5 × 4000 = 20000 counts. The encoder shows 4600, so it reports a much smaller movement, and the error is 20000 − 4600 = 15400 counts. That is far too large for a lost step or two, so check the numbers first: the count may have been reset, or the encoder may be miscounting. If the readings are real, the shaft turned less than commanded, falling short in the commanded direction.
Exercise
Why does a closed-loop stepper run cooler than an open-loop one holding the same position?
Show answer
The open-loop driver supplies the full set current whether or not the load needs it. A closed-loop driver reads the rotor angle and supplies only the current needed to hold the target, so a lightly loaded motor draws less current and makes less heat.