本文介绍了TIM4 上的 STM32 旋转编码器配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 TIM4 用于我的 STM32F4DISCOVERY 板上的正交编码器输入.这是我的代码:

I'm trying to use TIM4 for quadrature encoder input on my STM32F4DISCOVERY board.Here is my code :

RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6| GPIO_Pin_7;
GPIO_Init(GPIOB, &GPIO_InitStructure);

GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_TIM4);

/* Configure the timer */
TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);

/* TIM4 counter enable */
TIM_Cmd(TIM4, ENABLE);

遗憾的是,当我转动编码器时,TIM4->CNT 计数器不会移动.我与 TIM8 完美配合.这是工作 TIM8 和不工作 TIM4 的完整代码:https://gist.github.com/nraynaud/5082298

sadly, the TIM4->CNT counter won't move when I turn the encoder. I works perfectly with TIM8.Here is the full code of the working TIM8 and the not working TIM4 :https://gist.github.com/nraynaud/5082298

我在手动移动编码器后通过在 gdb 中打印 rT2() 来检查.

I check by printing rT2() in gdb after moving the encoder by hand.

推荐答案

我使用 STM32F407 从 3 个光学编码器读取编码器计数.我使用的是 ChibiOS RTOS,所以定时器结构体与 ST Peripheral 库定时器结构体略有不同,但信息基本相同.以下是我如何配置实际定时器的寄存器:

I have used an STM32F407 to read encoder counts from 3 optical encoders. I am using ChibiOS RTOS so the timer struct is slightly different from the ST Peripheral library timer struct, but the information is basically the same. Here is how I configure the registers of the actual timers:

stm32_tim_t * encoderTimers[3] = {STM32_TIM8, STM32_TIM3, STM32_TIM4};
for (auto timer : encoderTimers) {
  timer->SMCR = 3;          // Encoder mode 3
  timer->CCER = 0;          // rising edge polarity
  timer->ARR = 0xFFFF;      // count from 0-ARR or ARR-0
  timer->CCMR1 = 0xC1C1;    // f_DTS/16, N=8, IC1->TI1, IC2->TI2
  timer->CNT = 0;           // Initialize counter
  timer->EGR = 1;           // Generate an update event
  timer->CR1 = 1;           // Enable the counter
}

此外,请确保启用 RCC 的 APB1 或 APB2 寄存器中的定时器外设.类似的东西:

Also, make sure you enable the timer peripherals in the APB1 or APB2 registers of the RCC. Something like:

RCC->APB1ENR |= ((1 <<  2)  // TIM4  --  Front wheel angle measurement
             |   (1 <<  1));// TIM3  --  Steer angle measurement

最后,您需要确保正确配置 GPIO 设置.这意味着为备用功能配置 GPIO.

Finally, you need to make sure you configure the GPIO settings correctly. This means configuring the GPIO for Alternate Function.

这篇关于TIM4 上的 STM32 旋转编码器配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:13