Search code examples
arduinomicrocontrollerstm32millisecondsstm32f0

Arduino millis() in stm32


I am trying to port some Arduino library to stm32. In Arduino, millis() returns the number of milliseconds since boot. Is there an equivalent function in stm32? I am using stm32f0 MCU.


Solution

  • SysTick is an ARM core peripheral provided for this purpose. Adapt this to your needs:

    Firstly, initialise it

    // Initialise SysTick to tick at 1ms by initialising it with SystemCoreClock (Hz)/1000
    
    volatile uint32_t counter = 0;
    SysTick_Config(SystemCoreClock / 1000);
    

    Provide an interrupt handler. Your compiler may need interrupt handlers to be decorated with additional attributes.

    SysTick_Handler(void) {
      counter++;
    }
    

    Here's your millis() function, couldn't be simpler:

    uint32_t millis() {
      return counter;
    }
    

    Some caveats to be aware of.

    1. SysTick is a 24 bit counter. It will wrap on overflow. Be aware of that when you're comparing values or implementing a delay method.

    2. SysTick is derived from the processor core clock. If you mess with the core clock, for example slowing it down to save power then the SysTick frequency must be manually adjusted as well.