5  DC Motors

In 60 Seconds

DC motors convert electrical energy into continuous rotational motion and are controlled using PWM for speed and H-bridge circuits for direction. They are the most common motor type in IoT applications like fans, pumps, and wheels, and can be paired with PID controllers and encoders for precise speed regulation.

Key Concepts
  • DC Motor Operation: A DC motor converts electrical energy to rotational mechanical energy through electromagnetic interaction between current-carrying coils and a permanent magnet stator; speed is proportional to voltage, torque is proportional to current
  • PWM Speed Control: Pulse Width Modulation varies motor speed by switching the supply voltage on and off rapidly; duty cycle (0-100%) controls average voltage and thus average speed; frequency should be 20 kHz+ to avoid audible noise from motor windings
  • H-Bridge: A circuit of four switches (transistors/MOSFETs) arranged in an H configuration allowing the motor to be driven in both directions by reversing current flow; integrated H-bridge ICs (L298N, TB6612FNG, DRV8833) provide both direction control and PWM speed control
  • Back-EMF (Counter-EMF): Voltage generated by a spinning motor acting as a generator in reverse; must be suppressed with flyback diodes or brake modes to protect driver circuits from voltage spikes when motor current is switched off
  • Stall Current: The current drawn when the motor shaft is mechanically prevented from rotating; 5-10x the normal running current; driver circuits and power supplies must be rated for stall current to prevent burnout during startup or obstruction
  • Motor Encoder: A position/speed feedback device attached to the motor shaft; optical encoders use slotted discs and IR sensors; magnetic encoders use Hall sensors; provides closed-loop control enabling accurate position and speed regulation
  • Gear Reduction: Combining a motor with a gearbox reduces speed while multiplying torque by the gear ratio; a 100:1 gearbox on a motor spinning at 1000 RPM produces 10 RPM output with 100x the torque; most practical DC motor applications require geared motors
  • Motor Driver Current Rating: The continuous and peak current ratings of the driver IC must exceed the motor’s running and stall current respectively; operating a driver at 100% of its rated current without thermal management causes overheating and eventual failure

Learning Objectives

After completing this chapter, you will be able to:

  • Explain DC motor operating principles and torque-speed characteristics
  • Regulate DC motor speed using PWM (Pulse Width Modulation) duty cycle adjustments
  • Implement bidirectional control using H-bridge circuits
  • Interface DC motors with ESP32 using L298N and TB6612 drivers
  • Implement PID control for precise speed regulation with encoder feedback
  • Compare brushed and brushless DC (BLDC) motor control strategies

A DC motor is like a spinning top powered by a battery – it converts electrical energy into rotational motion. When you adjust how much power you give it (using a technique called PWM, which is like flickering a light switch very fast), the motor spins faster or slower. You will find DC motors in everyday things like fans, toy cars, and water pumps.

5.1 DC Motor Fundamentals

DC motors provide continuous rotational motion, controlled by voltage and PWM for speed regulation.

Characteristics:

  • Simple speed control via PWM
  • Direction control via H-bridge
  • High speed, low precision
  • Requires motor driver for high current
How It Works: H-Bridge Motor Control

Think of an H-bridge like a railway switch that can reverse a train’s direction. A DC motor spins one way when current flows left-to-right, and the opposite way when current flows right-to-left.

The H-Bridge Layout: Four switches (transistors) arranged in an “H” shape around the motor. By activating diagonal pairs, you control direction:

  1. Forward: Close switches top-left + bottom-right → current flows left-to-right through motor → forward rotation
  2. Reverse: Close switches top-right + bottom-left → current flows right-to-left → reverse rotation
  3. Brake: Close both bottom switches → motor terminals short to ground → motor stops quickly
  4. Coast: Open all switches → motor freewheels to a stop

Why you need it: Your microcontroller can’t directly reverse polarity on a motor. The H-bridge does this electronically without physically swapping wires. Combined with PWM on the enable pin, you get full speed + direction control from just 3 GPIO pins.

H-bridge circuit diagram showing four transistors (Q1-Q4) arranged around a DC motor, with control signals for forward, reverse, brake, and coast operation modes
Figure 5.1: H-Bridge Motor Driver: Bidirectional DC Motor Control with PWM Speed

5.2 PWM Speed Control

PWM (Pulse Width Modulation) is the standard method for controlling DC motor speed:

  • Duty cycle = Percentage of time the signal is HIGH (ON)
  • Frequency = How many times per second the signal repeats (typically 500Hz-20kHz for motors)
  • Average voltage = Supply voltage x Duty cycle (e.g., 12V x 0.75 = 9V)

Why use PWM? Digital microcontrollers can’t produce true analog voltages. Instead, they rapidly switch between 0V and 5V. A motor responds to the average voltage over time, creating smooth control without complex analog circuits.

A 75% PWM duty cycle on a 12V motor delivers \(V_{avg} = 0.75 \times 12 = 9\) V average. If the motor draws 400mA at this speed, power is \(P = V \times I = 9 \times 0.4 = 3.6\) W. Compare this to a linear voltage regulator dropping 12V to 9V: the regulator would dissipate \((12-9) \times 0.4 = 1.2\) W as heat (25% wasted), while the PWM MOSFET switch wastes only \(\approx 0.1\) W in switching losses (<3%). Over 8 hours of operation, PWM saves \((1.2 - 0.1) \times 8 = 8.8\) Wh compared to linear control.

Interactive PWM Efficiency Calculator:

PWM waveform diagrams showing 25%, 50%, and 75% duty cycles with corresponding average voltages (3V, 6V, 9V) and motor speeds
Figure 5.2: PWM Duty Cycle Waveforms: Speed and Brightness Control at 1kHz

5.2.1 PWM Frequency Selection

Tradeoff: PWM Frequency Selection for Motor Control

Option A: Low PWM frequency (1 kHz): Minimal switching losses (<1% power loss), audible motor whine at 1kHz, coarse current ripple causing motor heating, suitable for high-inertia loads (fans, pumps), driver efficiency 95-98%

Option B: High PWM frequency (20 kHz): Switching losses increase to 3-5%, inaudible operation (above human hearing), smooth current with reduced ripple/heating, required for precision positioning (servos, gimbals), driver efficiency 90-95%

Decision Factors: For consumer products (smart blinds, HVAC dampers), use 20kHz to eliminate audible noise complaints. For industrial pumps where noise is acceptable and efficiency matters, use 1-5kHz. Stepper motors typically use 1-2kHz to maintain torque at steps.

Motor Driver Selection Decision Framework

Choosing the wrong motor driver is the most common hardware mistake in student IoT projects. Use this 3-step process:

Step 1: Determine motor current requirements

Motor Type Typical Current Stall Current Minimum Driver Rating
Small hobby motor (3-6V) 100-300 mA 500-800 mA 1A per channel
N20 gear motor (6-12V) 200-500 mA 1-2 A 2A per channel
775 motor (12-24V) 1-3 A 5-10 A 15A per channel
Windshield wiper motor (12V) 3-8 A 15-25 A 30A per channel

Step 2: Match driver to current and features needed

Driver Current Rating Voltage Cost Best For
L293D 600 mA (1.2A peak) 4.5-36V $1.50 Small hobby motors only
L298N 2A per channel 5-35V $2.50 N20 gear motors, educational projects
TB6612FNG 1.2A (3.2A peak) 2.5-13.5V $3.00 Efficient small motors, battery projects
BTS7960 43A per channel 5.5-27V $8.00 775 motors, high-current applications
DRV8871 3.6A continuous 6.5-45V $4.50 Single motor, industrial grade

Step 3: Check thermal limits

The L298N has a total voltage drop of 2-4V across its internal Darlington transistors (both high-side and low-side combined). At 2A, this dissipates 4-8W of heat. The TB6612FNG uses MOSFETs with much lower resistance and has only ~0.5V total drop, dissipating 1W at the same current.

Worked example: Smart pet feeder with 12V N20 gear motor (400 mA continuous, 1.5A stall)

  • L298N: Adequate current (2A > 1.5A stall), but has ~2V total drop, wasting 2V × 0.4A = 0.8W as heat. Motor sees 10V instead of 12V (17% voltage loss). Cost: $2.50.
  • TB6612FNG: Current rating marginal (1.2A continuous vs 1.5A stall). Risk of thermal shutdown during jam. Not suitable.
  • DRV8871: 3.6A handles stall easily. Only ~0.3V total drop. Motor sees 11.7V. Cost: $4.50. Best choice.

Common mistake: Using an L298N with a 6V rated motor and 7.4V LiPo battery, expecting full motor performance. The L298N’s ~2V total drop means the motor actually gets 5.4V (27% below its 7.4V supply). The TB6612FNG would deliver 6.9V (only 7% loss).

5.3 L298N Motor Driver Implementation

The L298N is a popular dual H-bridge driver capable of controlling two DC motors or one stepper motor. This example demonstrates basic speed and direction control, showing how PWM duty cycle maps to motor speed.

// L298N H-Bridge Motor Driver — ESP32
#define MOTOR_IN1 26
#define MOTOR_IN2 27
#define MOTOR_EN 14  // PWM pin

const int pwmChannel = 0;

void setup() {
  Serial.begin(115200);
  pinMode(MOTOR_IN1, OUTPUT);
  pinMode(MOTOR_IN2, OUTPUT);
  ledcSetup(pwmChannel, 5000, 8);  // 5 kHz, 8-bit (0-255)
  ledcAttachPin(MOTOR_EN, pwmChannel);
}

void loop() {
  motorControl(150, true);   // Forward at ~60% speed
  delay(2000);
  motorControl(0, true);     // Stop
  delay(1000);
  motorControl(191, false);  // Backward at ~75% speed
  delay(2000);

  // Gradual acceleration and deceleration
  for (int speed = 0; speed <= 255; speed += 5) {
    motorControl(speed, true);
    delay(50);
  }
  for (int speed = 255; speed >= 0; speed -= 5) {
    motorControl(speed, true);
    delay(50);
  }
  delay(1000);
}

void motorControl(int speed, bool forward) {
  speed = constrain(speed, 0, 255);
  // Set direction via IN1/IN2, then set speed via PWM
  digitalWrite(MOTOR_IN1, forward ? HIGH : LOW);
  digitalWrite(MOTOR_IN2, forward ? LOW : HIGH);
  ledcWrite(pwmChannel, speed);
}

void motorBrake() {
  // Short brake: both inputs HIGH shorts motor terminals
  digitalWrite(MOTOR_IN1, HIGH);
  digitalWrite(MOTOR_IN2, HIGH);
  ledcWrite(pwmChannel, 255);
}

void motorCoast() {
  // Coast: both inputs LOW, motor spins freely to stop
  digitalWrite(MOTOR_IN1, LOW);
  digitalWrite(MOTOR_IN2, LOW);
  ledcWrite(pwmChannel, 0);
}

5.4 PID Motor Speed Control

For precise speed control, use a PID (Proportional-Integral-Derivative) controller with encoder feedback. This example builds on the L298N motor driver code shown earlier.

#include <PID_v1.h>

// Uses motorControl() from the L298N example above
#define ENCODER_A 32
#define ENCODER_B 33

volatile long encoderCount = 0;
unsigned long lastTime = 0;

// PID variables — tune Kp/Ki/Kd for your motor
double setpoint = 100.0, input, output;  // Target: 100 RPM
PID motorPID(&input, &output, &setpoint, 2.0, 5.0, 1.0, DIRECT);

void setup() {
  Serial.begin(115200);
  // Motor setup (same as L298N example above)
  pinMode(ENCODER_A, INPUT_PULLUP);
  pinMode(ENCODER_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENCODER_A), encoderISR, RISING);
  motorPID.SetMode(AUTOMATIC);
  motorPID.SetOutputLimits(0, 255);
  motorPID.SetSampleTime(100);  // Compute every 100ms
}

void loop() {
  unsigned long now = millis();
  if (now - lastTime >= 100) {
    // RPM = (pulses * 60s * 1000ms) / (PPR * elapsed_ms)
    float currentRPM = (encoderCount * 60000.0) / (20.0 * (now - lastTime));
    encoderCount = 0;
    lastTime = now;

    input = currentRPM;
    motorPID.Compute();
    motorControl((int)output, true);  // Apply PID output

    Serial.printf("Target: %.0f RPM | Current: %.1f RPM | PWM: %.0f\n",
                  setpoint, currentRPM, output);
  }
}

void encoderISR() {
  encoderCount += (digitalRead(ENCODER_B) == HIGH) ? 1 : -1;
}

Scenario: You want a cooling fan that runs at half speed when your ESP32 detects 25°C, and full speed above 30°C.

Setup: TT motor fan (3-6V), powered from 5V through an L298N driver.

Code:

if (temperature < 25) {
  motorControl(0, true);      // Fan OFF
} else if (temperature < 30) {
  motorControl(128, true);    // Half speed (128/255 = 50%)
} else {
  motorControl(255, true);    // Full speed (255/255 = 100%)
}

Why it works: PWM value 128 out of 255 gives 50% duty cycle = average 2.5V delivered to the motor = half speed. The motor sees the average voltage over many rapid on/off cycles.

Scenario: Prevent voltage drops and current spikes by ramping motor speed gradually.

Problem: Instant full-speed startup draws 5-8× running current, causing brownouts on battery systems.

Solution:

void softStart(int targetSpeed, int rampTime) {
  if (targetSpeed <= 0) return;  // Safety check

  int steps = targetSpeed / 5;  // Number of 5-unit steps
  if (steps == 0) steps = 1;    // Ensure at least one step

  for (int speed = 0; speed <= targetSpeed; speed += 5) {
    motorControl(speed, true);
    delay(rampTime / steps);  // Distribute ramp evenly over total time
  }
}

// Usage: ramp to 200/255 speed over 2 seconds
softStart(200, 2000);

What to observe: Ammeter shows gradual current increase. No sudden voltage drops on power rail. ESP32 doesn’t reset from brownout.

Scenario: Maintain precise 100 RPM motor speed despite varying loads (fan blades encountering air resistance).

Components needed: Motor + encoder (generates pulses as shaft rotates) + L298N driver

Approach: PID controller compares actual RPM (from encoder) vs target RPM, continuously adjusts PWM to minimize error.

// Simplified PID loop
error = targetRPM - measuredRPM;
integral += error;
derivative = error - lastError;

pwmOutput = Kp * error + Ki * integral + Kd * derivative;
motorControl(pwmOutput, true);

lastError = error;

Tuning (Ziegler-Nichols method): 1. Set Ki=0, Kd=0. Start with Kp=2 2. Gradually increase Kp until motor speed oscillates consistently (swings back and forth around setpoint) 3. Reduce Kp by 50% (this is Ku, the “ultimate gain”) 4. Add Ki (start with Kp/2) to eliminate steady-state error 5. Add Kd (start with Kp/8) only if oscillations persist

Safety: Test with motor unloaded first. Monitor current to prevent stall damage.

Result: Motor maintains 100 ±2 RPM even as load changes, vs ±20 RPM with open-loop PWM control.

5.5 Worked Examples

Worked Example: PWM Duty Cycle Calculation for DC Motor Speed Control

Scenario: You are designing a smart ceiling fan controller using an ESP32 and a 12V DC motor. The motor runs at 3000 RPM at full voltage and you need 5 discrete speed settings: Off, Low (600 RPM), Medium (1200 RPM), High (1800 RPM), and Max (3000 RPM).

Given:

  • Motor supply voltage: 12V DC
  • Motor no-load speed at 12V: 3000 RPM
  • PWM resolution: 8-bit (0-255)
  • PWM frequency: 5 kHz
  • Assumption: Speed is approximately proportional to average voltage (valid for no-load or light-load conditions)

Steps:

  1. Calculate target duty cycles for each speed:
    • Off: 0% duty cycle (0 RPM)
    • Low: 600/3000 = 20% duty cycle (600 RPM)
    • Medium: 1200/3000 = 40% duty cycle (1200 RPM)
    • High: 1800/3000 = 60% duty cycle (1800 RPM)
    • Max: 3000/3000 = 100% duty cycle (3000 RPM)
  2. Convert duty cycles to 8-bit PWM values (0-255):
    • Off: 0% × 255 = 0
    • Low: 20% × 255 = 51
    • Medium: 40% × 255 = 102
    • High: 60% × 255 = 153
    • Max: 100% × 255 = 255
  3. Account for motor startup threshold: Most DC motors require ~10-15% duty cycle to overcome static friction. Actual Low setting may need 25-30% (64-77) to reliably start from standstill.

Result: PWM values for 5-speed fan controller: 0 (Off), 64 (Low, adjusted), 102 (Medium), 153 (High), 255 (Max).

Interactive Calculator:

Worked Example: DC Motor Sizing for IoT Conveyor Belt

Scenario: You need to select a DC motor for a small package sorting conveyor. The conveyor must move packages weighing up to 2 kg at 0.5 m/s using a 50mm diameter drive roller.

Given:

  • Maximum package mass: 2 kg
  • Conveyor speed: 0.5 m/s
  • Drive roller diameter: 50 mm (radius = 0.025 m)
  • Coefficient of friction (belt/roller): 0.3
  • Safety factor: 1.5
  • Available supply voltage: 24V DC
  • Gear efficiency: 85%

Steps:

  1. Calculate required roller angular velocity:
    • omega = v / r = 0.5 m/s / 0.025 m = 20 rad/s
    • Convert to RPM: 20 rad/s × (60 / (2π)) = 191 RPM at output shaft
  2. Calculate load torque at roller:
    • Force to move package: F = m × g × μ = 2 kg × 9.81 m/s² × 0.3 = 5.89 N
    • Torque at roller: T_load = F × r = 5.89 N × 0.025 m = 0.147 Nm
  3. Apply safety factor:
    • Required torque: T_required = 0.147 Nm × 1.5 = 0.22 Nm (220 mNm)
  4. Calculate motor power requirement:
    • Mechanical power: P_mech = T × ω = 0.22 Nm × 20 rad/s = 4.4 W
    • Account for gear efficiency: P_motor = 4.4 W / 0.85 = 5.2 W minimum
  5. Select motor and gear ratio:
    • Typical 24V DC motor: 6000 RPM no-load, 15 mNm stall torque
    • Required gear ratio: 6000 RPM / 191 RPM = 31:1
    • Torque multiplication: 15 mNm × 31 × 0.85 = 395 mNm (exceeds 220 mNm requirement)

Result: Select a 24V DC motor (6000 RPM, 15 mNm) with 31:1 planetary gearbox.

Interactive Calculator:

5.6 Worked Example: Sizing a Motor for a Smart Valve

Scenario: You are designing an IoT-controlled ball valve for a smart irrigation system. The valve is a 1-inch brass ball valve that requires 90 degree rotation to fully open or close. The system operates on 12V DC from a solar-charged battery and must complete valve actuation within 5 seconds.

Goal: Select and size an appropriate motor and gearbox combination.

Ball valve torque specifications (from valve datasheet):

  • Breakaway torque (unseating): 2.5 Nm (worst case with sediment buildup)
  • Running torque: 0.8 Nm
  • Seating torque: 1.5 Nm (ensures tight seal)

Design margin: Apply 1.5× safety factor: T_required = 2.5 Nm × 1.5 = 3.75 Nm

Angular displacement: 90 degrees = 0.25 revolutions

Required speed: omega_output = 0.25 rev / 5 s = 0.05 rev/s = 3 RPM

Option: DC Gearmotor (JGB37-520 12V)

Parameter JGB37-520 12V Requirement Status
Voltage 12V DC 12V DC Pass
No-load speed 10 RPM 3 RPM Pass (margin)
Rated torque 5 Nm 3.75 Nm Pass
Stall torque 15 Nm - Pass (safety)
No-load current 80 mA - OK
Rated current 400 mA - OK
Gear ratio 1:488 - -
Cost $12 - Budget

Selected: JGB37-520 12V DC gearmotor with L298N driver

Key decisions:

  1. DC gearmotor over stepper: 3x lower cost, 4x lower power consumption
  2. 1:488 gear ratio: Converts high-speed/low-torque to low-speed/high-torque
  3. Limit switch feedback: Prevents motor stall damage
  4. L298N module: Built-in flyback protection

5.7 Interactive Lab: DC Motor Control

Try It Yourself: Control a DC Motor

What you’ll do: Control a DC motor’s speed and direction using an ESP32 and L298N driver.

What you’ll learn:

  • How to wire a DC motor to an H-bridge driver
  • How PWM duty cycle controls motor speed
  • How to reverse motor direction programmatically

Estimated time: 10 minutes

Interactive Challenges:

  1. Variable Speed Challenge: Add code to smoothly ramp up from 0% to 100% speed over 5 seconds
  2. Directional Control Challenge: Make the motor alternate between forward and reverse every 3 seconds
  3. Emergency Stop Challenge: Add a button that immediately stops the motor when pressed

5.8 Brushless DC (BLDC) Motor Control

Brushless DC (BLDC) motors have become the preferred actuator for high-performance IoT applications including drones, robotic arms, electric vehicles, and industrial automation.

5.8.1 Commutation Strategies

Six-Step (Trapezoidal) Commutation:

The simplest control method energizes two phases at a time:

Step Hall Sensors (H1 H2 H3) Active Phases Current Direction
1 1 0 1 A+, B- A to B
2 0 0 1 A+, C- A to C
3 0 1 1 B+, C- B to C
4 0 1 0 B+, A- B to A
5 1 1 0 C+, A- C to A
6 1 0 0 C+, B- C to B

Advantages: Simple implementation, low computational requirements

Disadvantages: Torque ripple (up to 14%), acoustic noise

Sinusoidal Commutation:

Applies continuously varying current to each phase for smoother operation:

  • I_A = I_m sin(θ)
  • I_B = I_m sin(θ - 120°)
  • I_C = I_m sin(θ - 240°)

Field-Oriented Control (FOC):

The most advanced control method for maximum efficiency and smooth operation.

5.8.2 Hardware Implementation

Recommended MCUs for IoT BLDC:

  • Entry level: STM32F103, ESP32 (6-step, basic sinusoidal)
  • Mid-range: STM32G4, ESP32-S3 (sinusoidal, basic FOC)
  • High-performance: STM32H7, TI C2000 (full FOC with observers)

5.9 Knowledge Check

    1. The PWM signal needs time to stabilize
    1. The motor must overcome static friction (stiction) before it begins to rotate
    1. The motor driver has a built-in delay
    1. The ESP32 cannot generate very low duty cycles

Answer: B) The motor must overcome static friction (stiction) before it begins to rotate. DC motors need a minimum voltage to generate enough torque to overcome the static friction of the brushes, bearings, and any mechanical load. Below this threshold, the motor receives power but cannot start spinning. Once running, the motor can operate at lower duty cycles because dynamic friction is less than static friction.

    1. To increase the motor’s maximum speed beyond its rated RPM
    1. To protect the motor from voltage spikes
    1. To allow bidirectional control (forward and reverse) by reversing current flow
    1. To convert AC power to DC power for the motor

Answer: C) To allow bidirectional control (forward and reverse) by reversing current flow. An H-bridge uses four switches (transistors or MOSFETs) arranged in an H-pattern. By activating different diagonal pairs, current flows through the motor in either direction, enabling forward and reverse rotation from a single power supply.

    1. It generates PWM signals to control motor speed
    1. It provides position/speed feedback for closed-loop control
    1. It limits the maximum current to the motor
    1. It converts analog signals to digital for the microcontroller

Answer: B) It provides position/speed feedback for closed-loop control. The encoder counts pulses as the motor shaft rotates, allowing the PID controller to calculate actual RPM. This measured speed is compared to the target setpoint, and the controller adjusts the PWM output to minimize the error, creating a closed-loop feedback system.

Key Takeaway

DC motors provide efficient continuous rotation controlled by PWM duty cycle for speed and H-bridge circuits for direction. For applications requiring precise speed regulation, a PID controller with encoder feedback creates a closed-loop system that automatically compensates for load variations. When selecting PWM frequency, choose 20 kHz for silent operation in consumer products or 1-5 kHz for maximum efficiency in industrial applications.

“Wheeee!” shouted DC Danny the Motor, spinning faster and faster. “Max, make me go even faster!”

Max the Microcontroller laughed. “I can’t just give you full power all at once, Danny! I use something called PWM – I flick your power switch on and off really, really fast. The longer I keep it ON, the faster you spin!”

“That’s like turning a light switch on and off super quickly?” asked Lila the LED.

“Exactly!” said Max. “If I keep it ON half the time, Danny spins at half speed. If I keep it ON 75% of the time, he goes at three-quarter speed. It happens so fast that Danny thinks he’s getting a smooth, steady push!”

“But what if I want to go backwards?” asked Danny.

“That’s where my H-bridge friend comes in!” said Max. “Think of it like a figure-eight track for electricity. By switching which path the electricity takes, you spin in reverse!”

Sammy the Sensor was watching Danny’s speed with his encoder. “I count every little tick as Danny spins. If he slows down because something is hard to push, I tell Max, and Max gives Danny more power. Teamwork!”

Bella the Battery reminded everyone, “Just remember – Danny drinks a LOT of my juice, so use only as much speed as you really need!”

5.10 Concept Relationships

Concept Relates To Connection Type
PWM Speed Control PWM Control Chapter Duty cycle determines average motor voltage
H-Bridge Operation Electronics Fundamentals Four transistors enable bidirectional current flow
PID Control Sensor Feedback Encoder + PID maintains precise speed regulation
Motor Drivers Actuator Safety Flyback diodes prevent inductive voltage spikes

5.11 See Also

Common Pitfalls

A typical small DC motor draws 100-500 mA; GPIO pins on ESP32 and Arduino are rated for 12-40 mA maximum. Directly connecting a motor to a GPIO pin permanently damages the microcontroller’s output driver within seconds. Always use a transistor, MOSFET, or H-bridge driver IC between GPIO and the motor.

When a transistor turns off a DC motor, the motor’s inductance generates a voltage spike (back-EMF) that can reach 10-50 V above the supply rail. Without a flyback diode across the motor terminals (cathode to positive supply), this spike punctures the transistor’s drain-source junction. Always add a fast recovery diode (1N4007 or Schottky) rated for the motor supply voltage.

PWM frequencies below 20 kHz produce audible tones from motor coil vibration (the coils mechanically vibrate at the PWM frequency). Set motor PWM frequency above 20 kHz (beyond human hearing range) to eliminate this noise. ESP32 can generate 20-40 kHz PWM; Arduino hardware timers may need configuration to reach these frequencies.

DC motors draw 3-10x their rated running current for the first few hundred milliseconds after power application. This startup surge can exceed driver IC peak current ratings or cause power supply voltage sag, triggering microcontroller brownout resets. Add current limiting in firmware (ramp PWM from 0 to operating duty cycle over 100-500 ms) to control startup current.

5.12 What’s Next?

Now that you can control DC motor speed and direction, explore related actuator types and supporting topics.

Next Topic Description
Servo Motors Precise angular positioning with PWM pulse-width control
Stepper Motors Open-loop position control with discrete step increments
PWM Control Deeper dive into duty cycle calculations and waveform generation
Actuator Safety Flyback protection, current limiting, and thermal management
Electronics Fundamentals Transistor and MOSFET circuits used in motor drivers