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


/************** TODO **********************
 - Find and fix bug in ADC initialization code
 - Perform actual measurement
 - Output actual calibrated temperature value (RTFM)
*/
int main()
{
    //Init and test LCD
    BSP_LCD_GLASS_Init();
    BSP_LCD_GLASS_DisplayBar(LCD_BAR_3);
    
    __HAL_RCC_ADC_CLK_ENABLE();
    __HAL_RCC_ADC_FORCE_RESET();
    __HAL_RCC_ADC_RELEASE_RESET();
    __HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_SYSCLK);
    
    ADC_HandleTypeDef hAdc;
    hAdc.Instance = ADC1;
    hAdc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV256;
    hAdc.Init.Resolution = ADC_RESOLUTION_12B;
    hAdc.Init.DataAlign  = ADC_DATAALIGN_RIGHT;
    hAdc.Init.ScanConvMode = ADC_SCAN_DISABLE;
    hAdc.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
    hAdc.Init.LowPowerAutoWait = DISABLE;
    hAdc.Init.ContinuousConvMode = DISABLE;
    hAdc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    hAdc.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
    hAdc.Init.OversamplingMode = DISABLE;
    
    ADC_ChannelConfTypeDef adcChannel;
    adcChannel.Channel = ADC_CHANNEL_VBAT;
    adcChannel.Rank = ADC_REGULAR_RANK_1;
    adcChannel.SamplingTime = ADC_SAMPLETIME_247CYCLES_5;
    adcChannel.SingleDiff = ADC_SINGLE_ENDED;
    adcChannel.OffsetNumber = ADC_OFFSET_NONE;
    
    HAL_ADC_Init(&hAdc);
    HAL_ADC_ConfigChannel(&hAdc,&adcChannel);
    
    HAL_ADCEx_Calibration_Start(&hAdc,ADC_SINGLE_ENDED);

    while(1)   {
        /// TBD: Start ADC, wait for end of onversion, read value
        uint8_t text[7];
        
        snprintf((char *)text, sizeof text,"%+04d~C", -999);
        BSP_LCD_GLASS_DisplayChar(&text[0], POINT_OFF, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_1);
        BSP_LCD_GLASS_DisplayChar(&text[1], POINT_OFF, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_2);
        BSP_LCD_GLASS_DisplayChar(&text[2], POINT_ON, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_3);
        BSP_LCD_GLASS_DisplayChar(&text[3], POINT_OFF, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_4);
        BSP_LCD_GLASS_DisplayChar(&text[4], POINT_OFF, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_5);
        BSP_LCD_GLASS_DisplayChar(&text[5], POINT_OFF, DOUBLEPOINT_OFF,LCD_DIGIT_POSITION_6);
        HAL_Delay(500);
    }
}
