Sub topic 12
Reversing Direction and Ramping Speed Safely
This chapter assumes you can already drive a motor with a signed-speed function like setMotor(). It also assumes you know what back-EMF and flyback paths are, and that you have a driver powered with a shared ground. If any of that is shaky, review the earlier chapters on motor basics, flyback protection, and the Arduino control code first.
By the end you will know why an abrupt reversal stresses the motor, the driver, and the supply. You will also be able to write a ramp that passes through zero, and you will know when the simple blocking version is not good enough.
Why abrupt reversal is hard on the hardware
A spinning brushed DC motor generates a voltage called back-EMF. It is proportional to speed and opposes the supply voltage. The current through the motor is roughly:
I = (Vsupply − VbackEMF) / R_winding
At standstill, back-EMF is zero. The current is limited only by the winding resistance, which is why stall and startup currents are the highest the motor draws.
Now suppose the motor spins forward at full speed and you flip the direction pins to reverse. The driver now applies the supply voltage with the opposite polarity. The back-EMF still has its old polarity, because the rotor has not slowed down yet. The two voltages no longer oppose each other. They add:
I = (Vsupply + VbackEMF) / R_winding
For a motor with a back-EMF near the supply voltage, this is close to twice the stall current. Three things suffer:
- The driver. It may exceed its peak current rating or trip its thermal shutdown. Bipolar drivers such as the L298N also dissipate more heat at high current.
- The supply. A sudden current surge pulls the rail down. On a shared supply, the Arduino can brown out and reset. A reset leaves the pins as inputs, so the motor coasts, and the code restarts from the beginning.
- The mechanics. The motor produces a large braking torque. Gears, couplings, and wheels take a shock load. Plastic gears can strip.
Two safe strategies
You have two main options. Pick based on how fast you need to reverse and how sturdy your mechanics are.
- Stop, pause, then reverse. Set speed to 0, wait long enough for the rotor to stop or nearly stop, then command the opposite direction. This is simple and works well for small, low-inertia loads.
- Ramp through zero. Change the speed command one small step at a time. The command crosses zero on its way from positive to negative, so the motor decelerates under control before it accelerates in the other direction.
Ramping also protects against the startup current surge when you go from 0 to a high speed. Even without reversing, a gentle acceleration is easier on the supply and the gears.
A ramp that passes through zero
The function below reuses setMotor() from the earlier chapter. It moves currentSpeed one count at a time toward the target. Because the count changes by one each step, going from +200 to −200 must visit 0, so the reversal is never abrupt.
const uint8_t IN1 = 7;
const uint8_t IN2 = 8;
const uint8_t EN = 9; // must be a PWM-capable pin
int currentSpeed = 0;
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(EN, OUTPUT);
}
// speed: -255 (full reverse) to 255 (full forward), 0 = stopped
void setMotor(int speed) {
speed = constrain(speed, -255, 255);
if (speed > 0) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
} else if (speed < 0) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
} else {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
analogWrite(EN, abs(speed));
}
// Move toward targetSpeed in small steps, passing through zero before reversing.
void rampTo(int targetSpeed, int stepDelayMs) {
while (currentSpeed != targetSpeed) {
if (currentSpeed < targetSpeed) {
currentSpeed++;
} else {
currentSpeed--;
}
setMotor(currentSpeed);
delay(stepDelayMs);
}
}
void loop() {
rampTo(200, 5);
delay(1000);
rampTo(-200, 5);
delay(1000);
rampTo(0, 5);
delay(2000);
}Timing for this sketch: going from 200 to −200 takes 400 steps at 5 ms, which is about 2 seconds. The ramp rate is therefore about 51 counts per second at stepDelayMs = 5 (1000 / 5 = 200 counts per second, so the full 255-count range takes about 1.3 seconds).
Choosing the ramp rate
The right step delay depends on the load, not on a formula. Start slow and speed up.
- A light load with a small motor may tolerate a full-range ramp in 200 to 300 ms.
- A heavy wheel or a geared robot may need one second or more.
- Measure the supply voltage at the driver during a reversal. If it sags by more than a few percent, or the Arduino resets, lengthen the ramp.
The dead zone at low duty cycle
A motor does not start turning at duty cycle 1. Friction and the motor's minimum starting voltage mean that very low PWM values produce only a hum. This region is called the dead zone, and it is typically somewhere between 20 and 80 counts, depending on the motor, load, and supply voltage.
The ramp above spends time in the dead zone, where nothing moves. That is harmless for safety, but it makes reversals feel sluggish. You can skip the dead zone when crossing zero only if you have confirmed the motor has actually stopped. A safer approach is to keep the ramp as it is and shorten the delay near zero.
Making the ramp non-blocking
rampTo() uses delay(), so the Arduino can do nothing else while it runs. It cannot read sensors, check buttons, or react to a stop command. For anything beyond a demo, use millis() so the ramp advances one step per timer tick while loop() keeps running.
const uint8_t IN1 = 7;
const uint8_t IN2 = 8;
const uint8_t EN = 9;
int currentSpeed = 0;
int targetSpeed = 0;
unsigned long lastStepMs = 0;
const unsigned long STEP_INTERVAL_MS = 5;
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(EN, OUTPUT);
}
void setMotor(int speed) {
speed = constrain(speed, -255, 255);
if (speed > 0) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
} else if (speed < 0) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
} else {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
analogWrite(EN, abs(speed));
}
// Call this on every pass through loop(). It moves one step when due.
void updateRamp() {
unsigned long now = millis();
if (now - lastStepMs < STEP_INTERVAL_MS) {
return;
}
lastStepMs = now;
if (currentSpeed < targetSpeed) {
currentSpeed++;
} else if (currentSpeed > targetSpeed) {
currentSpeed--;
} else {
return;
}
setMotor(currentSpeed);
}
void loop() {
// Example: alternate the target every 4 seconds.
static unsigned long lastSwitchMs = 0;
static bool forward = true;
if (millis() - lastSwitchMs >= 4000) {
lastSwitchMs = millis();
forward = !forward;
targetSpeed = forward ? 200 : -200;
}
updateRamp();
// Other work can go here, such as reading sensors.
}Subtracting lastStepMs from millis() keeps the comparison correct when millis() wraps around after about 49 days, because unsigned arithmetic wraps the same way.
Emergency stop
A ramp should not slow down an emergency stop. Add a separate path that bypasses the ramp:
void emergencyStop() {
targetSpeed = 0;
currentSpeed = 0;
setMotor(0);
}Setting both variables to zero keeps the ramp from restarting the motor on the next pass. Whether the stop is a brake or a coast depends on how your driver treats both inputs LOW. Check the datasheet. On an L298N, both inputs LOW with the enable pin at zero leaves the motor free to coast. If you need an active brake, you must set both inputs to the same level with the enable pin high.
Using the driver's brake before reversing
Ramping lets the motor slow down by reducing drive. If the load has high inertia, the motor may take a long time to stop on its own. You can speed this up by briefly applying the brake state before the opposite drive.
- Ramp down to a low speed.
- Apply brake (both low-side switches on, or both inputs at the same level, depending on the driver) for a short, fixed time such as 50 to 200 ms.
- Set the new direction and ramp up.
Braking dumps the rotor's kinetic energy as heat in the winding and the driver, so keep brake pulses short and avoid repeating them quickly.
Reversal timing summary
| Method | Reversal time | Peak current | Complexity | Best for |
|---|---|---|---|---|
| Direct flip | Fastest | Up to about 2× stall | Lowest | Nothing that you care about |
| Stop, pause, reverse | Slow, set by coast-down | Normal | Low | Light loads, simple tools |
| Blocking ramp | Set by step delay | Moderate | Low | Demos and tests |
| Non-blocking ramp | Set by step interval | Moderate | Medium | Robots, anything with sensors |
| Ramp plus short brake | Shorter than coasting | Moderate with brief braking load | Medium | High-inertia loads |
Common mistakes
- Ramping speed but not direction pins. If a library changes direction in one call and speed in another, make sure the speed reaches zero before the direction pins change.
- Step size too large. A step of 20 counts every 5 ms is almost as abrupt as no ramp. Prefer small steps and tune the interval.
- Forgetting
currentSpeedis shared state. CallingsetMotor()directly while a ramp is active makescurrentSpeeddisagree with the real output. Route all changes throughtargetSpeed, except for the emergency stop. - Judging by sound. A motor that sounds fine can still overload the supply. Measure the rail voltage.
Exercise
A motor runs forward at full speed from a 9 V supply, with a winding resistance of 3 ohms. Its back-EMF at that speed is about 8 V. Estimate the current if you flip the direction pins at once, and compare it with the stall current. Then say what a ramp through zero changes.
Show answer
With the direction flipped, back-EMF adds to the supply: I = (9 + 8) / 3 ≈ 5.7 A. The stall current is 9 / 3 = 3 A, so the reversal draws nearly twice the stall current. With a ramp through zero, the motor slows first, so back-EMF falls toward 0 V before the polarity changes. The current then stays near or below the stall value of 3 A, which is within what the driver and supply were chosen for.
Exercise
In the non-blocking sketch, why is now - lastStepMs < STEP_INTERVAL_MS safe when millis() wraps around, and why does emergencyStop() set currentSpeed as well as targetSpeed?
Show answer
Both values are unsigned long, so the subtraction wraps modulo 2^32 and still gives the correct elapsed time across the rollover. emergencyStop() sets currentSpeed to 0 so that the ramp, which compares currentSpeed with targetSpeed, sees them as equal and does nothing. If only targetSpeed were set, the ramp would keep stepping down from the old currentSpeed and drive the motor again after the stop.