STM32用一个定时器执行多任务写法

2023-12-15 09:34:24

文章目录

main.c

#include "stm32f4xx.h"

uint32_t Power_check_times;			  //电量检测周期
uint32_t RFID_Init_Check_times;  	//RFID检测周期

int main()
{
	Timer_Init(167,999);
	Power_check_times =  gt_get() + 200;//一开始最少是200ms+gt_get()的时间,所以最低是200ms
	RFID_Init_Check_times = gt_get() + 200;
	while(1)
	{				
//下面的两个if是这个文章想表达的具体实现什么不用管,本文章目的是用一个定时器,进行200ms进入执行程序
		if(gt_get_sub(Power_check_times) == 0) 	//目标时间200ms,然后定时器计时到了200ms则进来一次	
		{
			Power_check_times =  gt_get() + 200;			//电池电量检测,进来后让目标时间在+200,等程序出去后,就可以等待下一次的200ms测量
			Power_Check();
		} 
		if(gt_get_sub(RFID_Init_Check_times) == 0) 			
		{
			RFID_Init_Check_times =  gt_get() + 200;	//RFID初始化检测
			if(Rc522_GetLinkFlag() == 0)					
			{
				Readcard_daivce_Init();
				MP_SPK = !MP_SPK;
			} 
			else
			{
				MP_SPK = 0;
				LED4 = !LED4;
				Rc522_LinkTest();
			}
		 } 
}

Timer.c

#include "stm32f4xx.h"
#include "Timer.h"

volatile uint32_t global_times = 0;
volatile uint32_t delay_ms_const = 0;

void Timer_Init(uint16_t arr,uint16_t psc)//内部时钟168MHZ
{
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM10,ENABLE);
	
	TIM_InitStructure.TIM_Period = arr;
	TIM_InitStructure.TIM_Prescaler = psc;
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_InitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM10,&TIM_InitStructure);

	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
	NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 6;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	TIM_ITConfig(TIM10,TIM_IT_Update,ENABLE);
	TIM_Cmd(TIM10, ENABLE);
}


void TIM1_UP_TIM10_IRQHandler(void)//1ms进来一次,计数值global_times+1,global_times=1就代表为1ms
{
	if(TIM_GetITStatus(TIM10,TIM_IT_Update) == SET)
	{
			global_times++;
	}
	TIM_ClearITPendingBit(TIM10,TIM_IT_Update);
}

uint32_t gt_get(void)//获取计数值global_times
{
	return global_times;
}

uint32_t gt_get_sub(uint32_t c)
{
	if(c > global_times)//如果目标时间c大于计时时间global_times,则c=c-global_times,也就是算出它们的差值
		c -= global_times;
	else											//如果目标时间c小于等于计时时间global_times,则让返回值为0
		c = 0;
	return c;
}




Timer.h

#ifndef __TIMER_H__
#define __TIMER_H__

#include "stm32f4xx.h"                  // Device header

extern volatile uint32_t global_times;
extern volatile uint32_t delay_ms_const;

void Timer_Init(uint16_t arr,uint16_t psc);
uint32_t gt_get_sub(uint32_t c);
uint32_t gt_get(void);

#endif



文章来源:https://blog.csdn.net/2301_77540313/article/details/134930699
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。