dsPIC33A Pulse Width Modulation (PWM) Peripheral
Overview
This page shows you how to use the Pulse Width Modulation (PWM) peripheral in dsPIC33A microcontrollers. The PWM module can generate up to twelve pairs of outputs, depending on the device, and supports both standard and high-resolution modes. High-resolution mode enables fine control of output timing, down to 78 picoseconds on some devices.
You will explore the architecture of the PWM module, which includes multiple independent generators, each with its own timing and control features. The module supports various operating and output modes, such as independent, complementary, and push-pull outputs, as well as advanced triggering and synchronization options. You will learn how to use data buffering for smooth and synchronized updates, and how to use PWM Control Inputs (PCI) for features like fault handling and current limiting.
The course will also cover configurable dead-time for safe switching, fault handling, software override, and special features like event outputs and pseudo-random dithering to reduce Electromagnetic Interference (EMI). You will learn how to calculate key parameters like period, duty cycle, phase, and dead time using the provided equations.
Features
- Up to twelve pairs of outputs
- Multiple PWM modes in both edge and center aligned
- Multiple output modes including complementary
- Up to 78 ps resolution
- Advanced triggering capabilities
- Configurable Dead-time
- Data buffering for concurrent updates
- Specialized hardware to support allocations
Peripheral Architecture
High-level Overview
Top Level PWM Module
First, let’s take a look at the basic Top Level architecture of the High Resolution Pulse Width Modulation (PWM) module.
Although a typical device has only one PWM module, it is comprised of several PWM generators (PGs). Each independent PWM generator drives a dedicated pair of outputs and contains its own set of PWM generator-specific Special Function Registers (SFRs) and features. The PWM generators can be used together to implement a variety of complex systems and applications.
Additionally, there are several shared top level PWM module features, including input clock options, some top level shared data registers, a set of configurable PWM event outputs, combinatorial trigger logic, and combinatorial output logic features.
PWM Generator
Now let’s take a look at an individual PWM generator.
Each PWM generator within the PWM module is independently configurable with its own set of inputs, outputs, and Special Function Registers (SFRs).
The timebase generator receives the clock source selected at the top level PWM module and then generates output edges on compare events with the PWM generator data registers. This base PWM signal is then gated by the output control blocks to provide the capability to alter the PWM signal sent to the output pins.
The output control block performs several important functions, including basic Output mode behavior as well as fault shutdown, override, and deadtime features.
Each cycle of the PWM timebase generator requires a triggering event, called the Start-of-Cycle (SOC) trigger. SOC trigger options include a Self-Triggering mode, trigger outputs from other PWM generators, and triggers routed through the Sync PCI.
The PWM control input blocks have multiple purposes, including interfacing with some top level PWM features, signal conditioning, and fault detection. The PCI has command of the output control block as needed to perform these functions. For example, during a fault condition, the PWM hardware outputs can be quickly driven to a known state, overriding the PWM signal before the application can react to the fault condition.
A configurable output trigger is shared to the top level PWM system as well as to other PWM generators as a trigger input option. This is the primary method of sharing a trigger between PWM generators. Other configurable output triggers called “ADC triggers” are routed outside of the PWM module to trigger other device peripherals. While primarily intended for triggering ADC conversions, they are also available to the Digital-to-Analog Converter (DAC) and Peripheral Trigger Generator (PTG) peripheral modules.
Output and Operating Modes
Each PWM generator consists of a pair of outputs, shown here in Complementary output mode. Other output modes, including Independent and Push-Pull, are available.
While output modes control how the outputs themselves behave, operating modes control when and how the PWM module reacts to user data input. Operating modes include Independent Edge, Variable Phase, multiple Center-Aligned modes, and a Dual PWM mode.
Combining various output and operating modes enables a wide range of PWM waveforms, thereby supporting a broad spectrum of applications.
Output resolution is dependent on the specific dsPIC® DSC device. Up to 2 ns output resolution can be achieved in standard resolution mode, when using up to 500 MHz as the PWM input clock. Other dsPIC DSC devices can yield up to 1.25 ns output resolution in standard resolution mode. The dsPIC33AK512MPS512 has eight output generators (16 pairs) with Fine Edge Placement (FEP) resolution down to 78 ps, and four output generators (eight pairs) with resolution down to 1.25 ns.
Triggering
- SOC Trigger Selection
- Self-Triggering (Local End of Cycle)
- PWM Trigger Output
- Shared PWM Trigger Output
- Shared PWM Trigger Output with Phase Delay
- Daisy Chain PWM Trigger Output
- Daisy Chain PWM Trigger Output with Phase Delay
- PCI Sync Triggering
- Shared PWM Trigger PCI
- Retriggering Mode
- ADC Triggers
Every PWM cycle requires a trigger called the SOC trigger. The SOC trigger selection or Start-of-Cycle Selection (SOCS) options include a free-running Self-Triggering mode, which is enabled by default. Another option is the PWM Trigger Output from one of four other PWM generators. Triggers may also be routed through the PWM Control Input Sync Inputs. These inputs include device pins, other top-level PWM features, and other PWM generator signals.
Each PWM generator also produces a PWM Trigger Output. The source of this trigger can be synchronous with the PWM generator End of Cycle event, or after some delay by choosing one of the three available internal timers, Trigger A (TRIGA), Trigger B (TRIGB), or Trigger C (TRIGC).
Two other output triggers are also available to be shared with other peripherals while primarily intended to trigger ADC conversions, hence the names ADC Trigger 1 and ADC Trigger 2. They are also available to the Digital-to-Analog Converter (DAC) and Peripheral Trigger Generator (PTG) peripheral modules.
SOC Trigger Selection
Let’s take a closer look at the SOC trigger selection options available to you. By default, all PWM generators are configured for self-triggered operation. However, it is not possible to enable multiple free-running PWM generators in software and achieve synchronous operation.
To overcome this, an SOC trigger can be received directly from the PWM Trigger Output of another PWM generator. Note that PWM generators 1-4 and PWM generators 5-8 are grouped, and a PWM generator may only select another PWM generator from within its own group. This is the primary method of sharing a PWM trigger between PWM generators, and provides hardware-based synchronous operation.
Additionally, a SOC trigger may be received from the PWM Control Input Sync block. This allows triggering from any of the internal and external sources available to the PWM Control Input Source Selection. These inputs include PWM generator signals from outside of a PWM generator’s own group. However, there's a small delay incurred when sharing a trigger with other PWM generators using this method.
Self-Triggering
The PWM generators are self-triggered (i.e., Local End of Cycle) by default (SOCS setting of 0) and will free-run. The first SOC event is automatically triggered when the individual PWM generator ON bit is set. The End of Cycle event then becomes the SOC trigger for the next PWM cycle. In this way, the SOC and Local End of Cycle become synonymous.
PWM Trigger Output
A SOC trigger can also be received from another PWM generator within the same Local Group by choosing SOCS bit settings 1-4.
Here we have a PWM generator that is self-triggered and is also generating a PWM Trigger Output with each cycle. By default, the PWM Trigger Output occurs synchronously with the start of each PWM cycle. However, three trigger timers, Trigger A (TRIGA), Trigger B (TRIGB), and Trigger C (TRIGC) are available as sources for the PWM Trigger Output. Choosing one of these options, through the PWM generator Trigger Select bits, will delay the PWM Trigger Output event by the value held in the corresponding timer register.
Shared PWM Trigger Output
Now let’s look at an example where we share the PWM Trigger Output from one PWM generator with other PWM generators to create a synchronous multi-phase system.
The following diagram shows PWM generator 1 as self-triggered, and the PWM Trigger Output is left in its default setting to output synchronously with each PWM cycle.
PWM generators 2 and 3 both choose their SOCS bits to receive the PWM Trigger Output of PWM generator 1. You must enable PWM generators 2 and 3 before enabling PWM generator 1 to ensure all three PWM generators start simultaneously.
Shared PWM Trigger Output with Phase Delay
Phase offset can be added by using the PWM Phase delay register found in each PWM generator. Once a trigger has been received, the Start of Cycle is simply delayed by the value set in the PWM generator PHASE register. However, care is needed when events are delayed and the duty cycle of a phase extends beyond the End of Cycle boundary of the Initiating PWM generator (PWM generator 1 in this example).
Daisy Chain PWM Trigger Output
This next example illustrates another multi-phase system using a daisy-chain triggering configuration. Here we see again that PWM generator 1 is self-triggered and PWM generator 2 is triggered from the PWM Trigger Output of PWM generator 1. However, this time, PWM generator 3 is triggered from the PWM Trigger Output of PWM generator 2. You must enable PWM generator 3 and then PWM generator 2, before enabling PWM generator 1, to ensure all three PWM generators start simultaneously.
Daisy Chain PWM Trigger Output with Phase Delay
Next, we can add phase offset to the daisy chain configuration by delaying the PWM Trigger Output from each PWM generator using one of the three available Trigger Timers: TRIGA, TRIGB, or TRIGC. Since each PWM generator has its own dedicated set of Trigger timers, we’ll use the respective TRIGA timer to delay the PWM Trigger Output for both PWM generator 1 and PWM generator 2. Creating phase delay using this method ensures that each PWM generator has its own Start and End of Cycle, which may be needed in some applications using PWM Control Input (PCI) auto-termination or other End of Cycle events, and allows up to 100% duty cycle without crossing a cycle boundary.
PCI Sync Triggering
Another option for triggering a Start of Cycle event is the PWM control inputs. Specifically, the Sync PCI block is used to interface external signals as Start of Cycle triggers. The PWM Control Input synchronizes them to the PWM generator's clock domain and provides conditional logic to support a wide range of applications and uses. PWM Control Input Source Selection options include device pins, other device peripherals, Top-Level PWM features, and other PWM generator signals, including those outside of the local grouping of four.
Shared PWM Trigger PCI
In this example, PWM generator 1 is self-triggered and free-running. PWM generator 5 is configured to receive its Start of Cycle trigger from the Sync PWM Control Input, with PWM Control Input Source Selection configured to receive the raw Timebase Generator output of PWM generator 1. Again, this method of sharing a trigger does result in a small but consistent offset delay. Even if the PWM Outputs of PWM generator 5 in this example are not used, triggering a Phantom PWM generator like this is a great way to expand the features available to an application.
Retriggering Mode
Next, let’s discuss the available Retriggering mode. By default, once a Trigger has been received and a PWM cycle has started, subsequent triggers will be ignored until the End of Cycle has occurred.
However, when the Trigger Mode bit is set, the PWM generator may be re-triggered any time during a PMW cycle. This can be useful for variable frequency applications when a period is shortened.
ADC Triggers
With each PWM cycle, two output triggers called ADC Trigger 1 and ADC Trigger 2 are generated. As the name implies, the main purpose is to trigger ADC conversions at specific times within a PWM cycle.
One or more of the three Trigger timers in a PWM generator, TRIGA, TRIGB, and TRIGC can be used to trigger either ADC trigger output. In this example we use TRIGA for ADC Trigger 1 and TRIGB for ADC Trigger 2.
In addition to the ADC, other peripherals such as the DAC and PTG are also connected to the ADC Trigger outputs. Also note that ADC trigger 1 offers a post-scaler feature and an offset feature. This allows post-scaled trigger events to be interleaved with trigger events from other PWM generators.
PWM Control Input (PCI)
One of the major features of the PWM system is the PWM Control Input (PCI). The PWM Control Input Logic blocks are flexible state machines that can be used for a variety of purposes. Specifically, the PCI allows interfacing internal and external asynchronous input signals into the PWM clock domain. It can then provide an output to either gate the PWM outputs directly or trigger a PWM cycle as needed. This enables the PCI to perform output control and triggering algorithms in hardware instead of using software resources.
Each PWM generator has four PCI blocks with similar features and input options. The Fault, Current Limit, and Feed Forward PCI blocks interface with the PWM generator Output Control hardware to gate the PWM signals directly. The PCI blocks are named after typical uses cases but can be used for any purpose.
A priority scheme for Output Control, based on typical use cases, is implemented to allow nested operation in complex systems. In this case, Fault has the highest priority, followed by Current Limit and then finally Feed Forward.
The Sync PCI block has the same input options as the other PCI blocks, including other PWM generator signals, and is used to synchronize these inputs as PWM Start of Cycle triggers.
PWM Control Input (PCI) Architecture
Now let’s take a closer look at the PCI architecture and features. First, let's consider the inputs available to the PCI. Each PCI has four input muxes with a wide range of signal sources to choose from. Each mux can select one signal that has additional signal conditioning options and features such as synchronization and polarity control. The qualified inputs are then passed on to the acceptance logic function.
There are six available logic functions, three of which are latched with a flip-flop to provide the flexibility needed for complex applications. Not all logic functions require all four inputs. The combination of these signals and the logic function applied to them effectively creates a custom state machine capable of implementing a control system without CPU interaction.
The last component is the PCI Active output event and bypass features. All PCI blocks share their respective PCI Active signal for other PWM generators to sync with. All PCI blocks can also generate an interrupt through the top-level PWM generator Event Interrupt Logic.
The Fault, Current Limit, and Feed Forward PCI blocks can also be used to gate the PWM outputs. The Sync PCI block can be selected as a PWM generator Start of Cycle trigger.
The PCI also supports software control for software-based applications.
PCI Acceptance Logic: Non-latched Modes
Let's look further into the Acceptance logic functions, starting with the 3 Non-Latched modes. The most basic mode is ‘non-latched level detect’, which effectively “ANDs” the PCI source and Qualifier, hence the name ‘qualifier’. Two additional non-latched modes use edge detection instead of a level threshold to the PCI source. Edge detection can be either rising edge only or both rising and falling edge.
PCI Acceptance Logic: Latched Modes
The PCI supports additional “latched” acceptance modes by adding an SR latch and including a termination signal. Here we have Latched Level Detect.
The qualified terminator signal used to reset the SR latch is the logically “ANDed” result of the terminator and termination qualifier signals. This allows for complex entrance and exit of output gating to support a wide range of control applications. The terminator signal can be optionally latched and delayed until the End-of-Cycle (EOC). This feature assists in resuming the next PWM cycle after a PCI event.
Like the non-latching modes, two additional latched modes provide edge detection on the PCI source. Again, rising only and both rising and falling edge modes are available.
PCI Usage Example: Fault Handling
Let’s consider an example of how the PCI can be used to add flexible hardware-based fault handling to gate PWM outputs when an appropriate signal becomes active.
In this case, we have a PWM generator configured to output a typical waveform as shown. The Fault PCI block can be used to detect a Fault condition from one of several sources and has the highest priority access to the output control block. When a Fault condition is detected, the PCI Active signal is used to gate the PWM outputs directly in the Output Control hardware, so latency is minimized.
Typically, the fault signal is the output from a comparator measuring a voltage or a current. However, we can also choose the PCI Active signal from another PWM generator to share a Fault condition and gate multiple PWM outputs simultaneously in hardware.
Latched vs Non-latched Fault
Using the same Fault Handling example, let’s look at the difference between the Output waveforms we would expect when using latched and non-latched acceptance logic modes.
Here we see a brief fault condition in a non-latching mode. The Fault PCI Active signal is not latched and follows the Fault condition. The PWM Outputs are gated off for the duration of the Fault condition, and the PWM cycle resumes once the fault ceases.
If the same brief fault condition occurs in a Latched Acceptance Logic mode, the fault is effectively latched until an Active Termination signal is used to clear the condition. This can last multiple PWM cycles unless the PCI auto-termination feature is enabled. In this case, the PCI Active signal will reset at the end of each PWM cycle.
PCI Usage Example: Leading-edge Blanking
Now let’s review another typical PCI use case, Leading Edge Blanking in current sensing applications.
In this example, the Current Limit PCI block is being used to perform Current Limit Control, by comparing a Current Sense input against a predetermined threshold set by the DAC. When the comparator trips, the PWM cycle is truncated, the power switches turn off, and the current begins to reduce.
However, there can be large transients on the PCI inputs caused by the switching of power devices in current-sensing applications. This is of most concern on the Leading Edge of the PWM cycle when current is just beginning to increase.
Each PWM generator has its own Leading Edge Blanking timer resource that is used to ignore inputs to the PCI while active. For this application, the Leading Blanking timer is configured to start on the PWM High output rising edge. However, it can be configured to start on various PWM edge events, including the rising or falling edge of either the High or Low output.
To achieve the Leading Edge Blanking function, the PCI is configured for Latched acceptance logic and chooses the comparator as the PCI Source input. The Leading Edge Blanking timer is selected as the Acceptance Qualifier and is inverted to gate the PWM output when the LEB timer is NOT active. The Leading Edge Blanking timer effectively disqualifies the PCI Source input. The terminator is configured to auto-terminate, and no termination qualifier is needed.
Let’s look at the function as a waveform. Initially, the PWM High output drives high on the PWM Start of Cycle. The transitioning of power devices may cause transients large enough to trip the comparator being used for the current limit PCI input. However, since the Leading Edge Blanking timer is active for some time, the PCI active signal remains low. Later in the cycle when the Leading Edge Blanking timer has expired, inputs to the PCI are considered legitimate. Once the current threshold has been reached and the comparator trips, the PCI active signal will be asserted, and the outputs will be put in the state defined by the PCI’s output control.
The Auto termination feature creates a termination pulse when the PCI signal becomes inactive. This effectively resets the system for the next cycle.
Data Buffering
- Data Buffering and Updates Overview
- Buffered Data Registers
- Data Timing: Start of Cycle
- Data Timing: Immediate (DC Extension)
- Data Timing: Immediate (DC Truncation)
- Data Timing: Immediate (Post-Active DC)
- Data Timing: Immediate (Period Lengthen)
- Data Timing: Immediate (Period Shorten)
- Data Application Timing: Immediate (Period Shorten)
- Synchronizing Multiple PWM Data Updates
Data Buffering and Updates Overview
The PWM hardware typically runs at a higher clock speed than the CPU, meaning that writes to data registers by the CPU are asynchronous to all PWM events, such as the Start or End of a Cycle. This makes the timing of newly written data values non-deterministic with respect to the PWM hardware, which is especially troublesome in a multiphase system where all PWM generators need to have the same duty cycle or phase changes.
So, to synchronize the application with new data, the PWM module allows for certain Special Function Register (SFR) data values to be buffered and updated synchronously within the PWM clock domain. This allows you to safely modify PWM data in the CPU clock domain while the PWM generator operates on another set of data values. Once a valid update event occurs, any new data values are synchronized to the PWM data buffers in the PWM domain.
A valid update event consists of two parts: the update trigger and the data application timing selection.
After an update trigger has been received from the CPU domain, the data application timing option will determine when the data is synchronized within the PWM hardware. Until a valid update event occurs, writing Duty cycle or another buffered register will only update the SFR in the CPU domain.
The default option for the update trigger is for software to write a bit, named PWM Data Register Update Request (UPDREQ). This bit would typically be set in an Interrupt Service Routine (ISR), even if the duty cycle calculation happens somewhere else. The other 3 options use a data write to the specified SFR to automatically set the (UPDREQ) bit, reducing software overhead. Typical control loop items of duty cycle and phase are included. The trigger timer registers are also included here, as they are used to define edge placement in some modes, among other things.
Only certain SFR writes can be used as an update trigger; all buffered PWM registers will be updated on a valid update event. Also note that setting the MSTEN bit will allow a PWM generator to act as a host and broadcast the update request trigger to other PWM generators.
Once an update trigger is received from the CPU domain, there are a few options as to when the new data can be applied in the PWM hardware. Data can be applied at the start of the next PWM cycle; this is the default setting. Or data can be applied immediately, which has some restrictions and protection built in. There is also a Client option for both start of cycle and immediate settings, which are used to synchronize data updates across multiple PWM generators.
In a Client mode, the local update trigger selection is ignored and instead comes from a Host PWM generator with MSTEN enabled.
Buffered Data Registers
Registers that are typically changed during operation and integral to the control loop are buffered. This includes typical data values like period, duty cycle, phase, and dead time. Also included are the trigger timers, output swap control, and output override-related data.
Data Timing: Start of Cycle
Let’s take a closer look at each of the data timing options, beginning with Start of Cycle.
In this example, we are updating the duty cycle data, using a write to the duty cycle register as the update trigger. The data write is done in the current cycle, but the new value is not applied until the start of the next PWM cycle. The data write to the SFR needs to be completed before the next Start of Cycle, so the safest time to write a new data value is at the Start of Cycle (SOC). This allows maximum time before the value is copied to the PWM’s internal register. This is especially important when PWM is run significantly faster than the CPU.
There is no internal logic to prevent SFR writes at a given time, so it is possible that the write straddles the start of cycle boundary, and results in non-deterministic behavior. So, the recommended method is to use the PWM interrupt to schedule the SFR data write at the beginning of the cycle. By default, the PWM interrupt is configured for End of Cycle and can be used for this purpose.
Data Timing: Immediate (DC Extension)
Next, let’s review some examples using Immediate updates.
Immediate update timing has some hazards associated with its use, which depend on the application and use cases. Runt pulses (narrow pulses), missing cycles, and other undesirable behavior can result. The PWM has some internal safeguards to prevent this; however, care is needed for robust operation.
Let's consider the example shown of immediate update timing while writing new data to extend the duty cycle. Again, we are using the write to the duty cycle register as the data update trigger. A larger duty cycle is written while a cycle is in progress, before the current Duty Cycle (DC) has elapsed. The data is applied immediately, and the Duty Cycle is extended without interruption.
Data Timing: Immediate (DC Truncation)
Another case to consider is Immediate timing when shortening the Duty cycle.
If the PWM pulse is shortened by writing a smaller duty cycle, and the time base has already counted beyond the new duty cycle value, the Duty Cycle will be truncated near the time of the update. This is accomplished with special compare logic that operates on the upper 12 bits of data. Therefore, there may be a delay of up to four Least Significant Bits (LSBs) between update and truncation.
Data Timing: Immediate (Post-Active DC)
Now, let’s consider what happens when an immediate update happens later in a cycle, after the duty cycle has expired.
If the update trigger happens after the PWM duty cycle is already complete, the update will be delayed until the next cycle. This applies to both cases of lengthening or shortening the duty cycle and avoids a runt pulse or a 2nd active Duty Cycle.
Data Timing: Immediate (Period Lengthen)
Period updates are special. Immediate updates of the period value become effective instantaneously. If the period is lengthened, the current PWM cycle is extended to the new period length.
Data Timing: Immediate (Period Shorten)
However, when the period is shortened, we must consider when the immediate update arrives. If the PWM time base has NOT counted beyond the NEW shorter PWM period, the new period will be shortened within the current cycle.
Data Application Timing: Immediate (Period Shorten)
If the PWM time base HAS already counted beyond the NEW shorter PWM period, a long period will occur due to counter rollover. If immediate period updates are required, the best practice is to capture the time base value prior to the period update so a safe minimum period value may be calculated and written.
Synchronizing Multiple PWM Data Updates
Now that we have demonstrated both Start of Cycle and immediate updates, let's consider synchronizing data updates across multiple PWM generators.
Each PWM generator can broadcast an update trigger to all other PWM generators by setting the update enable bit “MSTEN”. Client start of cycle or Client immediate update modes receive the host update trigger. In this case, PWM generator 1 is configured to trigger a data update on a write to its duty cycle register and apply the update at the start of the next cycle. PWM generators 2 and 3 are configured to receive the host update trigger and apply new data at the start of the next cycle.
Though only the duty cycle is shown here, all buffered data registers will be updated synchronously. All new data should be written for all three PWM generators before writing to the register chosen as the update request trigger.
Operating and Output Modes
Operating Modes
- Independent Edge Operating Mode
- Dual Output Operating Mode
- Variable Phase Operating Mode
- Center-Aligned Operating Mode
- Double Update Center-Aligned Operating Mode
- Dual Edge Center-Aligned Operating Mode
Output Modes
The PWM module has multiple operating modes and output modes that determine how the PWM will behave for a given application. Operating modes are specific to how the PWM cycle operates and how the PWM data is applied. Output modes are specific to how the high and low PWM outputs behave relative to one another. Not all combinations of operating modes and output modes are valid. Multiphase systems should use the same configuration on all PWM generators to avoid unexpected behavior.
Independent Edge Operating Mode
The most basic operating mode is independent edge. This mode uses three data register values to define the PWM cycle. The rising edge is set by the PHASE register, the falling edge is set by the duty cycle register, and the cycle duration is set by the period register.
The PWM generator implements a PWM time base counter. The counter increments on each clock cycle and resets when it has reached the period register value. When the PWM timer has reached the phase or duty cycle value, the corresponding edge event is presented on the output.
Dual Output Operating Mode
Dual Output operating mode defines the PWM cycle edges like independent edge mode, but the high and low PWM outputs have their own data values.
The High PWM output uses the Phase and Duty cycle registers as usual to control edge timing. The Low PWM output uses the Trigger A (TRIGA) and Trigger B (TRIGB) timer registers for this purpose. This mode allows the high and low PWM outputs to have different phase offsets and duty cycles and is not compatible with complementary output mode. Also, Trigger A and Trigger B related features, such as the ADC trigger outputs, can still be used in this mode and would simply align with the corresponding output edge.
Variable Phase Operating Mode
The next operating mode is variable phase, which differs from independent edge in the way the duty cycle is defined. In this mode, duty cycle is defined as the time between the rising and falling edges, regardless of the phase offset.
This mode is useful as the duty cycle register can be programmed to a constant value, while the PHASE value can be modulated without impacting duty cycle. This is well-suited for multiphase systems that use a common duty cycle with different phase offsets on each phase of the system. Variable Phase mode cannot support active-duty cycles across End of Cycle boundaries. Therefore, the Phase and Duty cycle must be less than the Period to allow for completion of the duty cycle before the PWM cycle ends.
Center-Aligned Operating Mode
The remaining three operating modes are center aligned. Center-aligned refers to the waveform being symmetric around the center of the PWM cycle. The PWM cycle is comprised of two PWM timer count cycles, with the center being the end of the first and beginning of the second.
A single duty cycle value is used on both halves of the cycle to produce a single active pulse. As the duty cycle is changed, it remains symmetrical around the midpoint.
The effective period of a center-aligned PWM cycle is double that of the edge modes, as it takes two timebase counter cycles. A status bit, Half Cycle Status (Center-Aligned modes only) CAHALF, is available to determine which half of the cycle is currently in.
Buffer updates to the duty cycle or period are allowed only at the beginning of the first timer cycle. The EOC interrupt is generated only after the completion of both period cycles.
Double Update Center-Aligned Operating Mode
Double Update Center-Aligned PWM mode works identically to Center-Aligned PWM mode, except that two interrupts and two data buffer updates occur per PWM cycle. This allows more updates per cycle and reduces control loop latency, but symmetry is lost when the duty cycle is changed. The data value written is applied to the next half cycle.
Dual Edge Center-Aligned Operating Mode
The last operating mode is Dual Edge Center-Aligned mode, which adds separate control for the rising and falling edges. The PHASE register is used to set the rising edge, and the duty cycle register is used for the falling edge.
This mode provides the most flexibility in adjusting the center-aligned pulse, yet offers a lower frequency of interrupt events. Note that this will eliminate the symmetrical nature unless the Phase and Duty cycle are equal.
Though shown as a double update, Dual Edge Center-Aligned PWM mode also supports Single data buffer updates for additional flexibility.
Output Modes
Next, let's review the PWM output modes. Complementary mode, where the High and Low outputs are in opposite states to one another. Independent mode, where the High and Low outputs can be configured independently of one another, and Push Pull mode, where only one output is active every other cycle.
Complementary Output Mode
In Complementary Output mode, both the PWMxH and PWMxL signals are never active at the same time. This mode is typically used with bridge-type output structures, where one transistor or switch is on, and the other is off. If both switches are on at the same time, even for an instant, they will be stressed or damaged due to high current flowing directly across the power rails.
Complementary mode is the default selection and enables the use of deadtime. Dead time, polarity control, swap behavior, and output override are factored in at different stages to achieve deterministic behavior. If only one PWM output is needed with deadtime, complementary mode can be used with one output disabled.
Independent Output Mode
Independent output mode allows the high and low PWM pins to be driven separately. By default, the outputs will be the same as shown here. However, the High and Low outputs can be controlled directly by external hardware signals through the PWM Control Input (PCI) module or by software overrides.
When combined with the Dual PWM operating mode, the PWM generator will produce independent pulse widths on the high and low outputs as shown here. Recall that in Dual PWM operating mode, PHASE and Duty Cycle registers are used to define the edges on the High output, and the Trigger A (TRIGA) and Trigger B (TRIGB) registers are used to define the edges on the LOW output.
Push-Pull Output Mode
Push-Pull output mode differs from the other modes in that it is implemented over two PWM Timebase cycles. The high output goes active in the first cycle, and then the low output in the second cycle. This mode is typically used in transformer applications.
A status signal Output Steering Status (Push-Pull Output mode only) “STEER”, is provided to differentiate the cycle halves from one another. Since dead time is not available in Push-Pull mode, delays can be emulated by introducing a small phase offset using the PHASE register.
Combining Push-Pull with Center-Aligned modes results in four PWM timebase cycles per PWM cycle.
High-Resolution PWM
- Clocking Features
- Frequency Scaling
- PWM Period Equations (SR and HR)
- PWM DC and PHASE Equations
- PWM DC and PHASE Limitations
- High Resolution Mode
- Data Registers in Standard Resolution
Clocking Features
The PWM has flexible clocking options to support a wide range of applications. The clock source options for the PWM are device-specific and include the system clock and one or more Phased-Locked Loops (PLLs). This allows the PWM speed to be independent of the CPU or other high-speed peripherals. For example, the CPU can be run at 100 MHz using the main Phased-Locked Loop, and the PWM can be run at 500 MHz using an auxiliary PLL.
If a PLL source is selected, it will automatically request the PLL to be enabled. You should verify the PLL lock before using the PWM output to ensure proper timing.
The main clock selection has four input options:
- Fcy (system clock)
- Clock generator 7
- FRC / POSC
- PLLn
- BFRC
Each of these has two additional clocking features, a simple up to 16 divider and a frequency scaling circuit.
The PWM clock multiplexer enables you to select one of the three PWM clock options for each PWM generator (PG), as shown in the following figure.
By default, there is no clock selected for power saving until the PWM generator is configured during initialization. When multiple PWM generators are used to create a complex or multiphase system, they should all use the same clock source. When operating in standard resolution mode, the clock input frequency can range from 1 to 500 MHz.
Frequency Scaling
Frequency scaling provides the ability to drop clocks to effectively stretch the period or duty cycle, and is useful for resonant power control applications that require a variable frequency control input.
The frequency scaling circuit performs modulo arithmetic where the Frequency Scale (FSCL) value is accumulated until the sum is larger than the Frequency Scaling Minimum Period Register (FSMINPER) register value. When the sum becomes larger than the Frequency Scaling Minimum Period Register (FSMINPER) register value, a clock pulse is produced, and the accumulated value is reduced by the value in the “FSMINPER” register.
Note that the frequency scaling signal is applied only to the PWM time base counter and does not affect the operation of the dead time or the Leading-Edge Blanking (LEB) counters.
PWM Period Equations (SR and HR)
In the most basic form, the PWM is a timer. Once a count is reached, an action takes place.
Let's consider the period equation in the most basic mode. Once the count is reached, the timer rolls over and starts the next PWM cycle. The period is simply the input clock divided by the value stored in the period register, plus one.
The PWM system has minimum period and duty cycle limitations to prevent runt pulses. In standard resolution, the minimum period value is 20 HEX, or 78 HEX in high resolution mode. Operating modes or output modes that utilize two counter cycles per PWM cycle have an additional factor of two applied. Similarly, using center-aligned in conjunction with push-pull output mode results in four counter cycles and a factor of four.
When using a common period for all PWM generators, MPER, the equations are the same as PWM generator x Period Register (PGxPER).
PWM DC and PHASE Equations
The equations for duty cycle, phase, trigger, and dead time are similar to the period. They are not dependent on operating or output modes.
Duty cycle is typically expressed as a percentage, so the equation includes the period value.
The remaining timers, phase, trigger, and dead time are specified in time units.
From these equations, the operation of the PWM can be configured and controlled.
PWM DC and PHASE Limitations
Similar to the period, there are restrictions on the minimum pulse width. This can be due to duty cycle, phase offset, dead time, or some combination of them. The minimum active pulse width is 16 counts. Similarly, there is the same restriction for minimum inactive pulse count, which is approaching 100% duty cycle.
High Resolution Mode
Each of the PWM generators may independently operate in High-Resolution mode to enhance phase, duty cycle, and dead-time resolution up to 78 picoseconds. High resolution mode is implemented using a fine edge placement scheme that time-divides the input clock into 16 additional edges. This is how 78 ps resolution is achieved with only an 800 Megahertz input.
When high resolution mode is enabled, the fine edge placement circuitry is inserted into the signal path within the output control functions.
Although the edge timing may be time-divided further, the rest of the PWM internal logic continues to operate at the input frequency. Events like EOC are still on a 2 ns time boundary.
For dsPIC33A devices, the PWM input frequency range in high resolution mode is 400 to 800 MHz. High-Resolution mode cannot be used with frequency scaling or the clock divider.
Data Registers in Standard Resolution
When operating in standard resolution mode, some data registers are handled the same as high resolution, except that the 4 LSBs are zero. This is the effective shift by 16x.
Register | Behavior |
---|---|
PGxLEB | 4 lsb are ‘0’ |
PGxDCA (duty cycle alternate) | 11:0 |
PGxTRIGy | 4 lsb are ‘0’ except in dual PWM mode |
PGxCAP | 4 lsb are read as ‘0’ |
Fault Handling and Override
- Fault Handling Priority Scheme
- Fault Handling in Multi-phase Systems
- Fault Handling: Clearing Latched Faults
- Software Override
- Software Override Application Example
Fault Handling Priority Scheme
The PWM implements Fault handling in hardware to minimize latency. As discussed earlier, each PWM has three PWM Control Input (PCI) blocks that can be used for output control. All three PCI blocks can be used concurrently for either fault handling, control loop applications, or both at the same time.
The PCI’s control on the outputs is mitigated with a priority scheme as shown, with the debugger having top priority and software overrides the lowest.
Each PCI has unique override states for both high and low PWM output pins. These data fields can be applied in the priority scheme if multiple PCI blocks are used.
Priority | Event | Data applied to pins |
---|---|---|
1 | Debugger halt | DBDAT[1:0] |
2 | Fault PCI (F) | FLTDAT[1:0] |
3 | Current limit PCI (CL) | CLDAT[1:0] |
4 | Feed forward PCI (FF) | FFDAT[1:0] |
5 | Software over-ride | OVRDAT[1:0] |
Fault Handling in Multi-phase Systems
When fault handling is needed for a multi-phase system, a single PCI block can be used to ensure synchronous behavior across all PWM generators. The PCI block in any PWM generator can be used to gate the other PWM generators. The PCI active signal is effectively broadcast to all the others, and each PWM generator can then choose to use the external signal instead of its own, of that same type.
In this example, we have a 3-phase system consisting of PG1, PG2, and PG3. If a fault is detected, all three PWMs should be shut down immediately. PWM generators 1 “PG1’s” PCI is used to control all three. PG2 and PG3 bypass their own PCI and instead use that of PG1. PG2 and PG3 enable the feature by setting PCI Bypass Enable (BPEN) bit and select PG1 through PCI Bypass Source Selection “BPSEL”.
Fault Handling: Clearing Latched Faults
When using latched fault modes, some considerations must be made regarding how to exit fault conditions. There are three main options:
- Do nothing
- Handle with software
- Automatically handle with hardware
In catastrophic failure cases, it may be appropriate to leave outputs shut down by PCI and allow software to then take action on PWM or other peripherals. Each PCI implements a software feature to control both the terminator and the terminator qualifier. This essentially bypasses the input signal and allows software control. You can then control the behavior in software. The interrupt associated with each PCI can be used for this purpose.
To clear latched faults automatically, the PWM hardware supports a wide range of applications with the terminator and the terminator qualifier input signals. These signals can be configured to achieve the desired logic.
Two additional features are available to simplify fault clearing: Auto-Terminate and Manual-Terminate.
Manual-Terminate allows software to control the terminator subsystem. It is performed on a write of ‘1’ to the Software Termination (SWTERM) bit.
Auto-Terminate asserts the terminator signal when the PCI source transitions from active to inactive. The termination qualifier still needs to be considered in this case. Auto-Terminate cannot be used with ‘Latched on any edge’ logic modes.
Let's consider some special cases in latched modes. It is important to note the difference on the PCI input for level and edge-triggered modes. Edge modes require a change in logic level to impact behavior. If the signal is static, it won’t detect its current state in subsequent cycles.
The PCI SR latches used for latched modes include control of set or reset dominate behavior. Reset dominate mode is needed to exit certain types of fault conditions where the PCI source stays active, or level mode is used.
For example, consider a control loop case using rising edge latched mode, and the PCI source remains high across the cycle boundary. It is possible to reset the latch, and although the PCI source is still high, it is not detected on the next cycle. This can result in a 100% duty cycle.
Software Override
The PWM also supports software-controlled override. Like the PCI, overrides force a state at the outputs and have independent data states for both high and low outputs.
Override is achieved by setting a ‘1' to the OVRENH and low bit locations. The state of the pins when overridden will be that of the value written to Data Override bits (OVRDAT[1:0]), unless it conflicts with restrictions imposed by the given output mode, such as complementary. These control bits are double-buffered for flexibility.
Although override is software-controlled, provisions for hardware-timed triggers and synchronization are also supported. These features are controlled with the OSYNC[1:0] bits. They specify when your override values are applied to the PWM outputs. Overrides can be applied at the following times:
- At the start of a new PWM cycle
- Immediately (or as soon as possible)
Like data updates, the PWM Buffer Update Mode Selection (UPDMOD) feature also supports synchronization of multiple PWM generators with a host/client relationship. The update bit or other data writes are used to trigger.
Software Override Application Example
This example shows the override of a six-step commutation of a three-phase motor. The control is divided into sectors where only two of the six outputs are active at any one time.
At each sector boundary, software controls the Output Override Enable (OVREN) high and low bits of all three PWM generators to effectively gate four of the six outputs to a low output state. For simplicity, the override control of only PWM generator 1 is shown and corresponds with the effective waveform below it. The duty cycle is used to control the power delivered to the motor.
Dead Time Generator
Dead-Time Use Case
The PWM supports a flexible dead time generation feature. Dead-time is used in complementary output mode to provide a time period where neither output is active at the same time. This prevents both output driver devices, typically Field Effect Transistor (FET) switches in a bridge, from conducting at the same time.
If Field Effect Transistor Q1 and Field Effect Transistor Q2 are on at the same time, excessive current will flow and damage the switches. Switch turn-on and turn-off times are non-instantaneous, so dead time is added and set to ensure that only one device is active.
Dead-time is achieved by holding off the assertion of the active state. For the PWMxH output, this will delay the rising edge, and for the PWMxL, the falling edge. This is illustrated as the time period between dashed lines. We see that the PWMx output edges are delayed compared to the raw PWM signal.
Dead-time is implemented with compare logic and dedicated data registers for both the high and low outputs. The duration is configured using the PWM generator x Dead-Time Register (PGxDT) registers that hold a pair of up to 14-bit values, Dead Time High (DTH) and Dead Time Low (DTL). They are applied independently to the PWMxH and PWMxL outputs, respectively. High and low side switches typically have different turn-on and turn-off times, so deadtime can be controlled independently.
The effective bit width of the DTH and DTL registers is dependent on High-Resolution mode. When in standard resolution, the upper three bits (13:11) are not used.
Dead-Time Equation in Standard Resolution
The equations for dead-time are dependent on whether the system is in standard or high-resolution mode. When in standard resolution, the upper three bits (13:11) are not used. This yields a max value of 0x07FF in Standard Resolution mode.
In this example, the PWM clock input is 800 MHz, and the desired dead time is 2 microseconds. This yields a register value of 1000 decimal.
Dead-Time Compensation
The PWM also supports a feature called dead-time compensation. It is used for Alternating Current (AC) motor applications to correct for crossover distortion in the current waveform when dead time is being applied. To help mitigate this, a different amount of duty cycle can be selectively applied to the system using the dead-time compensation feature.
When active, an additional amount of duty cycle will be added to the system. The feature is controlled with a PCI input for flexibility.
Dead-time compensation is enabled by writing a non-zero value to the PGxDCA register. By default, it will use the sync PCI block of the corresponding PWM generator. The Dead-Time Compensation Select DTCMPSEL allows use of the feed-forward PCI as an alternative if sync is needed for another purpose.
The dead-time compensation input signal from the PCI logic is sampled at the end of a PWM cycle for use in the next PWM cycle. The modification of the duty cycle duration via the PWM generator x Duty Cycle Adjustment Register “PGxDCA” occurs during the end (trailing edge) of the duty cycle.
In this example, we can see that although the PCI goes active in the first cycle, the additional duty cycle is applied in the next.
In High-Resolution mode, the three least significant bits “LSbs” of the PWM generator x Duty Cycle Adjustment Register “PGxDCA” are forced to ‘0’ to compensate for the 8x timing difference.
Special Features
- Event Selection
- Event Output
- Time Base Capture
- Linear Feedback Shift Register
- Combinatorial Logic
- Combinatorial Trigger
Event Selection
The Event Selection feature allows routing signals and information to other parts of the PWM, the CPU, or the outside world. It can also be a useful feature for debugging and code development.
Each PWM generator has an event selection block for interrupts, ADC triggers, and SOSC triggers. The feature is controlled with the PWM generator x Event Register PGxEVT registers.
The following figure illustrates the interrupt portion of the feature. An interrupt event selection mux can select different events as an interrupt source in addition to the PCI events. This allows flexible use of interrupt timing to support complex applications.
Event Output
The PWM System events and triggers can be routed outside the PWM generator using the Event Output feature. There are typically six instances of the event output feature, labeled A through F, that are shared across the PWM generator at the top level of the PWM.
Each Event Output can select an event from a specific PWM generator and route it to another PWM generator, another peripheral such as the PTG, a device pin, or generate an interrupt. The event output interrupts are in addition to the PWM interrupt discussed previously. This allows for complex interconnectivity of PWMs to one another or other peripherals. It is also useful for debugging, where a signal can be routed externally to a pin and monitored with an oscilloscope or logic analyzer.
The following figure depicts a single instance of an event output block. A signal from a specific PWM generator is selected through the muxes and then can be further conditioned by stretching, inversion, and synchronization.
Time Base Capture
The time base capture feature is used by software to determine where it is in the PWM cycle. This can be useful to schedule events like data updates or to measure timing between events.
The feature is provided as the PWM timer itself is not directly readable. When the timer value is needed, it may be captured and read via the PGxCAP register. There are two methods to capture a value, either manually with software or with hardware on a PCI event.
To manually capture the timer value, write a "1" to the PWM generator x Capture Register PGxCAP[0]. The Time Base Capture (CAP) status bit (PGxSTAT[5]) will be set to indicate the capture is complete, and then you may read the PGxCAP register.
Similarly, when a PCI block is used to capture a time-based event, a read operation is needed to reset the logic to allow a subsequent capture event.
It is recommended to read the time base capture status bit to verify it is set before reading PGxCAP. This is to avoid a read of the PGxCAP register at the same time as the PWM hardware is writing it. An alternative method is to schedule reads with an interrupt to avoid concurrent access.
Linear Feedback Shift Register
The Linear Feedback Shift Register (LFSR) implements a Fibonacci sequence. It is deterministic, implements 215 pseudo-random values, and can be used for dithering to reduce EMI peaks.
Combinatorial Logic
The combinatorial logic output feature can be used to generate control signals for synchronous rectification or other applications. Any two PWM generators can be used as inputs to a selectable logic function, and the output routed to a PWM output.
User control includes:
- PWM Input sources
- Input polarity
- Logic functions: AND, OR, and XOR
- Output destination
When assigned to a PWM output, the combinational logic function replaces the PWM signal that would normally be connected to that pin.
Combinatorial Trigger
The combinatorial trigger feature is used to generate complex triggering algorithms. The feature logically ORs the trigger outputs from up to eight PWM generators.
The trigger signals are those available in the PWM Generator Trigger Output Selection PGTRGSEL mux and include EOC and the three TRIGy timers. To use the feature, the corresponding PWM generator is enabled in the Combinational Trigger Register CMBTRIG register.
Common Pitfalls
- Data Updates
- Syncing Outside Group of Four PGs
- ON Bit Order
- Event Timing in HR Mode
- Using Re-triggerable Mode to Avoid Missing Cycles
Data Updates
Data updates are the most common pitfall in complex applications. After the ON bit is set, in order to change any buffered data value, the update request bit must be set. Just writing the SFR will not cause a change in PWM behavior.
Immediate updates should be avoided unless required by the application. This allows deterministic application of new data values and avoids issues like missing cycles that may occur rarely but are still problematic.
Even when using SOC updates, the write of the new value must be done such that it can be applied before EOC. The safest way is to write the new value right after SOC, which can be scheduled using the PWMx interrupt configured for SOC.
The update request bit must be set at least three CPU cycles, followed by three PGx_clk cycles, followed by another three CPU cycles, before the next PWM cycle boundary in order to take effect. Otherwise, the data update will be delayed until the following PWM cycle.
Often, the new data value is calculated asynchronously, perhaps after the ADC reading or on a timer interval. The SFR write should still be scheduled to ensure enough time for the CPU and PWM hardware to complete the data application cycle.
Another common pitfall with data updates is period updates. This inherently moves EOC, and depending on where in the cycle the update is performed, can cause missing or 100% DC pulses. For variable frequency systems that alter PER in a control loop, it is recommended to use the capture feature to obtain the counter value to determine if it is a safe time to write. Another method is to write at the SOC to give maximum margin.
Syncing Outside Group of Four PGs
The PWM system was designed to allow up to four PWM generators to have automatic synchronous operation. When more than four PWM generators need to be synchronized, or a PWM generator needs to be synchronized to another PG that is outside its group of four, the PCI block is used to do so.
For example, we can trigger PG5 from PG1. PG5's Sync PCI is used to trigger PG5, with PCI source select set to the PWM PCI Source Selection PWMPCI mux. The PWMPCI mux is set to select PWM1.
Alternatively, a PWM event can also be used. PWM Event A PWMEVTA can be configured to be PG1's SOC through the PWM generator Trigger Output Selection bits PGTRGSEL selection. PG1's PGTRGSEL is set to SOC, or one of the TRIGy timers if an offset is desired.
There is a delay associated with the synchronization when using TRIG timers, although it is deterministic and constant, so it can be mitigated with a phase offset of the source PWM.
For dual-core devices such as dsPIC33 "CH" devices, the PWMs from the main and secondary cores can be synchronized to one another. The PWM event signals are used for this, and the opposite core’s PWMEVTs are available via peripheral pin select. The client PWM PCI then selects the remappable pin as a trigger.
ON Bit Order
When synchronizing multiple PWMs, the primary or host PWM should be enabled last. This effectively holds off all the synchronized or client PWMs from starting the first cycle until the host is started.
Let’s consider the example where PWM2 through PWM8 are synchronized to PWM1. All eight PWMs are initialized, but none of the ON bits are set. Then PWM2 through PWM8 are enabled by setting their respective ON bits. They will not receive their start of cycle (SOC) trigger until PWM1 is activated. Lastly, PWM1s’ ON bit is set, and all eight start synchronously.
PG2CONLbits.ON = 1; // Enable module
PG3CONLbits.ON = 1; // Enable module
PG4CONLbits.ON = 1; // Enable module
PG5CONLbits.ON = 1; // Enable module
PG6CONLbits.ON = 1; // Enable module
PG7CONLbits.ON = 1; // Enable module
PG8CONLbits.ON = 1; // Enable module
PG1CONLbits.ON = 1; // Enable host last to start all at once
Event Timing in HR Mode
When operating in high resolution mode, only the PWM output edges are placed on the additional 8× resolution. All other events and timing remain on the input clock boundary, which is what the PWM internal logic is clocked on. Events like SOC, EOC, ADC triggers, and others may misalign to PWMx output edge events up to seven high-resolution clocks. This can be avoided by using period or duty cycle data values that have the last 3 lsb.
Using Re-triggerable Mode to Avoid Missing Cycles
The PWM, by default, will only accept one trigger per period. If a subsequent trigger comes in, it is ignored. For increased flexibility, the system includes a re-triggerable mode that will restart an active duty cycle on subsequent triggers.
This can be useful in different applications, including variable frequency systems where the period is changed as part of the control loop. The situation becomes more complicated in multiphase, variable frequency applications. Soft start is another example of a variable frequency operation where the frequency is ramped up from a startup condition.
In the case where the period is shortened, the next start of cycle trigger may occur during the current cycle. The trigger is ignored, and the active duty cycle of the next cycle will be missed. To mitigate this, the re-triggerable mode is enabled, and the next pulse is generated with the start of cycle trigger.