前言
- 模仿HAL库编程的Systick
- 滴答定时器
头文件
#ifndef STM32_STD_TEMPLATE_BSP_SYSTICK_H
#define STM32_STD_TEMPLATE_BSP_SYSTICK_H
#include "sys_core.h"
#define MAX_DELAY 0xFFFFFFFFU
typedef enum {
TICK_FREQ_10HZ = 100U,
TICK_FREQ_100HZ = 10U,
TICK_FREQ_1KHZ = 1U,
TICK_FREQ_DEFAULT = TICK_FREQ_1KHZ
} tick_freq_typedef;
extern __IO uint32_t uwTick;
extern tick_freq_typedef uwTickFreq;
void sys_tick_set(tick_freq_typedef tick_freq);
void sys_tick_init();
SYS_WEAK void sys_delay(uint32_t delay);
SYS_WEAK uint32_t sys_get_tick(void);
SYS_WEAK void sys_inc_tick(void);
#endif
源文件
#include "bsp_systick.h"
__IO uint32_t uwTick;
tick_freq_typedef uwTickFreq = TICK_FREQ_DEFAULT;
void sys_tick_set(tick_freq_typedef tick_freq) {
uwTickFreq = tick_freq;
}
void sys_tick_init() {
RCC_ClocksTypeDef RCC_Clocks;
RCC_GetClocksFreq(&RCC_Clocks);
SysTick_Config(RCC_Clocks.HCLK_Frequency / (1000U / uwTickFreq));
}
SYS_WEAK void sys_delay(uint32_t delay) {
uint32_t tick_start = sys_get_tick();
uint32_t wait = delay;
if (wait < MAX_DELAY) {
wait += (uint32_t) (uwTickFreq);
}
while ((sys_get_tick() - tick_start) < wait);
}
SYS_WEAK uint32_t sys_get_tick(void) {
return uwTick;
}
SYS_WEAK void sys_inc_tick(void) {
uwTick += uwTickFreq;
}
中断函数调用
void SysTick_Handler(void) {
sys_inc_tick();
}