如何在STM32F411E上将通用定时器设置为计数器模式?

时间:2017-04-08 17:03:25

标签: stm32f4discovery

我需要一个定时器,以便在GPIO引脚的上升沿递增。我无法找到任何代码示例。

我有一个数字霍尔传感器,可以感应磁铁接近传感器,我想计算磁铁绕传感器传来的次数。当磁铁绕过时,传感器给出正脉冲。我想用这个脉冲增加计数器值。

我知道如何将定时器设置为基本向上计数模式(带内部时钟)。

TIM_TimeBaseInitTypeDef TIM_BaseStruct;
/*  Configure TIMER4*/
TIM_BaseStruct.TIM_Prescaler = 40000;
TIM_BaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_BaseStruct.TIM_Period = 500;
TIM_BaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_BaseStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM4, &TIM_BaseStruct);
TIM_Cmd(TIM4, ENABLE);

这很有效,但我需要将时钟切换到外部信号。我该怎么做?

修改

使用(我不使用HAL库)库中定义的函数重写Guillaume Michel回答的代码后,我想出了一个代码

TIM_TimeBaseInitTypeDef timer4;
timer4.TIM_Prescaler=0;
timer4.TIM_CounterMode=TIM_CounterMode_Up;
timer4.TIM_Period=5;
timer4.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM4,&timer4);

TIM_ETRClockMode2Config(TIM4,TIM_ExtTRGPSC_DIV2,TIM_ExtTRGPolarity_NonInverted, 0);

TIM_SelectSlaveMode(TIM4,TIM_SlaveMode_Reset);
TIM_SelectMasterSlaveMode(TIM4, TIM_MasterSlaveMode_Disable);

RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; 
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_PinAFConfig(GPIOD,GPIO_Pin_13,GPIO_AF_TIM4);
GPIO_Init(GPIOD, &GPIO_InitStructure);

这是可编译但不可工作的代码。我将定时器周期设置为5,并且每次定时器计数完全时我设置中断以切换LED,但无论我在传感器周围运行磁铁多少次,LED都不会亮起。有一些明显的错误吗?我能做些什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

您可以尝试连接STM32F411的GPIO上的霍尔传感器输出,并将此GPIO设置为定时器的时钟。这看起来像是:

TIM_HandleTypeDef htim4;
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;

htim4.Instance = TIM4;
htim4.Init.Prescaler = 0;
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = 65535;
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_Base_Init(&htim4);

sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_ETRMODE2;
sClockSourceConfig.ClockPolarity = TIM_CLOCKPOLARITY_NONINVERTED;
sClockSourceConfig.ClockPrescaler = TIM_CLOCKPRESCALER_DIV1;
sClockSourceConfig.ClockFilter = 0;
HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig);

sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig);

GPIO的设置如下:

//Set PE0 as TIM4_ETR 
__HAL_RCC_GPIOE_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM4;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);