Ads

Get STM32 tutorial using HAL at $10 for a limited time!

Saturday, April 18, 2015

STM32F4 Discovery Tutorial 5 - Make Delay Using System Timer (SysTick)

In this tutorial, I’ll explain about system timer (SysTick). SysTick timer can be used to make delay function. STM32F4 has a 24-bit system timer, that counts down from RELOAD value to zero (16,777,215 to 0). The SysTick clock source is 168 MHz so 168,000,000 ticks per second. The time required to make one tick is 1 ÷ 168,000,000 ≈ 5.952 ns.

To use SysTick timer we have to call SysTick_Config function which responsible to initializes the system tick timer and its interrupt and start the system tick timer. The timer is in free running mode to generate periodical interrupts. Parameter input of SysTick_Config function is number of ticks between two interrupts (time between two interrupts). You can see SysTick_Config function in core_cm4.h.


For example, if we want to make interrupt every 1 ms we can put 1,000,000 ÷ 5.952 ≈ 168,010.752 tick to the SysTick_Config function. But, the data type of input parameter of that function is uint32_t so we can only put integer number. If we round the tick to 168,000, we can simply call SystemCoreClock variable divided by 1000. SystemCoreClock is a global variable that contains the system frequency which is 168MHz.

This is the example code for making delay with SysTick timer:
#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"

__IO uint32_t msTick;

// This function will be called every 1ms
void SysTick_Handler(void)
{
    msTick--;
}

int main(void)
{
    // Enable GPIOD
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

    // Initialization for GPIO pin 13 (orange LED) as output
    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOD, &GPIO_InitStruct);

    // Update SystemCoreClock variable
    SystemCoreClockUpdate();
    // Make SysTick overflow every 1ms
    SysTick_Config(SystemCoreClock / 1000);

    while (1)
    {
        // Toggle LED
        GPIO_ToggleBits(GPIOD, GPIO_Pin_13);

        // Set delay 1s (1000ms)
        msTick = 1000;
        // Do nothing until msTick is zero
        while (msTick);
    }
}

2 comments :