//PWM初始化
void Driver_PWMON(u8 ch,u8 Num)
{
//开TIM1时钟
CLK->PCKENR1 |= CLK_PCKENR1_TIM1;
//设置PWM频率,Fpwm=Fmaster/TIM2_ARR
//这里Fpwm = 2000000/100 = 20K
TIM1->ARRH = 0;
TIM1->ARRL = 100;
//启动计数,开始PWM输出
TIM1->BKR |= TIM1_BKR_MOE;
switch(ch)
{
case 1:
TIM1->CCMR1 |= 0x70;//设置TIM1_CH1为PWM模式2 有效电平为高电平
pwm_ch_on(1);//开启TIM1_CH1 通道输出
TIM1->CCR1H = 0;//初始化PWM通道占空比 1:1
TIM1->CCR1L = Num;
break;
case 2:
TIM1->CCMR2 |= 0x70;//设置TIM1_CH2为PWM模式2 有效电平为高电平
pwm_ch_on(2);//开启TIM1_CH1 通道输出
TIM1->CCR2H = 0;//初始化PWM通道占空比 1:1
TIM1->CCR2L = Num;
break;
case 3:
TIM1->CCMR3 |= 0x70;//设置TIM1_CH3为PWM模式2 有效电平为高电平
pwm_ch_on(3);//开启TIM1_CH1 通道输出
TIM1->CCR3H = 0;//初始化PWM通道占空比 1:1
TIM1->CCR3L = Num;
break;
case 4:
TIM1->CCMR4 |= 0x70;//设置TIM1_CH4为PWM模式2 有效电平为高电平
pwm_ch_on(4);//开启TIM1_CH1 通道输出
TIM1->CCR4H = 0;//初始化PWM通道占空比 1:1
TIM1->CCR4L = Num;
break;
}
TIM1->CR1 |= TIM1_CR1_CEN;
}
//PWM占空比调节 0-100
void Driver_PWMSet(u8 ch,u8 Num)
{
if(Num > 100)
return;
switch(ch)
{
case 1:
TIM1->CCR1L = Num;
break;
case 2:
TIM1->CCR2L = Num;
break;
case 3:
TIM1->CCR3L = Num;
break;
case 4:
TIM1->CCR4L = Num;
break;
}
}
//打开PWM通道
void pwm_ch_on(u8 ch)
{
switch(ch)
{
case 1:
TIM1->CCER1 |= 0x01;
break;
case 2:
TIM1->CCER1 |= 0x10;
break;
case 3:
TIM1->CCER2 |= 0x01;
break;
case 4:
TIM1->CCER2 |= 0x10;
break;
}
}
//关闭PWM通道
void pwm_ch_close(u8 ch)
{
switch(ch)
{
case 1:
TIM1->CCER1 &= ~0x01;
break;
case 2:
TIM1->CCER1 &= ~0x10;
break;
case 3:
TIM1->CCER2 &= ~0x01;
break;
case 4:
TIM1->CCER2 &= ~0x10;
break;
}
}
//运行主函数
int main(void)
{
Driver_PWMON(1,0);
Driver_PWMON(2,0);
Driver_PWMON(3,0);
while(1)
{
u8 a= 0,b=0;
for(b=1 ;b<4; b++)
{
for(a=1;a<99;a++)
{
Driver_PWMSet(b,a);
delay_ms(5);
}
for(a=99;a>0;a--)
{
Driver_PWMSet(b,a);
delay_ms(5);
}
}
}
}
|