每次做板载的呼吸灯都觉的挺有意思的,似乎是一个永不褪色的主题。板子做的好,正好有一个led灯对应着定时器,及PB7对应着定时器4的通道2。 呼吸灯的原理基本就是在程序中不断的改变PWM占空比,使led呈现忽明忽暗的呼吸效果。 首先当然是初始化引脚: - GPIO_InitStruct.Pin = GPIO_PIN_7;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- GPIO_InitStruct.Alternate = GPIO_AF2_TIM4;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
复制代码
初始化定时器: - htim4.Instance = TIM4;
- htim4.Init.Prescaler = uhPrescalerValue;
- htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
- htim4.Init.Period = 1000-1;
- htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
- sConfigOC.OCMode = TIM_OCMODE_PWM1;
- sConfigOC.Pulse = 100;
- sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
- sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
-
- sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
- sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
- if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
- {
- Error_Handler();
- }
- // HAL_TIM_MspPostInit(&htim4);
- if (HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2) != HAL_OK)
- {
- /* PWM Generation Error */
- Error_Handler();
- }
复制代码
在程序中不断的修改占空比: - if(flag == 0)
- {
- Value+=5;
- HAL_Delay(20);
- PWM_Chang(Value);
- if(Value>=200)
- flag =1;
- }
复制代码
最后呢,就是效果了:
|