用keil和stm32f103c8t6写定时器,并读取定时器定时了多久
时间: 2023-05-19 21:00:54 浏览: 102
可以使用以下代码来实现定时器并读取定时器定时了多久:
#include "stm32f10x.h"
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
// 定时器中断处理
}
}
int main(void)
{
// 初始化定时器
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitStruct.TIM_Prescaler = 7200 - 1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period = 1000 - 1;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
// 启动定时器
TIM_Cmd(TIM2, ENABLE);
// 配置定时器中断
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
while (1)
{
// 读取定时器计数值
uint16_t count = TIM_GetCounter(TIM2);
// 计算定时器定时了多久
uint32_t time = count * 1000 / 72000000;
// 延时一段时间
for (int i = 0; i < 1000000; i++);
}
return 0;
}
注意:以上代码仅供参考,具体实现方式可能会因为不同的硬件平台和软件环境而有所不同。
阅读全文