新手上路
- 积分
- 25
- 金钱
- 25
- 注册时间
- 2016-10-27
- 在线时间
- 4 小时
|
发表于 2016-10-13 15:27:24
|
显示全部楼层
我不用库函数模式,给你个TIM2的参考,希望能帮助到你
#define PWM_20K
void init_timer2(void)
{
TIM2_CR1 = 0;
TIM2_CCMR3 = 0b01010000; //通道3配置为PWM模式2,初始化强制为(L)
TIM2_CCER2 = 0b00000011; //通道3:低电平输出有效,信号输出到对应端口 0b00000011
//初始化自动装载寄存器,决定PWM方波的频率
//TIM2_ARR = fmaster/Fpwm
//2/0.250=8 16/0.250=64(0x40) 16/0.10=160(0xA0) 16/0.01=1600(0x640) 16/0.001=16000(0x3E80)
//16/1216(0x4C0)=0.013158 16/1067(0x42B)=0.014995 16/0.02=800(0x320) 16/0.05=320(0x140)
//16/0.01=1600(640) 16/(1/(3.5*20))=1120(0x460)
#ifdef PWM_100K
TIM2_ARRH = 0x00; //自动重载寄存器,160
TIM2_ARRL = 0xA0;
#define TIM2_CH3_PWM_DUTYS 16 //10%占空比值,赋占空比,可直接(TIM2_CH3_PWM_DUTYS*十分比),如:30%占空比=TIM2_CH3_PWM_DUTYS*3
#endif
#ifdef PWM_50K
TIM2_ARRH = 0x01; //自动重载寄存器,320
TIM2_ARRL = 0x40;
#define TIM2_CH3_PWM_DUTYS 32
#endif
#ifdef PWM_20K
TIM2_ARRH = 0x03; //自动重载寄存器,800
TIM2_ARRL = 0x20;
#define TIM2_CH3_PWM_DUTYS 80
#endif
#ifdef PWM_14K
TIM2_ARRH = 0x04; //自动重载寄存器,1120
TIM2_ARRL = 0x60;
#define TIM2_CH3_PWM_DUTYS 112
#endif
#ifdef PWM_10K
TIM2_ARRH = 0x06; //自动重载寄存器,1600
TIM2_ARRL = 0x40;
#define TIM2_CH3_PWM_DUTYS 160
#endif
//决定PWM方波的占空比
TIM2_CCR3H = TIM2_CCR3L = 0;
//设置分频系数
TIM2_PSCR = 0;
//TIM2_IER = 0b00000001; //允许更新使能中断,在每个频率周期中断,中断时间-50K:20us
CLK_PCKENR1 |= 0b00100000; //使能TIM2时钟,时钟在过程不能关闭,关闭必须重新初始化,否则不能启动
}
void Start_Timer2_CH3_PWM(void)
{
TIM2_CCR3H = (uchar)(iTimer2Ch3Duty>>8);
TIM2_CCR3L = (uchar)(iTimer2Ch3Duty);
TIM2_CCMR3 = 0b01111000; //通道3配置为PWM模式2 0b01111000
//TIM2_IER = 0b00000001; //允许更新使能中断,在每个频率周期中断
TIM2_CR1 = 0b10000001; //使能定时器
}
void Stop_Timer2_CH3_PWM(void)
{
TIM2_CCMR3 = 0b01010000; //通道3配置为PWM模式2,初始化强制为(L)
TIM2_IER = 0;
TIM2_CR1 = 0; //定时器
} |
|