STM32F429基于HAL库实现通用定时器3的编码器接口(Encoder Mode)模式

原文链接:https://www.itdoy.com/index.php/post/15.html
编码器型号:62SY22D11-3(品牌:HUAVEI)
ARM IC:STM32F429IGT6

一、编码器建议电路图

STM32F429基于HAL库实现通用定时器3的编码器接口(Encoder Mode)模式_第1张图片

需要注意的是,编码器的AB两个接口需要2.2K的上拉电阻。

二、定时器3的初始化函数

TIM_HandleTypeDef hTimEncoder;

void eNcoderInit(void)
{
	TIM_Encoder_InitTypeDef hEncoder;
	TIM_MasterConfigTypeDef sMasterConfig;
	
	hTimEncoder.Instance = TIM3;
	hTimEncoder.Init.Prescaler = 0;
	hTimEncoder.Init.CounterMode = TIM_COUNTERMODE_UP;
	hTimEncoder.Init.Period = 0xFFFF;
	hTimEncoder.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	
	hEncoder.EncoderMode = TIM_ENCODERMODE_TI12;
	hEncoder.IC1Polarity = TIM_ICPOLARITY_RISING;
	hEncoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
	hEncoder.IC1Prescaler = TIM_ICPSC_DIV1;
	hEncoder.IC1Filter = 0;
	hEncoder.IC2Polarity = TIM_ICPOLARITY_RISING;
	hEncoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
	hEncoder.IC2Prescaler = TIM_ICPSC_DIV1;
	hEncoder.IC2Filter = 0;
	
	HAL_TIM_Encoder_Init(&hTimEncoder,&hEncoder);
	
	sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
        sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
        HAL_TIMEx_MasterConfigSynchronization(&hTimEncoder, &sMasterConfig);
	
	HAL_TIM_Encoder_Start(&hTimEncoder,TIM_CHANNEL_ALL);
}

void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim)
{
	if(htim->Instance==TIM3)
	{
		GPIO_InitTypeDef GPIO_Initure;
		__HAL_RCC_GPIOA_CLK_ENABLE();//使能TIM3时钟
		__HAL_RCC_TIM3_CLK_ENABLE();//开启GPIOA时钟

		GPIO_Initure.Pin=GPIO_PIN_6|GPIO_PIN_7;
		GPIO_Initure.Mode=GPIO_MODE_AF_OD;     //输入
		GPIO_Initure.Pull=GPIO_NOPULL;          //无上下拉
		GPIO_Initure.Alternate=GPIO_AF2_TIM3;
		HAL_GPIO_Init(GPIOA,&GPIO_Initure);
	}

}
三、主函数中读取数据

if(__HAL_TIM_DIRECTION_STATUS(&hTimEncoder)==0)i=i+__HAL_TIM_GetCounter(&hTimEncoder);
else if(__HAL_TIM_GetCounter(&hTimEncoder)!=0)i=i-(0xFFFF-__HAL_TIM_GetCounter(&hTimEncoder)+1);
printf("%d\n",i);
__HAL_TIM_SetCounter(&hTimEncoder,0);
vTaskDelay(100);

你可能感兴趣的:(STM32)