EAZYLife STEM LAB · MODULE 19

Digital Control, Motor Control and Feedback Systems

Move beyond simply powering a motor. Learn how drivers switch motor current, how PWM changes average drive, how encoders measure motion, and how feedback control corrects speed errors under changing loads.

Free open lesson Motor drivers Feedback control
DRIVE · MEASURE · CORRECT
01 · FROM GPIO TO MOTOR

A microcontroller pin is not a motor driver

A motor is an electromagnetic load. It can draw a large starting or stall current, generate electrical noise, and produce a voltage transient when its current is interrupted. A microcontroller pin is designed for logic signals, not for supplying motor power. Use a suitable driver stage and a motor supply selected for the actual motor.

Typical motor-control system

ControllerPWM · directionMotor driverH-bridgeDC motortorque · speedLoadwheel / shaftlogicmotor powerencoder pulses / speed feedbackMotor supplyThe controller provides commands; the driver switches energy from the motor supply.

The encoder is attached to the motor or driven mechanism. Its signal is measurement feedback, not motor power.

02 · PWM AND MOTOR SPEED

PWM controls average drive, not a guaranteed RPM

Pulse-width modulation rapidly switches a driver on and off. Duty cycle is the fraction of each period spent in the active state. A higher duty cycle often increases average motor voltage and speed, but the relationship is not linear or fixed. Load torque, supply voltage, winding resistance, friction, driver losses and motor characteristics all matter.

PWM waveform

ONOFFOne PWM periodDuty cycle = ON time ÷ period

Illustrative waveform only. Real PWM frequency and polarity depend on the controller and driver configuration.

Duty-cycle calculator

Duty cycle50.2%
Ideal average of a 6 V switched supply3.01 V

This is an ideal arithmetic average, not a prediction of motor terminal waveform, current, torque or RPM. H-bridge voltage drops and switching behaviour are omitted.

03 · H-BRIDGE DIRECTION AND BRAKING

Reverse the current to reverse the motor

An H-bridge has four controlled switching paths arranged around a motor. Activating one diagonal pair drives current in one direction; activating the opposite pair reverses it. Driver ICs integrate switching devices and often provide interlocks, current protection or thermal shutdown, but the exact behaviour is device-specific.

Conceptual H-bridge

+VMOTORGNDQ1Q2Q3Q4DC MOTORM1 · M2High sideLow sideHigh sideLow side

Functional topology, not a transistor-level build schematic. Never turn on both switches in the same bridge leg: that creates a direct supply short called shoot-through.

Left legRight legTypical result
High-side ONLow-side ONDrive current in one direction
Low-side ONHigh-side ONDrive current in the opposite direction
Both motor terminals high or both lowSame potential at both terminalsDynamic braking on many drivers
All switches offMotor terminals released on many driversCoast, subject to driver design

These are conceptual states. Some integrated drivers use different input truth tables, decay modes and enable behaviour. Read the exact driver's truth table. Direction changes should include suitable deceleration/dead time where required, rather than abruptly reversing a spinning motor.

04 · ENCODERS AND SPEED MEASUREMENT

Measure motion instead of guessing it

An encoder produces signals related to shaft movement. A single-channel pulse output can estimate speed; a quadrature encoder uses two phase-shifted channels, commonly called A and B, to determine direction as well as movement. Resolution must be interpreted using the manufacturer's definition: pulses per motor-shaft revolution, counts per revolution, and gearbox output-shaft counts are not interchangeable.

Quadrature signals

ABB changes a quarter-cycle after ATime →

The phase order A-before-B or B-before-A indicates direction. Actual decoding depends on edge/counting method.

Speed calculation

For a pulse counter measured over a known interval:

RPM = pulses × 60,000 ÷ (PPR × intervalms)

Use the pulse count and PPR for the same shaft. If the encoder is on the motor shaft, account for gearbox ratio when calculating output-shaft speed.

For low pulse rates, measure the time between edges or use a longer observation window to reduce quantisation error. Filter noise without discarding genuine pulses.

05 · OPEN-LOOP AND CLOSED-LOOP CONTROL

Feedback corrects the error caused by real conditions

Open-loop command

CommandPWM valueDrivermotor voltageMotor + loadactual speed

Apply a command and assume the motor responds as expected. Simple, but speed can change with load, battery voltage, friction and temperature.

Closed-loop speed control

TargetRPMΣPI / PIDcontrollerDriverPWMMotor+ loadEncodermeasured RPM

The controller compares target and measured speed. The difference is the error. Feedback allows correction when the load or supply changes, provided the sensor and controller are designed correctly.

06 · PI AND PID FUNDAMENTALS

Three terms, three different jobs

Proportional (P)

Responds to the present error. A larger proportional gain generally produces a stronger correction, but too much can cause oscillation or instability.

P = Kp × error

Integral (I)

Accumulates error over time. It can remove persistent steady-state error, but excessive integral action can cause overshoot and windup when the output saturates.

I = Ki × ∫ error dt

Derivative (D)

Responds to the rate of change of error. It can add damping, but amplifies measurement noise and is often filtered or omitted in simple speed loops.

D = Kd × d(error)/dt

A PI controller is often a useful starting point for motor speed regulation. Tune on a safe, unloaded or lightly loaded test rig first. Use output limits and anti-windup, filter noisy measurements appropriately, and document sample time and units. A gain set from one motor, gearbox, encoder, supply and load should not be copied blindly to another system.

Interactive feedback thought experiment

Change the disturbance and controller correction to see how much speed error remains in this deliberately simplified static model.

Open-loop speed loss25%
Illustrative closed-loop residual loss5%

Conceptual arithmetic only: residual = disturbance × (1 − correction effectiveness). This is not a dynamic motor, PID or stability simulation.

07 · PRACTICAL BUILD

Control a small encoder-equipped DC gearmotor

Build a low-voltage speed-control test rig. Start with open-loop PWM, confirm encoder pulses, then add a measured-speed controller. Keep the wheel or output shaft clear during tests.

Functional wiring overview

Arduino UnoD5 · PWMD7 · AIN1D8 · AIN2D4 · STBYD2 · Encoder A5V · logic / encoder*TB6612FNGPWMA · AIN1 · AIN2STBY · VCC · GNDVM · AO1 · AO2DC gearmotorwith encoderSeparate motor supplywithin motor/driver ratingsEncoder A → D2; encoder supply per module datasheet*Only if encoder module output and supply are compatible with the Uno input voltage.

Conceptual connection map. Confirm the exact breakout-board pin labels, motor supply range, encoder voltage and logic compatibility before wiring. All grounds must share a reference unless the design is intentionally isolated.

Components

  • Arduino Uno-compatible 5 V board.
  • TB6612FNG-based motor driver breakout with documented pinout.
  • Small extra-low-voltage brushed DC gearmotor with encoder.
  • Motor supply matched to the motor and driver, with current limiting.
  • USB or regulated logic supply for the controller.
  • Wires, common ground connection and optional local supply bypass capacitor per driver datasheet.

Before powering up

  1. Check motor rated voltage and stall current from its datasheet or a safe current-limited measurement.
  2. Check driver continuous and peak current, thermal limits and supply range. Do not size from peak current alone.
  3. Verify encoder output type and voltage. Use level shifting or pull-ups as required.
  4. Keep the motor mechanically unloaded or the wheel lifted.
  5. Check for shorts and confirm the driver standby state before enabling the motor.

Connection sequence

  1. Connect Arduino D5 to PWMA, D7 to AIN1, D8 to AIN2 and D4 to STBY.
  2. Connect driver VCC to the compatible logic supply and driver VM to the separate motor supply.
  3. Connect driver GND, Arduino GND and motor-supply negative together.
  4. Connect AO1 and AO2 to the two motor terminals. Swap them only if you need to reverse the chosen forward direction.
  5. Connect encoder channel A to D2. Power the encoder only as specified by its datasheet; connect its ground to the common reference.
  6. With power off, inspect wiring and ensure the shaft can rotate freely. Start with a low PWM command.

Arduino sketch: measure speed and apply a basic PI correction

This example assumes one encoder pulse channel, a known pulse count per motor output-shaft revolution, and a compatible 5 V logic-level encoder output. Set PULSES_PER_OUTPUT_REV from the encoder/gearbox documentation and confirm whether the chosen interrupt edge matches that definition.

#define PWM_PIN 5
#define IN1_PIN 7
#define IN2_PIN 8
#define STBY_PIN 4
#define ENCODER_PIN 2

const float PULSES_PER_OUTPUT_REV = 20.0; // CHANGE to your measured/documented value
const float TARGET_RPM = 80.0;
const unsigned long SAMPLE_MS = 100;

volatile unsigned long pulseCount = 0;
unsigned long lastSample = 0;
float integral = 0.0;
float measuredRPM = 0.0;
int pwmCommand = 0;

// Begin with conservative gains; tune for this exact motor and load.
const float KP = 1.2;
const float KI = 0.8; // integral gain per second

void encoderPulse() {
  pulseCount++;
}

void setup() {
  pinMode(PWM_PIN, OUTPUT);
  pinMode(IN1_PIN, OUTPUT);
  pinMode(IN2_PIN, OUTPUT);
  pinMode(STBY_PIN, OUTPUT);
  pinMode(ENCODER_PIN, INPUT_PULLUP);

  digitalWrite(STBY_PIN, LOW); // keep driver disabled during setup
  digitalWrite(IN1_PIN, HIGH);
  digitalWrite(IN2_PIN, LOW);  // forward direction
  attachInterrupt(digitalPinToInterrupt(ENCODER_PIN), encoderPulse, RISING);
  Serial.begin(115200);

  digitalWrite(STBY_PIN, HIGH);
  lastSample = millis();
}

void loop() {
  unsigned long now = millis();
  unsigned long elapsed = now - lastSample;

  if (elapsed >= SAMPLE_MS) {
    lastSample = now;

    noInterrupts();
    unsigned long pulses = pulseCount;
    pulseCount = 0;
    interrupts();

    float dt = elapsed / 1000.0;
    measuredRPM = (pulses * 60.0) /
                  (PULSES_PER_OUTPUT_REV * dt);

    float error = TARGET_RPM - measuredRPM;
    integral += error * dt;

    float output = KP * error + KI * integral;
    output = constrain(output, 0.0, 255.0);

    // Basic anti-windup: stop integrating farther into saturation.
    if ((output >= 255.0 && error > 0) ||
        (output <= 0.0 && error < 0)) {
      integral -= error * dt;
    }

    pwmCommand = (int)output;
    analogWrite(PWM_PIN, pwmCommand);

    Serial.print("Target RPM: ");
    Serial.print(TARGET_RPM);
    Serial.print("  Measured RPM: ");
    Serial.print(measuredRPM);
    Serial.print("  PWM: ");
    Serial.println(pwmCommand);
  }
}

Teaching example, not production firmware. It is a basic fixed-period PI loop with one pulse channel, no direction decoding, no robust encoder fault detection, no acceleration ramp, and only simple anti-windup. Low pulse counts produce coarse speed estimates. Confirm the motor is stopped before changing wiring or gains.

Observe, measure and improve

  1. Run the motor at a low fixed PWM command. Record the measured RPM and supply voltage.
  2. Apply a small, safe mechanical load without touching moving parts. Compare speed before and after.
  3. Enable the PI sketch. Record target RPM, measured RPM and PWM command at regular intervals.
  4. Compare steady-state error with open-loop operation.
  5. Change one gain at a time. Record settling, overshoot, oscillation and response to a load change.
  6. Repeat with a different target speed. Do not increase current or mechanical load beyond the motor, driver or supply ratings.
08 · SELECTION, TROUBLESHOOTING AND SAFETY

Control quality begins with correct hardware

Driver and motor selection

  • Motor rated voltage and expected operating current.
  • Stall current, startup current and load torque.
  • Driver continuous current at the actual PCB thermal conditions.
  • Peak-current duration, thermal shutdown and current-limit behaviour.
  • Supply transient handling, decoupling and wiring resistance.
  • PWM frequency, switching losses and audible noise.
  • Encoder resolution, maximum speed and output voltage.

Common faults

  • Motor does not move: check STBY/enable, VM, common ground, direction inputs and motor wiring.
  • Controller resets: motor supply sag or noise may be coupling into logic power; improve supply separation, wiring and decoupling.
  • Speed reading is zero: check encoder power, output type, pull-up, interrupt-capable pin and signal polarity.
  • RPM is unstable: inspect encoder noise, loose couplings, low pulse count and sample interval.
  • Motor overheats: reduce load and investigate stall current, driver losses, gearing and duty cycle.
  • Control oscillates: reduce excessive gain, verify units and sample time, and inspect measurement delay/noise.

Safety boundary

  • Use only extra-low-voltage, current-limited supplies for this lesson.
  • Never connect a motor directly to a microcontroller GPIO pin.
  • Keep fingers, clothing, wires and loose objects away from rotating shafts, gears and wheels.
  • Secure the motor and lift wheels clear of the bench during initial tests.
  • Do not stall or deliberately short a motor or driver output.
  • Check exact datasheets for voltage, current, logic thresholds, thermal limits and protection requirements.
  • Do not treat this educational PI sketch as suitable for a vehicle, lift, medical device, industrial machine or safety-critical actuator.

1. Why should a motor not be powered directly from a GPIO pin?

2. What does an encoder provide?

3. What is the key difference between open-loop and closed-loop speed control?

4. What can excessive integral action cause?

KEEP LEARNING · GO FURTHER

Free to learn. More support when you need it.

Explore these open lessons at your own pace. For personalised explanations, project-specific troubleshooting, guided practical training or masterclasses, EazyLife offers paid support tailored to your learning goals.

Free or sponsored lesson referrals may be available through active programmes; they are not guaranteed.

Enquire about guidance