摘要:本文爲你帶來關於stm32定時器的使用的便利和優點之處。
使用定時器去計算獲取一條的時間html
stm32定時器時鐘圖以下:segmentfault
定時器2-7:普通定時器
定時器一、8:高級定時器函數
如下,我使用定時器7(如下TIM7)去實現計算獲取一條指令的運行時間。spa
1.TIM7初始化code
如下初始化函數中htm
void Timer7_Init(TIM_TypeDef * TIMx, unsigned short arr, unsigned short psc) { TIM_TimeBaseInitTypeDef timer_initstruct; NVIC_InitTypeDef nvic_initstruct; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM7, ENABLE); nvic_initstruct.NVIC_IRQChannel = TIM7_IRQn; timer_initstruct.TIM_CounterMode = TIM_CounterMode_Up; timer_initstruct.TIM_Period = arr; timer_initstruct.TIM_Prescaler = psc; TIM_TimeBaseInit(TIMx, &timer_initstruct); TIM_ITConfig(TIMx, TIM_IT_Update, ENABLE); //使能更新中斷 nvic_initstruct.NVIC_IRQChannelCmd = ENABLE; nvic_initstruct.NVIC_IRQChannelPreemptionPriority = 1; nvic_initstruct.NVIC_IRQChannelSubPriority = 1; NVIC_Init(&nvic_initstruct); TIM_Cmd(TIMx, ENABLE); //使能定時器 }
2.中斷服務函數blog
產生更新中斷時進入ip
void TIM7_IRQHandler(void) { if(TIM_GetITStatus(TIM7, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(TIM7, TIM_IT_Update); timer_info.timer7Out++; } }
其中timer_info爲結構體,存放更新次數變量(也能夠用靜態變量)rem
typedef struct { unsigned char timer7Out; } TIM_INFO; extern TIM_INFO timer_info; TIM_INFO timer_info = {0};
3.使用例程get
如下代碼爲計算usart1發送"hello word!"的時間
#include "stm32f10x.h" #include "delay.h" #include "usart.h" #include "timer.h" void Hardware_Init(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//中斷控制器分組設置 Delay_Init(); //Systick初始化,用於普通的延時 Usart1_Init(9600); //初始化串口1,波特率9600 Timer6_7_Init(TIM7, 49999, 71); //1us計數一次,50ms中斷一次 TIM_Cmd(TIM7, DISABLE); //關閉定時器 TIM_SetCounter(TIM7, 0); //清零計數器 } int main(void) { unsigned int time = 0; Hardware_Init(); //硬件初始化 while(1) { TIM_Cmd(TIM7, ENABLE); //使能定時器計時 UsartPrintf(USART1, "\r\nhello word!!n\r\n"); TIM_Cmd(TIM7, DISABLE); //關閉定時器 time = timer_info.timer7Out * 50000; //測算時間-中斷次數*中斷週期 time += TIM_GetCounter(TIM7); //獲取當前中斷前的剩餘值 TIM_SetCounter(TIM7, 0); //清零 timer_info.timer7Out = 0; UsartPrintf(USART1, "發送時間: %d微秒\r\n", time); DelayMs(2500); } }
效果以下