STM32定时器溢出模式计时设置

时间:2022-06-28 23:32:48

STM32定时器溢出模式设置


本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.


环境:

主机:WIN7

开发环境:MDK4.23

MCU:STM32F103CBT6


源代码1:

说明:定时器采用TIM2,时钟源为内部8M晶振,向上溢出模式.此定时器用在延时函数,最小可以延时1us,故没有采用中断形式定时.

初始化代码:

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//重新将Timer设置为缺省值
TIM_DeInit(TIM2);
//采用内部时钟给TIM2提供时钟源
TIM_InternalClockConfig(TIM2);

timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //定时器基准频率8MHz
timInitStruct.TIM_Prescaler = 8 - 1; //计数频率为1us跳转1次
timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
timInitStruct.TIM_RepetitionCounter = 0;
timInitStruct.TIM_Period = 0; //这个值实际上就是TIMX->ARR,延时开始时重新设定即可

TIM_TimeBaseInit(TIM2, &timInitStruct);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); //计数溢出时触发中断
TIM_Cmd(TIM2, ENABLE); //开启计数器


延时函数代码:

//延时1us
//最大65536us
void _delay_us(uint16_t t)
{
TIM_SetCounter(TIM2,0);
TIM_SetAutoreload(TIM2,t - 1);
//等待时间到
while (TIM_GetITStatus(TIM2,TIM_FLAG_Update) == 0);
//停止计数
TIM_SetAutoreload(TIM2,0);
//清中断标志
TIM_ClearITPendingBit(TIM2,TIM_FLAG_Update);
}

//延迟1ms
//最大65ms
void _delay_ms(uint8_t t)
{

if (t > 65)
{
t = 65;
}
_delay_us(t * 1000);
}

源代码2:

说明:定时器采用TIM3,时钟源为内部8M晶振,向上溢出模式.此定时器用在长时间计时,最小计时间隔为100us,故采用中断形式定时.

初始化代码:

//中断NVIC设置:允许中断,设置优先级
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //更新事件
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应优先级1
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //允许中断
NVIC_Init(&NVIC_InitStructure); //写入设置

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
//重新将Timer设置为缺省值
TIM_DeInit(TIM3);
//采用内部时钟给TIM3提供时钟源
TIM_InternalClockConfig(TIM3);

timInitStruct.TIM_ClockDivision = TIM_CKD_DIV2; //定时器基准频率8MHz
timInitStruct.TIM_Prescaler = 800 - 1; //计数频率为100us跳转1次
timInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
timInitStruct.TIM_RepetitionCounter = 0;
timInitStruct.TIM_Period = 0; //这个值实际上就是TIMX->ARR,延时开始时重新设定即可

TIM_TimeBaseInit(TIM3, &timInitStruct);
//清溢出中断标志
TIM_ClearFlag(TIM3, TIM_FLAG_Update);
//禁止ARR预装载缓冲器
TIM_ARRPreloadConfig(TIM3, DISABLE);
//开启中断
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM3, ENABLE); //开启计数器

中断函数代码:

//TIM3中断
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET)
{
TIM3->ARR = 0;
//清中断溢出标志
TIM_ClearITPendingBit(TIM3,TIM_FLAG_Update);

//发送信号
Sig_Table.stop_require = 1;
}
}