STM32F0 TIM17配置生成PWM控制步進(jìn)電機(jī)
掃描二維碼
隨時(shí)隨地手機(jī)看文章
因?yàn)椴竭M(jìn)電機(jī)的轉(zhuǎn)速只跟所給的脈沖數(shù)相關(guān),而與占空比無(wú)關(guān),所以下面的配置就只考慮脈沖數(shù)的變化,對(duì)于占空比,則不做多考慮,(占空比=TIM_OCInitStructure.TIM_Pulse/TIM_TimeBaseStructure.TIM_Period,如果在初始化后沒生成PWM,可能就是給的參數(shù)剛好讓這兩者的比值為0或1)
/*參數(shù)pulse為輸出的脈沖數(shù),在這里不能取0,0不能當(dāng)除數(shù)*/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必須使用下面的函數(shù)使能,否則無(wú)法生成pwm*/TIM_CtrlPWMOutputs(TIM17,ENABLE);}123456789101112131415161718192021222324252627282930313233343536373839404142
voidmain(){Timer17_PWM_Config(1000);while(1){}}12345
如果希望脈沖輸出為0,能可以通過修改占空比的方法來處理
/*下面的寄存器操作就是將TIM_OCInitStructure.TIM_Pulse的值設(shè)置為0,從而使占空比為0,也就不再輸出脈沖,電機(jī)也就不轉(zhuǎn)了*/voidTIM_PWM_Stop(){TIM17->CCR1=0;}