选用定时器的主从模式,TIM2为主,TIM4为从。TIM2 输出PWM,TIM4记录脉冲数;选用PA3做为方向控制接线引脚。
关键代码如下:
//定时器2主模式,定时器4从模式
//PWM输出
/*设置PA3引脚,使用PA3作为方向控制信号的控制脚*/
void DIR_config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;//GPIO设置,创建结构体
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; //控制电机运动方向
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
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_SetBits(GPIOA,GPIO_Pin_3);
}
/*打开定时器2,并把TIM2设定为主定时器,*/
void TIM2_config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;//GPIO设置,创建结构体
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;//定时器设置结构体
TIM_OCInitTy