/**
  ******************************************************************************
  * @file    Project/Internal_OSC_Calib/src/main.c 
  * @author  MCD Application Team
  * @version V1.1.0
  * @date    24-January-2012
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * FOR MORE INFORMATION PLEASE READ CAREFULLY THE LICENSE AGREEMENT FILE
  * LOCATED IN THE ROOT DIRECTORY OF THIS FIRMWARE PACKAGE.
  *
  * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2>
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx.h"
#include <stdio.h>
#include "InternOscCalibration.h"
#include "LSIMeasurement.h"
#include "MSIMeasurement.h"

#ifdef USE_STM32L152_EVAL
 #include "stm32l152_eval/stm32l152_eval_lcd.h"
#elif defined USE_STM32L152D_EVAL
 #include "stm32l152d_eval/stm32l152d_eval_lcd.h"
#endif

/** @addtogroup Internal_OSC_Calib
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define CALIBRATION_MIN_ERROR

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
USART_InitTypeDef USART_InitStructure;
static __IO uint32_t TimingDelay;
RCC_ClocksTypeDef RCC_Clocks;

uint32_t InternOscAfterCalib = 0;
uint16_t LSIFrequency = LSI_VALUE;
uint32_t MSIFrequency = 2097152;  /* default MSI value (range 5) */
uint32_t CurrentHSIFrequency = 0;
uint32_t CurrentMSIFrequency = 0;

uint8_t TxBuffer[20]; /* for displaying messages on LCD */

/* Private function prototypes -----------------------------------------------*/
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

void Delay(__IO uint32_t nTime);
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32l1xx_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32l1xx.c file
     */

  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);

  /* Initialize the LCD */
#ifdef USE_STM32L152_EVAL
  STM32L152_LCD_Init();
#elif defined USE_STM32L152D_EVAL
  STM32L152D_LCD_Init();
#endif 

  /* Display message on STM32L1XX-EVAL LCD ************************************/
  /* Clear the LCD */ 
  LCD_Clear(LCD_COLOR_WHITE);

  /* Set the LCD Back Color */
  LCD_SetBackColor(LCD_COLOR_BLUE);

  /* Set the LCD Text Color */
  LCD_SetTextColor(LCD_COLOR_WHITE);
  LCD_DisplayStringLine(LCD_LINE_0, " Intern Oscillators ");
  LCD_DisplayStringLine(LCD_LINE_1, "     Calibration    ");
  LCD_DisplayStringLine(LCD_LINE_2, "                    ");

  /* Initialize LEDs available on STM32L1XX-EVAL board ************************/
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);

  /* Turn on leds available on STM32L1XX-EVAL *********************************/
  STM_EVAL_LEDOn(LED1);
  STM_EVAL_LEDOn(LED2);

#ifdef CALIBRATION_MIN_ERROR
  /* Get the internal oscillator (HSI/MSI) value after calibration */
  InternOscAfterCalib = InternOsc_CalibrateMinError();

  /* Display the internal osc value after calibration */
  if (InternOscAfterCalib != 0)
  {
    LCD_DisplayStringLine(LCD_LINE_3, "After calibration:  ");
    if (RCC_GetSYSCLKSource() == 0x04) /* system clock source is HSI */
    {
      sprintf((char*)TxBuffer,     "HSI is     %d.%d%d MHz", InternOscAfterCalib / 1000000, ((InternOscAfterCalib % 1000000)/100000), ((InternOscAfterCalib % 100000)/10000));
      LCD_DisplayStringLine(LCD_LINE_4, TxBuffer);

      /* Measure MSI oscillator frequency at range 1 MHz */
      MSIFrequency = MSI_FreqMeasure(InternOscAfterCalib);

      LCD_DisplayStringLine(LCD_LINE_8, "MSI value is:       ");
      sprintf((char*)TxBuffer, "         %d.%d KHz  ", (MSIFrequency / 1000), (MSIFrequency % 1000)/10);
      LCD_DisplayStringLine(LCD_LINE_9, TxBuffer);
    }
    else if (RCC_GetSYSCLKSource() == 0x00) /* system clock source is MSI */
    {
      sprintf((char*)TxBuffer,     "MSI is      %d.%d%d MHz", InternOscAfterCalib / 1000000, ((InternOscAfterCalib % 1000000)/100000), ((InternOscAfterCalib % 100000)/10000));
      LCD_DisplayStringLine(LCD_LINE_4, TxBuffer);
    }
  }
  else
  {
    /* System clock source is neither HSI nor MSI */
    LCD_DisplayStringLine(LCD_LINE_4, "          Error !   ");
  }

  /* Measure LSI oscillator frequency */
  LSIFrequency = LSI_FreqMeasure(InternOscAfterCalib);

  LCD_DisplayStringLine(LCD_LINE_6, "LSI value is:       ");
  sprintf((char*)TxBuffer, "           %d.%d%d KHz", (LSIFrequency / 1000), (LSIFrequency % 1000) / 100, (LSIFrequency % 100) / 10);
  LCD_DisplayStringLine(LCD_LINE_7, TxBuffer);

#else /* CALIBRATION_MIN_ERROR isn't defined */

  /* Check system clock source */
  if (RCC_GetSYSCLKSource() == 0x04) /* system clock source is HSI */
  {
    /* Calibrate HSI oscillator with the maximum allowed error in Hz */
    /* Fix the maximum value of the error frequency at +/- 40000Hz */
    HSI_CalibrateFixedError(40000, &CurrentHSIFrequency);
    LCD_DisplayStringLine(LCD_LINE_3, "After calibration:  ");
    sprintf((char*)TxBuffer,     "HSI is     %d.%d%d MHz", CurrentHSIFrequency / 1000000, ((CurrentHSIFrequency % 1000000)/100000), (CurrentHSIFrequency % 100000)/10000);
    LCD_DisplayStringLine(LCD_LINE_4, TxBuffer);

    /* Measure MSI oscillator frequency at range 1 MHz */
    MSIFrequency = MSI_FreqMeasure(CurrentHSIFrequency);
    LCD_DisplayStringLine(LCD_LINE_8, "MSI value is:       ");
    sprintf((char*)TxBuffer, "         %d.%d KHz  ", (MSIFrequency / 1000), (MSIFrequency % 1000)/10);
    LCD_DisplayStringLine(LCD_LINE_9, TxBuffer);

    /* Measure LSI oscillator frequency */
    LSIFrequency = LSI_FreqMeasure(CurrentHSIFrequency);

    LCD_DisplayStringLine(LCD_LINE_6, "LSI value is:       ");
    sprintf((char*)TxBuffer, "           %d.%d%d KHz", (LSIFrequency / 1000), (LSIFrequency % 1000) / 100, (LSIFrequency % 100) / 10);
    LCD_DisplayStringLine(LCD_LINE_7, TxBuffer);
  }
  else if (RCC_GetSYSCLKSource() == 0x00) /* system clock source is MSI */
  {
    /* Calibrate MSI oscillator with the maximum error allowed in Hz */
    /* Fix the maximum value of the error frequency at +/- 20000Hz */
    MSI_CalibrateFixedError(20000, &CurrentMSIFrequency);
    LCD_DisplayStringLine(LCD_LINE_3, "After calibration:  ");
    sprintf((char*)TxBuffer,     "MSI is      %d.%d%d MHz", CurrentMSIFrequency / 1000000, ((CurrentMSIFrequency % 1000000)/100000), ((CurrentMSIFrequency % 100000)/10000));
    LCD_DisplayStringLine(LCD_LINE_4, TxBuffer);

    /* Measure LSI oscillator frequency */
    LSIFrequency = LSI_FreqMeasure(CurrentMSIFrequency);

    LCD_DisplayStringLine(LCD_LINE_6, "LSI value is:       ");
    sprintf((char*)TxBuffer, "           %d.%d%d KHz", (LSIFrequency / 1000), (LSIFrequency % 1000) / 100, (LSIFrequency % 100) / 10);
    LCD_DisplayStringLine(LCD_LINE_7, TxBuffer);
  }
  else
  {
    /* System clock source is neither HSI nor MSI */
    LCD_DisplayStringLine(LCD_LINE_3, "          Error !   ");
  }

#endif /* CALIBRATION_MIN_ERROR */

  /* Infinite loop */
  while (1)
  {
    /* Toggle LD1 */
    STM_EVAL_LEDToggle(LED1);

    /* Insert 50 ms delay */
    Delay(5);

    /* Toggle LD2 */
    STM_EVAL_LEDToggle(LED2);

    /* Insert 50 ms delay */
    Delay(5);
  }
}

/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART */
  USART_SendData(EVAL_COM1, (uint8_t) ch);

  /* Loop until the end of transmission */
  while (USART_GetFlagStatus(EVAL_COM1, USART_FLAG_TC) == RESET)
  {}

  return ch;
}

/**
  * @brief  Inserts a delay time.
  * @param  nTime: specifies the delay time length, in 10 ms.
  * @retval None
  */
void Delay(__IO uint32_t nTime)
{
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

/**
  * @brief  Decrements the TimingDelay variable.
  * @param  None
  * @retval None
  */
void TimingDelay_Decrement(void)
{
  if (TimingDelay != 0x00)
  { 
    TimingDelay--;
  }
}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/******************* (C) COPYRIGHT 2012 STMicroelectronics *****END OF FILE****/
