定时器之编码器接口

发布时间 2023-08-22 22:11:32作者: 磕伴

实现对正交(相位相差90°)编码器自动计次

 这个编码器接口。其实就相当于是一个带有方向控制的外部时钟

它同时控制着CNT的计数时钟和计数方向

每隔一段事件计数并清零,就可以得到其速度

正交信号精度高,可以抗噪声(一个引脚不变,另外引脚毛刺的话,计数的值会+1-1循环,而保持不变)

 

 uint16_t:减到0继续就是65535  改为int16_t就是-1

TODU: 按键按一下,显示当前速度

 

 

外部模块空闲默认输出高电平,就选择上拉输入(保持一致);外部信号很小,就用浮空输入

 

void Encoder_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	//不需要内部时钟
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 65536 - 1;		//ARR
	TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1;		//PSC
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
	
	TIM_ICInitTypeDef TIM_ICInitStructure; 
	TIM_ICStructInit(&TIM_ICInitStructure);//结构体初始化
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
	TIM_ICInitStructure.TIM_ICFilter = 0xF;
	TIM_ICInit(TIM3, &TIM_ICInitStructure);
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
	TIM_ICInitStructure.TIM_ICFilter = 0xF;
	TIM_ICInit(TIM3, &TIM_ICInitStructure);
	//配置编码器接口
	TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
	//TIM_ICPolarity_Rising 这里的上升沿代表高低电平不反转(在边沿检测器那里)

	TIM_Cmd(TIM3, ENABLE);
}

int16_t Encoder_Get(void)
{
	int16_t Temp;
	Temp = TIM_GetCounter(TIM3);
	TIM_SetCounter(TIM3, 0);
	return Temp/4;
}

定时中断为一秒是因为在Timer—init那里配置了预分频和计数值

在system里有个timer是定时器2的初始化,所以这里直接用了定时器2的中断