写一个STM32的旋转编码器初始化代码
以下是一个基本的STM32旋转编码器初始化代码,仅供参考:
#include "stm32f4xx.h"
void encoder_init(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); // 使能GPIOA时钟
// 配置GPIOA0和GPIOA1为输入模式
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// 配置TIM2为编码器模式
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 使能TIM2时钟
TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
TIM_TimeBaseStruct.TIM_Prescaler = 0; // 预分频器值
TIM_TimeBaseStruct.TIM_Period = 65535; // 自动重载寄存器值
TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up; // 计数器模式
TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1; // 时钟分割
TIM_TimeBaseStruct.TIM_RepetitionCounter = 0; // 重复计数器值
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStruct);
TIM_EncoderInterfaceConfig(TIM2, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising); // 配置编码器模式为TI1和TI2
TIM_SetCounter(TIM2, 0); // 计数器清零
TIM_Cmd(TIM2, ENABLE); // 使能TIM2
}
原文地址: http://www.cveoy.top/t/topic/bfvd 著作权归作者所有。请勿转载和采集!