STM32使用TIM2旋转电机

时间:2016-09-26 07:04:36

标签: c stm32

我的代码可以让马达旋转它运作良好:

#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"

void Delay(unsigned int t) {
   unsigned int i;
   for (i = 0; i < t; i++)
      ;
}
void GPIOD_Initialize() {
   GPIO_InitTypeDef GPIOA_Stepper;
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
   GPIOA_Stepper.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
   GPIOA_Stepper.GPIO_Mode = GPIO_Mode_Out_PP;
   GPIOA_Stepper.GPIO_Speed = GPIO_Speed_50MHz;
   GPIO_Init(GPIOA, &GPIOA_Stepper);
}
void RotateToRight() {
   const int time = 25000;
   uint16_t commands[8] = { GPIO_Pin_0 | GPIO_Pin_2, GPIO_Pin_0, GPIO_Pin_3
         | GPIO_Pin_0, GPIO_Pin_3, GPIO_Pin_1 | GPIO_Pin_3, GPIO_Pin_1,
         GPIO_Pin_2 | GPIO_Pin_1, GPIO_Pin_2 };
   for (int i = 0; i < 8; i++) {
      GPIO_Write(GPIOA, commands[i]);
      Delay(time);
   }
}
int main(void) {
   GPIOD_Initialize();
   while (1) {
      RotateToRight();
   }
}

然后我决定使用计时器TIM2重写此代码。我认为我做错了,因为电机不会旋转而只会发出哔哔声。第二个代码中的pwm信号问题。但我没有示波器来检查腿上信号的物理特性。如何修复第二个代码?

#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"

void Delay(unsigned int t) {
   unsigned int i;
   for (i = 0; i < t; i++)
      ;
}
int main(void) {
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

   RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

   GPIO_InitTypeDef PORT;

   PORT.GPIO_Pin = (GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3);

   PORT.GPIO_Mode = GPIO_Mode_AF_PP;
   PORT.GPIO_Speed = GPIO_Speed_2MHz;
   GPIO_Init(GPIOA, &PORT);

   TIM2->CCER |=
         (TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E);

   TIM2->CCMR1 |= (TIM_CCMR1_OC2M_0 | TIM_CCMR1_OC2M_1 | TIM_CCMR1_OC2M_2);
   TIM2->CCMR2 |= (TIM_CCMR2_OC3M_0 | TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3M_2
         | TIM_CCMR2_OC4M_0 | TIM_CCMR2_OC4M_1 | TIM_CCMR2_OC4M_2);
   TIM2->CR1 |= TIM_CR1_CEN;
   while (1) {
      int value = 10;
      int time = 25000;
      TIM2->CCR1 = value;
      TIM2->CCR3 = value;
      Delay(time);
      TIM2->CCR1 = value;
      Delay(time);
      TIM2->CCR4 = value;
      TIM2->CCR1 = value;
      Delay(time);
      TIM2->CCR4 = value;
      Delay(time);
      TIM2->CCR2 = value;
      TIM2->CCR4 = value;
      Delay(time);
      TIM2->CCR2 = value;
      Delay(time);
      TIM2->CCR3 = value;
      TIM2->CCR2 = value;
      Delay(time);
      TIM2->CCR3 = value;
      Delay(time);
   }
}

0 个答案:

没有答案