/**
  ******************************************************************************
  * @file    main.c
  * @author  MCD Application Team
  * @version V1.0.1
  * @date    29-May-2012
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2>
  *
  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  * You may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  *
  *        http://www.st.com/software_license_agreement_liberty_v2
  *
  * Unless required by applicable law or agreed to in writing, software 
  * distributed under the License is distributed on an "AS IS" BASIS, 
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/** @addtogroup STM320518_EVAL_Demo
  * @{
  */

/** @defgroup MAIN
  * @brief    Main program body
  * @{
  */

/** @defgroup MAIN_Private_Types
  * @{
  */
/**
  * @}
  */

/** @defgroup MAIN_Private_Defines
  * @{
  */

/**
  * @}
  */

/** @defgroup MAIN_Private_Macros
  * @{
  */
/**
  * @}
  */

/** @defgroup MAIN_Private_Variables
  * @{
  */

static __IO uint32_t TimingDelay = 0;
static __IO uint32_t LedShowStatus = 0;
static __IO uint32_t DOWNStatus = 0x00, UPStatus = 0x00, SELStatus = 0x00;
__IO uint32_t ADCConversionValue = 0x00;

/**
  * @}
  */

/** @defgroup MAIN_Private_FunctionPrototypes
  * @{
  */

/**
  * @}
  */

/** @defgroup MAIN_Private_Functions
  * @{
  */

/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /* Initialize the Demo */
  Demo_Init(); 
  
  /* The DOWNStatus, SELStatus or UPStatus will be set in stm32f0xx_it.c 
    when the joystick button(DOWN, SEL or UP) is pressed */
  while (1)
  {
    if (DOWNStatus != 0x00)
    {
      /* Reset DOWNStatus value */
      DOWNStatus = 0;
      /* External Interrupt Disable */
      Demo_IntExtOnOffCmd(DISABLE);
      /* Execute DOWN Function */
      Menu_DownFunc();
      /* External Interrupt Enable */
      Demo_IntExtOnOffCmd(ENABLE);
    }
    else if (SELStatus != 0x00)
    {
      /* Reset SELStatus value */
      SELStatus = 0;
      /* External Interrupt Disable */
      Demo_IntExtOnOffCmd(DISABLE);
      /* Execute SEL Function */
      Menu_SelFunc();
      /* External Interrupt Enable */
      Demo_IntExtOnOffCmd(ENABLE);
    }
    else if (UPStatus != 0x00)
    {
      /* Reset UPStatus value */
      UPStatus = 0;
      /* External Interrupt Disable */
      Demo_IntExtOnOffCmd(DISABLE);
      /* Execute UP Function */
      Menu_UpFunc();
      /* External Interrupt Enable */
      Demo_IntExtOnOffCmd(ENABLE);
    }
  }
}

/**
  * @brief  Initializes the demonstration application.
  * @param  None
  * @retval None
  */
void Demo_Init(void)
{
  /*------------------- Resources Initialization -----------------------------*/
  /* Enable GPIOA, GPIOB and GPIOC clocks */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC | \
                        RCC_AHBPeriph_GPIOF, ENABLE);
  
  /* Initialize the LED's, Joystick, Button Key and Button Tamper */
  Demo_EVAL_Init();
  
  /* Initialize the LCD */
  STM320518_LCD_Init();

  /* Clear the LCD */
  LCD_Clear(LCD_COLOR_WHITE);

  /* Interrupt Configuration */
  Demo_Interrupt_Init();

  /* Configure the systick */
  Demo_SysTick_Init();
  /*------------------- Drivers Initialization -------------------------------*/
  
  /* Initialize the low power application */
  LowPower_Init();
  
  /* If HSE is not detected at program startup */
  if (RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET)
  {
    /* Generate NMI exception */
    SCB->ICSR |= SCB_ICSR_NMIPENDSET_Msk;
  }
  
  /* Checks the availability of the bitmap files */
  Demo_CheckBitmapFilesStatus(); 
  
  /* Display the STM32 introduction */
  Menu_STM32Intro();
  
  /* Clear the LCD */
  LCD_Clear(LCD_COLOR_WHITE);

#if defined (CALENDAR_SUBDEMO) || defined (LOWPOWERMODE_SUBDEMO)
  /* Disable the JoyStick interrupt */
  Demo_IntExtOnOffCmd(DISABLE);
  
  /* Initialize the Calendar */
 Calendar_Init();
  
  /* Enable the JoyStick interrupt */
  Demo_IntExtOnOffCmd(ENABLE);
#endif /*CALENDAR_SUBDEMO, LOWPOWERMODE_SUBDEMO */
 
  /* Enable Leds toggling */
  Demo_LedShow(ENABLE);

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

  /* Set the LCD Text Color */
  LCD_SetTextColor(LCD_COLOR_WHITE);

  /* Initialize the Menu */
  Menu_Init();

  /* Display the main menu icons */
  Menu_ShowMenuIcons();
}

/**
  * @brief  Configures the used IRQ Channels and sets their priority.
  * @param  None
  * @retval None
  */
void Demo_Interrupt_Init(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;
  EXTI_InitTypeDef EXTI_InitStructure;

  /* Enable the TIM6 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TIM6_DAC_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the TIM15 UP Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TIM15_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 2;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the EXTI line 17 (connected to the RTC Alarm event) */
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Line = EXTI_Line17;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

  /* Enable the RTC Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the EXTI4_15_IRQn Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI4_15_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
  /* Enable the EXTI line 15 (connected to SDCard detect) */
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Line = EXTI_Line15;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

  /* Enable the EXTI0 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI0_1_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
  
   /* Enable the TIM6 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TS_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}

/**
  * @brief  Configure a SysTick Base time to 10 ms.
  * @param  None
  * @retval None
  */
void Demo_SysTick_Init(void)
{
  /* Setup SysTick Timer for 10 ms interrupts  */
  if (SysTick_Config(SystemCoreClock / 100))
  {
    /* Capture error */
    while (1);
  }

  /* Configure the SysTick handler priority */
  NVIC_SetPriority(SysTick_IRQn, 0x0);
}

/**
  * @brief  Enables or disables EXTI for the menu navigation keys, i.e. EXTI lines 0,
  *         6 and 7 which correpond respectively to "SEL", "UP" and "DOWN".
  * @param  NewState: New state of the navigation keys. 
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void Demo_IntExtOnOffCmd(FunctionalState NewState)
{
  EXTI_InitTypeDef EXTI_InitStructure;
 
  /* Initializes the EXTI_InitStructure */
  EXTI_StructInit(&EXTI_InitStructure);

  /* Disable the EXTI line 0, 6 and 7 on falling edge */
  if (NewState == DISABLE)
  {
    EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line6 | EXTI_Line7;
    EXTI_InitStructure.EXTI_LineCmd = DISABLE;
    EXTI_Init(&EXTI_InitStructure);
  }
  /* Enable the EXTI line 0, 6 and 7 on falling edge */
  else
  {
    /* Clear the the EXTI line 0, 6 and 7 interrupt pending bit */
    EXTI_ClearITPendingBit(EXTI_Line0 | EXTI_Line6 | EXTI_Line7);
    
    EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line6 | EXTI_Line7;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);
  }
}

/**
  * @brief  Inserts a delay time.
  * @param  nCount: specifies the delay time length (time base 10 ms).
  * @retval None
  */
void Demo_Delay(__IO uint32_t nCount)
{
  TimingDelay = nCount;
  /* Enable the SysTick Counter */
  SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
  while (TimingDelay != 0);
  /* Disable the SysTick Counter */
  SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
  /* Clear the SysTick Counter */
  SysTick->VAL = (uint32_t)0x0;
}

/**
  * @brief  Inserts a delay time while no joystick RIGHT, LEFT and SEL are pressed.
  * @param  nTount: specifies the delay time length (time base 10 ms).
  * @retval Pressed Key. This value can be: NOKEY, RIGHT, LEFT or SEL.
  */
uint32_t Demo_DelayJoyStick(__IO uint32_t nTime)
{
  __IO uint32_t keystate = 0;
  TimingDelay = nTime;

  while ((TimingDelay != 0) && (keystate != RIGHT) && (keystate != LEFT) && (keystate != SEL))
  {
    keystate = Menu_ReadKey();
  }

  return keystate;
}

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

/**
  * @brief  Delay.
  * @param  nCount
  * @retval None
  */
void Delay(__IO uint32_t nCount)
{
  /* Decrement nCount value */
  while (nCount != 0)
  {
    nCount--;
  }
}

/**
  * @brief  Configures the leds pins as output pushpull: LED1, LED2, LED3 and LED4
  * @param  None
  * @retval None
  */
void Demo_EVAL_Init(void)
{
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  TIM_OCInitTypeDef  TIM_OCInitStructure;
  
  /* Configure Joystick pins as input floating with EXTI */
  STM_EVAL_PBInit(BUTTON_UP, BUTTON_MODE_EXTI);
  STM_EVAL_PBInit(BUTTON_DOWN, BUTTON_MODE_EXTI);
  STM_EVAL_PBInit(BUTTON_SEL, BUTTON_MODE_EXTI);
  
  STM_EVAL_PBInit(BUTTON_LEFT, BUTTON_MODE_GPIO);
  STM_EVAL_PBInit(BUTTON_RIGHT, BUTTON_MODE_GPIO);
  
  /* Configure LEDs GPIO: as output push-pull */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);
  
  /* TIM15 clocks enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM15, ENABLE); 
  
  /* Time Base configuration 100ms*/
  TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
  TIM_TimeBaseStructure.TIM_Prescaler = 1000;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 0x0C80;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
  TIM_TimeBaseInit(TIM15, &TIM_TimeBaseStructure);
  
  /* Channel 1, 2, 3 and 4 Configuration in Timing mode */
  TIM_OCStructInit(&TIM_OCInitStructure);
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 0x0;
  
  TIM_OC1Init(TIM15, &TIM_OCInitStructure);
}

/**
  * @brief  Enables or disables LED1, LED2, LED3 and LED4 toggling.
  * @param  None
  * @retval None
  */
void Demo_LedShow(FunctionalState NewState)
{
  /* Enable LEDs toggling */
  if (NewState == ENABLE)
  {
    LedShowStatus = 1;
    /* Enable the TIM Update Interrupt */
    TIM_ITConfig(TIM15, TIM_IT_Update, ENABLE);
    /* TIM counter enable */
    TIM_Cmd(TIM15, ENABLE);
  }
  /* Disable LEDs toggling */
  else
  {
    LedShowStatus = 0;
    /* Disable the TIM Update Interrupt */
    TIM_ITConfig(TIM15, TIM_IT_Update, DISABLE);
    /* TIM counter disable */
    TIM_Cmd(TIM15, DISABLE);
  }
}

/**
  * @brief  Get the LedShowStatus value.
  * @param  None
  * @retval LedShowStatus Value.
  */
uint32_t Demo_Get_LedShowStatus(void)
{
  return LedShowStatus;
}

/**
  * @brief  Checks the bitmap files availability and display a warning message
  *         if these files doesn't exit.
  * @param  None
  * @retval None
  */
void Demo_CheckBitmapFilesStatus(void)
{
  /* Checks if the Bitmap files are loaded */
  if (Menu_CheckBitmapFiles() != 0)
  {
    /* Double checking for Demo to make sure micro SD can be correctly read*/
    if (Menu_CheckBitmapFiles() != 0)
    {
       /* Double checking for Demo to make sure micro SD can be correctly read*/
       if (Menu_CheckBitmapFiles() != 0)
        {
          /* 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, "      Warning       ");
          LCD_DisplayStringLine(LCD_LINE_1, "No loaded Bitmap    ");
          LCD_DisplayStringLine(LCD_LINE_2, "files. Demo can't be");
          LCD_DisplayStringLine(LCD_LINE_3, "executed.           ");
          LCD_DisplayStringLine(LCD_LINE_4, "Please be sure that ");
          LCD_DisplayStringLine(LCD_LINE_5, "all files are       ");
          LCD_DisplayStringLine(LCD_LINE_6, "correctly programmed");
          LCD_DisplayStringLine(LCD_LINE_7, "in the MicroSD Card ");
          LCD_DisplayStringLine(LCD_LINE_8, "                    ");
          LCD_DisplayStringLine(LCD_LINE_9, "                    ");

         /* Deinitializes the RCC */
          RCC_DeInit();

         /* Demo Can't Start */
         while (1)
        {}
      }  
    }
  }
}

/**
  * @brief  Sets the DOWNStatus variable
  * @param  None
  * @retval None
  */
void Set_DOWNStatus(void)
{
  DOWNStatus = 1;
}

/**
  * @brief  Sets the UPStatus variable
  * @param  None
  * @retval None
  */
void Set_UPStatus(void)
{
  UPStatus = 1;
}

/**
  * @brief  Sets the SELStatus variable
  * @param  None
  * @retval None
  */
void Set_SELStatus(void)
{
  SELStatus = 1;
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert 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) */
  LCD_Clear(LCD_COLOR_WHITE);
  LCD_DisplayStringLine(LCD_LINE_0, "   Assert Function  ");
  /* Infinite loop */
  while (1)
  {}
}
#endif

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

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