STM8L PWM 示例
#include "stm8l15x.h"
#define F_CPU 2000000 //系统时钟2MHz
//设置PWM频率和占空比 duty: 0~100 高电平百分比
void pwm_set_duty(uint16_t duty)
{
TIM2->CCR1H=duty>>8;
TIM2->CCR1L=duty;
}
//设置频率 frq为KHz为单位
uint16_t pwm_set_freq(uint16_t frq)
{
uint16_t tmp;
tmp=(uint16_t)(F_CPU/1000/frq);
TIM2->ARRH=tmp>>8;
TIM2->ARRL=tmp;
return tmp;
}
//初始化 frq为KHz为单位,返回设置占空比最大值,初始占空比为0
uint16_t pwm_init(uint16_t frq)
{
uint16_t ret;
CLK->PCKENR1 |= CLK_PCKENR1_TIM2; //tim2时钟允许
ret=pwm_set_freq(frq);
TIM2->PSCR = 0;//不分频
TIM2->CCR1H=0;
TIM2->CCR1L=0;
TIM2->CCMR1=(6<<4)|TIM_CCMR_OCxPE; //PWM模式1 预装载使能 通道1设置为输出
TIM2->CCER1=TIM_CCER1_CC1E;//通道1输出引脚连接,高电平有效
TIM2->BKR|=TIM_BKR_MOE;//主输出使能,此处与STM8S不同,需注意
TIM2->CR1 = TIM_CR1_ARPE|TIM_CR1_CEN;//向上计数,预装载,开始计数
return ret;
}
void pwm_uninit(void)
{
TIM2->CR1=0;//关闭定时器
CLK->PCKENR1 &= ~CLK_PCKENR1_TIM2; //tim2时钟关闭
}
|
|