/*******************************************************************************
 * ON Semiconductor                                                            *
 * NCV7383 Evaluation KIT                                                      *
 *                                                                             *
 * main.c                                                                      *
 * Code for NCV7383 Evaluation KIT                                             *
 *                                                                             *
 * Created by: Filip Brtan                                                     *
 * Date: 30.07.2012                                                            *
 *******************************************************************************/
 
/* Common defines and macros */
#include <hidef.h>

/* S12X derivative information */ 
#include "mc9s12xf512.h"     

#include <string.h>
#include "xgate.h"

/* Variable types and common definitions */
#include "typedefs.h"    

/* CPU definitions */
#include "Cpu.h"

/* Interrupt service routines prototypes */
#include "Interrupts.h"

/* Macro definitions for general purpose I/O handling */
#include "GPIO_macros.h"

/* ADC routines definition */
#include "ADC.h"

/* Serial communication interface SCI0 */
#include "SCI0.h"

/* Host command module */
#include "Host.h" 

/* Host communication module */
#include "HostComm.h"   

/* CAN channel definitions and function prototypes */
#include "CAN.h"

/* FlexRay communication controller function prototypes */
#include "FlexRay_CC.h"

/* Flexray bus driver function prototypes */
#include "FlexRay_BD.h"

/* this variable definition is to demonstrate how to share data between XGATE and S12X */
//#pragma DATA_SEG SHARED_DATA
//volatile int shared_counter; /* volatile because both cores are accessing it. */
//#pragma DATA_SEG DEFAULT

/*******************************************************************************/
word aux;
Fr_POC_state_type POC_state;       
Fr_bd_status_register bd_status_register_A;
Fr_bd_status_register bd_status_register_B;

byte ADC_return_value;

void main(void) 
{       
    Clock_Settings();       /* System clock and PLL initialization */ 
    IPLL_Startup();         /* FlexRay IPLL initialization */
    Peripheral_Settings();  /* CPU, memory and ports settings */     
    Interrupts_Init();      /* Interrupts configuration */               
    FlexRay_CC_initialized = FALSE;
    FlexRay_Init();         /* FlexRay module configuration */
    SCI0_init();            /* SCI module initialization */  
    CAN_init(0x00FF & (word)SW_ADDRESS);          /* Initialize MSCAN module */ 
    ADC_init();             /* ADC module initialization */
    PIT_Init();             /* PIT module initialization (Programmable Interrupt Timer) */  
    SPI_Init();             /* SPI module initialization */
    PMF_Init();             /* PMF module initialization */
      
    hostcomm_initialize (); /* initialization of the host communication */
     
    ENABLE_INTERRUPTS();
    EnableCAN_BD();         /* Enable CAN transceiver (STB = 1) */
    
   
    for (;;) /* Endless loop,waiting for interrupts */ 
    {       
  
      while (Enter_STOP_MODE)
      {
        /* FlexRay PLL OFF */
        CGMCTL_PLLON = 0;    /* Disable FlexRay clock (IPLL)  */
        //while(!CGMFLG_UNLOCKF); /* Wait until the IPLL is OFF */       
        
        // RTI OFF
        CRGFLG_RTIF = 1;    /* Clear real time interrupt flag */    
        CRGINT_RTIE = 0;    /* Disalble real time interrupt */ 
        
        /* Autonomous Periodical Interrupt (API) ON */
        /* This will periodically wakeup MCU from STOP mode to check the FR Bus Wakeup status */
        VREGAPICL_APIF = 1;
        VREGAPICL_APIFE = 1;

        DisableCAN_BD();    /* CAN Transceiver Standby mode */
        PMFENCA_PWMENA = 0; /* Disable PWM output */
        
        PLLCTL_FSTWKP = 1; /* Fast wake-up from full stop mode is enabled */        
      
        {asm CLI;} // Enable Maskable interrupts
        LEDS_PORT = 0xFF; // Turn off the LEDs 
        STOP();
              
        if(Enter_STOP_MODE == FALSE)
        {
          DISABLE_INTERRUPTS();

          LEDS_PORT = 0x00;  // Turn on LEDS
          
          PMFENCA_PWMENA = 1; /* Enable PWM output */
          
          PLLCTL_FSTWKP = 0;  /* Start the oscillator, the clock monitor and the clock quality check */
          while (CRGFLG_SCM); /* Wait till MCU is operating normally with OSCCLK available */                                  
          
          /* Enable PLL */
          PLLCTL_PLLON = 1;        /* PLL enabled */
          while(!CRGFLG_LOCK)      /* Wait until the PLL is within the desired tolerance of the target frequency */            
          CLKSEL_PLLSEL = 1;       /* Select clock source from PLL */
          
          /* Enable FlexRay PLL */
          CGMCTL_PLLON = 1;    /* IPLL enabled */
          while(!CGMFLG_LOCK); /* Wait until the PLL is within the desired tolerance of the target frequency */
          // Clear LOCKIF flag
          if(CGMFLG_LOCKIF) 
            CGMFLG_LOCKIF = 1;
          // Clear UNLOCKF flag - this is necessary to enable FlexRay CC transmit enable ports
          if(CGMFLG_UNLOCKF) 
            CGMFLG_UNLOCKF = 1;

          /* Read bus driver internal status registers */
          bd_status_register_A = fr_bd_read_status(FR_CHANNEL_A);
          bd_status_register_B = fr_bd_read_status(FR_CHANNEL_B);
          if (bd_status_register_A.Flags.Bits.RemoteWakeUp == 1) 
          {
            NOP();
          }
          
          if (bd_status_register_B.Flags.Bits.RemoteWakeUp == 1) 
          {
            NOP();
          }
      
          /* Change FlexRay Bus Driver (NCV7383) mode to Normal Mode */
          fr_bd_change_mode(FR_CHANNEL_AB, FR_BD_NORMAL);
          
          /* Enable Transmitter Function - BGE = High  */ 
          FR_BGE_A = 1;
          FR_BGE_B = 1;
          
          /* Wait 100 us */
          wait_1us(100);         
          
          /* Initialize FlexRay Communication Controller and start communication */
          FlexRay_Init();
          
          // RTI ON
          CRGFLG_RTIF = 1;    /* Clear real time interrupt flag */    
          CRGINT_RTIE = 1;    /* Enable real time interrupt */ 
          
          EnableCAN_BD();     /* CAN Transceiver NORMAL mode */
          
          ENABLE_INTERRUPTS();
          
          LEDS_PORT = 0xFF; /* Turn OFF all LEDS */
        }
      }
     
      
      //hostcomm_process_SCI0 ();
      //hostcomm_process_CAN ();
      
      /* Check the current FlexRay CC POC state */
      POC_state = Fr_get_POC_state();
      switch (POC_state)
      {
        case FR_POCSTATE_NORMAL_ACTIVE: break;
        case FR_POCSTATE_STARTUP: break;
        case FR_POCSTATE_WAKEUP: break;
        /* In case the protocol operetion is not in Normal or startup state, reinitialize the controller */
        case FR_POCSTATE_NORMAL_PASSIVE:
        case FR_POCSTATE_CONFIG: 
        case FR_POCSTATE_DEFAULT_CONFIG: 
        case FR_POCSTATE_HALT: 
        case FR_POCSTATE_READY: 
          FlexRay_Init(); 
          break;
        
        default: break;
      }

      // Measure Battery voltage
      ADC_return_value = ADC_measure_VBAT(&voltage_VBAT);
      
      /* Enter WAIT mode - decrease the MCU current consumption */
      /* RTI and IPLL are enabled in WAIT mode */
      WAIT();
    };                                            
}           

/*******************************************************************************/