|
本帖最后由 ruan18278816371 于 2015-2-4 09:17 编辑
之前发过一贴没大侠回帖,今天换个板块发悬赏希望大侠们多多指教。用STM32F103R8T6配置了六路PWM输出,其中0 1 4 5这四路PWM任意一路都可以输出,唯独通道2和通道3不能输出,之前怀疑这两路可能是复用其他功能了,但是查了没有啊,刚上STM32看PWM底层驱动好晕,只会库函数开发,下面粘出代码,向大侠们求解!
/******************************************************************************
* 描述 : 启动PWM,这里默认系统时钟频率是 72MHz,如果不是,分频部分的代码需
* 描述 : 要修改
* 输入参数 : pwmRoad: 开启哪路Pwm, frequency:Pwm频率, dutyRatio:占空比
*******************************************************************************/
static void Start(int pwmRoad, int frequency, int dutyRatio)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
uint arr = 0;
uint psc = 0;
uint duty = 0;
//这样分频的目的是获得更准确的频率
if(frequency >= 1098)//当频率大于 1098Hz 时,不分频,直接用 arr 计数获取频率
{
psc = 0;
arr = 72000000/frequency;
}
else if(frequency < 1098 && frequency >= 15)//当频率在 15Hz ~ 1098Hz 之间时,将频率降为 1 MHz
{
psc = 71;
arr = 1000000/frequency;
}
else if(frequency < 15 && frequency >= 1)//当频率在 1Hz ~ 15Hz 之间时,将频率降为 100 KHz
{
psc = 719;
arr = 100000/frequency;
}
duty = arr * dutyRatio / 100; //计算占空比对应的比较值
ArrBackup[pwmRoad] = arr; //备份
TIM_TimeBaseStructure.TIM_Period = arr - 1; //设置在下一个更新事件装入活动的自动重装载寄存(TIMx_ARR)器周期的值.与PWM的f有关 72000/900=80K
TIM_TimeBaseStructure.TIM_Prescaler = psc - 1; //设置用来作为TIMx时钟频率除数的预分频值 0x0不分频,这里分到的时钟频率为12 MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
if(pwmRoad < 2) //这样做的目的是为了不影响串口1
{
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
}
else
{
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
}
TIM_OCInitStructure.TIM_Pulse = duty;
if(pwmRoad < 2)
{
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_Cmd(TIM3, ENABLE);
}
else
{
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_ARRPreloadConfig(TIM1, ENABLE);
TIM_Cmd(TIM1, ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
}
switch(pwmRoad)
{
case 0:
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
break;
case 1:
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
break;
case 2: //不能正常输出
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
break;
case 3: //不能正常输出
TIM_OC1Init(TIM1, &TIM_OCInitStructure); //TIM1
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
break;
case 4:
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
break;
case 5:
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
break;
default:
break;
}
} |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|