初始化代码
void Enchor1_Init(void)
{
// GPIO口初始化
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure; // GPIO口的输入模式配置很重要,不正确的话会读不到数据
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_11;
GPIO_Init(GPIOE, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource9, GPIO_AF_TIM1);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource11,GPIO_AF_TIM1);
// 定时器编码器模式初始化
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_DeInit(TIM1);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 这里可以自己设置,或使用默认值
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising ,TIM_ICPolarity_Rising); // 这里配置了编码器模式
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICStructInit(&TIM_ICInitStructure);
//TIM_ICInitStructure.TIM_ICFilter = 10; // 这里可以自己设置,或使用默认值
TIM_ICInit(TIM1, &TIM_ICInitStructure);
TIM_SetCounter(TIM1, 0);
TIM_Cmd(TIM1, ENABLE);
}
读取函数:
int Read_Encoder1(void)
{
int encoder_num;
encoder_num = (int)((int16_t)(TIM1->CNT)); // 这里尤其需要注意数据类型
//TIM_SetCounter(TIM3, 0);
return encoder_num;
}