- UID
- 852722
|
目的: 用STM32 的 TIM1 来产生PWM方波信号(占空比50%),来控制步进电机运转,在通过更新TIM1的period来改变电机的旋转速度,要求从0m/s到0.7m/s,在2S(秒)内完成加速过程。
下面是本人写的代码,不足之处是:一开始不会进行加速,而是电机不动,过来有1分钟左右,然后电机从很慢的速度开始加速。我不知道用什么命令来直接实现即时的频率更换。
代码如下:
PWM配置函数:
void Pwm_Configure(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM1_TimeBaseInitTypeDef TIM1_TimeBaseStructure;
TIM1_OCInitTypeDef TIM1_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 ,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_FullRemap_TIM1,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 ,ENABLE);
GPIO_PinRemapConfig(GPIO_FullRemap_TIM2,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13|GPIO_Pin_14 ;
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
GPIO_Init(GPIOE,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 ;//|GPIO_Pin_11 ;
GPIO_Init(GPIOB,&GPIO_InitStructure);
TIM1_DeInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 ,ENABLE);
TIM1_TimeBaseStructure.TIM1_Prescaler = 0x44A0; //72MHz/0xAF = Hz 0x15
TIM1_TimeBaseStructure.TIM1_CounterMode =TIM1_CounterMode_Up;
TIM1_TimeBaseStructure.TIM1_Period = 0xFFF; // KHz/4096(0xFFF+1)=100Hz
TIM1_TimeBaseStructure.TIM1_ClockDivision =0x0;
TIM1_TimeBaseStructure.TIM1_RepetitionCounter =0x0;
TIM1_TimeBaseInit(&TIM1_TimeBaseStructure);
TIM1_OCInitStructure.TIM1_OCMode =TIM1_OCMode_PWM2;
TIM1_OCInitStructure.TIM1_OutputState =TIM1_OutputState_Enable;
TIM1_OCInitStructure.TIM1_Pulse =0x7FF;
TIM1_OCInitStructure.TIM1_OCPolarity =TIM1_OCPolarity_Low;
TIM1_OCInitStructure.TIM1_OCIdleState =TIM1_OCIdleState_Set;
TIM1_OC3Init(&TIM1_OCInitStructure);
....
....
}
下面是main函数里面的死循环,变量的定义在这里省略了。
while(1)
{
u16 Prescale_value = (u16) 0x44A0 ; //对应PWM的输出频率的1Hz左右
if(Prescale_value> (u16) 0x15) //0x15对应PWM输出的800多Hz对应电机速度约0.7m/s
{
Prescale_value =Prescale_value - (u16)0x05;
TIM1_PrescalerConfig(Prescale_value,TIM1_PSCReloadMode_Update);
TIM1_GenerateEvent(TIM1_EventSource_Update);
OSTimeDly(100);
GPIO_ResetBits(GPIOC, GPIO_Pin_8 | GPIO_Pin_9);//指示灯,观察程序是进入这里。
OSTimeDly(5);
}
} |
|