STM32F103 SPL Tutorial 4 – Create a Delay Function with System Timer

STM32F103 System Timer

STM32F103 System Timer or SysTick is a timer inside the CPU. SysTick is a basic countdown timer. SysTick can be polled by software or can be configured to generate an interrupt. To use SysTick, we must load a value to the reload value register. The width of reload value register is 24-bit, so it can counts from 0x00FFFFFF to 0. In this tutorial, I will explain how to use SysTick for creating a delay function. SysTick can be configured through the registers below.

SysTick register

To easily configure SysTick, we can use SysTick_Config() function. This function is defined in core_cm3.h. This function will initialize SysTick and its interrupt, then start the SysTick. The counter is in free running mode to generate periodic interrupts. The input parameter of this function is the number of ticks between two interrupts.

Create A Delay Function

In this tutorial, I will create 2 delay functions (DelayUs() and DelayMs()). To create DelayUs() function, we should configure the SysTick interrupt to be triggered every 1 us by using SysTick_Config() function. There is a variable called usTicks that holds the value of ticks in us. Every time we call DelayUs() function, we should load this variable with the delay value in us and then we poll this variable until reach 0. This variable will be decremented by 1 every 1 us by SysTick_Handler() ISR. To create DelayMs() function, we should load the delay value in ms, then it will be decremented by 1 every 1000 us using DelayUs() function. This is the code for delay library. To use the delay functions, you should call the DelayInit() function first. For the project file you can get it from here.

Go to the part 5 of the tutorial.