STM32Cube learning (5) - PWM

1 Introduction

MCU: STM32F407ZGT6;
emulator: ST Link V2;
development environment: STM32CubeIDE 1.10.1;
function description: use the MCU timer to generate PWM to realize the breathing light effect.

Summary:
STM32Cube Learning (1) - Lighting & Configuration
STM32Cube Learning (2) - Timer Interrupt
STM32Cube Learning (3) - ADC
STM32Cube Learning (4) - UART Serial Port

Reference materials:
[STM32] HAL library STM32CubeMX tutorial seven - PWM output (breathing light)
STM32F4 data sheet

2. STM32CubeIDE configuration

Select the TIM14 channel and enable Channel1 as PWM (because the LED pin of the development board is this)
insert image description here

In the parameter settings, configure
the Counter Settings counter configuration as follows:
Prescaler (frequency divider) - 71
Counter Mode - Up
Counter Period - 499
auto-reload preload (automatic reload initial value) - enable
PWM Generation Channel 1:
Pulse (initial pulse) - 0
Output compare preload - enable
CH Polarity (channel polarity) - Low
insert image description here
The formula for calculating the PWM frequency is as follows
insert image description here
:
fpwmWorking frequency for pwm;
clkis the timer frequency72MHz
arris the counter value499
pscpre-assigned value71
The calculation shows that the PWM frequency is 2000Hz

The duty cycle is obtained by modifying CCR1, and the calculation formula is arr/CCR1, such as 50% duty cycle, that is, arr=499; CCR1=250;

3. Code

The following code refers to "Z small spin"

int main(void)
{
    
    
  /* USER CODE BEGIN 1 */
    uint16_t pwmVal=0;   //PWM占空比
    uint8_t dir=1;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM14_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_PWM_Start(&htim14,TIM_CHANNEL_1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    
    
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  if(pwmVal< 500)
	  {
    
    
	  		  pwmVal++;
	  		  __HAL_TIM_SetCompare(&htim14, TIM_CHANNEL_1, pwmVal);    //修改比较值,修改占空比
		  		  HAL_Delay(1);
	  }
	  if(pwmVal<=500)
	  {
    
    
	  		  pwmVal--;
	  		  __HAL_TIM_SetCompare(&htim14, TIM_CHANNEL_1, pwmVal);    //修改比较值,修改占空比
	 	  		HAL_Delay(1);
	  }
	  HAL_Delay(200);
  }
  /* USER CODE END 3 */
}

Guess you like

Origin blog.csdn.net/u014798590/article/details/126740168