STM32 Input Capture Mode Explained

In the previous article, STM32 PWM Mode Explained, the compare register decided when an output pin changed its level. This is used by the timer to produce a PWM signal. Input capture works in the opposite direction, because the timer now records a signal that comes from the outside. When a selected edge arrives at a timer input pin, the hardware copies the current counter value into the capture/compare register, and the program receives an exact timestamp of that edge without any software delay.

In this article, we will first look at what input capture is and how it differs from calculating a frequency directly. Then we will follow the signal through the input channel, the edge detector, the counter, and the capture register. After that, we will read the captured values with the HAL library, handle counter wraparound, and measure the period of a real signal.

The examples in this article use the NUCLEO-F446RE board, with the same clock setup as in the previous articles, so the APB1 timer clock is 90 MHz. TIM3 generates a test signal of 1 kHz on pin PA6, and TIM2 captures this signal on pin PA0 through a single jumper wire, so the example needs no external instruments. Other STM32 families work in a similar way, but timer names, pin assignments, and counter widths can differ. This article is part of the STM32 timer tutorial series.

What Is Input Capture

A timer counts clock ticks at a fixed, known rate, so its counter value always shows how much time has passed since the timer started. Input capture reads this counter at the moment an external event occurs and keeps the value as a time record of that event. When the selected edge of the input signal arrives, the timer copies the current value of the counter CNT into the capture/compare register CCR of that channel, and this happens in hardware within a single clock tick. The value in the CCR is therefore a timestamp, which tells us at which counter value the edge occurred.

The word capture is important here, because the timer does not measure anything on its own. It does not calculate a period, a frequency, or a pulse width, and it only stores one number for every edge that it sees. The measurement is made by the program, which reads two timestamps, subtracts the older one from the newer one, and converts the difference from timer ticks into time.

Timing diagram of an input signal and a free-running counter, with three rising edges captured as values C1, C2, and C3

Why Not Use a GPIO Interrupt

A GPIO interrupt, as described in GPIO Interrupts and EXTI, can also react to an edge, and the program could read a running timer inside the handler. The result would then depend on the interrupt latency, which changes when another interrupt is active or when the CPU is busy. In input capture, the hardware latches the counter at the moment of the edge, so the timestamp stays exact even when the interrupt handler starts a few microseconds later. The only requirement is that the program reads the value before the next capture replaces it.


How Input Capture Works

Input capture uses the same counter, prescaler, and auto-reload register that we described in the STM32 Timer Prescaler, Counter and ARR Explained article. Although, it gives the capture/compare register of a channel a different role. In PWM mode, the CCR is an input of the comparator, whereas in input capture mode, it is a register that the hardware fills. The channel pin is now an input, and the diagram below shows the path that the signal takes from the pin to the register.

Block diagram of an STM32 input capture channel from the input pin through the filter, edge detector, and prescaler to CCR1

Input Channel and Edge Detector

The signal enters through a timer channel pin, which must be configured for the matching alternate function, as described in GPIO Alternate Functions Pins. The first block after the pin is a digital input filter, which accepts a new level only after it has been stable for a number of consecutive samples. A larger filter value removes shorter glitches, but it also limits the highest signal frequency that the channel can follow.

The edge detector then decides which transition counts as an event. It can react to rising edges, to falling edges, or on some timers to both.

Behind the detector sits a capture prescaler, which can ignore edges and capture only every second, fourth, or eighth one. This is useful for fast signals, because it lowers the number of captures that the program has to handle while the signal itself stays unchanged.


Capture Flag, Interrupt, and DMA

Every capture sets the capture flag of the channel, which is called CC1IF for channel 1. If the channel interrupt is enabled, the flag also raises an interrupt request, and the program reads the new value from the CCR inside the handler. As an alternative, the channel can send a DMA request, so that the DMA controller copies each captured value into a memory buffer and the CPU is not involved for every edge. The flag clears when the program reads the CCR or when the HAL interrupt handler clears it.

When a new capture arrives while the previous flag is still set, the old value has not been read in time. The hardware then sets the overcapture flag (CC1OF) and replaces the stored value with the newer one. This flag does not stop anything, but it tells us that at least one timestamp was lost.


Rising and Falling Edge Capture

The polarity setting selects the edge that triggers the capture. With rising-edge polarity, the timestamp is taken when the signal changes from low to high, and with falling-edge polarity, it is taken when the signal changes from high to low. Two successive captures of the same polarity are separated by exactly one period, so they are the basis of period and frequency measurements. A rising edge followed by a falling edge gives the high time of the pulse instead, and the program can switch between the two polarities at run time with the macro __HAL_TIM_SET_CAPTUREPOLARITY(). A second channel in indirect mode can also capture the opposite edge of the same pin, which is possible on timers that have at least two channels.


Input Capture in CubeMX

In this section, we will configure TIM2 in STM32CubeMX so that it captures rising edges on pin PA0 with a counter clock of 1 MHz. If you are not yet familiar with STM32CubeMX, the article STM32CubeMX Explained describes it in detail.

Select the Timer Channel and Pin

Open Pinout & Configuration, and select TIM2. Set Clock Source to Internal Clock, and then set Channel1 to Input Capture direct mode. The word direct means that the channel uses its own pin as the signal source. On the STM32F446, TIM2 is a 32-bit timer, which gives the counter a very large range.

CubeMX assigns the channel to a pin when the mode is selected, and the pin list of TIM2_CH1 contains PA0, PA5, and PA15. We use PA0 because PA5 is connected to the LED LD2 on the board, and PA0 is available on the Arduino connector as A0. The pin works as alternate function AF1 for TIM2.

STM32CubeMX pinout with TIM2 Channel1 set to Input Capture direct mode on pin PA0

Set the Counter Clock

Next, open the Parameter Settings of TIM2. The counter should run at 1 MHz, so each tick lasts 1 ยตs and the values are easy to read. With an APB1 timer clock of 90 MHz, a prescaler value of 89 divides the clock by 90, as we calculated in the previous articles. The counter period is set to the largest possible 32-bit value, so the counter runs through its full range before it wraps around.

ParameterValueReason
Prescaler (PSC โ€“ 16 bits value)89Divides 90 MHz by 90 to give a 1 MHz counter clock
Counter ModeUpThe counter runs from 0 to ARR
Counter Period (AutoReload Register โ€“ 32 bits value)4294967295The full 32-bit range, so wraparound happens only after about 71.6 minutes
auto-reload preloadDisableThe period stays constant in this example
TIM2 parameter settings in CubeMX with prescaler 89 and a 32-bit counter period for a 1 MHz capture clock

Set Polarity, Prescaler, and Filter

The Input Capture Channel 1 group in the same tab holds the settings of the edge detector and the filter. We use the values below, which capture every rising edge without any filtering.

ParameterValueReason
Polarity SelectionRising EdgeThe timestamp is taken when the signal goes from low to high
IC SelectionDirectThe channel uses its own pin as input
Prescaler Division RatioNo divisionEvery edge is captured
Input Filter (4 bits value)0No filtering, because the test signal is clean

For a real signal, a small filter value is often useful, and the pull resistor of the pin can be set in the GPIO Settings tab. The article GPIO Pull-Up and Pull-Down Resistors explains when a pull-up is needed, for example when the signal source is an open-drain output or a mechanical contact.


Enable the Interrupt

Open the NVIC Settings tab of TIM2 and enable TIM2 global interrupt. Without this setting, the capture flag is set but the CPU never runs the callback, which is the same behavior that we saw for the update interrupt in STM32 Timer Interrupts Explained. After the code is generated, the function MX_TIM2_Init() contains the settings below.

As with the earlier timer modes, the generated code prepares the peripheral but does not start it, so the capture stays idle until we add the start call ourselves.

CubeMX NVIC settings with the TIM2 global interrupt enabled for input capture

Read Input Capture Values with HAL

The configuration is complete, so the program only has to start the channel and handle the captured values. The HAL library offers one start function for each way of collecting the data, and it reports each capture through a callback.

Start the Capture

The function HAL_TIM_IC_Start_IT() starts the counter, enables the capture on the selected channel, and enables the channel interrupt. It takes the timer handle and the channel as arguments.

Two related functions cover the other collection methods. HAL_TIM_IC_Start() starts the capture without an interrupt, so the program has to poll the capture flag, and HAL_TIM_IC_Start_DMA() lets the DMA controller store the captured values in a buffer. The matching stop functions end the capture again.


Read the Timestamp in the Callback

When a capture occurs, the interrupt handler TIM2_IRQHandler() calls HAL_TIM_IRQHandler(), which clears the flag and then calls the function HAL_TIM_IC_CaptureCallback(). The HAL library defines this function as a weak function, so we can write our own version in the user code section of main.c. The callback is shared by all timers and channels, and therefore it first checks which timer and which channel produced the event.

The function HAL_TIM_ReadCapturedValue() returns the current content of the CCR of the chosen channel. As in the previous interrupt article, the callback should stay short, so it stores the value and leaves the longer calculations to the main loop.


Store the Timestamps

A period needs two timestamps, so the program keeps the previous value in a variable and subtracts it from the new one in each callback. The first capture after the start has no previous value, so a flag marks whether the stored value is valid. Variables that the callback changes and the main loop reads must be declared volatile, otherwise the compiler may keep an old copy in a register.


Handle Counter Wraparound

The counter does not stop when it reaches its maximum value, and it continues from 0. Two timestamps can therefore lie on different sides of this wrap, and the newer value is then smaller than the older one. The diagram below shows a 16-bit counter with a previous capture at 65000 and a new capture at 464, which are 1000 ticks apart.

Counter wraparound on a 16-bit timer between a capture at 65000 and the next capture at 464, a distance of 1000 ticks

The solution is to use unsigned arithmetic. If both timestamps are stored in unsigned variables that match the counter width, and the counter period is set to the full range, the subtraction (new โˆ’ old) returns the correct number of ticks even when the counter has wrapped between the two captures. This works because the result of the subtraction wraps around in the same way as the counter itself. In the diagram, 464 โˆ’ 65000 gives 1000 in 16-bit arithmetic, which is the real distance between the two captures.

When the auto-reload value is smaller than the full range, the wrap happens at ARR instead, and the difference must be corrected explicitly. The expression below covers both cases, because for a full-range 32-bit counter the sum arr + 1U wraps to 0 and the result is still correct.

The counter width decides how long an interval can be before the result becomes ambiguous. A 32-bit counter at 1 MHz wraps after about 71.6 minutes, whereas a 16-bit counter at the same clock wraps after only 65.536 ms. This method assumes that the true interval between two captures is shorter than one full counter cycle. For longer intervals on a 16-bit timer, the program must either use a larger prescaler or count the overflows with the update interrupt from STM32 Timer Interrupts Explained.


Measure Signal Period with Input Capture

We can now combine the steps in a working example. TIM3 produces a PWM signal on one pin, the signal is passed to the input pin of TIM2, and the program captures two successive rising edges and calculates the period. Because the source is a second timer on the same board, the expected result is known exactly, which makes the example a good check of the whole setup.

Wiring and Requirements

The table below lists everything that the example needs. Both pins belong to the same microcontroller and use 3.3 V logic, so no level shifting and no extra ground connection are required.

ItemSetting
BoardNUCLEO-F446RE
Signal sourceTIM3 channel 1 on PA6 (Arduino connector pin D12), alternate function AF2
Capture inputTIM2 channel 1 on PA0 (Arduino connector pin A0), alternate function AF1
ConnectionOne jumper wire from PA6 to PA0
Logic level3.3 V on both pins
Test signal1 kHz with a duty cycle of 25%

The pins of this example are specific to the STM32F446 and the NUCLEO-F446RE. On another device, you have to find a pin for each timer channel in the alternate function table of the datasheet, and you should confirm the Arduino connector labels in the user manual of your board.

NUCLEO-F446RE wiring with a jumper wire from PA6 (TIM3 PWM output) to PA0 (TIM2 input capture)

Generate the Test Signal

TIM3 is configured as in STM32 PWM Mode Explained, with Channel1 set to PWM Generation CH1 and pin PA6 as TIM3_CH1. The values in the table below give a period of 1000 ticks of 1 ยตs each, which is a frequency of 1 kHz.

ParameterValueReason
Prescaler (PSC โ€“ 16 bits value)89A 1 MHz counter clock
Counter Period (AutoReload Register โ€“ 16 bits value)999A period of 1000 ticks, which is 1 ms
ModePWM mode 1The output is active while CNT is lower than CCR
Pulse (16 bits value)250A duty cycle of 25%
CH PolarityHighAn active channel drives the pin high
TIM3 parameter settings in CubeMX for a 1 kHz PWM test signal with prescaler 89, period 999, and pulse 250

The duty cycle has no influence on the period measurement, because the program uses only the rising edges. The signal is started with a single call in the user code section.


Capture and Calculate

The conversion from ticks to time follows from the counter clock. One tick lasts (PSC + 1) / f_timer seconds, so the period in seconds is the tick difference multiplied by this value.

T = ticks ร— (PSC + 1) / f_timer

With PSC = 89 and f_timer = 90 MHz, one tick lasts 1 ยตs, and the tick difference equals the period in microseconds. The code below defines the counter clock once, so the conversion stays correct when the prescaler is changed in CubeMX, as long as the constant is updated as well.

The callback stores the timestamp, subtracts the previous one with unsigned arithmetic, and signals the main loop that a new period is available.

The main function starts both timers, and the main loop converts the tick count whenever a new value is ready.


Check the Result

Build the project, start a debug session, and add the variables ic_period_ticks, period_us, and frequency_hz to the Live Expressions view of STM32CubeIDE. With the jumper wire in place, ic_period_ticks should show 1000, period_us should show 1000, and frequency_hz should show 1000. Both timers run from the same clock, so the value should stay stable, whereas a signal from an external generator would show a small variation of one or two ticks from capture to capture.

To confirm that the measurement follows the source, change the TIM3 period to 1999 and run the program again. The captured tick count then becomes 2000, the period becomes 2000 ยตs, and the frequency becomes 500 Hz. When the jumper wire is removed, the captured values stop updating, which shows that the measurement depends on the physical connection.

STM32CubeIDE Live Expressions showing a captured period of 1000 ticks, 1000 ยตs, and a frequency of 1000 Hz

Calculate Frequency from Period

The frequency of a periodic signal is the inverse of its period, which is f = 1 / T. When the period is available as a tick count, the frequency follows directly from the counter clock, so f = f_counter / ticks, where f_counter is f_timer / (PSC + 1). In the example, 1 000 000 / 1000 gives 1000 Hz. The capture hardware only provides the timestamps, and the division is a normal calculation in the program, which is why the main example stays focused on the capture itself.

The accuracy of this result depends on the number of ticks in one period. A measurement can be off by about one tick, because the edge falls between two counter clock edges, so a larger tick count gives a smaller relative error. The table below shows how this error grows with the signal frequency for two prescaler choices.

Signal frequencyTicks at 1 MHzError of one tickTicks at 90 MHzError of one tick
1 kHz10000.1%900000.001%
10 kHz1001%90000.011%
100 kHz1010%9000.11%

For fast signals, a smaller prescaler therefore gives a better result. With PSC = 0, a 32-bit counter still wraps only after about 47.7 seconds, so periods of up to this length can be measured without extra handling. For slow signals, the opposite choice is better, because a larger prescaler keeps the tick count inside the counter range. The program can also average several successive periods to reduce the effect of the single-tick error.


Common Input Capture Problems

Most input capture problems come from the pin setup, the polarity, the interrupt configuration, or the counter range. Because the capture happens in hardware, a wrong setting usually produces no value at all instead of a value that is slightly wrong.

Wrong Input Pin or Alternate Function

The timer can only capture a signal that reaches its channel input, and the pin must be configured for the matching alternate function. If the jumper wire is connected to a different pin than the one that CubeMX assigned, or if another peripheral uses the same pin, the capture value never changes. The fix is to compare the pin label in the Pinout view with the physical connection and with the alternate function table of the datasheet.


Incorrect Edge Polarity

A rising-edge setting on a signal that is normally high and goes low only briefly produces timestamps at the end of each low pulse, which can look like a wrong result. The captured period is still correct, but a pulse width measurement gives the wrong portion of the signal. When the polarity is wrong for the intended measurement, the polarity setting in CubeMX or the macro __HAL_TIM_SET_CAPTUREPOLARITY() has to be changed.


Callback Not Running or Capture Overrun

When the callback never runs, the usual cause is a missing interrupt setting. The TIM2 global interrupt must be enabled in the NVIC, and the program must start the channel with HAL_TIM_IC_Start_IT() instead of HAL_TIM_IC_Start(). The name of the callback must also match the HAL definition exactly, since a misspelled function is simply never called.

When the callback runs but some edges are missing, the program is probably too slow for the signal. In this case, the overcapture flag CC1OF is set, and the program can check it with __HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1OF) and clear it with __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1OF). The remedies are a shorter callback, a capture prescaler that skips edges, or the DMA transfer.


Counter Overflow Not Accounted For

A period that suddenly shows a wrong value only once in a while usually points to a wrap of the counter that the calculation did not handle. This happens when the subtraction is made with signed variables, with variables narrower than the counter, or when the time between two captures is longer than a full counter cycle on a 16-bit timer. Using unsigned variables of the full counter width and a prescaler that matches the signal solves most of these cases.


Signal Voltage Level and Noise

The input pin works with the logic levels of the microcontroller, which are 3.3 V on this board. A signal with a higher amplitude can damage the pin unless the pin is marked as five-volt tolerant in the datasheet, and a signal with a lower amplitude may never cross the input threshold. Voltages above the supply or below ground should be handled with a voltage divider, a level shifter, or a protection circuit before they reach the pin. Noise on the line creates extra edges, which show up as captures with very short periods, and the input filter of the channel, a shorter wire, and a common ground between the signal source and the board reduce this effect. A floating input also picks up noise, so a pull resistor is advisable when the source can leave the line undriven.


Conclusion

Input capture lets a timer record the exact counter value at the moment of an input edge. The edge detector, the optional filter, and the capture prescaler decide which edges count, and the hardware copies the counter into the CCR without any help from the CPU. The program then turns the timestamps into a measurement, so the period is the difference of two successive captures of the same polarity, and the frequency is the inverse of this period.

The most important points are to choose a counter clock that gives enough ticks per period, to use unsigned arithmetic for the subtraction so that wraparound is handled, and to remember that the callback only runs when both the timer interrupt and the NVIC are enabled. The same timestamps can also give pulse widths and duty cycles when the polarity is switched between rising and falling edges. In the next articles of the timer series, we will continue with other timer modes that build on the same counter and channel logic.


Download the Project Here

Download the CubeMX project files and HAL source code โ€” all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

What to Read Next

Article by Yashmiti

Yashmiti is a technical writer at STM32Guide, where she creates tutorials and guides that help embedded-systems learners and developers work confidently with STM32 microcontrollers. Her writing covers tools like STM32CubeIDE and STM32CubeMX, along with peripherals and communication protocols โ€” always with an emphasis on clear explanations and hands-on examples that take readers from concept to working project.

She's also part of the effort to build STM32Guide into an organized, easy-to-navigate resource for the STM32 community.

Leave a Comment