PWM Control with Microcontrollers
1. Definition and Basic Principles of Pulse Width Modulation
Definition and Basic Principles of Pulse Width Modulation
Pulse Width Modulation (PWM) is a technique for encoding analog signal levels into digital pulses by varying the width of the pulse while keeping the frequency constant. The fundamental principle relies on rapidly switching a digital signal between high and low states, where the ratio of the high-state duration (ton) to the total period (T) defines the duty cycle:
For a microcontroller-generated PWM signal with a fixed frequency f = 1/T, the average output voltage Vavg delivered to a load is proportional to the duty cycle:
where Vmax is the logic-level voltage (e.g., 3.3V or 5V). This equivalence holds when the PWM frequency is sufficiently higher than the load's time constant, allowing the load to behave as a low-pass filter.
Time-Domain Characteristics
The temporal resolution of PWM is constrained by the microcontroller's clock frequency and timer/counter hardware. For an n-bit timer, the minimum pulse width increment Δt is:
Higher-resolution timers enable finer control of analog-like outputs, critical for applications like precision motor control or LED dimming. Modern microcontrollers often implement 16-bit timers, providing 65,535 discrete duty cycle steps.
Spectral Analysis
The Fourier series representation of an ideal PWM waveform with duty cycle D reveals harmonic content at integer multiples of the fundamental frequency:
This harmonic spectrum necessitates careful frequency selection to avoid interference with sensitive analog circuits. A common design practice sets the PWM frequency at least 10× higher than the system's bandwidth requirements.
Implementation Variants
- Center-aligned PWM: Pulses are symmetrically distributed around the timer's midpoint, reducing electromagnetic interference (EMI) in power electronics.
- Edge-aligned PWM: Simpler to implement but generates higher harmonic distortion, suitable for non-critical applications.
- Phase-correct PWM: Microcontrollers like AVR and ARM provide hardware support for this mode, which eliminates direction-changing artifacts in motor control.

1.2 Duty Cycle and Frequency: Key Parameters
Defining Duty Cycle
The duty cycle (D) of a PWM signal represents the fraction of time the signal remains in the active (high) state relative to its total period. Mathematically, it is expressed as:
where ton is the active pulse duration and T is the total period of the waveform. For example, a 50% duty cycle implies the signal is high for exactly half the period. In microcontroller applications, this directly translates to proportional control in systems like motor speed regulators or LED dimmers.
Frequency and Its Implications
The frequency (f) of a PWM signal, defined as f = 1/T, determines how rapidly the pulses repeat. Higher frequencies reduce ripple in filtered outputs but may introduce switching losses in power electronics. The choice of frequency depends on the application:
- Low frequencies (1 Hz–1 kHz): Used in slow-response systems like thermal control.
- Medium frequencies (1 kHz–20 kHz): Common in motor control and audio applications.
- High frequencies (>20 kHz): Employed in switched-mode power supplies to minimize audible noise.
Interaction Between Duty Cycle and Frequency
While duty cycle controls the average power delivered, frequency determines the system's dynamic response. For instance, driving a DC motor with a low-frequency PWM (e.g., 100 Hz) at 50% duty cycle may cause noticeable vibration, whereas the same duty cycle at 20 kHz results in smoother operation due to the motor's inductance filtering the pulses.
This relationship highlights how duty cycle scales the effective power output, while frequency affects the harmonic content and switching efficiency.
Practical Considerations in Microcontroller Implementation
Microcontrollers generate PWM signals using timer peripherals configured for specific frequency and resolution. The achievable duty cycle granularity depends on the timer's bit depth. For example, an 8-bit timer offers 256 discrete duty cycle steps (0–100%), while a 16-bit timer provides 65,536 steps. The frequency is constrained by the clock speed and prescaler settings:
where N is the prescaler value and TOP is the timer's maximum count. Trade-offs arise between frequency and resolution—higher frequencies reduce the available duty cycle steps.
Real-World Application: LED Dimming
In LED dimming, a 1 kHz PWM signal with adjustable duty cycle allows precise brightness control. The human eye perceives the average light output due to persistence of vision, while higher frequencies (>200 Hz) eliminate flicker. For instance, a 75% duty cycle at 1 kHz delivers 75% of the LED's maximum luminous intensity.
Harmonic Content and Filtering
The Fourier series of a PWM signal reveals harmonics centered around multiples of the switching frequency. For a signal with duty cycle D and amplitude A, the harmonic amplitudes are given by:
Low-pass filtering attenuates these harmonics, leaving the DC component proportional to D. This principle underpins Class-D audio amplifiers, where PWM encodes analog signals.

1.3 Applications of PWM in Electronics
Motor Control
Pulse-width modulation is extensively used in motor control systems, particularly for driving DC and stepper motors. The average voltage applied to the motor windings is directly proportional to the duty cycle (D) of the PWM signal:
For brushed DC motors, PWM allows precise speed control without the inefficiency of linear voltage regulation. In brushless DC (BLDC) motors, PWM modulates the commutation sequence to control both speed and torque. Field-oriented control (FOC) algorithms often employ space-vector PWM (SVPWM) to minimize harmonic distortion and improve efficiency.
Power Conversion
Switch-mode power supplies (SMPS) rely on PWM to regulate output voltage. Buck, boost, and buck-boost converters use PWM to control the switching frequency (fsw) and duty cycle, achieving high efficiency (typically 85-95%). The output voltage in a buck converter is given by:
For isolated topologies like flyback or forward converters, PWM controls both voltage regulation and transformer core resetting. Advanced techniques like current-mode control improve transient response and stability.
LED Dimming
PWM provides superior LED brightness control compared to analog dimming, maintaining consistent chromaticity across intensity levels. The human eye perceives the time-averaged light output:
High-frequency PWM (>200 Hz) eliminates visible flicker while enabling 16-bit resolution in professional lighting systems. Hybrid approaches combine PWM with analog current reduction for optimal efficiency in battery-powered devices.
Audio Applications
Class D amplifiers use PWM to encode audio signals into high-frequency switching waveforms. The audio signal modulates the PWM duty cycle, which is then reconstructed through an LC filter. Key performance metrics include:
- Total harmonic distortion (THD) < 0.01% in modern designs
- Power efficiency > 90% across most of the output range
- Signal-to-noise ratios exceeding 110 dB
Advanced techniques like feedback error correction and multi-level PWM further improve linearity and reduce electromagnetic interference (EMI).
Precision Actuators
PWM enables nanometer-scale positioning in piezoelectric actuators through charge control. The relationship between applied charge (Q) and displacement (x) is:
where d33 is the piezoelectric coefficient and C is the actuator capacitance. High-resolution PWM (≥ 24-bit) combined with sigma-delta modulation achieves sub-nanometer positioning in atomic force microscopes and adaptive optics systems.
RF Applications
In software-defined radio (SDR), PWM-based direct digital synthesis (DDS) generates programmable RF waveforms. The Nyquist criterion requires:
Modern implementations use bandpass sigma-delta modulation to shift the PWM spectrum to RF frequencies while suppressing baseband quantization noise. This technique enables fully digital transmitters with >60 dB adjacent channel power ratio (ACPR).
2. Hardware PWM vs. Software PWM
2.1 Hardware PWM vs. Software PWM
Fundamental Differences
Pulse-width modulation (PWM) can be generated either through dedicated hardware peripherals or via software-driven timing loops. The choice between hardware and software PWM impacts performance, precision, and resource utilization in embedded systems.
Hardware PWM Characteristics
Hardware PWM is implemented using dedicated timer/counter peripherals in microcontrollers. These peripherals operate independently of the CPU, providing deterministic timing and minimal jitter. A typical hardware PWM block consists of:
- A free-running counter with programmable period
- Compare registers for duty cycle control
- Automatic output toggling logic
- Dead-time generation for power electronics
where fCLK is the system clock frequency, PRESCALER divides the clock input, and PERIOD sets the counter's maximum value. The duty cycle resolution is given by:
Software PWM Implementation
Software PWM uses general-purpose timers and GPIO toggling via interrupts or polling. While flexible, it suffers from:
- CPU overhead proportional to PWM frequency
- Jitter due to interrupt latency and instruction pipeline effects
- Limited maximum frequency (typically <1% of CPU clock)
The minimum achievable pulse width in software PWM is constrained by the ISR latency (tISR) and GPIO toggle time (tGPIO):
Performance Comparison
| Parameter | Hardware PWM | Software PWM |
|---|---|---|
| Maximum Frequency | Up to 1/2 CPU clock | ~1% CPU clock |
| Jitter | <1 clock cycle | 10-100 clock cycles |
| CPU Load | 0% | Scales with frequency |
| Resolution | 16-bit typical | 8-10 bit practical |
Application-Specific Considerations
Hardware PWM is essential for:
- Motor control (requiring precise timing and dead-time management)
- Switch-mode power supplies (where jitter affects regulation)
- High-frequency applications (>100kHz)
Software PWM may suffice for:
- LED dimming at low frequencies
- Prototyping before hardware configuration
- Systems with abundant CPU cycles
Modern Microcontroller Features
Contemporary MCUs often include advanced PWM features that blur the hardware/software distinction:
- DMA-driven PWM updates (reducing CPU intervention)
- Event systems for hardware-triggered changes
- Pattern generators for complex waveforms

Configuring PWM Modules in Common Microcontrollers
PWM Register Configuration in AVR Microcontrollers
AVR microcontrollers, such as the ATmega328P, utilize Timer/Counter modules for PWM generation. The Fast PWM mode is commonly selected by setting the WGM02:0 bits in the TCCRxA and TCCRxB registers. For an 8-bit resolution PWM, the OCR0A or OCR0B registers define the duty cycle. The PWM frequency is determined by the clock prescaler (set via CS02:0 bits) and the timer's top value:
where N is the prescaler value (1, 8, 64, 256, or 1024). Phase-correct PWM mode, selected by WGM02:0 = 1, provides symmetric waveforms but halves the frequency.
STM32 PWM Setup Using HAL Libraries
STM32 microcontrollers leverage hardware timers (e.g., TIM1, TIM2) with advanced PWM capabilities. Configuration involves:
- Initializing the timer peripheral using HAL_TIM_PWM_Init()
- Setting the prescaler (TIMx_PSC) and auto-reload register (TIMx_ARR) for frequency control
- Configuring the capture/compare register (TIMx_CCRx) for duty cycle
- Enabling PWM output channels with HAL_TIM_PWM_Start()
The PWM period TPWM is calculated as:
ESP32 LEDC Peripheral for PWM
The ESP32 employs the LED Control (LEDC) module, which supports up to 16 PWM channels with configurable resolution (1–16 bits). Key configuration steps include:
- Setting resolution via ledc_timer_config_t::duty_resolution
- Defining frequency using ledc_timer_config_t::freq_hz
- Assigning GPIO pins with ledc_channel_config_t::gpio_num
The achievable frequency range depends on the selected resolution and the APB clock frequency (typically 80 MHz):
RP2040 PWM Configuration on Raspberry Pi Pico
The RP2040 microcontroller features eight independent PWM slices, each with two outputs. Configuration involves:
- Setting the wrap value (PWM_CHx_TOP) to determine the period
- Writing the compare register (PWM_CHx_CC) for duty cycle control
- Configuring clock division via PWM_CHx_DIV
The PWM frequency is derived from the system clock (typically 125 MHz):
Dead-Time Insertion in Advanced PWM Modules
High-end microcontrollers (e.g., STM32F4, dsPIC33) support programmable dead-time insertion for H-bridge control. The dead-time generator delays the rising edge of complementary PWM signals to prevent shoot-through. The dead-time duration Tdead is typically configured through a dedicated register (e.g., BDTR in STM32) and scales with the timer clock:
where DTG is the 8-bit dead-time value (0–255) and Tclk is the timer clock period.

2.3 Timer and Counter Setup for PWM Generation
Timer Modes and PWM Configuration
Microcontrollers generate PWM signals using timer peripherals configured in specific modes. The most common modes for PWM generation are Fast PWM and Phase-Correct PWM. Fast PWM provides higher frequency operation but introduces harmonic distortion, while Phase-Correct PWM ensures symmetric pulses, reducing EMI at the cost of reduced maximum frequency.
The duty cycle in Fast PWM mode is determined by the comparison between the timer counter (TCNT) and the output compare register (OCR). When TCNT matches OCR, the output pin toggles, creating the PWM signal. The resolution of the PWM signal depends on the timer's bit-width (e.g., 8-bit, 16-bit). For an 8-bit timer, the duty cycle resolution is 256 discrete steps.
Prescaler and Frequency Control
The PWM frequency is derived from the microcontroller's system clock (CLKsys) divided by a prescaler (N) and the timer's maximum count value (MAX_COUNT). The prescaler allows fine-tuning the PWM frequency without sacrificing resolution.
For example, an 8-bit timer (MAX_COUNT = 255) with a 16 MHz clock and a prescaler of 8 yields:
Timer Registers and Initialization
Configuring a timer for PWM involves setting up several registers:
- TCCRxA/TCCRxB: Control timer behavior (mode, prescaler, compare output).
- OCRxy: Output Compare Register, sets the duty cycle.
- TCNTx: Timer Counter Register, holds the current count value.
For an AVR microcontroller, Fast PWM mode is enabled by setting the WGM bits in TCCRxA and TCCRxB. The COMxy bits configure the output pin behavior (e.g., non-inverting or inverting PWM).
AVR Timer1 Fast PWM Initialization Example
// Configure Timer1 for 10-bit Fast PWM, non-inverting output on OC1A
TCCR1A = (1 << COM1A1) | (1 << WGM11) | (1 << WGM10);
TCCR1B = (1 << WGM12) | (1 << CS10); // No prescaling
OCR1A = 512; // 50% duty cycle for 10-bit resolution
Dead-Time Insertion for H-Bridge Control
In motor control or H-bridge applications, dead-time insertion prevents shoot-through currents. Advanced timers (e.g., STM32's TIM1, AVR's Timer/Counter1) support programmable dead-time generators (DTG) that delay the rising edge of complementary PWM signals.
where DTG is the dead-time register value and TCLK_DTG is the dead-time generator clock period.
Practical Considerations
High-frequency PWM reduces ripple in LC filters but increases switching losses. A trade-off exists between resolution and frequency; doubling the PWM frequency halves the resolution. For precise control, 16-bit timers (e.g., Timer1 in AVR, TIM2 in STM32) are preferred when fine granularity is required.

3. Writing PWM Code in C for AVR and ARM Microcontrollers
PWM Control with Microcontrollers
3.1 Writing PWM Code in C for AVR and ARM Microcontrollers
Pulse-width modulation (PWM) is a fundamental technique for controlling power delivery to loads such as motors, LEDs, and actuators. Microcontrollers like AVR (e.g., ATmega328P) and ARM (e.g., STM32) provide dedicated hardware timers to generate PWM signals with minimal CPU overhead. The implementation differs between architectures due to variations in register configurations and clock management.
AVR Microcontrollers: Timer/Counter Modules
AVR microcontrollers typically feature 8-bit and 16-bit timers with PWM capabilities. For fast PWM mode on Timer0 (8-bit), the duty cycle is set via the OCR0A or OCR0B registers, while the frequency is determined by the prescaler and TOP value (usually 0xFF for 8-bit resolution). The following code configures Timer0 for PWM on OC0A (PD6 on ATmega328P):
#include <avr/io.h>
void PWM_init() {
DDRD |= (1 << PD6); // Set PD6 (OC0A) as output
TCCR0A |= (1 << COM0A1) // Non-inverting mode
| (1 << WGM01) // Fast PWM mode (WGM02:0 = 0b011)
| (1 << WGM00);
TCCR0B |= (1 << CS01); // Prescaler = 8 (clock speed dependent)
}
void set_duty_cycle(uint8_t duty) {
OCR0A = duty; // Duty cycle = (OCR0A + 1) / 256
}
The PWM frequency is calculated as:
where N is the prescaler value (1, 8, 64, 256, or 1024). For a 16MHz clock with N=8, this yields 7.81kHz.
ARM Microcontrollers: Advanced Timer Configurations
ARM Cortex-M microcontrollers (e.g., STM32) offer more flexible PWM generation through advanced timers (TIM1, TIM8) and general-purpose timers (TIM2–TIM5). The STM32 HAL library simplifies setup:
#include "stm32f4xx_hal.h"
TIM_HandleTypeDef htim2;
TIM_OC_InitTypeDef sConfigOC;
void PWM_init() {
htim2.Instance = TIM2;
htim2.Init.Prescaler = 79; // 80MHz/80 = 1MHz
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 999; // 1kHz PWM (1MHz/1000)
HAL_TIM_PWM_Init(&htim2);
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 500; // 50% duty cycle
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
}
Key differences in ARM PWM implementation include:
- Flexible clock tree: ARM cores allow finer clock division via PLL multipliers and APB prescalers.
- Higher resolution: 16-bit or 32-bit timers support precise duty cycle control (e.g., 0.0015% resolution at 16-bit).
- Complementary outputs: Advanced timers support dead-time insertion for motor drive applications.
Duty Cycle and Frequency Trade-offs
The effective resolution of PWM is constrained by the timer's clock speed and desired frequency:
For example, an STM32 running at 80MHz with a 20kHz PWM signal achieves 12-bit resolution (80MHz/20kHz = 4000 steps, 212 = 4096).

3.2 Using Arduino IDE for PWM Control
PWM Hardware Timers in AVR Microcontrollers
The Arduino Uno (ATmega328P) utilizes three hardware timers (Timer0, Timer1, and Timer2) for PWM generation. Each timer controls specific PWM-capable pins:
- Timer0 (8-bit): Pins 5 and 6 (Fast PWM mode, used for
delay()andmillis()) - Timer1 (16-bit): Pins 9 and 10 (supports phase-correct and Fast PWM)
- Timer2 (8-bit): Pins 3 and 11 (supports asynchronous operation)
where N is the prescaler value (1, 8, 64, 256, or 1024) and fCPU is 16 MHz for ATmega328P.
Register-Level PWM Configuration
For advanced users needing precise control, direct timer register manipulation outperforms analogWrite(). The key registers are:
// Fast PWM mode on Timer1 (Channel A)
TCCR1A = (1 << COM1A1) | (1 << WGM11); // Clear OC1A on compare match
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // No prescaling
ICR1 = 0x03FF; // 10-bit resolution
OCR1A = 512; // 50% duty cycle
Arduino API Functions
The Arduino IDE provides three abstraction layers for PWM:
| Function | Resolution | Underlying Mechanism |
|---|---|---|
analogWrite(pin, duty) |
8-bit (0-255) | Configures timer hardware automatically |
analogWriteResolution(bits) |
Up to 16-bit | Requires SAM/SAMD boards |
setPwmFrequency(pin, freq) |
Variable | Third-party libraries (e.g., PWM.h) |
Phase-Correct vs. Fast PWM
The ATmega328P offers two fundamental PWM modes with distinct spectral characteristics:
- Phase-Correct PWM: Symmetric waveform generation reduces harmonic content, preferred for motor control
- Fast PWM: Higher maximum frequency but introduces odd-order harmonics
Advanced Techniques
For research-grade applications, consider:
- Dead-time insertion using
GTCCRregister for H-bridge control - Timer overflow interrupts for dynamic duty cycle modulation
- Input capture units for PWM frequency measurement
// Dynamic PWM adjustment with interrupts
void setup() {
TCCR0A = (1 << WGM01) | (1 << WGM00); // Fast PWM
TIMSK0 = (1 << TOIE0); // Overflow interrupt
sei();
}
ISR(TIMER0_OVF_vect) {
OCR0A = readSensor(); // Real-time duty cycle update
}

3.3 Debugging and Optimizing PWM Signals
Signal Integrity Analysis
PWM signal integrity is critical for precise control, particularly in high-frequency applications. Common issues include:
- Ringing caused by impedance mismatches in transmission lines
- Overshoot/undershoot from improper termination or excessive drive strength
- Jitter due to clock instability or power supply noise
The time-domain behavior can be modeled using transmission line theory. For a signal with rise time tr propagating through a line with characteristic impedance Z0:
Oscilloscope Measurement Techniques
When probing PWM signals:
- Use 10X probes to minimize circuit loading
- Ensure ground leads are as short as possible (<5cm)
- Trigger on the PWM carrier frequency, not the modulation envelope
Critical measurements include:
- Duty cycle accuracy (±0.1% for precision applications)
- Rise/fall times (should be <5% of PWM period)
- Period jitter (should be <1% of period for stable control)
Frequency Domain Analysis
Spectrum analysis reveals harmonic content and switching noise. The Fourier series of an ideal PWM signal with duty cycle D and frequency fPWM is:
Key spectrum characteristics to examine:
- Fundamental at fPWM
- First null at 1/(πtr)
- Harmonic roll-off rate (-20dB/decade for trapezoidal waves)
Microcontroller-Specific Optimization
For ARM Cortex-M PWM peripherals (e.g., STM32 TIMx):
- Use DMA for buffer updates to prevent jitter from interrupt latency
- Configure dead-time insertion hardware when driving H-bridges
- Align PWM updates with counter overflow using repetition counters
The optimal prescaler setting balances resolution and frequency:
where PSC is the prescaler value and ARR is the auto-reload register value.
Noise Reduction Strategies
Effective techniques include:
- Snubber circuits (R-C networks) across switching elements
- Ferrite beads on PWM output lines
- Ground plane partitioning to separate analog and digital returns
The optimal snubber resistor can be calculated from:
Real-Time Debugging with Logic Analyzers
Advanced triggering capabilities enable capture of:
- Glitches during duty cycle transitions
- Phase alignment between multiple PWM channels
- Synchronization events in multi-controller systems
Protocol decoders can verify:
- PPM (Pulse Position Modulation) timing
- Space Vector Modulation patterns
- Dead-time compliance in motor drives

4. Phase-Correct PWM vs. Fast PWM
Phase-Correct PWM vs. Fast PWM
Fundamental Operational Differences
Phase-correct PWM and fast PWM are two distinct modulation techniques implemented in microcontrollers, differing primarily in their counting behavior and symmetry. Fast PWM operates by incrementing the timer register from zero to its maximum value (e.g., TOP), then resetting to zero, producing an asymmetric waveform. Phase-correct PWM, however, counts up and then down symmetrically, resulting in a centered pulse with lower harmonic distortion.
Here, fclk is the system clock frequency, N is the prescaler value, and TOP is the timer’s maximum count value (e.g., 255 for 8-bit resolution).
Harmonic Distortion and Applications
Phase-correct PWM’s symmetric counting reduces even-order harmonics, making it preferable for audio applications and motor control where smooth transitions are critical. Fast PWM’s higher frequency capability suits switching power supplies and LED dimming, where switching speed outweighs harmonic concerns.
Timer Configuration in Microcontrollers
For an AVR microcontroller (e.g., ATmega328P), fast PWM is enabled by setting WGM02:0 bits to 011 (mode 3) in TCCRnA/B registers, while phase-correct PWM uses 001 (mode 1). The following code snippet configures phase-correct PWM on Timer1:
// Phase-correct PWM, 10-bit resolution (TOP = 0x03FF)
TCCR1A = (1 << COM1A1) | (1 << WGM11);
TCCR1B = (1 << WGM13) | (1 << CS10);
ICR1 = 0x03FF; // TOP value
Trade-offs and Performance
- Fast PWM: Higher effective frequency but introduces jitter in duty cycle transitions.
- Phase-Correct PWM: Lower frequency but eliminates glitches during duty cycle updates, critical for H-bridge motor drivers.

Using PWM for Motor Speed Control
Fundamentals of PWM-Based Motor Control
Pulse-width modulation (PWM) enables precise control of DC motor speed by varying the average voltage applied to the motor terminals. The effective voltage Veff delivered to the motor is determined by the duty cycle D of the PWM signal:
where D ranges from 0 (0%) to 1 (100%). For a 12V supply with 75% duty cycle, the motor sees an effective 9V. This voltage control method is more efficient than linear regulation because the switching transistor operates either fully on (saturated) or fully off, minimizing power dissipation.
Microcontroller Implementation
Modern microcontrollers generate PWM signals through dedicated hardware timers. For an 8-bit timer (common in AVR and ARM Cortex-M0), the duty cycle resolution is:
Higher resolution (16-bit timers) enables finer speed control but requires more computation. The PWM frequency must exceed the motor's electrical time constant to prevent audible noise and mechanical vibration. Typical frequencies range from 5-20 kHz for small DC motors.
H-Bridge Circuit Requirements
An H-bridge driver is essential for bidirectional control and handling inductive kickback. Key design parameters include:
- Peak current rating: Must exceed motor stall current by 25-50% margin
- Dead time: Typically 100-500ns to prevent shoot-through
- Flyback diodes: Fast recovery (≤100ns) for inductive spike protection
The H-bridge's switching losses Psw can be estimated as:
where tr and tf are the MOSFET rise/fall times, and fPWM is the switching frequency.
Closed-Loop Speed Regulation
For precision applications, encoder feedback enables PID control. The error term e(t) between desired and actual speed drives the duty cycle adjustment:
Practical implementations often use trapezoidal integration and derivative filtering to reduce noise sensitivity. The sampling rate should be at least 10× the motor's mechanical time constant.
Practical Considerations
Electromagnetic interference (EMI) mitigation requires:
- Twisted pair wiring for motor connections
- RC snubber networks (2-10Ω with 0.1-1μF) across motor terminals
- Star grounding at the power supply
Thermal management becomes critical at high currents. The junction temperature Tj of power MOSFETs must satisfy:
where RθJC and RθCA are junction-case and case-ambient thermal resistances.

4.3 Implementing PWM for LED Dimming and Color Mixing
PWM Fundamentals for LED Control
The average voltage delivered to an LED via PWM is governed by the duty cycle D, defined as the ratio of the ON time (Ton) to the total period (T):
where D ranges from 0 (fully off) to 1 (fully on). For LEDs, this translates to luminous flux control since light output is approximately linear with forward current in the operational range. The PWM frequency must exceed the flicker fusion threshold (typically >100 Hz) to avoid visible flicker.
Microcontroller Implementation
Modern microcontrollers implement PWM via dedicated hardware timers and compare registers. For an 8-bit resolution PWM (common in basic microcontrollers), the duty cycle is set by writing to an 8-bit register (CCRx), giving 256 discrete brightness levels:
where n is the bit resolution. Higher-end microcontrollers offer 16-bit PWM (65,536 levels) for smoother dimming. The timer overflow frequency is determined by:
where N is the prescaler value and TOP is the maximum counter value.
Color Mixing with RGB LEDs
Trichromatic color mixing follows the Grassmann's laws of additive color mixing. The resulting chromaticity coordinates (x, y) are weighted sums of the primary LED coordinates:
where φi is the luminous flux of each primary. In practice, this requires:
- Individual PWM channels for each color (R, G, B)
- Gamma correction to account for nonlinear human perception
- Calibration to compensate for LED manufacturing variations
Gamma Correction
The perceived brightness L relates to the PWM duty cycle by a power law:
where γ ≈ 2.2 for typical displays. This is implemented via a lookup table or real-time computation:
// Gamma correction lookup table for 8-bit PWM
const uint8_t gamma_table[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
// ... (precomputed values)
255, 255, 255, 255, 255, 255, 255, 255
};
void set_led_brightness(uint8_t channel, uint8_t level) {
PWM_REGISTER[channel] = gamma_table[level];
}
Advanced Techniques
Dithering combines temporal and spatial modulation to achieve effective resolution beyond hardware limits. For a 16-bit color depth using 8-bit PWM:
where Dcoarse is the 8-bit value and Dfine modulates the occurrence of Dcoarse+1 pulses.
Current Regulation maintains color consistency by compensating for temperature-dependent LED efficiency variations. This requires:
- Real-time current sensing (e.g., shunt resistors)
- Closed-loop PWM adjustment
- Thermal modeling of LED junctions
5. Building a PWM-Based Fan Speed Controller
5.1 Building a PWM-Based Fan Speed Controller
PWM Fundamentals for Fan Control
Pulse-width modulation (PWM) is a highly efficient method for controlling the power delivered to an electrical load, such as a DC fan. The technique works by rapidly switching the power supply on and off, where the average voltage (and thus speed) is controlled by the duty cycle—the ratio of the on-time to the total period. For a fan with a nominal voltage Vnominal, the effective voltage Veff is given by:
where D is the duty cycle (0 ≤ D ≤ 1). The PWM frequency must be high enough to avoid audible noise but low enough to prevent excessive switching losses. A typical range for fan control is 20–25 kHz.
Microcontroller PWM Configuration
Most modern microcontrollers (e.g., ARM Cortex-M, AVR, or PIC) include dedicated PWM peripherals. For an 8-bit timer, the duty cycle resolution is 256 steps (0–255), while a 16-bit timer offers 65,536 steps. The PWM period TPWM is determined by:
where PR is the timer's period register value and fclock is the input clock frequency. For example, an AVR microcontroller running at 16 MHz with a prescaler of 8 and a period register value of 199 yields:
Hardware Implementation
A typical PWM-based fan controller consists of:
- Microcontroller: Generates the PWM signal.
- MOSFET Driver: Amplifies the PWM signal to drive the fan.
- N-Channel MOSFET: Acts as a switch for the fan.
- Flyback Diode: Protects the circuit from inductive voltage spikes.
The MOSFET's gate charge and on-resistance (RDS(on)) must be selected to minimize power dissipation. The power loss in the MOSFET is:
Software Implementation
Below is an example code snippet for configuring PWM on an AVR microcontroller (ATmega328P) using Timer1:
#include <avr/io.h>
void PWM_Init() {
// Set PWM frequency to ~25kHz (16MHz / 1 / 640)
TCCR1A = (1 << COM1A1) | (1 << WGM11); // Non-inverting PWM, Fast PWM (mode 14)
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // No prescaler
ICR1 = 639; // Top value for 25kHz
DDRB |= (1 << PB1); // Set OC1A (PB1) as output
}
void PWM_SetDuty(uint16_t duty) {
OCR1A = duty; // Set duty cycle (0-639)
}
Thermal Considerations
The MOSFET must be heatsinked if the fan current exceeds 500mA. The junction temperature TJ can be estimated using:
where TA is ambient temperature and RthJA is the thermal resistance from junction to ambient. A TO-220 package typically has RthJA ≈ 62°C/W.
Closed-Loop Control
For precise speed regulation, a closed-loop system can be implemented using a tachometer feedback signal from the fan. The proportional-integral (PI) control law adjusts the duty cycle to minimize the error between desired and actual RPM:
where e is the RPM error, and Kp and Ki are tuning constants.

5.2 Designing a PWM-Controlled Servo System
Servo Motor Fundamentals
Servo motors are electromechanical devices that convert PWM signals into precise angular displacement. A typical servo consists of a DC motor, gear train, potentiometer for feedback, and control circuitry. The relationship between the PWM duty cycle and the output shaft angle is linear, defined by:
where θ is the output angle, D is the duty cycle, and subscripts denote the operational limits. Standard servos typically respond to PWM frequencies between 50-300 Hz, with pulse widths ranging from 1-2 ms corresponding to 0-180° rotation.
Microcontroller PWM Generation
Modern microcontrollers implement PWM through dedicated timer/counter hardware. For an 8-bit timer with a prescaler value P and system clock frequency fclk, the PWM frequency is given by:
The duty cycle resolution is determined by the timer's bit depth. For example, a 16-bit timer provides 65,536 discrete duty cycle steps, enabling microdegree positioning precision when combined with appropriate gearing.
Closed-Loop Control Implementation
An effective servo control system requires feedback integration. The control law for a proportional-integral-derivative (PID) controller can be expressed as:
where u(t) is the control signal, e(t) is the position error, and Kp, Ki, Kd are tuning constants. Digital implementation requires discretization:
where Ts is the sampling period. Anti-windup mechanisms must be incorporated to prevent integral term saturation during prolonged errors.
Hardware Design Considerations
The power stage requires careful design to handle the motor's inductive load. The freewheeling diode's reverse recovery time trr must satisfy:
where ton is the switch conduction time. For high-current applications (>1A), MOSFET selection should ensure the gate charge Qg can be fully delivered within the microcontroller's output current capability:
Software Architecture
A robust implementation separates timing-critical PWM generation from higher-level control logic. The following structure is recommended:
- Hardware abstraction layer: Direct timer register manipulation for PWM
- Control layer: PID computation at fixed intervals (e.g., 1kHz)
- Application layer: Trajectory planning and user interface
Real-time performance can be verified using worst-case execution time (WCET) analysis:
where Ci represents the execution time of each task in the control loop.

5.3 Creating a Variable Brightness LED Display
Pulse-width modulation (PWM) enables precise control over LED brightness by varying the duty cycle of a square wave signal. The perceived brightness of an LED is proportional to the average current flowing through it, which is directly determined by the duty cycle D of the PWM signal:
where Imax is the peak current when the LED is fully on. For typical microcontroller applications, PWM frequencies between 100 Hz and 1 kHz are sufficient to avoid visible flicker while maintaining smooth brightness transitions.
Microcontroller PWM Hardware Implementation
Most modern microcontrollers include dedicated PWM peripherals that generate signals without CPU intervention. For an 8-bit PWM resolution (common in basic microcontrollers), the duty cycle can be adjusted in 256 discrete steps (0-255). The duty cycle register value OCR relates to the output voltage as:
where n is the PWM resolution in bits. Higher resolution (e.g., 12- or 16-bit) enables finer brightness control but requires more computational resources.
LED Driver Circuit Considerations
A basic LED driver circuit consists of:
- Current-limiting resistor: Calculated based on forward voltage and desired maximum current
- Switching transistor: MOSFETs (e.g., 2N7000) for low-power applications or BJTs for simple circuits
- Flyback diode: Essential when driving inductive loads or long LED strips
The minimum resistor value is determined by:
where Vf is the LED forward voltage and If(max) is the maximum forward current.
Advanced Techniques for Uniform Brightness
Human perception of brightness follows a logarithmic scale (Weber-Fechner law), requiring gamma correction for linear perceived brightness:
where γ ≈ 2.2 for typical LEDs. This can be implemented via lookup tables or real-time computation. For multi-LED displays, temporal dithering techniques can achieve effective resolutions beyond the hardware limitations.
Microcontroller Code Implementation
// Example: Arduino PWM brightness control with gamma correction
const byte ledPin = 9; // PWM-capable pin
const float gamma = 2.2;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int i = 0; i <= 255; i++) {
int corrected = pow(i / 255.0, gamma) * 255;
analogWrite(ledPin, corrected);
delay(10);
}
}
For professional applications, consider using dedicated LED driver ICs (e.g., TLC5940) that offer higher resolution, constant current outputs, and built-in grayscale control.

6. Essential Books on PWM and Microcontrollers
6.1 Essential Books on PWM and Microcontrollers
- PWM regulation based on microcontroller control - IEEE Xplore — This paper presents the common applications of PWM in electronics, and then introduces three ways to implement PWM output by using 51 Microcontrollers as an example. Using time delay to realize PWM output; using the timer to output PWM; using self-contained PWM interface microcontroller output. The program to implement PWM output in three ways is given, and part of the program flow chart ...
- PDF Controlling Dc Motor Using Microcontroller Pic16f72 With Pwm — This blog post explores the fundamentals of controlling a DC motor using the popular PIC16F72 microcontroller and Pulse Width Modulation (PWM) technique. It delves into the theoretical background, practical circuit implementation, and the key advantages of using PWM for motor control. Additionally, it discusses current trends in DC motor control and examines ethical considerations associated ...
- AT90PWM81-An Overview of Pulse Width Modulation Using Atmel ... — The AT90PWM81 microcontroller can produce pulse signals with varying duty fields called pulse width modulation (PWM) that can be utilized in control systems like motor control, brightness control of lighting, and many others. In this commentary, I aim to give a summary of what PWM involves, the methodology behind it, and how the AT90PWM81 microcontroller can generate PWM signals.
- Power Electronic Converters: PWM Strategies and Current Control ... — A voltage converter changes the voltage of an electrical power source and is usually combined with other components to create a power supply. This title is devoted to the control of static converters, which deals with pulse-width modulation (PWM) techniques, and also discusses methods for current control. Various application cases are treated. The book is ideal for professionals in power ...
- Control of Power Electronic Converters with Microgrid Applications — The aim of this book is twofold: to review the control theories used for smart power converter control and to review the applications of these control concepts in power electronic converters used in power distribution systems.
- Microcontrollers Fundamentals for Engineers and Scientists — This text serves as a comprehensive tutorial on microcontrollers, aimed specifically at practicing scientists and engineers. It covers fundamental concepts and subsystems relevant to various microcontroller technologies, facilitating the understanding of microcontrollers applicable across different designs. The structure of the book moves from digital design fundamentals to practical ...
- PDF Advanced Programming with STM32 Microcontrollers — The ARM Cortex-M is a 32-bit microcontroller which is the best choice for more computationally intensive tasks compared to what is available from older 8-bit microcontrollers such as the 8051, PIC, and AVR microcontrollers.
- PDF Mahesh Patil Pankaj Rodey Control Systems for Power Electronics A ... — The primary intent of this material is to get expertise in practical control system engineering with a motive of transforming control theory to an implementable control system in a microcontroller and electronics.
- PDF Microcontrollers - Dr. P's Engineering Classes — This book contains all of the information you will need to learn about the ATmega328P microcontroller as well as about embedded sys-tem design. First, microcontrollers and embedded systems will be described and explained at a zoomed-out level.
- Pulse-width Modulation (PWM) Timers in Microcontrollers — This article is the second of a series on microcontroller timers. This article describes a more complex timer called the PWM or pulse-width modulation timer.
6.2 Online Resources and Datasheets
- PDF High-Speed, Microcontroller-Adaptable, Pulse Width Modulator — Additional Information: • Microchip's web site: www.microchip.com • Product Selector Guide, Order No. DS00148 • Analog & Interface Families Data Book 2002, Order No. DS00207 • Stand-Alone Analog and Interface Solutions, Brochure, DS21060 • MCP1630 High-Speed, Microcontroller-Adaptable, Pulse Width Modulator, Data Sheet, DS21896 Information subject to change.
- PDF NCP1230 - PWM Controller, Fixed Frequency, Current Mode - onsemi — NCP1230 www.onsemi.com 5 ELECTRICAL CHARACTERISTICS (For typical values TJ = 25°C, for min/max values TJ = −40°C to +125°C, Max TJ = 150°C, VCC = 13 V, VPIN8 = 30 V unless otherwise noted.) Characteristic Symbol Pin Min Typ Max Unit Supply Section (All frequency versions, otherwise noted) Turn−On Threshold Level, VCC Going Up (Vfb = 2.0 V) VCCOFF 6 11.6 12.6 13.6 V
- PDF Single-phase PWM controller for automotive applications — The A6727 is a single-phase PWM controller with embedded high-current drivers that provides complete control logic and protection to realize a general DC-DC step-down converter. Designed to drive N-channel MOSFETs in a synchronous buck topology, with its high level of integration, this 8-pin device allows a reduction of cost and size of the power
- PWM Controller Enables Digital Control - Electronic Design — Designed for use with a microcontroller, the MCP1630 PWM enables precision control, digital communications and programmability for initial settings or on-the-fly adjustment or calibration.
- DRV88703.6-A Brushed DC Motor Driver (PWM Control) datasheet (Rev — other small machines. Two logic inputs control the H-bridge driver, which consists of four N-channel MOSFETs that can control motors bidirectionally with up to 3.6-A peak current. The inputs can be pulse-width modulated (PWM) to control motor speed, using a choice of current-decay modes. Setting both inputs low enters a low-power sleep mode.
- PDF Getting started with the six-step reference design firmware for STEVAL ... — the step commutation. This allows less microcontroller computation and better average speed estimation. 6.6 SENSE_COMPARATORS (mandatory) The symbol sets the BEMF sensing method through comparators. Note: This is the only control method supported by the STEVAL-ESC002V1 hardware. 6.7 OPEN_LOOP_RAMP The symbol enables the ramp-up phase at motor ...
- LM5033 100-V Push-Pull Voltage Mode PWM Controller — An IMPORTANT NOTICE at the end of this data sheet addresses availability, warranty, changes, use in safety-critical applications, intellectual property matters and other important disclaimers. PRODUCTION DATA. LM5033 SNVS181C -APRIL 2004-REVISED AUGUST 2016 LM5033 100-V Push-Pull Voltage Mode PWM Controller 1 1 Features
- TL594 Pulse-Width-Modulation Control Circuit - Texas Instruments — TL594 Pulse-Width-Modulation Control Circuit 1 1 Features 1• Complete PWM Power-Control Circuitry • Uncommitted Outputs for 200-mA Sink or Source Current • Output Control Selects Single-Ended or Push-Pull Operation • Internal Circuitry Prohibits Double Pulse at Either Output • Variable Dead Time Provides Control Over Total Range
- PDF High performance current mode PWM controller - STMicroelectronics — The UC384xB family of control ICs provdesi the nec-essary features to implement off-line or DC to DC fixed frequency current mode control schemes with a minimal external parts count. Internally imple-mented circuits include a trimmed oscillator for pre-cise DUTY CYCLE CONTROL under voltage lock-out featuring start-up current el ss than 0.5mA, a ...
- PDF Buck Converter Design and Feedback Controller Using Core Independent ... — are independent of the CPU, allowing the microcontroller to do any other task in parallel. In 2. Closed Loop Voltage Control using Core Independent Peripherals , a short overview of the feedback controller is given, as well as how to implement it using the core independent peripherals. The general design of the buck converter is covered in 3.
6.3 Recommended Development Kits and Tools
- COT and PWM Controllers | Microchip Technology — Development Tools Listing; Development Tools Selector (DTS) Last Chance Deals; 8-bit MCU Tools; 16-bit MCU Tools; dsPIC® DSC Tools; 32-bit MCU Tools; 32-bit MPU Tools; 64-bit MPU Tools; Analog Product Tools; FPGA Tools; Curiosity Development Boards; Curiosity Nano Development Platform; Xplained Boards; Maker and DIY Solutions; Third-Party ...
- STM32MotorControl:6-step Firmware Algorithm - stm32mcu - STMicroelectronics — 1. Introduction. This document describes the software library that implements the 6-step algorithm, also known as a trapezoidal algorithm, contained in the X-CUBE-MCSDK STM32 motor control software development kits (SDKs) designed for, and to be used with, STM32 microcontrollers. The 6-step library allows the control of a 3-phase permanent magnet (PMSM) or brushless direct current motor (BLDC).
- Getting started SDK 6.0.0 - STMicroelectronics — 1. Introduction. STM32 microcontrollers offer the performance of the industry-standard Arm ® Cortex ®-M cores running either field-oriented control (FOC) or 6-step modes, widely used in motor-control applications such as high-performance drives for air conditioning, home appliances, drones, building and industrial automation, medical, and e-bike.The STM32 motor-control software development ...
- MSPM0Gx51x Mixed-Signal Microcontrollers With CAN-FD Interface datasheet — LP-MSPM0G3519 LaunchPad development kit. kit. MSPM0 Software Development Kit (SDK) Motor control. Home appliances. Uninterruptible power supplies and inverters. Electronic point of sale systems. Medical and healthcare. Test and measurement. Factory automation and control. Industrial transport. Grid infrastructure. Smart metering. Communication ...
- Getting Started With C2000 Real-Time Control Microcontrollers (MCUs ... — For those new to C2000, but exploring application specific development the best place to begin is with Section 3.5. These kits are categorized by power conversion and motor drive applications. Each category of application kits has its own software development kit (SDK), Digital Power SDK , and Motor Control SDK , respectively.
- Renesas Electronics Corporation | Renesas — A global leader in microcontrollers, analog, ... Boards & Kits; Development Tools; Packaging; Software & Drivers; Software & Tools; Cross-reference Search; Gadget Renesas Maker Resources; 8786bf49-094e-4e2e-b1c4-4e857090a66c ... 9-Axis Industrial Motor Control with Ethernet.
- STM32 Motor Control Software Development Kit (MCSDK) — STMicroelectronics' newly-released 6.0 version of the advanced Motor Control Software Development Kit (SDK) brings a brand new Workbench tool, featuring a modern UI with a fully reworked use flow. This new UI has been designed to guide the user through every phase of the configuration.
- PWM Controllers - STMicroelectronics — The STCH03 features a built-in high-voltage start-up circuit with zero power consumption, fully integrated blocks for primary-side constant-current output regulation and advanced power management, making it the best choice for high efficiency and ultra-low standby consumption power supplies with excellent dynamic performance.. Designed to provide a constant output current (CC) regulation using ...
- Pulse-Width Modulation - Microchip Technology — Although they are designed slightly differently for each architecture, the PWM peripherals available in PIC ® and AVR ® microcontrollers (MCUs) provide your system with a hardware-driven PWM generator that does not occupy any CPU resources at runtime. They also have built-in hardware to accommodate PWM-related tasks such as dead-band delay and auto shutdown.
- How to Choose the Best Development Kit: The ... - PREDICTABLE DESIGNS — A development kit will serve as the brains of your project and will communicate with all the interconnected electronic components. But here's the thing about choosing development kits — it's a super-complex decision, with lots of technical attributes that don't seem to make a lot of sense, especially if you're just getting started ...







