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);

}

最后可以调用这个函数实现小车的前进,后退,左转,右转。。好的,,今天就写到这里,希望地大家有用。。

上一篇:说说oracle中的面向对象与面向集合


下一篇:源代码解说ActionBar的各种使用方法