PWM Control with Microcontrollers

#PWM #microcontrollers #duty cycle #AVR #ARM #timer #counter #hardware PWM #software PWM #pulse width modulation

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:

$$ D = \frac{t_{on}}{T} \times 100\% $$

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:

$$ V_{avg} = D \times V_{max} $$

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:

$$ \Delta t = \frac{T}{2^n - 1} $$

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:

$$ V(t) = DV_{max} + \sum_{m=1}^{\infty} \frac{2V_{max}}{m\pi} \sin(m\pi D) \cos(2\pi mft) $$

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

0% 25% 50% 75% 100% Duty Cycle Variation
Definition and Basic Principles of Pulse Width Modulation in PWM Control with Microcontrollers
Diagram Description: The section describes PWM waveforms with varying duty cycles and their mathematical relationships, which are inherently visual concepts.

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:

$$ D = \frac{t_{\text{on}}}{T} \times 100\% $$

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:

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.

$$ P_{\text{avg}} = D \times V_{\text{peak}} \times I_{\text{peak}} $$

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:

$$ f_{\text{PWM}} = \frac{f_{\text{clock}}}{(N \times (1 + \text{TOP}))} $$

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.

Time (T) Duty Cycle = 50%

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:

$$ c_n = \frac{2A}{n\pi} \left| \sin(n\pi D) \right| $$

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.

Duty Cycle and Frequency: Key Parameters in PWM Control with Microcontrollers
Diagram Description: The section explains duty cycle and frequency with mathematical relationships, but a visual representation of PWM waveforms with varying duty cycles and frequencies would concretely show their time-domain behavior and interactions.

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:

$$ V_{avg} = D \cdot V_{supply} $$

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:

$$ V_{out} = D \cdot V_{in} $$

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:

$$ L_{perceived} = D \cdot L_{max} $$

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:

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:

$$ x = d_{33} \cdot \frac{Q}{C} $$

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:

$$ f_{PWM} \geq 2 \cdot f_{RF} $$

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:

$$ f_{PWM} = \frac{f_{CLK}}{(PRESCALER)(PERIOD + 1)} $$

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:

$$ Resolution_{bits} = \log_2(PERIOD + 1) $$

Software PWM Implementation

Software PWM uses general-purpose timers and GPIO toggling via interrupts or polling. While flexible, it suffers from:

The minimum achievable pulse width in software PWM is constrained by the ISR latency (tISR) and GPIO toggle time (tGPIO):

$$ t_{min} = t_{ISR} + t_{GPIO} $$

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:

Software PWM may suffice for:

Modern Microcontroller Features

Contemporary MCUs often include advanced PWM features that blur the hardware/software distinction:

Hardware PWM vs. Software PWM in PWM Control with Microcontrollers
Diagram Description: The section compares hardware and software PWM timing behaviors, which are fundamentally visual concepts involving waveforms and timing diagrams.

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:

$$ f_{PWM} = \frac{f_{clk}}{N \cdot 256} $$

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:

The PWM period TPWM is calculated as:

$$ T_{PWM} = \frac{(ARR + 1) \cdot (PSC + 1)}{f_{TIMx}} $$

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:

The achievable frequency range depends on the selected resolution and the APB clock frequency (typically 80 MHz):

$$ f_{max} = \frac{f_{APB}}{2^{resolution}} $$

RP2040 PWM Configuration on Raspberry Pi Pico

The RP2040 microcontroller features eight independent PWM slices, each with two outputs. Configuration involves:

The PWM frequency is derived from the system clock (typically 125 MHz):

$$ f_{PWM} = \frac{f_{sys}}{DIV \cdot (TOP + 1)} $$

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:

$$ T_{dead} = \frac{DTG \cdot T_{clk}}{128} $$

where DTG is the 8-bit dead-time value (0–255) and Tclk is the timer clock period.

Configuring PWM Modules in Common Microcontrollers in PWM Control with Microcontrollers
Diagram Description: The section covers multiple microcontroller PWM configurations with register interactions and timing relationships, which are inherently visual.

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.

$$ \text{Duty Cycle} = \left( \frac{\text{OCR}}{\text{MAX\_COUNT}} \right) \times 100\% $$

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.

$$ f_{\text{PWM}} = \frac{f_{\text{CLK\_sys}}}{N \times (\text{MAX\_COUNT} + 1)} $$

For example, an 8-bit timer (MAX_COUNT = 255) with a 16 MHz clock and a prescaler of 8 yields:

$$ f_{\text{PWM}} = \frac{16 \times 10^6}{8 \times 256} = 7.8125 \text{kHz} $$

Timer Registers and Initialization

Configuring a timer for PWM involves setting up several registers:

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.

$$ \text{Dead Time} = \text{DTG} \times T_{\text{CLK\_DTG}} $$

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.

Timer and Counter Setup for PWM Generation in PWM Control with Microcontrollers
Diagram Description: The section describes PWM signal generation with timer modes and dead-time insertion, which are inherently visual concepts involving waveform timing relationships.

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:

$$ f_{PWM} = \frac{f_{CPU}}{N \times 256} $$

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:

Duty Cycle and Frequency Trade-offs

The effective resolution of PWM is constrained by the timer's clock speed and desired frequency:

$$ R_{effective} = \log_2\left(\frac{f_{timer}}{f_{PWM}}\right) $$

For example, an STM32 running at 80MHz with a 20kHz PWM signal achieves 12-bit resolution (80MHz/20kHz = 4000 steps, 212 = 4096).

Writing PWM Code in C for AVR and ARM Microcontrollers in PWM Control with Microcontrollers
Diagram Description: The section compares PWM implementations across architectures with timing and register configurations, which would benefit from a visual comparison of waveform generation and timer block diagrams.

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:

$$ f_{PWM} = \frac{f_{CPU}}{N \cdot 256} $$

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:

$$ THD_{\text{phase-correct}} = \frac{4V_{DC}}{\pi}\sum_{n=1,3,5...}^{\infty}\frac{1}{n}J_0\left(n\pi D\right) $$

Advanced Techniques

For research-grade applications, consider:


// 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
}
  
Using Arduino IDE for PWM Control in PWM Control with Microcontrollers
Diagram Description: The section discusses phase-correct vs. Fast PWM modes with mathematical THD analysis, which requires visualization of waveform symmetry and harmonic content.

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:

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:

$$ V(t) = V_0 \left(1 - e^{-\frac{t}{\tau}}\right) $$ $$ \tau = \frac{L}{Z_0} = Z_0 C $$

Oscilloscope Measurement Techniques

When probing PWM signals:

Critical measurements include:

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:

$$ V(t) = A \left[D + \sum_{n=1}^{\infty} \frac{2}{n\pi} \sin(n\pi D) \cos(2\pi n f_{PWM} t)\right] $$

Key spectrum characteristics to examine:

Microcontroller-Specific Optimization

For ARM Cortex-M PWM peripherals (e.g., STM32 TIMx):

The optimal prescaler setting balances resolution and frequency:

$$ f_{PWM} = \frac{f_{CPU}}{(PSC + 1)(ARR + 1)} $$

where PSC is the prescaler value and ARR is the auto-reload register value.

Noise Reduction Strategies

Effective techniques include:

The optimal snubber resistor can be calculated from:

$$ R_{snub} = \sqrt{\frac{L_{trace}}{C_{stray}}} $$

Real-Time Debugging with Logic Analyzers

Advanced triggering capabilities enable capture of:

Protocol decoders can verify:

Debugging and Optimizing PWM Signals in PWM Control with Microcontrollers
Diagram Description: The section discusses time-domain behavior, signal integrity issues, and frequency domain analysis, which are highly visual concepts.

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.

$$ \text{Fast PWM Frequency} = \frac{f_{clk}}{N \cdot (1 + TOP)} $$
$$ \text{Phase-Correct PWM Frequency} = \frac{f_{clk}}{2 \cdot N \cdot TOP} $$

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.

Fast PWM (Asymmetric) Phase-Correct PWM (Symmetric)

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

Phase-Correct PWM vs. Fast PWM in PWM Control with Microcontrollers
Diagram Description: The section compares asymmetric (fast PWM) and symmetric (phase-correct PWM) waveforms, which are inherently visual concepts.

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:

$$ V_{eff} = D \times V_{supply} $$

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:

$$ \Delta D = \frac{1}{2^8} = 0.39\% $$

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:

The H-bridge's switching losses Psw can be estimated as:

$$ P_{sw} = \frac{1}{2} V_{DS} I_D (t_r + t_f) f_{PWM} $$

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:

$$ D(t) = K_p e(t) + K_i \int_0^t e(\tau) d\tau + K_d \frac{de(t)}{dt} $$

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:

Thermal management becomes critical at high currents. The junction temperature Tj of power MOSFETs must satisfy:

$$ T_j = T_a + (R_{\theta JC} + R_{\theta CA}) \times (P_{cond} + P_{sw}) < T_{j(max)} $$

where RθJC and RθCA are junction-case and case-ambient thermal resistances.

Using PWM for Motor Speed Control in PWM Control with Microcontrollers
Diagram Description: The section covers PWM signal generation, H-bridge operation, and closed-loop control, which are inherently visual concepts involving signal timing and circuit topology.

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):

$$ V_{avg} = D \cdot V_{supply} $$

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:

$$ D = \frac{CCRx}{2^n - 1} $$

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:

$$ f_{PWM} = \frac{f_{CPU}}{N \cdot (TOP + 1)} $$

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:

$$ x_{mix} = \frac{\sum \phi_i x_i}{\sum \phi_i}, \quad y_{mix} = \frac{\sum \phi_i y_i}{\sum \phi_i} $$

where φi is the luminous flux of each primary. In practice, this requires:

Gamma Correction

The perceived brightness L relates to the PWM duty cycle by a power law:

$$ L \propto D^\gamma $$

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:

$$ D_{effective} = D_{coarse} + \frac{D_{fine}}{256} $$

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:

Time Amplitude Duty Cycle = 40%
PWM LED Control: Waveforms & Color Mixing A diagram showing PWM waveforms for LED control, RGB color mixing vectors, and gamma correction curve. Time Voltage T_on T V_supply R G B x y Duty Cycle (D) Luminance (L) γ=2.2
Diagram Description: The section covers PWM waveforms, duty cycle relationships, and RGB color mixing—all inherently visual concepts where diagrams clarify timing, voltage levels, and color space interactions.

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:

$$ V_{eff} = D \cdot V_{nominal} $$

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:

$$ T_{PWM} = \frac{(PR + 1)}{f_{clock}} $$

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:

$$ T_{PWM} = \frac{(199 + 1)}{2 \times 10^6} = 100 \mu s \quad (f_{PWM} = 10 \text{kHz}) $$

Hardware Implementation

A typical PWM-based fan controller consists of:

The MOSFET's gate charge and on-resistance (RDS(on)) must be selected to minimize power dissipation. The power loss in the MOSFET is:

$$ P_{loss} = I_{fan}^2 \cdot R_{DS(on)} \cdot D $$

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:

$$ T_J = T_A + (P_{loss} \cdot R_{thJA}) $$

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:

$$ D_{new} = D_{old} + K_p \cdot e + K_i \cdot \sum e $$

where e is the RPM error, and Kp and Ki are tuning constants.

Building a PWM-Based Fan Speed Controller in PWM Control with Microcontrollers
Diagram Description: The section covers PWM waveforms, MOSFET switching, and closed-loop control, which are inherently visual concepts.

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:

$$ \theta = \theta_{\text{min}} + \left( \frac{\theta_{\text{max}} - \theta_{\text{min}}}{D_{\text{max}} - D_{\text{min}}} \right) (D - D_{\text{min}}) $$

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:

$$ f_{\text{PWM}} = \frac{f_{\text{clk}}}{P \times 256} $$

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:

$$ u(t) = K_p e(t) + K_i \int_0^t e(\tau) d\tau + K_d \frac{de(t)}{dt} $$

where u(t) is the control signal, e(t) is the position error, and Kp, Ki, Kd are tuning constants. Digital implementation requires discretization:

$$ u_k = K_p e_k + K_i T_s \sum_{i=0}^k e_i + K_d \frac{e_k - e_{k-1}}}{T_s} $$

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:

$$ t_{\text{rr}} \ll \frac{1}{f_{\text{PWM}}} - t_{\text{on}}} $$

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:

$$ I_{\text{drive}} \geq \frac{Q_g}{t_{\text{rise}}} $$

Software Architecture

A robust implementation separates timing-critical PWM generation from higher-level control logic. The following structure is recommended:

Real-time performance can be verified using worst-case execution time (WCET) analysis:

$$ \sum_{i=1}^n C_i \leq T_s $$

where Ci represents the execution time of each task in the control loop.

Designing a PWM-Controlled Servo System in PWM Control with Microcontrollers
Diagram Description: The section involves PWM signal timing relationships, servo angle mapping, and PID control flow, which are inherently visual concepts.

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:

$$ I_{avg} = D \times I_{max} $$

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:

$$ D = \frac{OCR}{2^n - 1} $$

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:

The minimum resistor value is determined by:

$$ R_{min} = \frac{V_{cc} - V_f}{I_{f(max)}} $$

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:

$$ D_{corrected} = D^{\gamma} $$

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.

Creating a Variable Brightness LED Display in PWM Control with Microcontrollers
Diagram Description: The section involves PWM waveforms and their relationship to LED brightness, which is inherently visual and time-domain behavior.

6. Essential Books on PWM and Microcontrollers

6.1 Essential Books on PWM and Microcontrollers

6.2 Online Resources and Datasheets

6.3 Recommended Development Kits and Tools