#include "led.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"

void led_init(uint16_t led)
{
    GPIO_InitTypeDef  GPIO_InitStructure = {
        .GPIO_Pin = led,
        .GPIO_Mode = GPIO_Mode_OUT,
        .GPIO_OType = GPIO_OType_PP,
        .GPIO_Speed = GPIO_Speed_2MHz,
        .GPIO_PuPd = GPIO_PuPd_NOPULL,
    };

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
    GPIO_Init(PORT_LED, &GPIO_InitStructure);
    led_off(led);
}

void led_off(uint16_t led)
{
    GPIO_SetBits(PORT_LED, led);
}

void led_on(uint16_t led)
{
    GPIO_ResetBits(PORT_LED, led);
}

void led_loop(void)
{
    static uint32_t ms = 0;
    static uint32_t led_cnt = 0;

    if (system_tick_cnt < (ms + 200)) {
        return;
    }
    ms = system_tick_cnt;

    led_cnt = led_cnt & 3;
    switch (led_cnt) {
        case 0: led_off(LED1 | LED2); break;
        case 1: led_off(LED1); led_on(LED2);break;
        case 2: led_on(LED1); led_off(LED2); break;
        case 3: led_on(LED1 | LED2); break;
    }
    led_cnt++;
}
