本人在学习写PWM,驱动电机。
硬件是crazepony的板子,代码如下
void MotorInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
uint16_t PrescalerValue = 0; //用于控制电机PWM频率
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //打开GPIOA的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //打开定时器2时钟
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //利用TIM2,所以复用输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3; //PA0123
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //搞不懂为什么用2Mhz
GPIO_Init(GPIOA, &GPIO_InitStructure);
//复位定时器
TIM_DeInit(TIM2);
/*这里配置计时器*/
PrescalerValue = (uint16_t) (SystemCoreClock / 24000000) - 1; //一秒钟计数多少次,2次
TIM_TimeBaseStructure.TIM_Period = 999; //单次计数个数
TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue; //设置预分频系数
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
/*配置TIM2为PWM输出模式*/
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //设置为PWM1模式
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //开启OC*输出到对应引脚
TIM_OCInitStructure.TIM_Pulse = 0; //CCR1设置为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //高电平有效
TIM_OC1Init(TIM2,&TIM_OCInitStructure); //初始化指定外设
TIM_OC2Init(TIM2,&TIM_OCInitStructure);
TIM_OC3Init(TIM2,&TIM_OCInitStructure);
TIM_OC4Init(TIM2,&TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable); //使能预装载器
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM2,ENABLE);//使能TIM3在 ARR 上的预装载寄存器。
//启动定时器
TIM_Cmd(TIM2,ENABLE);
printf("Motor init success...\r\n");
}
初始化完后,是不是修改CCRx中的值就能运行?还是有什么其他的设置。
void MotorPwmFlash(int16_t MOTO1_PWM, int16_t MOTO2_PWM, int16_t MOTO3_PWM, int16_t MOTO4_PWM)
{
if(MOTO1_PWM>=Moto_PwmMax) MOTO1_PWM = Moto_PwmMax;
if(MOTO2_PWM>=Moto_PwmMax) MOTO2_PWM = Moto_PwmMax;
if(MOTO3_PWM>=Moto_PwmMax) MOTO3_PWM = Moto_PwmMax;
if(MOTO4_PWM>=Moto_PwmMax) MOTO4_PWM = Moto_PwmMax;
if(MOTO1_PWM<=0) MOTO1_PWM = 0;
if(MOTO2_PWM<=0) MOTO2_PWM = 0;
if(MOTO3_PWM<=0) MOTO3_PWM = 0;
if(MOTO4_PWM<=0) MOTO4_PWM = 0; //限定输入不能小于0,大于999
TIM2->CCR1 = MOTO1_PWM;
TIM2->CCR2 = MOTO2_PWM;
TIM2->CCR3 = MOTO3_PWM;
TIM2->CCR4 = MOTO4_PWM; //对定时器寄存器进行赋值
printf("TIM->CCR1 %d ", TIM2->CCR1);
printf("TIM->CCR1 %d ", TIM2->CCR2);
printf("TIM->CCR1 %d ", TIM2->CCR3);
printf("TIM->CCR1 %d \n", TIM2->CCR4);
}
我在main函数中调用,并没有成功转起来。请问会是什么没弄好呢?谢谢
|