定时器每隔一秒计次一次
1,创建 .C .H 文件
Timer.c
Timer.h
2,包含头文件
#include "ch32v30x.h"
//#include "debug.h"
#include "Timer.h"
注意:如果不包含第一第二个头文件uint、int这些定义就会报错,实际上不包含debug.h也可,个人猜测是ch32v30x.h也包含了debug.h。
3,配置Timer_Init()相关
/*
* 1,开启RCC-TIM时钟
* 2,TIM选择时钟源,这里选择内部时钟
* 3,初始化TIM
* 4,使能更新中断 -->TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
* 5,NVIC分组 -->NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
* 6,NVIC初始化
* 7,(开启)启动定时器 -->TIM_Cmd(TIM2,ENABLE);
* 8,声明定时器中断2函数是一个中断 -->void TIM2_IRQHandler(void)__attribute__((interrupt));
* */
extern uint16_t Num;
void Timer_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_InternalClockConfig(TIM2); //选择内部时钟
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; //系统时钟不分频
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInitStruct.TIM_Period = 10000 - 1; //ARR自动重装值
TIM_TimeBaseInitStruct.TIM_Prescaler = 14400-1; //PSC预分频值 144000000 / 14400 = 10000 ,我选择系统时钟是144M
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0; //重复计数值,高级定时器才有,通用计时器和基本定时器没有
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);
TIM_ClearFlag(TIM2,TIM_IT_Update),
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStruct);
TIM_Cmd(TIM2,ENABLE);
}
void TIM2_IRQHandler(void)__attribute__((interrupt("WCH-Interrupt-fast")));
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET)
{
Num++;
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}
4,实验现象