This post talks about the PWM comparator of the STM32 series. This function is relatively simple to implement, so I won't go into details. Connecting the PWM output pin to the LED light can adjust the brightness. A typical application is the PWM breathing light. To output the PWM signal, you need to initialize the timer. Here I choose channel 2, channel 3, and channel 4 of timer 3, and the corresponding GPIO ports are PE4-PE6:
Connecting these three PWM output pins to the RGBLED light can achieve the breathing light changes of three colors alternating. Timer initialization function:
TIM_HandleTypeDef TIM3_Handler; TIM_OC_InitTypeDef TIM3_CHHandler; GPIO_InitTypeDef GPIO_InitStruct; void TIM3_PWM_Init(int arr,int psc) { __HAL_RCC_TIM3_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); GPIO_InitStruct.Pin=GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6; GPIO_InitStruct.Mode=GPIO_MODE_AF_PP; GPIO_InitStruct.Speed=GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate= GPIO_AF2_TIM3; HAL_GPIO_Init(GPIOE,&GPIO_InitStruct); TIM3_Handler.Instance=TIM3; TIM3_Handler.Init.Prescaler=psc;//Frequency division number TIM3_Handler.Init.CounterMode=TIM_COUNTERMODE_UP;//Up counting mode TIM3_Handler.Init.Period=arr;//Auto reload value TIM3_Handler.Init.ClockDivision=TIM_CLOCKDIVISION_DIV1; HAL_TIM_PWM_Init(&TIM3_Handler); TIM3_CHHandler.OCMode=TIM_OCMODE_PWM1; //Select PWM1 mode TIM3_CHHandler.Pulse=arr/2; //Set the comparison value to half of the reload value TIM3_CHHandler.OCPolarity=TIM_OCPOLARITY_LOW; //Output comparison polarity is low HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHHandler,TIM_CHANNEL_2); HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_2); HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHHandler,TIM_CHANNEL_3); HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_3); HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHHandler,TIM_CHANNEL_4); HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_4); }
This content is originally created by donatello1996, a user of EEWORLD forum. If you need to reprint or use it for commercial purposes, you must obtain the author's consent and indicate the source.