delay.c
/*
* delay.c
*
* Created on: Dec 5, 2019
* Author: admin
*/
#include "delay.h"
#include "main.h"
#include <string.h>
#if 0
void delay_us(unsigned int nus)
{
unsigned int i, j;
for(i = 0; i < nus; i++)
{
for(j = 0; j < 1000; j++)
{
}
}
}
#else
#define SYS_CORE_CLOCK_MHZ 72
void delay_us(unsigned int us)
{
unsigned int ticks = us * SYS_CORE_CLOCK_MHZ;
unsigned int tickcount = 0, tnow = 0, told = SysTick->VAL;
do
{
tnow = SysTick->VAL; //获取当前值。
tickcount += (
told > tnow ? (told - tnow) : (SysTick->LOAD + told - tnow));
told = tnow;
} while (tickcount < ticks);
}
#endif
#if CONTER_LIST_MAX
static CounterList conter_list[CONTER_LIST_MAX] =
{ 0 };
void Init_Timers(void)
{
memset(&conter_list, 0x0, sizeof(conter_list));
}
int Register_Conter(unsigned int id, unsigned int counter)
{
int i = 0, index = -1;
for (i = 0; i < CONTER_LIST_MAX; i++)
{
if (conter_list[i].id == id)
{
conter_list[i].counter = counter;
conter_list[i].valid = 1;
return 0;
}
else if (conter_list[i].valid == 0 && index == -1)
{
index = i;
}
}
if (i >= CONTER_LIST_MAX && index >= 0)
{
conter_list[index].id = id;
conter_list[index].counter = counter;
conter_list[index].valid = 1;
return 0;
}
return -1;
}
void UnRegister_Conter(unsigned int id)
{
unsigned int i = 0;
for (i = 0; i < CONTER_LIST_MAX; i++)
{
if (conter_list[i].id == id)
{
conter_list[i].id = 0;
conter_list[i].counter = 0;
conter_list[i].valid = 0;
}
}
}
int Get_Conter(unsigned int id)
{
unsigned int i = 0;
for (i = 0; i < CONTER_LIST_MAX; i++)
{
if (conter_list[i].id == id && conter_list[i].valid)
{
return conter_list[i].counter;
}
}
return -1;
}
void Conter_CallBack(void)
{
unsigned int i = 0;
for (i = 0; i < CONTER_LIST_MAX; i++)
{
if (conter_list[i].valid)
{
if (conter_list[i].counter > 0)
{
conter_list[i].counter--;
}
}
}
}
#endif //CONTER_LIST_MAX
delay.h
/*
* delay.h
*
* Created on: Dec 5, 2019
* Author: admin
*/
#ifndef BSP_DELAY_H_
#define BSP_DELAY_H_
#define CONTER_LIST_MAX 3
void delay_us(unsigned int nus);
#if CONTER_LIST_MAX
typedef struct
{
unsigned int id; //计数器ID
int counter; //计数器的值
unsigned char valid; //计数器有效?
} CounterList;
void Init_Timers (void);
int Register_Conter(unsigned int id, unsigned int counter);
void UnRegister_Conter(unsigned int id);
unsigned int Get_Conter(unsigned int id);
void Conter_CallBack (void);
#endif //CONTER_LIST_MAX
#endif /* BSP_DELAY_H_ */
用法:
#define TIMER_ID 0x0001
void main(void)
{
delay_ms(1000);
while(1)
{
if(Get_Conter(TIMER_ID) == 0)
{
//用户代码
Register_Conter(TIMER_ID, 500);
}
}
}
//定时器3定时1ms中断
void Timer3_Interrupt (void) interrupt 14
{
if(TMR3CN & 0x80) //高位溢出
{
TMR3CN = TMR3CN & 0x7F; //清除高位中断标志位
AdduwTick();
#if CONTER_LIST_MAX
Conter_CallBack();
#endif //CONTER_LIST_MAX
}
else if(TMR3CN & 0x40) //低位溢出
{
TMR3CN = TMR3CN & 0xBF; //清除低位中断标志位
}
}
全篇完。
本人是一个嵌入式未入门小白,博客仅仅代表我个人主观见解,记录成长笔记。
笔记是以最简单的方式,只展示最核心的原理。
若有与 大神大大 见解有歧义,我绝对坚信 大神大大 见解是对的,我的是错的。
若无积分等无法下载源码,可加入QQ群657407920下载交流经验。感谢~!