//----------------------------main()--------------------

//stm32f103c8t6有3个普通1个高级定时器
//每次进入中断服务程序间隔时间为
//((1+TIM_Prescaler )/72M)*(1+TIM_Period )=((1+7199)/72M)*(1+9999)=1秒
#include<stm32f10x.h>
#define D13_ON GPIO_ResetBits(GPIOC,GPIO_Pin_13)
#define D13_OFF GPIO_SetBits(GPIOC,GPIO_Pin_13) void GPIO_Config(void);
void TIM2_Config(u16 arr,u16 psc);
void NVIC_Config(void); //主函数
int main(void)
{
GPIO_Config();
//((1+arr )/72M)*(1+psc )=((1+1999)/72M)*(1+35999)=1秒
TIM2_Config(1999,35999);
NVIC_Config();
while(1); } //初始化GPIO
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE); //PC13灯
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC,&GPIO_InitStructure);
GPIO_ResetBits(GPIOC,GPIO_Pin_13); //关闭LED
} //初始化TIM2定时器及中断
//每次进入中断服务程序间隔时间为
//((1+arr )/72M)*(1+psc )=((1+1999)/72M)*(1+35999)=1秒
void TIM2_Config(u16 arr,u16 psc)
{
//定时器时间是1s TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//清除中断标志位
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);//TIM_ClearFlag(TIM2,TIM_FLAG_Update);//两者作用相同 //自动装载的周期值0-0xffff,72M/36000=2000
TIM_TimeBaseStructure.TIM_Period = arr;
//时钟除数预分频值0-oxffff,下面是36000分频
TIM_TimeBaseStructure.TIM_Prescaler = psc;
////普通和高级才有下面两行
//时钟分割,暂时为0,高级应用才用
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//计数模式,向上下,中央对齐123
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure); //开启中断
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
//开启外设
TIM_Cmd(TIM2,ENABLE);
} //初始化中断向量控制器NVIC void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
} //--------------------stm32f10x_it.c------------------------
//中断函数中自己编写
void TIM2_IRQHandler(void)
{
//判断TIM3更新中断是否发生
if(TIM_GetITStatus(TIM2,TIM_IT_Update)!=RESET)
{
//必须清楚标志位
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
//状态取反
GPIO_WriteBit(GPIOC,GPIO_Pin_13,(BitAction)(!GPIO_ReadOutputDataBit(GPIOC,GPIO_Pin_13)));
} }
---------------------
作者:sea1216
来源:CSDN
原文:https://blog.csdn.net/sea1216/article/details/80621489
版权声明:本文为博主原创文章,转载请附上博文链接!