【stm32开发日志】用stm32精确控制步进电机角度

  1. 前言:精确控制步进电机的原理见我之前写的一篇博文:https://blog.csdn.net/weixin_39589455/article/details/89409634

程序:
1.此处是pwm输出,及普通的设置,用到TIM1的CH1通道,这里不加太多注释,可参考我的另一篇博文:https://blog.csdn.net/weixin_39589455/article/details/87902849
唯一不同的是加入了中断计数

void TIM1_PWM_Init(u16 arr,u16 psc)
{
        GPIO_InitTypeDef GPIO_InitStructure;
        TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
        TIM_OCInitTypeDef  TIM_OCInitStructure;
        NVIC_InitTypeDef   NVIC_InitStructure;
 
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_TIM1,ENABLE);
        //RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);;
        GPIO_DeInit(GPIOA); 
 
        GPIO_InitStructure.GPIO_Pin=GPIO_Pin_8;
        GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA,&GPIO_InitStructure);     
 
        TIM_TimeBaseStructure.TIM_Period=arr;
        TIM_TimeBaseStructure.TIM_Prescaler=psc;
        TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
        TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
        TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure);
        TIM_ITConfig(TIM1,TIM_IT_Update,ENABLE );
 
        TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
        //TIM_OCInitStructure.TIM_Channel=TIM_Channel_1;
        TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
        TIM_OCInitStructure.TIM_Pulse=0;
        TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
        TIM_OC1Init(TIM1, &TIM_OCInitStructure);
        TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
        TIM_CtrlPWMOutputs(TIM1,ENABLE);
        TIM_ARRPreloadConfig(TIM1, ENABLE);
        TIM_CtrlPWMOutputs(TIM1,ENABLE);
    
        NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; 
        NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; 
        NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
        NVIC_Init(&NVIC_InitStructure);
 
        TIM_Cmd(TIM1,ENABLE);
}

中断服务程序:此处的100为脉冲数,使电机转45°。由于:360/800=0.45即每个脉冲使电机转0.45°,故电机转动100*0.45=45度

void TIM1_UP_IRQHandler(void)
{
	if(TIM_GetITStatus (TIM1 ,TIM_IT_Update )!=RESET )
		{
			TIM_ClearITPendingBit(TIM1 ,TIM_IT_Update );
			Pulse_Cnt++;
			if(Pulse_Cnt>100)
			{
				  Pulse_Cnt = 0;
			    TIM_Cmd(TIM1,DISABLE);
			}
		}
}

3.主函数

int main(void)
{
  pwm_init();
	moto_shun();
}

注:这里使用中断来实现控制,比较占用片内资源,如果有其他方法欢迎和我讨论呀

源代码:https://download.csdn.net/download/weixin_39589455/11129458

你可能感兴趣的:(stm32学习)