因為步進電機的轉速只跟所給的脈沖數相關,而與占空比無關,所以下面的配置就只考慮脈沖數的變化,對于占空比,則不做多考慮,(占空比=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;}