Bird
Raised Fist0
Embedded Cprogramming~15 mins

Input capture mode in Embedded C - Deep Dive

Choose your learning style10 modes available
Overview - Input capture mode
What is it?
Input capture mode is a feature in microcontrollers that records the exact time when an input signal changes. It uses hardware timers to measure the time of events like button presses or signal edges. This helps programmers know when something happened without constantly checking the input. It is often used in embedded systems to measure signal timing precisely.
Why it matters
Without input capture mode, programmers would have to guess or frequently check inputs, which wastes processing power and can miss fast events. Input capture mode solves this by automatically recording event times with hardware, making timing measurements accurate and efficient. This is crucial in real-time systems like motor control, communication protocols, or sensor reading where timing matters.
Where it fits
Before learning input capture mode, you should understand basic microcontroller timers and interrupts. After mastering input capture, you can explore output compare mode, pulse width modulation, and advanced timer features for controlling hardware precisely.
Mental Model
Core Idea
Input capture mode is like a stopwatch that automatically notes the exact moment a signal changes, using hardware timers to record event times precisely.
Think of it like...
Imagine you are watching a race and you have a stopwatch that starts running all the time. When a runner crosses a special line, the stopwatch automatically records the exact time without you pressing any button. Input capture mode works the same way for signals in a microcontroller.
┌─────────────────────────────┐
│       Input Signal           │
│  ──┐      ┌─────┐    ┌───    │
│    │      │     │    │      │
│    └──────┘     └────┘      │
├─────────────────────────────┤
│      Timer Counter           │
│  0 → 1 → 2 → 3 → 4 → 5 → 6 │
├─────────────────────────────┤
│ Input Capture Register (ICR)│
│  Records timer value at edge │
│  e.g. 2, 5                  │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding hardware timers basics
🤔
Concept: Learn what hardware timers are and how they count time in microcontrollers.
Hardware timers are special counters inside microcontrollers that increase at a fixed rate, like a clock. They count from zero upwards and can reset or overflow. Timers help measure time intervals without using the CPU constantly.
Result
You know that timers keep counting numbers automatically, which can be used to track time.
Understanding timers is essential because input capture mode depends on these timers to record event times accurately.
2
FoundationBasics of signal edges and events
🤔
Concept: Learn what signal edges are and why detecting them matters.
Signals in electronics change between low (0) and high (1). The change from low to high is called a rising edge, and from high to low is a falling edge. Detecting these edges helps know when an event happens, like a button press or sensor trigger.
Result
You can identify when a signal changes state, which is the event input capture mode records.
Knowing signal edges helps you understand what input capture mode is detecting and recording.
3
IntermediateHow input capture records timer values
🤔Before reading on: do you think input capture mode needs the CPU to read the timer, or does it record automatically? Commit to your answer.
Concept: Input capture mode automatically saves the timer count when a signal edge occurs.
When input capture mode is enabled, the hardware timer runs normally. When the input signal changes (rising or falling edge), the timer's current count is copied into a special register automatically by hardware. This means the CPU does not need to watch the input constantly.
Result
The exact timer value at the moment of the signal change is stored for later use.
Understanding that hardware does the recording automatically frees the CPU and ensures precise timing.
4
IntermediateConfiguring input capture for edge detection
🤔Before reading on: do you think input capture can detect both rising and falling edges at the same time? Commit to your answer.
Concept: Input capture can be set to detect rising edges, falling edges, or both, depending on configuration.
Microcontrollers allow you to configure input capture to trigger on rising edges, falling edges, or both. This lets you measure different types of events, like when a signal starts or ends. You set this by changing control registers before starting the timer.
Result
You can customize which signal changes cause the timer value to be recorded.
Knowing how to configure edge detection lets you tailor input capture to your specific timing needs.
5
IntermediateUsing interrupts with input capture
🤔Before reading on: do you think input capture mode alone notifies the CPU when an event happens, or do you need interrupts? Commit to your answer.
Concept: Input capture often works with interrupts to alert the CPU immediately when an event is recorded.
When input capture records a timer value, it can trigger an interrupt. This interrupt tells the CPU to run a special function to process the event, like reading the captured value or starting a new measurement. This makes event handling fast and efficient.
Result
The CPU responds quickly to input events without polling, improving performance.
Understanding interrupts with input capture helps build responsive embedded systems that react instantly to signals.
6
AdvancedMeasuring pulse width with input capture
🤔Before reading on: do you think measuring pulse width requires one or two input capture events? Commit to your answer.
Concept: Pulse width measurement uses two input capture events to find the duration of a signal being high or low.
To measure how long a signal stays high, input capture records the timer value at the rising edge and again at the falling edge. Subtracting these two values gives the pulse width. This technique is used in sensors, communication, and motor control.
Result
You can measure precise durations of signals automatically using input capture.
Knowing how to measure pulse width with input capture unlocks many practical embedded applications.
7
ExpertHandling timer overflows in input capture
🤔Before reading on: do you think input capture registers handle timer overflows automatically, or must the programmer manage them? Commit to your answer.
Concept: Input capture does not handle timer overflows automatically; programmers must manage them to get correct timing.
Timers have limited size and overflow back to zero after reaching their max count. If an input capture event happens after overflow, the raw captured value alone is not enough. Programmers use overflow interrupts and counters to track how many times the timer wrapped around, combining this with captured values to get full timing.
Result
You get accurate timing measurements even when events span multiple timer cycles.
Understanding overflow handling prevents subtle bugs in timing measurements and is critical for reliable embedded designs.
Under the Hood
Input capture mode uses dedicated hardware logic connected to a timer counter and an input pin. When the configured edge is detected on the input pin, the hardware copies the current timer count into a capture register instantly. This operation is atomic and does not require CPU intervention. The timer continues counting independently. If enabled, an interrupt is generated to notify the CPU. The CPU reads the capture register to get the event time. Overflow interrupts track timer wraparounds to extend timing range.
Why designed this way?
Input capture was designed to offload timing measurements from the CPU to hardware, enabling precise and low-latency event timing. Early microcontrollers lacked this feature, forcing software polling which was inefficient and error-prone. Hardware capture ensures no events are missed and timing is accurate to the timer clock. Alternatives like software polling were rejected due to CPU load and timing inaccuracies.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Input Signal  │──────▶│ Input Capture │──────▶│ Capture Reg   │
│ (Pin)         │       │ Hardware      │       │ (Stores Timer │
└───────────────┘       └───────────────┘       │ Value at Edge)│
                                                  └───────────────┘
       ▲
       │
┌───────────────┐
│ Timer Counter  │
│ (Counts time) │
└───────────────┘
       │
       ▼
┌───────────────┐
│ Interrupt     │
│ Controller    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does input capture mode require the CPU to constantly check the input pin? Commit to yes or no.
Common Belief:Input capture mode means the CPU must keep checking the input pin to record events.
Tap to reveal reality
Reality:Input capture mode uses hardware to automatically record timer values on signal edges without CPU polling.
Why it matters:Believing CPU polling is needed leads to inefficient code that wastes processing power and can miss fast events.
Quick: Can input capture detect multiple edges without resetting? Commit to yes or no.
Common Belief:Input capture can only record one event and then stops until reset.
Tap to reveal reality
Reality:Input capture hardware can record multiple events by triggering interrupts and reading capture registers repeatedly.
Why it matters:Thinking it records only once limits designs and causes confusion about how to handle multiple events.
Quick: Does input capture automatically handle timer overflows for long measurements? Commit to yes or no.
Common Belief:Input capture registers automatically adjust for timer overflows to give correct timing.
Tap to reveal reality
Reality:Programmers must track timer overflows separately to get accurate timing over long intervals.
Why it matters:Ignoring overflow handling causes incorrect timing results and bugs in applications measuring long durations.
Quick: Is input capture mode only useful for measuring pulse widths? Commit to yes or no.
Common Belief:Input capture mode is only for measuring how long a signal stays high or low.
Tap to reveal reality
Reality:Input capture is useful for any event timing, including frequency measurement, event timestamping, and communication protocols.
Why it matters:Limiting input capture to pulse width reduces its perceived usefulness and misses many applications.
Expert Zone
1
Input capture timing resolution depends on the timer clock frequency, so choosing the right timer prescaler is critical for accuracy.
2
Some microcontrollers support dual-edge capture, allowing measurement of both rising and falling edges without reconfiguration.
3
Input capture registers may be buffered or double-buffered to prevent data loss during rapid events, a detail often overlooked.
When NOT to use
Input capture mode is not suitable when event timing is not critical or when the microcontroller lacks hardware timers. In such cases, software polling or external timing ICs might be better. Also, for very high-frequency signals beyond timer capability, specialized hardware or logic analyzers are preferred.
Production Patterns
In real-world embedded systems, input capture is used for motor speed sensing by measuring encoder pulses, ultrasonic sensor distance measurement by timing echo pulses, and communication protocols like pulse-position modulation. It is combined with interrupts and DMA for efficient, low-latency event handling in production code.
Connections
Interrupt handling
Input capture mode often triggers interrupts to notify the CPU of events.
Understanding interrupts helps grasp how input capture events are processed immediately without polling.
Pulse width modulation (PWM)
Input capture measures pulse widths, while PWM generates pulses of specific widths.
Knowing input capture clarifies how PWM signals can be measured and analyzed in embedded systems.
Event timestamping in distributed systems
Both input capture and event timestamping record exact times of events for synchronization.
Recognizing this connection shows how precise timing is critical across fields from embedded hardware to networked systems.
Common Pitfalls
#1Ignoring timer overflow causes wrong timing calculations.
Wrong approach:uint16_t start = ICR1; // capture register uint16_t end = ICR1; // later capture uint16_t duration = end - start; // no overflow check
Correct approach:volatile uint32_t overflow_count = 0; // In overflow ISR: overflow_count++; uint32_t start = (overflow_count << 16) + start_ICR; uint32_t end = (overflow_count << 16) + end_ICR; uint32_t duration = end - start;
Root cause:Not accounting for timer wraparound leads to negative or incorrect duration values.
#2Configuring input capture for wrong edge causes missed events.
Wrong approach:Set input capture to detect only rising edges when signal events happen on falling edges.
Correct approach:Configure input capture to detect falling edges to match the actual signal transitions.
Root cause:Misunderstanding signal behavior leads to wrong edge selection and missed captures.
#3Reading capture register too late overwrites data.
Wrong approach:Ignoring interrupts and reading capture register only occasionally, missing rapid events.
Correct approach:Use input capture interrupt to read and store capture values immediately on event.
Root cause:Not handling interrupts promptly causes loss of captured events.
Key Takeaways
Input capture mode uses hardware timers to record the exact time of input signal changes automatically.
It frees the CPU from constant checking and ensures precise timing for real-time embedded applications.
Configuring edge detection and handling timer overflows are essential for accurate measurements.
Combining input capture with interrupts enables fast and efficient event processing.
Understanding input capture unlocks many practical uses like pulse width measurement, frequency counting, and event timestamping.

Practice

(1/5)
1. What is the main purpose of Input Capture Mode in embedded C timer modules?
easy
A. To record the timer value when a specific input event occurs
B. To generate PWM signals automatically
C. To reset the timer periodically
D. To output a fixed frequency signal

Solution

  1. Step 1: Understand Input Capture Mode function

    Input Capture Mode records the timer count when an input event (like a signal edge) happens.
  2. Step 2: Compare options with this function

    Only To record the timer value when a specific input event occurs describes recording the timer value on an input event, which matches the purpose.
  3. Final Answer:

    To record the timer value when a specific input event occurs -> Option A
  4. Quick Check:

    Input Capture = Record timer on event [OK]
Hint: Input Capture records timer on input events [OK]
Common Mistakes:
  • Confusing Input Capture with PWM generation
  • Thinking it resets the timer automatically
  • Assuming it outputs signals instead of capturing
2. Which of the following is the correct way to configure an input capture to trigger on a rising edge in embedded C?
easy
A. Clear the timer counter register
B. Set the capture edge select bit to 0
C. Set the capture edge select bit to 1
D. Enable the PWM output mode

Solution

  1. Step 1: Identify capture edge select bit meaning

    Usually, setting the capture edge select bit to 1 configures capture on rising edge; 0 is for falling edge.
  2. Step 2: Match options with rising edge setting

    Set the capture edge select bit to 1 sets the bit to 1, which is correct for rising edge trigger.
  3. Final Answer:

    Set the capture edge select bit to 1 -> Option C
  4. Quick Check:

    Edge select = 1 for rising edge [OK]
Hint: Rising edge capture usually means edge bit = 1 [OK]
Common Mistakes:
  • Confusing edge select bit values
  • Trying to clear timer instead of setting edge
  • Enabling unrelated PWM mode
3. Given this code snippet for input capture:
volatile uint16_t captured_value = 0;
void ISR_InputCapture() {
  captured_value = TIMER_CAPTURE_REG;
  CLEAR_CAPTURE_INTERRUPT_FLAG();
}

// Assume timer increments every 1us
// Input event occurs at 1500us
What will be the value of captured_value after the input event?
medium
A. 1500
B. 0
C. Timer overflow value
D. Undefined

Solution

  1. Step 1: Understand timer and capture behavior

    The timer increments every 1 microsecond, so at 1500us the timer count is 1500.
  2. Step 2: ISR captures timer value on input event

    The ISR stores the current timer count (1500) into captured_value.
  3. Final Answer:

    1500 -> Option A
  4. Quick Check:

    Timer count at event = captured value = 1500 [OK]
Hint: Captured value equals timer count at event time [OK]
Common Mistakes:
  • Assuming captured value resets to zero
  • Confusing overflow with current count
  • Ignoring ISR capture assignment
4. Identify the error in this input capture interrupt service routine:
void ISR_InputCapture() {
  uint16_t value = TIMER_CAPTURE_REG;
  process(value);
  CLEAR_CAPTURE_INTERRUPT_FLAG();
}
What is the main problem?
medium
A. The process function should not be called inside ISR
B. The interrupt flag is cleared before reading the capture register
C. The ISR does not enable the timer
D. The captured value is stored in a local variable and lost after ISR ends

Solution

  1. Step 1: Analyze variable scope in ISR

    The variable value is local to ISR and lost after ISR finishes.
  2. Step 2: Consider data usage outside ISR

    If the captured value is needed elsewhere, it should be stored in a global or volatile variable.
  3. Final Answer:

    The captured value is stored in a local variable and lost after ISR ends -> Option D
  4. Quick Check:

    Local variable in ISR = lost data [OK]
Hint: Store captured data in global variable, not local [OK]
Common Mistakes:
  • Clearing interrupt flag too early
  • Not enabling timer before capture
  • Avoiding function calls in ISR (not always wrong)
5. You want to measure the pulse width of a signal using input capture mode on a timer. Which approach correctly uses input capture to find the pulse width?
hard
A. Reset timer on every input event and read timer after fixed delay
B. Capture timer value on rising edge, then capture again on falling edge; subtract first from second
C. Capture timer value only on rising edges and multiply by 2
D. Use input capture only on falling edges and ignore rising edges

Solution

  1. Step 1: Understand pulse width measurement

    Pulse width is the time between rising and falling edges of a signal.
  2. Step 2: Use input capture on both edges

    Capture timer value at rising edge (start) and falling edge (end), then subtract to get pulse width.
  3. Final Answer:

    Capture timer value on rising edge, then capture again on falling edge; subtract first from second -> Option B
  4. Quick Check:

    Pulse width = falling edge time - rising edge time [OK]
Hint: Measure pulse by capturing rising and falling edges [OK]
Common Mistakes:
  • Capturing only one edge and guessing width
  • Resetting timer incorrectly
  • Ignoring one edge of the pulse
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard