STM32F103定時器輸出PWM波控制直流電機
這個暑假沒有回家,在學校準備九月份的電子設計競賽。今天想給大家分享一下STM32高階定時器輸出PWM波驅動直流電機的問題。。
要想用定時器輸出的PWM控制直流電機,,首先要理解“通道”的概念。。一個定時器可以支援一個PWM,要支援多個,就需要各路PWM週期相同而佔空比不同。。利用定時器的通道這一概念就可以實現。STM32微控制器定時器有四個通道,每個通道的TIM1——CCRx(x=1、2、3、4)存放一個值。。計數器從0開始計數,此時PWM輸出為0。。當計數值達到寄存值時,此時PWM電平發生翻轉,輸出1。。所以設定四個不同的佔空比的值,就可以產生四路PWM波。
本例程使用高階定時器TIM1輸出兩路PWM波分別控制左邊兩個輪子輪和右邊兩個輪子。TIM1時鐘頻率是72MHz,如果要輸出20KHz的PWM波,,應該把TIM1_Period設為3600-1。具體程式碼如下所示:
void TIM_Configuration(vu16 CCR1,vu16 CCR2)
{
TIM1_TimeBaseInitTypeDef TIM1_TimeBaseStructure;
TIM1_OCInitTypeDef TIM1_OCInitStructure;
TIM1_CtrlPWMOutputs(DISABLE);
/* TIM1 Peripheral Configuration */
TIM1_DeInit();
/* Time Base configuration */
TIM1_TimeBaseStructure.TIM1_Prescaler = 0;
TIM1_TimeBaseStructure.TIM1_CounterMode = TIM1_CounterMode_Up;
TIM1_TimeBaseStructure.TIM1_Period = 3599;
TIM1_TimeBaseStructure.TIM1_ClockDivision = 0;
TIM1_TimeBaseStructure.TIM1_RepetitionCounter = 0;
TIM1_TimeBaseInit(&TIM1_TimeBaseStructure);
/* Channel 1, 2,3 and 4 Configuration in PWM mode */
TIM1_OCInitStructure.TIM1_OCMode = TIM1_OCMode_PWM2;
TIM1_OCInitStructure.TIM1_OutputState = TIM1_OutputState_Enable;
TIM1_OCInitStructure.TIM1_OutputNState = TIM1_OutputNState_Enable;
TIM1_OCInitStructure.TIM1_Pulse = CCR1;
TIM1_OCInitStructure.TIM1_OCPolarity = TIM1_OCPolarity_Low;
TIM1_OCInitStructure.TIM1_OCNPolarity = TIM1_OCNPolarity_Low;
TIM1_OCInitStructure.TIM1_OCIdleState = TIM1_OCIdleState_Set;
TIM1_OCInitStructure.TIM1_OCNIdleState = TIM1_OCIdleState_Reset;
TIM1_OC1Init(&TIM1_OCInitStructure);
TIM1_OCInitStructure.TIM1_Pulse = CCR2;
TIM1_OC2Init(&TIM1_OCInitStructure);
/* TIM1 counter enable */
TIM1_Cmd(ENABLE);
/* Main Output Enable */
TIM1_CtrlPWMOutputs(ENABLE);
}
最後可以呼叫這個函式實現小車的前進,後退,左轉,右轉。。好的,,今天就寫到這裡,希望地大家有用。。