📟

STM32 Timer Series: PWM Input Mode

Jul 12, 2024

STM32 Timer Series: PWM Input Mode

Overview

  • Topic: PWM Input Mode on STM32 microcontrollers
  • Objective: Measure input frequency and duty cycle using PWM Input Mode
  • Tools Used: STM32F446RE, CubeIDE

Project Setup

Initial Setup

  1. Create Project: In CubeIDE for STM32F446RE
  2. Clock Configuration:
    • Use external crystal
    • Set crystal frequency (example: 8 MHz)
    • Choose HSE for external crystal, PCLK for PLL clock
    • Set controller frequency, e.g., 180 MHz

Timer Configuration

  • Timer 1: For PWM output (covered in previous video)
    • Example: Connected to PB2 clock at 180 MHz
    • Example Output Frequency: 100 kHz (with auto reload period of 1800)
  • Timer 2: For PWM input
    • Clock Source: Internal
    • Channel Configuration: Use Timer 2 Channel 1 for input clock (PA0 pin)
    • Parameters:
      • Prescaler: 0 (APB1 clock at 90 MHz)
      • Auto Reload: Maximum value (32-bit register)
      • Internal Clock Division: No Division (DTS clock same as internal clock)
      • Input Trigger: TI1FP1 (connected to capture 1 after filter and polarity)
      • Polarity: Rising Edge (for channel 1)
      • Input Capture: Direct (input signal directly to the channel)
      • Prescaler Division Ratio: Example - highest value for capturing every 8 events
      • Filter: Not used (sample frequency at DTS, internal clock)
      • Channel 2 Polarity: Falling Edge (indirectly connected to channel 1 to calculate duty cycle)

Code Implementation

Main Function

  • Start Timer in input capture mode for Channel 1
  • Start PWM for Timer 1
  • Set Capture Compare Register for duty cycle
  • Interrupt Handling: Use callback function for capturing and calculating frequency and duty cycle

Callback Function

  • Trigger Check: Ensure interrupt was triggered by Channel 1 (rising edge)
  • Read Capture Values: For both Channel 1 (rising edge) and Channel 2 (falling edge)
  • Calculation:
    • Frequency: Based on Timer 2 clock (e.g., 90 MHz)
    • Duty Cycle: Pulse high time as percentage of total time

Testing & Results

Testing Steps

  1. Initial Test: Example - 100 kHz frequency, 50% duty cycle
  2. Higher Frequencies:
    • Example: 400 kHz frequency, 50% duty cycle
    • Example: 1 MHz, 2 MHz, 3 MHz with varying duty cycles

Observations

  • Interrupts at High Frequencies: Limitations noted at higher frequencies (e.g., > 1 MHz)
  • Suggestions: Keep measurements below 1 MHz for optimal performance

Advanced Method

  • High Frequency Measurement: Potential up to 18 MHz with different method
  • Future Video: Issues with CubeMX settings for advanced method

Conclusion

  • Download Code: Link in description
  • Comments & Queries: Encouraged from viewers
  • Next Steps: Future video on advanced high frequency measurement method