根据上述原理图 从而写清
#include "counter.h"
#include "stdio.h"TIM_HandleTypeDef counter_handle ={0};
uint16_t new_count =0;
uint16_t old_count =0;void counter_init(uint16_t arr,uint16_t psc )
{TIM_SlaveConfigTypeDef slave_config ={0};counter_handle.Instance =TIM2;counter_handle.Init.Prescaler=psc;counter_handle.Init.Period =arr;counter_handle.Init.CounterMode = TIM_COUNTERMODE_UP;HAL_TIM_IC_Init(&counter_handle);slave_config.SlaveMode = TIM_SLAVEMODE_EXTERNAL1; //选择外部时钟模式1slave_config.InputTrigger =TIM_TS_TI2FP2; //选择通道2slave_config.TriggerFilter =TIM_TRIGGERPOLARITY_FALLING ; //默认选择下降沿检测slave_config.TriggerPolarity =0; //滤波器为0HAL_TIM_SlaveConfigSynchro(&counter_handle,&slave_config);HAL_TIM_IC_Start(&counter_handle,TIM_CHANNEL_2);}void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
{if(htim->Instance == TIM2){ //①定义初始化结构体GPIO_InitTypeDef gpio_initstruct;//打开时钟__HAL_RCC_GPIOA_CLK_ENABLE(); //注意看硬件原理图中LED灯的引脚在哪一个组__HAL_RCC_TIM2_CLK_ENABLE(); //开启定时器时钟//调用GPIO初始化函数gpio_initstruct.Pin = GPIO_PIN_0; //LED1、LED2对应的引脚gpio_initstruct.Pull = GPIO_MODE_AF_PP; //复用推挽输出gpio_initstruct.Mode =GPIO_MODE_OUTPUT_PP; //上拉gpio_initstruct.Speed =GPIO_SPEED_FREQ_HIGH; //高速HAL_GPIO_Init(GPIOA,&gpio_initstruct);}
}void count_get(void)
{new_count=__HAL_TIM_GET_COUNTER(&counter_handle); if(old_count!=new_count) //设置新老比较的原因是 __HAL_TIM_GET_COUNTER()会把未按键的当前值一直在while中循环 使得持续输出{old_count =new_count;printf("CNT: %d\r\n",new_count);}
}
只需注意新老的值比较 这是因为避免未按键时一直循环
最终结果