基于STM32实现软件定时器,在软件定时器时间到达后调用回掉函数,执行特定功能,功能上比较简单 ,主要是分享出来 ,为大家提供一个思路。
不废话直接上代码:
#include "timer.h"
timer_t timerlist[TIMER_LIST_MAX];
uint32_t timer3_tick =0;
extern void timer0_backcall_func(void);
void timer_task(void)
{
uint8_t i;
for(i=0;i<TIMER_LIST_MAX ;i++){
if(timerlist[i].state==0)continue;
else{
timerlist[i].count++;
}
if(timerlist[i].count==timerlist[i].expire){
timerlist[i].count = 0;
// if(timerlist[i].opt==0){//此单次定时器功能暂时不用
// timerlist[i].expire = 0;
// }
timerlist[i].callback();
}
}
}
/**
* 开启定时器
* num 定时器编号 val 计数时间
*/
void timer_enable(uint8_t num,uint32_t val,void (* timer_backcall_func) (void))
{
timerlist[num].state = 1;//定时器使用情况
timerlist[num].expire = val+timer3_tick;//定时值
timerlist[num].callback = timer_backcall_func;
}
void timer_disable(uint8_t num)
{
timerlist[num].state = 0;
}
void Timer3_init(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
/* TIM3 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period =200; //count max number 50000, time 50ms
TIM_TimeBaseStructure.TIM_Prescaler = 720-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
/* TIM Interrupts enable */
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
/* Enable the TIM3 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 6;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
timer3_tick++;
timer_task();
}
}
/***************************************************/
#ifndef _TIMER_H_
#define _TIMER_H_
#include "stm32f10x.h"
#define TIMER_LIST_MAX 5 /*定时器数量*/
typedef void (*tmr_fnct_ptr) (void);
typedef uint8_t TMR_STATE;
typedef struct{
uint32_t expire; /* 定时器到期时间 */
uint32_t count; /*定时器计数*/
tmr_fnct_ptr callback; /* 回调函数 */
uint8_t state; /* 定时器状态 */
uint8_t opt; /* 操作类型 1连续 0单次 */
}timer_t;
void Timer3_init(void);
void Timer3_enable(void);
void Timer3_disable(void);
#endif
|