频率(HZ)是频率的基本单位1HZ是1s的倒数
STM32F103C8T6一般情况给定时器的内部时钟都是72MHz(系统主频率)
TIM基本构成
计数器、预分频器、自动化重装 // 都是16位
其中计数器、自动化重装,都是16位换算成10进制范围为[0, 655536]
时间 = 1 / [(1 + 自动化重装) * (1 + 预分频器) / 72M ]
其中自动分频器取值为[0, 65535]
分频 = 自动分频器取值 + 1
例如:
自动化重装为72、预分频器取值为2^16 - 1、计数器为2^16 - 1
那么计数器完成计数所耗费的时间为:
1/[65536 * 65536 / 72M] = 59.65s
定时器基本结构
朴素的讲计数器计数达到自动重装值就会申请NVIC中断,此过程耗费的时间就是我们想要的时间
代码:
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"uint16_t num = 0;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;/*初始化通用定时器TIM2*/
void Timer_Init(void){RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);//APB1外设开启TIM_InternalClockConfig(TIM2);//选择内部时钟/*初始化时基单元*/TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上计数TIM_TimeBaseInitStructure.TIM_Period = 10000 - 1;//ARR自动重装TIM_TimeBaseInitStructure.TIM_Prescaler = 7200 - 1;//psc预分频器TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;//高级计时器内容直接给零//记录1s TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);//刚初始化完就会进中断TIM_ClearFlag(TIM2, TIM_FLAG_Update);//消除中断标志位//使能更新中断TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);/*配置中断*/NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//选择组2NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;//定时器2在NVIC内的通道NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;NVIC_Init(&NVIC_InitStructure);TIM_Cmd(TIM2, ENABLE);//启动定时器
}void TIM2_IRQHandler(void){//定时器2的中断函数,名字固定if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET){num = num + 1;TIM_ClearITPendingBit(TIM2, TIM_IT_Update);//清除标志位}
}int main(void){OLED_Init();//初始化OLEDTimer_Init();while(1){ OLED_ShowNum(1,1, num, OLED_GetNumLength(num));OLED_ClearLocation(1,OLED_GetNumLength(num));}
}
其中:
uint8_t OLED_GetNumLength(uint16_t num){uint8_t length = 0;if(num == 0) return (uint8_t)1;while(num > 0){num = num / 10;length = length + 1;}return length;
}
void OLED_ClearLocation(uint8_t row, uint8_t len)
{ uint8_t i, j;for (j = row * 2 - 2; j < row * 2; j++){OLED_SetCursor(j, len * 8);for(i = len * 8; i < 128; i++){OLED_WriteData(0x00);}}
}
效果:
每过一秒,数字增加1