- 脉冲计数配置步骤
1.硬件
2.软件
#include "sys.h"
#include "delay.h"
#include "led.h"
#include "uart1.h"
#include "counter.h"
int main(void)
{
HAL_Init();
stm32_clock_init(RCC_PLL_MUL9);
led_init();
uart1_init(115200);
printf("hello world!\r\n");
counter_init(65536 - 1, 0);
while(1)
{
count_get();
}
}
- **
counter_init(65536 - 1, 0);
**语句定时参考
#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;
slave_config.InputTrigger = TIM_TS_TI2FP2;
slave_config.TriggerPolarity = TIM_TRIGGERPOLARITY_FALLING;
slave_config.TriggerFilter = 0;
HAL_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();
__HAL_RCC_TIM2_CLK_ENABLE();
gpio_initstruct.Pin = GPIO_PIN_0;
gpio_initstruct.Mode = GPIO_MODE_AF_PP;
gpio_initstruct.Pull = GPIO_PULLUP;
gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &gpio_initstruct);
}
}
void count_get(void)
{
new_count = __HAL_TIM_GET_COUNTER(&counter_handle);
if(old_count != new_count)
{
old_count = new_count;
printf("CNT: %d\r\n", new_count);
}
}
#ifndef __COUNTER_H__
#define __COUNTER_H__
#include "sys.h"
void counter_init(uint16_t arr, uint16_t psc);
void count_get(void);
#endif
3.实物效果
- 硬件模块接线
KEY一端—>PA0
KEY另一端—>GND
ST-Link下载方式
将定时器 2 通道 2 输入的低电平脉冲作为定时器 2 的时钟,并通过串口打印脉冲数
PSC=0,ARR=65535
外部时钟模式1、触发选择、上升沿触发、不分频、不滤波