Description

100%
100%

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

Clock Setup

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

TIM Setup

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

IC_Val1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);

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.

IC_Val2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3);

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.

Duty_Cycle = (IC_Val2*100/IC_Val1);
Frequency = (2*HAL_RCC_GetPCLK1Freq()/IC_Val1);

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

100%
100%

Result

100%
100%
Check out the VIDEO Below
100%
100%

DOWNLOAD

100%
100%

You can buy me a coffee sensor ūüôā

Or just Download the code below

100%
100%
5 1 vote
Article Rating
Subscribe
Notify of
guest
4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Menu
4
0
Would love your thoughts, please comment.x
()
x