delay.c
#include "delay.h"
//à?ó??μí3μ?′e?¨ê±£?±àD′μ??óê±oˉêy
static u8 fac_us=0; //us?óê±±?3?êy
static u16 fac_ms=0; //ms?óê±±?3?êy
/****************************************************************************
* ?? 3?: delay_init()
* 1| ?ü£o?óê±oˉêy3?ê??ˉ
* è??ú2?êy£o?T
* ·μ??2?êy£o?T
* ?μ ?÷£o
****************************************************************************/
void delay_init(void)
{
SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
//?a?μí3?¨ê±?÷????ê±?ó?a HCLK 8·??μ 72MHz / 8 = 9MHz
fac_us = SYSCLK / 8;
//?¢??μ?±?3?êy = 72 / 8 = 9
//X * fac_us?í?àμ±óúóDX???¢??
fac_ms = (u16)fac_us * 1000;
//????msDèòaμ?systickê±?óêy(1ms = 1000us),?ùò?fac_us*1000
//X * fac_ms?í?àμ±óúóDX??oá??
}
/****************************************************************************
* ?? 3?: void delay_us(u32 nus)
* 1| ?ü£o?óê±nus
* è??ú2?êy£oòa?óê±μ??¢??êy
* ·μ??2?êy£o?T
* ?μ ?÷£onusμ??μ,2?òa′óóú1864135us
****************************************************************************/
/*
í¨1y?à1?ê?2á?ò??á??aμ?,±?·Y?μ??′??÷oíμ±?°?μ??′??÷μ??μ×?′ó?a16M - 1
?ò??μ??¢????μ??óê±oˉêyμ?±?3?êy?a9?ùò?16M - 1 / 9 = 1864135
*/
void delay_us(u32 nus)
{
u32 midtime; //±£′???′??÷μ?×′ì?
SysTick->LOAD = nus * fac_us; //ê±???ó??(?àμ±óúóDnus???¢??)
SysTick->VAL = 0x00; //??????êy?÷
SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; //ê1?ü?μí3?¨ê±?÷??êy
do
{
midtime = SysTick->CTRL;
}
while((midtime & 0x01) && !(midtime & (1 << 16)));//μè′yê±??μ?′?
SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; //1?±???êy?÷
SysTick->VAL = 0X00; //??????êy?÷
}
/****************************************************************************
* ?? 3?: void delay_xms(u16 nms)
* 1| ?ü£o?óê±nms
* è??ú2?êy£oòa?óê±μ?oá??êy
* ·μ??2?êy£o?T
* ?μ ?÷£oSysTick->LOAD?a24????′??÷,?ùò?,×?′ó?óê±?a: nms<=0xffffff*8*1000/SYSCLK
??9Mì??t??,nms<=1864ms
****************************************************************************/
void delay_xms(u16 nms)
{
u32 midtime;
SysTick->LOAD = (u32)nms*fac_ms; //ê±???ó??(SysTick->LOAD?a24bit)
SysTick->VAL = 0x00; //??????êy?÷
SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; //?aê?μ1êy
do
{
midtime = SysTick->CTRL;
}
while((midtime & 0x01) && !(midtime & (1 << 16)));//μè′yê±??μ?′?
SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; //1?±???êy?÷
SysTick->VAL = 0X00; //??????êy?÷
}
/****************************************************************************
* ?? 3?: void delay_ms(u16 nms)
* 1| ?ü£o?óê±nms
* è??ú2?êy£oòa?óê±μ?oá??êy
* ·μ??2?êy£o?T
* ?μ ?÷£onms:0~65535
****************************************************************************/
void delay_ms(u16 nms)
{
u8 repeat = nms / 540; //????óD?àéù????μ?540ms
u16 remain = nms % 540; //????óD?àéù??2?1?540ms
while(repeat)
{
delay_xms(540);
repeat--;
}
if(remain)delay_xms(remain);
}
delay.h
#ifndef __DELAY_H
#define __DELAY_H
#include "stm32f10x_conf.h"
#define SYSCLK 72
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
void delay_init(void);
void delay_ms(u16 nms);
void delay_us(u32 nus);
#endif