PWM waveform
Illustrative waveform only. Real PWM frequency and polarity depend on the controller and driver configuration.
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.
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.
The encoder is attached to the motor or driven mechanism. Its signal is measurement feedback, not motor power.
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.
Illustrative waveform only. Real PWM frequency and polarity depend on the controller and driver configuration.
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.
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.
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 leg | Right leg | Typical result |
|---|---|---|
| High-side ON | Low-side ON | Drive current in one direction |
| Low-side ON | High-side ON | Drive current in the opposite direction |
| Both motor terminals high or both low | Same potential at both terminals | Dynamic braking on many drivers |
| All switches off | Motor terminals released on many drivers | Coast, 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.
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.
The phase order A-before-B or B-before-A indicates direction. Actual decoding depends on edge/counting method.
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.
Apply a command and assume the motor responds as expected. Simple, but speed can change with load, battery voltage, friction and temperature.
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.
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
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
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.
Change the disturbance and controller correction to see how much speed error remains in this deliberately simplified static model.
Conceptual arithmetic only: residual = disturbance × (1 − correction effectiveness). This is not a dynamic motor, PID or stability simulation.
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.
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.
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.
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.