🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Timers, PWM Generation, and Capture-Compare Units

Embedded SystemsTimers and PWMđŸŸĸ Free Lesson

Timers, PWM Generation, and Capture-Compare Units

What You'll Learn

  • 1Configure prescalers and timer modes
  • 2Generate PWM with correct frequency and duty
  • 3Measure pulses with input capture
  • 4Build software timers on hardware ticks

Timers are the metronome of an embedded system. They schedule RTOS ticks, generate pulse width modulation for motors and LEDs, measure external pulse widths, and time protocol bit periods. A timer counts a clock divided by a prescaler, and compare channels match that count against programmed values. Understanding resolution, rollover, and trigger sources is essential for both control loops and accurate timekeeping.

Counting Modes and Prescaling

Counters may run up, down, or up and down for center aligned PWM that reduces harmonic content. The prescaler divides the peripheral clock to reach the desired tick, and the auto reload value sets the period. Together they determine resolution: a 16 bit counter at one megahertz gives sixty five milliseconds of range with microsecond steps.

Free running timers with extended software counters handle long durations, while one shot modes create precise delays. Overflow interrupts provide a time base when the counter itself is too short for the required span.

PWM Generation and Output Compare

A compare channel drives an output high when the count matches one value and low at another, producing a duty cycle equal to compare value over reload value. Edge aligned PWM is simple; center aligned PWM halves current ripple in motor drives by symmetrical pulses. Complementary outputs with dead time protect half bridge stages from shoot through.

Resolution limits matter: sixteen bits of reload gives about zero point zero zero one five percent duty steps at best, and lower reload values reduce it further. Filter and blanking settings around compare events avoid glitches from noise on trigger paths.

Input Capture and Time Base Usage

Input capture latches the counter value on an edge, letting software compute pulse width and period from successive latches. Combined with a known timer clock, this measures remote control signals, ultrasonic distance sensors, and tachometer feedback precisely.

For timekeeping, a slow prescaled timer with overflow counting gives a monotonic clock. Beware reading a counter and its overflow flag in the wrong order, which can stall the clock for one full period near rollover.

Timer Modes and Typical Uses

ModeWhat It ProducesTypical Use
Up countPeriod and compare eventsBasic scheduling
Center alignedSymmetric PWM pulsesMotor and inverter control
One shotSingle precise delayProtocol timeouts
Input captureLatched edge timestampsPulse width measurement
External clockCounts external eventsEvent tally and tachometers

Real-World Examples

  • Motor PWM at 20 kilohertz — A center aligned timer with dead time drives a three phase bridge above the audible band.
  • LED dimming channel — Eight bit duty control with a period long enough to avoid visible flicker and camera banding.
  • Ultrasonic distance sensor — Capture records echo start and stop so software converts the difference into centimeters.
  • RTOS tick source — A prescaled timer interrupts at one kilohertz to drive scheduling and software timers.

💡Check Rollover on Every Capture

Read overflow state before and after latching the counter, or long measurements will silently gain or lose one full period.

Common Mistakes

Choosing prescaler and reload by guess

Fix: Period equals prescaler times reload over timer clock; compute it and verify with a scope.

Ignoring dead time in bridges

Fix: High side and low side switches can overlap and short the supply during transitions.

Reading timers non atomically

Fix: Multi byte counter reads can tear when an update interrupt lands mid read.

Key Takeaways

  • Prescaler and auto reload together set timer period and resolution.
  • Center aligned PWM with dead time suits power stages.
  • Input capture turns edges into precise time measurements.
  • Atomic reads and rollover handling keep timekeeping correct.

Frequently Asked Questions

Why does my PWM frequency shift when I change duty?

Some implementations reload the period immediately rather than at rollover, so use shadow registers or manual update events.

How accurate is input capture?

Resolution equals one timer clock tick; with a ten megahertz timer clock that is one hundred nanoseconds per step.

Can timers run while the CPU sleeps?

Yes, on many parts a low power timer keeps running from a slow clock to wake the device on schedule.

Interview Questions

Q1: How do you generate a 20 kilohertz motor PWM from a 84 megahertz clock?

Divide with a prescaler and set auto reload so prescaler times reload equals clock over frequency, choosing center aligned mode for clean pulses.

Q2: Explain dead time and why it matters.

A short delay inserted between high side turn off and low side turn on prevents shoot through current that would destroy the bridge.


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Embedded Systems Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement