#include "delay.h"
#include "core_cm3.h"
#include "gd32f1x0_misc.h"
static uint8_t fac_us=0;//usÑÓʱ±¶³ËÊý
static uint16_t fac_ms=0;//msÑÓʱ±¶³ËÊý
//³õʼ»¯ÑÓ³Ùº¯Êý
//SYSTICKµÄʱÖӹ̶¨ÎªHCLKʱÖÓµÄ1/8
//SYSCLK:ϵͳʱÖÓ ÕâÀïΪ72MHZ
void delay_init(uint8_t SYSCLK)
{
SysTick_CKSource_Enable(SYSTICK_CKSOURCE_HCLK_DIV8);
fac_us=SYSCLK/8; //,fac_us¶¼ÐèҪʹÓÃ8·ÖƵ
fac_ms=(uint16_t)fac_us*1000;//´ú±íÿ¸ömsÐèÒªµÄsystickʱÖÓÊý
}
//ÑÓʱnus
//nusΪҪÑÓʱµÄusÊý.
//×¢Òâ:nusµÄÖµ,²»Òª´óÓÚ798915us
void delay_us(uint32_t nus)
{
uint32_t temp;
SysTick->LOAD=nus*fac_us; //ʱ¼ä¼ÓÔØ
SysTick->VAL=0x00; //Çå¿Õ¼ÆÊýÆ÷
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //¿ªÊ¼µ¹Êý
do
{
temp=SysTick->CTRL;
}
while((temp&0x01)&&!(temp&(1<<16)));//µÈ´ýʱ¼äµ½´ï
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //¹Ø±Õ¼ÆÊýÆ÷
SysTick->VAL =0X00; //Çå¿Õ¼ÆÊýÆ÷
}
//ÑÓʱnms
//×¢ÒânmsµÄ·¶Î§
//SysTick->LOADΪ24λ¼Ä´æÆ÷,ËùÒÔ,×î´óÑÓʱΪ:
//nms<=0xffffff*8*1000/SYSCLK
//SYSCLKµ¥Î»ÎªHz,nmsµ¥Î»Îªms
//¶Ô168MÌõ¼þÏÂ,nms<=798ms
void delay_xms(uint16_t nms)
{
uint32_t temp;
SysTick->LOAD=(uint32_t)nms*fac_ms;//ʱ¼ä¼ÓÔØ(SysTick->LOADΪ24bit)
SysTick->VAL =0x00; //Çå¿Õ¼ÆÊýÆ÷
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //¿ªÊ¼µ¹Êý
do
{
temp=SysTick->CTRL;
}
while((temp&0x01)&&!(temp&(1<<16)));//µÈ´ýʱ¼äµ½´ï
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //¹Ø±Õ¼ÆÊýÆ÷
SysTick->VAL =0X00; //Çå¿Õ¼ÆÊýÆ÷
}
//ÑÓʱnms
//nms:0~65535
void delay_ms(uint16_t nms)
{
uint8_t repeat=nms/540; //ÕâÀïÓÃ540,ÊÇ¿¼Âǵ½Ä³Ð©¿Í»§¿ÉÄܳ¬ÆµÊ¹ÓÃ,
//±ÈÈ糬Ƶµ½248MµÄʱºò,delay_xms×î´óÖ»ÄÜÑÓʱ541ms×óÓÒÁË
uint16_t remain=nms%540;
while(repeat)
{
delay_xms(540);
repeat--;
}
if(remain)delay_xms(remain);
}
.h文件:
#include "gd32f1x0_rcc.h"
void delay_init(uint8_t SYSCLK);
void delay_ms(uint16_t nms);
void delay_us(uint32_t nus);
|