引言
本篇博客将讲解PWM做呼吸灯的一个方法。
本篇博客将不会从TIM1设置做引入,而是从呼吸灯实际功能实现做引入。
STM8S105K4相关
已知的可以作为TIM1 PWM的输出通道为PC1、PC2、PC3、PC4。
已知可选的TIM1时钟为fmaster。
若使用的STM8S的芯片不为105K4,请查阅芯片相对应的文档,确认TIM1的PWM的输出通道,同时设置相应的选项字节。
呼吸灯功能需求设置
呼吸灯有这么两个最常见的功能需求:
- LED灯一次灭到亮的耗时T(s),即周期/2
- LED灯的刷新率P(Hz)
由这两个参数可得:
- LED灯一次灭到亮需要刷新的次数N,N = T × P
例如:
- LED灯一次灭到亮需求为1.5s
- LED灯的刷新率为60Hz(约每0.017s刷新一次)
- LED灯一次灭到亮需要刷新的次数为90次
至此,LED功能需求约定完成。
TIM1的PWM设置
由ST所提供的官方库中,有这么一个函数。
/**
* @brief Initializes the TIM1 Time Base Unit according to the specified parameters.
* @param TIM1_Prescaler specifies the Prescaler value.
* @param TIM1_CounterMode specifies the counter mode from @ref TIM1_CounterMode_TypeDef .
* @param TIM1_Period specifies the Period value.
* @param TIM1_RepetitionCounter specifies the Repetition counter value
* @retval None
*/
void TIM1_TimeBaseInit(uint16_t TIM1_Prescaler,
TIM1_CounterMode_TypeDef TIM1_CounterMode,
uint16_t TIM1_Period,
uint8_t TIM1_RepetitionCounter)
{
/* Check parameters */
assert_param(IS_TIM1_COUNTER_MODE_OK(TIM1_CounterMode));
/* Set the Autoreload value */
TIM1->ARRH = (uint8_t)(TIM1_Period >> 8);
TIM1->ARRL = (uint8_t)(TIM1_Period);
/* Set the Prescaler value */
TIM1->PSCRH = (uint8_t)(TIM1_Prescaler >> 8);
TIM1->PSCRL = (uint8_t)(TIM1_Prescaler);