本帖最后由 感动 于 2019-9-15 12:04 编辑
前面的**介绍了单片机控制步进电机四相四拍、四相八拍的方式。用的是持续电平驱动,这种驱动方式电机的噪音大,震动明显,下面介绍正弦波驱动方式,这种方式能很好的解决噪音和震动问题。 首先需要准备下stm32的正弦波PWM表,可以用EXCEL生成,文件在附件中。 配置单片机定时器的PWM输出。 void TIM_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period=512;
TIM_TimeBaseStructure.TIM_Prescaler= 7;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_Pulse=512;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC4Init(TIM1, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM1, ENABLE);
TIM_Cmd(TIM1, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_CtrlPWMOutputs(TIM1,ENABLE);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
}
配置定时器的数据更新中断,在中断里更新CCR的值改变占空比。 void TIM1_UP_IRQHandler(void)
{
if (TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET)
{
pwm1_index++;if(pwm1_index>36)pwm1_index=0;
pwm2_index++;if(pwm2_index>36)pwm2_index=0;
pwm3_index++;if(pwm3_index>36)pwm3_index=0;
pwm4_index++;if(pwm4_index>36)pwm4_index=0;
TIM1->CCR1 = indexWave[pwm1_index];
TIM1->CCR2 = indexWave[pwm2_index];
TIM1->CCR3 = indexWave[pwm3_index];
TIM1->CCR4 = indexWave[pwm4_index];
TIM_ClearITPendingBit (TIM1, TIM_IT_Update);
}
至此可以看到定时器输出的符合正弦波规律的PWM波。 程序在这里 可以对比下用正弦波代替持续电平的效果
|
值得点赞,楼主好样的。