STM32F407光栅尺测速
//TIM5初始化为编码器接口模式,读取光栅尺数值
//分频psc=0;自动重装载值arr根据定时器位数定
void TIM5_Config(u32 arr,u32 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE); //TIM5时钟使能
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); //使能PORTF时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1; //光栅尺
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; //开漏输出
GPIO_InitStructure.GPIO_PuPd= GPIO_PuPd_UP; //上拉
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100MHz
GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PD
GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM5); //复用为TIM5
GPIO_PinAFConfig(GPIOA,GPIO_PinSource1,GPIO_AF_TIM5); //复用为TIM5
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler=psc; //定时器分频
TIM_TimeBaseStructure.TIM_Period=arr; //自动重装载值16位 0xFFFF 65535; 32位0xFFFFFFF
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; //时钟分频
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInit(TIM5,&TIM_TimeBaseStructure); //初始化TIM5
//编码器模式1 – 根据TI1FP1的电平,计数器在TI2FP2的边沿向上/下计数。
TIM_EncoderInterfaceConfig(TIM5,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising); //编码器接口模式配置
TIM_ICStructInit(&TIM_ICInitStructure); //默认值赋值
TIM_ICInitStructure.TIM_ICFilter =0x2; //滤波 0x0~0xF
TIM_ICInit(TIM5, &TIM_ICInitStructure); //初始化
TIM_ClearFlag(TIM5, TIM_FLAG_Update);//清除标志位
TIM_ITConfig(TIM5, TIM_IT_Update, ENABLE); //更新中断
TIM_SetCounter(TIM5,0); //计数器清零
TIM_Cmd(TIM5, ENABLE);
}
|