This is my Third tutorial in this series of using Input capture to measure different things. I have already covered how to measure the pulse frequency and Pulse width separately using input capture, so today in this tutorial I am going to show you how to do it combined i.e. measure the frequency and duty cycle of a PWM input signal.
I will be using STM32F103C8 controller and SW4STM IDE, But the code should work in any other STM32 microcontroller too.
How it works
Let’s go to the explanation along the CubeMx setup. Take a look at the Clock setup below
As you can see above that APB1 TIM clock is at 72MHz. Also the TIM Clock is PCLK1 x 2. This is going to be useful in a while. Let’s see the TIMER Setup now
As shown on the picture above here is the setup:-
- Slave Mode -> RESET Mode
- Trigger Source -> TI2FP2
- Channel 2 -> Input Capture Rising EDGE
- Channel 3 -> Input Capture Falling EDGE
- Prescalar -> 0
- ARR -> 0xffff
NOTE THAT the Prescalar is 0 this time so the TIM Clock will be 72MHz and as the ARR value is 0xffff (65536), The minimum frequency that we can measure will be equal to ((72 MHz)/65536) = 1098 Hz.
Also Channel 2 is configured for the rising EDGE so it’s better if you connect the input PIN to the CHANNEL 2.
Some Insight into the CODE
Captures the first TIMESTAMP when the Rising edge is detected and stores it in the variable IC_Val1. This value corresponds to the “Time Period” of the pulse.
Captures the first TIMESTAMP when the Falling edge is detected and stores it in the variable IC_Val2. And (IC_Val2/IC_Val1) value corresponds to the “Duty Cycle” of the pulse.
Frequency can be calculated using the IC_Val1. Here (2* HAL_RCC_GetPCLK1Freq) is for the reason that the TIM2 CLOCK is 2x PCLK1.
YOU CAN DOWNLOAD FULL CODE AT THE END OF THIS POST