STM32F103 series_delay function using system clock SysTick

STM32F103 series_delay function using system clock SysTick

Design origin

Using the TIM clock for delay is a waste of TIM. In order to make full use of the STM32 clock, we use a very accurate system clock for delay.

code

Delay.c

//延时函数初始化
#include "stm32f10x.h"
#include "Delay.h"

void Delay_Init(void)
{
    
    
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8); //选择外部时钟
}

//微秒延时
void Delay_us(u16 n)
{
    
    
	u32 temp;
	SysTick->LOAD = n * 9;					  //时间加载
	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;							//清空计数器
}

//毫秒延时
void Delay_ms(u16 n)
{
    
    
	u32 temp;
	SysTick->LOAD = (u32)n * 9000;			  //时间加载
	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;							//清空计数器
}

//秒延时
void Delay_s(u16 n)
{
    
    
	for (u16 x = 0; x < n; x++)
	{
    
    
		u32 temp;
		SysTick->LOAD = 9000000;				  //时间加载
		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;							//清空计数器
	}
}

Delay.h

#ifndef __DELAY_H
#define __DELAY_H 			   

extern void Delay_Init(void);

extern void Delay_ms(u16 n);
extern void Delay_us(u16 n);
extern void Delay_s(u16 n);

#endif

Instructions

1. Call the Delay.h header file in the main function, and call Delay_Init() to initialize the delay function;
2. Use Delay_us() to perform a microsecond level delay. Fill in the number in the brackets for the number of microseconds the delay is;
3. Use Delay_ms() to perform millisecond-level delay. If the delay is in milliseconds, fill in the number in the brackets. 4.
Use Delay_s() to perform the second-level delay. If the delay is in seconds, fill in the number in the brackets.

Guess you like

Origin blog.csdn.net/xingdala/article/details/121590559