//!
//! @file main.c,v
//!
//! Copyright (c) 2008 Atmel.
//!
//! @brief Main module : It is based on an infinite loop
//!
//! @version 1.21
//!

//_____  I N C L U D E S ___________________________________________________
#include "config.h"

#include "mc_interface.h"
#include "mc_control.h"
#include "mc_drv.h"
#include "DB101_IF.h"
#include "adc_drv.h"

#include "uart\uart_lib.h"
#include "ushell_task.h"
#include "clksys_driver.h"

//_____ M A C R O S ________________________________________________________


//_____ D E F I N I T I O N S ______________________________________________

//_____ D E C L A R A T I O N S ____________________________________________
U16 g_regulation_period = 0;  //!< Define the sampling period
U16 motor_speed = 0;          //!< User Speed Order
extern Bool g_tick;           //see mc_drv.c Use for sampling time

void clock_init(void)
{
	/* Set system clock to 32MHz. */
	CLKSYS_Enable(OSC_RC32MEN_bm);//CLKSYS_Enable(OSC_XOSCEN_bm);
	do {} while ( CLKSYS_IsReady( OSC_RC32MRDY_bm ) == 0 );//do {} while ( CLKSYS_IsReady( OSC_XOSCRDY_bm ) == 0 );
	
	CLKSYS_PLL_Config( OSC_PLLSRC_RC32M_gc, 16 );//CLKSYS_PLL_Config( OSC_PLLSRC_XOSC_gc, 4 );
	CLKSYS_Enable(OSC_PLLEN_bm);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_2_2_gc);
	do {} while ( CLKSYS_IsReady( OSC_PLLRDY_bm ) == 0 );
	CLKSYS_Main_ClockSource_Select( CLK_SCLKSEL_PLL_gc );
}


//! Main Entry
//!
//! The main entry point for the control motor application.\n
//! The mc_regulation_loop() function is launched every 80ms.\n
//!
int main(void)
{

    clock_init();
  // init motor
  mc_init();  // launch initialization of the motor application

  //init_adc();

  // Initialyze the communication system for External Command through Uart
  ushell_task_init();

  // Start the motor
  mci_set_motor_speed(0);
  mci_run();

  PMIC.CTRL |= PMIC_LOLVLEX_bm;
  __enable_interrupt();


  while(1)
  {
	
    // Launch regulation loop
    // Timer 1 generate an IT (g_tick) all 250us
    // Sampling period = n * 250us
    if (g_tick == TRUE)
    {
      g_tick = FALSE;
      mc_ADC_Scheduler();
      g_regulation_period += 1;
      if ( g_regulation_period >= 1000 ) //n * 250us = Te
      {
        g_regulation_period = 0;

        if (ushell_active == FALSE)
        {
          // Set User Speed Command with potentiometer
          mci_set_motor_speed(mc_get_potentiometer_value());
        }
        mc_regulation_loop(); // launch regulation loop   
#ifdef DB101        
        UpdateScreen();      
#endif        
      }
      ushell_task();
      mc_inrush_task(); /* manage the inrush current */
    }

    // Show PSC state according to the Over Current information
    //if(PCTL2 & (1<<PRUN2))  switch_OFF_LED();// PSC ON
    //else  switch_ON_LED();//PSC OFF => Over_Current
  }
}
