一、实验目的
将定时器 2 通道 2 输入的低电平脉冲作为定时器 2 的时钟,并通过串口打印脉冲数
PSC=0,ARR=65535
外部时钟模式1、触发选择、上升沿触发、不分频、不滤波
二、实验前配置
复制项目文件19-串口打印功能,重命名23-脉冲计数
加载文件
别忘了这里
三、代码:
main.c
#include "sys.h"
#include "delay.h"
#include "led.h"
#include "uart1.h"
#include "counter.h"int main(void)
{HAL_Init(); /* 初始化HAL库 */stm32_clock_init(RCC_PLL_MUL9); /* 设置时钟, 72Mhz */led_init();//初始化led灯uart1_init(115200);counter_init(0,65536-1);while(1){ counter_get();}
}
counter.c
#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 psc,uint16_t arr)
{TIM_SlaveConfigTypeDef slave_config = {0};counter_handle.Instance = TIM2;counter_handle.Init.RepetitionCounter = psc;counter_handle.Init.Period = arr;counter_handle.Init.CounterMode = TIM_COUNTERMODE_UP;//向上计数HAL_TIM_IC_Init(&counter_handle);slave_config.InputTrigger = TIM_TS_TI2FP2;//定时器2通道2slave_config.SlaveMode = TIM_SLAVEMODE_EXTERNAL1;slave_config.TriggerFilter = 0;slave_config.TriggerPolarity = TIM_TRIGGERPOLARITY_FALLING;HAL_TIM_SlaveConfigSynchro(&counter_handle,&slave_config);HAL_TIM_IC_Start(&counter_handle,TIM_CHANNEL_2);
}//msp函数初始化
void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
{if(htim->Instance == TIM2){GPIO_InitTypeDef gpio_initstruct;//打开时钟__HAL_RCC_TIM2_CLK_ENABLE();__HAL_RCC_GPIOA_CLK_ENABLE();gpio_initstruct.Mode = GPIO_MODE_AF_PP;//复式推挽输出gpio_initstruct.Pin = GPIO_PIN_1;gpio_initstruct.Pull = GPIO_PULLUP;//上拉电阻gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;//高速HAL_GPIO_Init(GPIOA,&gpio_initstruct);}}//获取CNT的值
void counter_get(void)
{new_count = __HAL_TIM_GET_COUNTER(&counter_handle);if(new_count != old_count){old_count = new_count;printf("CNT: %d\r\n",new_count);}
}
counter.h
#ifndef __COUNTER_H__
#define __COUNTER_H__#include "sys.h"
void counter_init(uint16_t psc,uint16_t arr);
void counter_get(void);#endif
打卡串口助手
按下KEY2