/**
	************************************************************
	************************************************************
	************************************************************
	*	ļ 	delay.c
	*
	*	ߣ 		ż
	*
	*	ڣ 		2016-11-23
	*
	*	汾 		V1.0
	*
	*	˵ 		systickʽʱ
	*
	*	޸ļ¼	
	************************************************************
	************************************************************
	************************************************************
**/

//Ƭͷļ
#include "stm32f10x.h"

//delayͷļ
#include "delay.h"



//ʱϵ
unsigned char UsCount = 0;
unsigned short MsCount = 0;



/*
************************************************************
*	ƣ	Delay_Init
*
*	ܣ	systickʼ
*
*	ڲ	
*
*	ز	
*
*	˵		
************************************************************
*/
void Delay_Init(void)
{

	SysTick->CTRL &= ~(1 << 2);		//ѡʱΪHCLK(72MHz)/8		103--9MHz
	
	UsCount = 9;					//΢뼶ʱϵ
	
	MsCount = UsCount * 1000;		//뼶ʱϵ

}

/*
************************************************************
*	ƣ	DelayUs
*
*	ܣ	΢뼶ʱ
*
*	ڲ	usʱʱ
*
*	ز	
*
*	˵		ʱ(21MHz)ʱ798915us
************************************************************
*/
void DelayUs(unsigned short us)
{

	unsigned int ctrlResult = 0;
	
	us &= 0x00FFFFFF;											//ȡ24λ
	
	SysTick->LOAD = us * UsCount;								//װ
	SysTick->VAL = 0;
	SysTick->CTRL = 1;											//ʹܵ
	
	do
	{
		ctrlResult = SysTick->CTRL;
	}
	while((ctrlResult & 0x01) && !(ctrlResult & (1 << 16)));	//֤СǷ񵹼0
	
	SysTick->CTRL = 0;											//رյ
	SysTick->VAL = 0;

}

/*
************************************************************
*	ƣ	DelayXms
*
*	ܣ	뼶ʱ
*
*	ڲ	msʱʱ
*
*	ز	
*
*	˵		
************************************************************
*/
void DelayXms(unsigned short ms)
{

	unsigned int ctrlResult = 0;
	
	if(ms == 0)
		return;
	
	ms &= 0x00FFFFFF;											//ȡ24λ
	
	SysTick->LOAD = ms * MsCount;								//װ
	SysTick->VAL = 0;
	SysTick->CTRL = 1;											//ʹܵ
	
	do
	{
		ctrlResult = SysTick->CTRL;
	}
	while((ctrlResult & 0x01) && !(ctrlResult & (1 << 16)));	//֤СǷ񵹼0
	
	SysTick->CTRL = 0;											//رյ
	SysTick->VAL = 0;

}

/*
************************************************************
*	ƣ	DelayMs
*
*	ܣ	΢뼶ʱ
*
*	ڲ	msʱʱ
*
*	ز	
*
*	˵		εDelayXmsʱ
************************************************************
*/
void DelayMs(unsigned short ms)
{

	unsigned char repeat = 0;
	unsigned short remain = 0;
	
	repeat = ms / 500;
	remain = ms % 500;
	
	while(repeat)
	{
		DelayXms(500);
		repeat--;
	}
	
	if(remain)
		DelayXms(remain);

}
