#include "stm32f401xe.h"
#include "system_stm32f4xx.h"

volatile uint32_t g_ms = 0;

static void systick_init_1ms(void)
{
    SystemCoreClockUpdate();                 // bitno: osveži SystemCoreClock
    SysTick->LOAD = (SystemCoreClock / 1000u) - 1u;
    SysTick->VAL  = 0u;
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
                    SysTick_CTRL_TICKINT_Msk   |
                    SysTick_CTRL_ENABLE_Msk;
}

static void delay_ms(uint32_t ms)
{
    uint32_t start = g_ms;
    while ((uint32_t)(g_ms - start) < ms) {
        __WFI(); // opcionalno
    }
}

int main(void)
{
    // Clock za GPIOA
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    (void)RCC->AHB1ENR;

    // PA5 kao output (LD2 na NUCLEO-F401RE je PA5)
    GPIOA->MODER &= ~(3u << (5u * 2u));
    GPIOA->MODER |=  (1u << (5u * 2u));
    GPIOA->OTYPER &= ~(1u << 5u);           // push-pull
    GPIOA->OSPEEDR |= (2u << (5u * 2u));    // medium/high (nije kritično)
    GPIOA->PUPDR &= ~(3u << (5u * 2u));     // no pull

    systick_init_1ms();

    while (1) {
        GPIOA->ODR ^= (1u << 5u);
        delay_ms(500);
    }
}
