作者:陈广
日期:2021-12-17
tim.c 文件:
#include "tim.h"
/* TIM2 init function */
void MX_TIM2_Init(void)
{
LL_GPIO_InitTypeDef GPIO_InitStruct = {0};
/* Peripheral clock enable */
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOA);
/**TIM2 GPIO Configuration
PA0-WKUP ------> TIM2_CH1
*/
GPIO_InitStruct.Pin = LL_GPIO_PIN_0;
GPIO_InitStruct.Mode = LL_GPIO_MODE_FLOATING;
LL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* TIM2 interrupt Init */
NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(),0, 0));
NVIC_EnableIRQ(TIM2_IRQn);
/* USER CODE BEGIN TIM2_Init 1 */
TIM2->CCMR1 = 1;
/* USER CODE END TIM2_Init 2 */
}
/* USER CODE BEGIN 1 */
volatile int time; //计数器溢出次数
volatile int end; //用于判断捕获是否结束,0表示未结束,1表示已结束,-1表示等待超时
volatile int rising; //上升沿时间
volatile int falling; //下降沿时间
void Delay_ms(uint32_t delay)
{
TIM2->PSC = 7200 - 1;
TIM2->ARR = 10 * delay - 1;
TIM2->EGR |= 1;
TIM2->CR1 = 0x0D;
while(!(TIM2->SR & 1));
TIM2->SR = 0;
}
void Delay_us(uint32_t delay)
{
TIM2->PSC = 8 - 1;
TIM2->ARR = 9 * delay - 1;
TIM2->EGR |= 1;
TIM2->CR1 = 0x0D;
while(!(TIM2->SR & 1));
TIM2->SR = 0;
}
int Measuer_Use_Capture(void)
{
time = 0;
end = 0;
TIM2->PSC = 72 - 1;
TIM2->ARR = 0xFFFF;
TIM2->CCER = 1;
TIM2->EGR |= 3;
TIM2->SR = 0;
TIM2->DIER = 3;
TIM2->CR1 = 1;
while(!end);
TIM2->CR1 = 4;
TIM2->DIER = 0;
TIM2->CCER = 0;
if(end == -1) return -1;
if(time == 0)
{
return falling - rising;
}
else
{
return 65535 - rising + falling;
}
}
void TIM2_IRQHandler(void)
{
if(TIM2->SR & 1) //定时器到期中断
{
TIM2->SR &= ~1;
time++;
if(time > 2) end = -1;
}
if(TIM2->SR & 2) //通道1中断
{
if(TIM2->CCER & 2) //如果为下降沿
{
falling = TIM2->CCR1;
TIM2->CCER &= ~2;
end = 1;
}
else //如果为上升沿
{
rising = TIM2->CCR1;
TIM2->CCER |= 2;
}
}
}
/* USER CODE END 1 */
;