#define USE_STM32L476G_DISCO_REVC
#include "stm32l476g_discovery.h"
#include "stm32l4xx_hal.h"

TIM_HandleTypeDef hTim;
TIM_OC_InitTypeDef timOutChannel;
RCC_ClkInitTypeDef RCC_ClkInitStruct;

int main()
{
    // Configure Timer base
    __HAL_RCC_TIM1_CLK_ENABLE();

    hTim.Instance = TIM1;
    hTim.Init.Prescaler = 8000;
    hTim.Init.Period = 10000;
    hTim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    hTim.Init.CounterMode = TIM_COUNTERMODE_UP;
    hTim.Init.RepetitionCounter = 0;
    HAL_TIM_PWM_Init(&hTim);

    // Configure Timer channel
    timOutChannel.OCMode       = TIM_OCMODE_PWM1;
    timOutChannel.OCPolarity   = TIM_OCPOLARITY_HIGH;
    timOutChannel.OCFastMode   = TIM_OCFAST_DISABLE;
    timOutChannel.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
    timOutChannel.OCNIdleState = TIM_OCNIDLESTATE_RESET;
    timOutChannel.OCIdleState  = TIM_OCIDLESTATE_RESET;
    timOutChannel.Pulse = 5000;
    HAL_TIM_PWM_ConfigChannel(&hTim, &timOutChannel, TIM_CHANNEL_1);
    HAL_TIMEx_OCN_Start(&hTim, TIM_CHANNEL_1);

    // Configure GPIO
    LED5_GPIO_CLK_ENABLE();
    GPIO_InitTypeDef gpio;

    gpio.Mode = GPIO_MODE_AF_PP;
    gpio.Pull = GPIO_NOPULL;
    gpio.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    gpio.Alternate = GPIO_AF1_TIM1;
    gpio.Pin = LED5_PIN;
    HAL_GPIO_Init(LED5_GPIO_PORT, &gpio);

    //Start timer
    HAL_TIM_Base_Start(&hTim);
    HAL_TIM_PWM_Start(&hTim, TIM_CHANNEL_1);

    while(1)   {}
}

/************** TODO **********************
  - Increase frequency
  - Control pwm brightness with joystick

*/
