0
0
Embedded Cprogramming~15 mins

Input capture mode in Embedded C - Deep Dive

Choose your learning style9 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.