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
| Mode | What It Produces | Typical Use |
|---|---|---|
| Up count | Period and compare events | Basic scheduling |
| Center aligned | Symmetric PWM pulses | Motor and inverter control |
| One shot | Single precise delay | Protocol timeouts |
| Input capture | Latched edge timestamps | Pulse width measurement |
| External clock | Counts external events | Event 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
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
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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