STM32F0 TIM17配置生成PWM控制步进电机
扫描二维码
随时随地手机看文章
因为步进电机的转速只跟所给的脉冲数相关,而与占空比无关,所以下面的配置就只考虑脉冲数的变化,对于占空比,则不做多考虑,(占空比=TIM_OCInitStructure.TIM_Pulse/TIM_TimeBaseStructure.TIM_Period,如果在初始化后没生成PWM,可能就是给的参数刚好让这两者的比值为0或1)
/*参数pulse为输出的脉冲数,在这里不能取0,0不能当除数*/voidTimer17_PWM_Config(u16pulse){TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;TIM_OCInitTypeDefTIM_OCInitStructure;GPIO_InitTypeDefGPIO_InitStructure;u16TimerPeriod=(SystemCoreClock/pulse)-1;RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM17,ENABLE);GPIO_InitStructure.GPIO_Pin=GPIO_Pin_7;GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);GPIO_PinAFConfig(GPIOA,GPIO_PinSource7,GPIO_AF_5);TIM_TimeBaseStructure.TIM_Prescaler=0;TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;TIM_TimeBaseStructure.TIM_Period=TimerPeriod;TIM_TimeBaseStructure.TIM_ClockDivision=0;TIM_TimeBaseStructure.TIM_RepetitionCounter=0;TIM_TimeBaseInit(TIM17,&TIM_TimeBaseStructure);TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;TIM_OCInitStructure.TIM_OutputNState=TIM_OutputNState_Enable;TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;TIM_OCInitStructure.TIM_OCNPolarity=TIM_OCNPolarity_Low;TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;TIM_OCInitStructure.TIM_OCNIdleState=TIM_OCIdleState_Reset;TIM_OCInitStructure.TIM_Pulse=100;TIM_OC1Init(TIM17,&TIM_OCInitStructure);TIM_Cmd(TIM17,ENABLE);/*在TIM1,TIM15,TIM16,TIM17必须使用下面的函数使能,否则无法生成pwm*/TIM_CtrlPWMOutputs(TIM17,ENABLE);}123456789101112131415161718192021222324252627282930313233343536373839404142
voidmain(){Timer17_PWM_Config(1000);while(1){}}12345
如果希望脉冲输出为0,能可以通过修改占空比的方法来处理
/*下面的寄存器操作就是将TIM_OCInitStructure.TIM_Pulse的值设置为0,从而使占空比为0,也就不再输出脉冲,电机也就不转了*/voidTIM_PWM_Stop(){TIM17->CCR1=0;}