思路就是:将主函数的程序分为几块,不使用死延时函数,利用定时器中断,每1MS中断一次,然后中断1000次之后,过去了一秒钟,将1S标志位置1,然后主函数接收到之后,运行1S任务
#include "stm32f10x.h"
#include "usart.h"
#include "delay.h"int Time1ms;
int Time50ms;
int Time1s;unsigned char TIMER_1MS_EN_FLAG=1;
unsigned char TIMER_50MS_EN_FLAG=1;
unsigned char TIMER_1S_EN_FLAG =1; void TIM2_Config(void)
{TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;NVIC_InitTypeDef NVIC_InitStructure;//使能TIM2时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_DeInit(TIM2);//将TIMx外围寄存器初始化为其默认重置值NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;//TIM2中断NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//IRQ通道被使能NVIC_Init(&NVIC_InitStructure); //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器//定时器定时时间T计算公式:T=(TIM_Period+1)*(TIM_Prescaler+1)/TIMxCLKTIM_TimeBaseStructure.TIM_Period = 1000;//自动重装载值1000TIM_TimeBaseStructure.TIM_Prescaler =(72 - 1);//预分频值,+1为分频系数 72M/72 1ms定时TIM_TimeBaseStructure.TIM_ClockDivision =0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位TIM_ClearFlag(TIM2, TIM_FLAG_Update); // 清除溢出中断标志 TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE); //使能TIM2中断源TIM_Cmd(TIM2, ENABLE); //使能TIMx外设 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 , ENABLE); //先关闭等待使用
}void TIM2_IRQHandler(void)
{ if ( TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET ) //是否发生中断{ TIM_ClearITPendingBit(TIM2 , TIM_FLAG_Update); //清除中断待处理位Time1ms++;if(Time1ms>=1){TIMER_1MS_EN_FLAG=1; Time1ms=0;}Time50ms++;if(Time50ms>=50){TIMER_50MS_EN_FLAG=1; Time50ms=0;}Time1s++;if(Time1s >= 1000){TIMER_1S_EN_FLAG =1; Time1s=0;}}
}int main(void)
{ delay_init(); //延时函数初始化 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级uart_init(115200); //串口初始化为115200TIM2_Config();while(1){if(TIMER_1MS_EN_FLAG==1){TIMER_1MS_EN_FLAG=0;}if(TIMER_50MS_EN_FLAG == 1){TIMER_50MS_EN_FLAG=0;}if(TIMER_1S_EN_FLAG == 1){printf("1s\r\n");TIMER_1S_EN_FLAG=0;}}}