Sub topic 7
Controlling speed with PWM
This chapter assumes you can use pinMode, digitalWrite, and analogWrite, and that you know the H-bridge direction states from the earlier chapters. You should also know Ohm's law and that a motor's speed rises with the voltage across it. Here you will turn that last fact into code: how a digital pin sets motor speed, what the duty cycle means electrically, and where the simple model breaks down.
Why not just lower the voltage?
A brushed DC motor turns faster when you give it more voltage. An Arduino pin can only output fully on or fully off, so it cannot produce 3.7 V from a 9 V supply. A linear regulator could, but it burns the difference as heat. At a 2 A load, dropping 5 V costs 10 W in the regulator.
Pulse-width modulation (PWM) avoids this. PWM switches the driver fully on and fully off many times per second. The fraction of each cycle spent on is the duty cycle. A transistor that is fully on or fully off dissipates little power, so the driver stays efficient.
The averaging model
The motor winding is an inductor, and the rotor has mechanical inertia. Both smooth the pulses, so the motor responds to the average voltage:
Vavg = duty × Vmotor
Here V_motor is the voltage the driver actually delivers while on, not the supply voltage. With 9 V delivered and a 50% duty cycle, the motor sees about 4.5 V on average.
analogWrite(pin, value) takes 0 to 255. The duty cycle is value / 255, so 128 is about 50%. A value of 0 holds the pin low and 255 holds it high, with no switching at either extreme.
Where to apply the PWM
On a driver with separate direction and enable inputs, such as the L298N or L293D, the simplest scheme is to hold IN1 and IN2 fixed and PWM the enable pin. This is the scheme used in the code below.
What the motor does during the off part of each cycle depends on the scheme you pick.
| Scheme | During PWM off-time | Effect |
|---|---|---|
| PWM on EN, IN1/IN2 fixed | Outputs disabled (coast) | Current recirculates through body diodes. Decay is fast, so the motor responds more weakly at low duty. |
| PWM on the active input, other input low, EN high | Both outputs low (brake) | Current recirculates through the low-side path. Decay is slow, and torque at low duty is generally smoother. |
The first is easier to wire. The second often gives better low-speed behavior but needs a PWM-capable pin for each direction. The previous chapter covered brake and coast. The point to remember here is that the off-time state changes how the motor feels at low duty.
Signed speed in code
The sketch below wraps direction and speed in one function. It also handles the dead zone, which the next section explains.
const uint8_t IN1 = 7;
const uint8_t IN2 = 8;
const uint8_t EN = 9; // must be a PWM-capable pin
// Smallest PWM value that reliably starts YOUR motor under YOUR load.
// Measure it; 60 is only a placeholder.
const int MIN_PWM = 60;
void setup() {
Serial.begin(9600);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(EN, OUTPUT);
}
// percent: -100 (full reverse) to 100 (full forward), 0 = stopped
void setMotorPercent(int percent) {
percent = constrain(percent, -100, 100);
if (percent > 0) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
} else if (percent < 0) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
} else {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
int pwm = 0;
if (percent != 0) {
pwm = map(abs(percent), 1, 100, MIN_PWM, 255);
}
analogWrite(EN, pwm);
}
void loop() {
for (int p = 0; p <= 100; p += 10) {
setMotorPercent(p);
Serial.print("percent=");
Serial.println(p);
delay(1000);
}
setMotorPercent(0);
delay(2000);
}The map call spreads 1 to 100 percent over MIN_PWM to 255. Without it, the bottom part of the range would do nothing.
The dead zone and stiction
Speed is roughly proportional to average voltage, but only above a threshold. A stopped motor needs enough torque to overcome friction in the brushes and bearings, called stiction. It also needs enough torque to move its load. Below a certain duty cycle the motor hums or twitches and does not turn.
Once the motor is spinning, friction drops, so it can keep turning at a duty cycle lower than the one needed to start it. This is why the start threshold and the stall threshold differ.
To find MIN_PWM, raise the duty slowly from zero with the motor loaded as it will be in use. Note the value where it reliably starts. Add a small margin, since a battery that sags will raise the threshold. Because the threshold depends on load and supply voltage, a value measured on the bench may be wrong in the finished robot.
For a heavy load, apply a short "kick" of full power for 20 to 50 ms, then drop to the requested duty. This gets the rotor moving without forcing the whole low range to be unusable.
Supply voltage and driver drop
The model uses the voltage the driver delivers, and that is lower than the supply. Bipolar drivers such as the L298N drop roughly 2 V or more across their output transistors. Modern MOSFET drivers drop far less. On a 12 V supply with a bipolar driver, the motor sees about 10 V at 100% duty. At 50% the average is about 5 V, not 6 V.
Two consequences follow:
- With a 6 V motor on a 6 V supply and a bipolar driver, full duty gives well under rated speed. This is a supply problem, and no code change fixes it.
- Open-loop speed (no sensor feedback) changes with supply voltage and load. The same PWM value gives a different speed as the battery drains or the motor climbs a slope. For constant speed you need feedback from an encoder, which is outside this chapter.
Ripple current and frequency
The motor current is not constant. It rises during on-time and falls during off-time, and the winding inductance sets how fast. If the PWM period is long compared with the winding's electrical time constant, the current ripples heavily. The ripple causes audible buzz and heats the winding without adding useful torque.
On an Uno or Nano (ATmega328P), analogWrite runs at about 490 Hz on pins 3, 9, 10, and 11, and about 980 Hz on pins 5 and 6. Those frequencies sit in the audible range, which is why motors often whine. Raising the frequency can reduce the whine, but it increases switching losses in the driver. Some drivers also cap their switching rate, so check the datasheet before changing timers. The PWM frequency chapter covers this in detail.
Common errors
- Motor only runs at full speed. The enable pin is not PWM-capable, or the EN jumper on the module is still fitted. Many L298N modules ship with a jumper that ties EN high, which overrides your PWM. Remove the jumper and connect the pin.
- Motor hums but does not turn at low values. The duty is inside the dead zone. Raise MIN_PWM or add a start kick.
- Speed barely changes between 200 and 255. The driver drop and the motor's top speed compress the upper range. This is normal. Check that the supply is high enough for the motor's rating.
- Arduino resets when the motor speeds up. The supply sags under the motor's current. Power and grounding were covered earlier, and the troubleshooting chapter returns to it. The duty cycle is a symptom of the load and not the cause.
- Speed is not linear in the PWM value. Friction, load, and driver drop make it a curve. Calibrate by measuring if you need a particular speed.
Summary of the working model
- The duty cycle sets the fraction of time the driver is on.
- The winding and rotor average the pulses, so speed follows average voltage.
- Average voltage is the duty times the voltage the driver delivers, not the nominal supply.
- Below a load-dependent threshold the motor does not start.
- Off-time state (coast or brake) changes low-speed behavior.
Exercise
A bipolar H-bridge driver is powered from a 12 V supply and drops about 2 V in total across its on-state transistors. You call analogWrite(EN, 128) with the direction pins fixed. Roughly what average voltage does the motor receive?
Show answer
The driver delivers about 12 − 2 = 10 V while on. The duty cycle is 128 / 255, about 50%, so the average is about 0.5 × 10 V = 5 V.
Exercise
A motor spins steadily at analogWrite(EN, 70), but when you start from rest with the same value it only hums. Explain why, and give two ways to fix it in code.
Show answer
Stiction (static friction in the brushes and bearings) needs more torque to overcome than rolling friction does, so the start threshold is higher than the level needed to keep running. Fixes: set a minimum PWM value above the start threshold and map the speed range onto it, or apply a short full-power kick of about 20 to 50 ms and then drop to the requested duty.