/********************** START OF THE PROGRAM *****************/

#include "XTWR-S08JE.h"
#include "sci.h"
#include "ascii.h"
#include "com_protocol.h"
#include "infrared.h"
#include "S08_Flash.h"

const unsigned char boot1@0x040A = 0; //zero out checksum to bypass boot loader 
const unsigned char boot2@0xFFBA = 0; //bypass checksum  


void vfnMGC_init(void);

void main(void) 
{
  /* Turn off Watchdog Timer and enable RST and BGND pins*/
  SOPT1 = SOPT1_RSTPE_MASK | SOPT1_BKGDPE_MASK;  
  vfnMGC_init();      /* Clock at 48 MHz using 16 MHz external crystal*/   
  FlashInit();        /* Configures the Flash clock for erase and program operations */
  
  if(u8SCI_init(USED_PORT, BAUDRATE, DATA_LENGTH_EIGTH, PARITY_NONE, (IR_ACTIVE+1), RX_NOT_INVERTED, PIN_OPTION_ALTERNATIVE)) for(;;){};
  if(u8IR_TX_init(USED_PORT, IR_ACTIVE, MODULATION_DISABLED, TX_INTERRUPT_DISABLED)) for(;;){};
    
  /* Send a Welcome string */
  EnableInterrupts; /* enable interrupts */
  
  sendCR();
  vfnSCI_SendMsg(USED_PORT,"**********************************************************************"); 
  u8SCI_SendChr(USED_PORT, CR);
  u8SCI_SendChr(USED_PORT, LF);
  vfnSCI_SendMsg(USED_PORT,"Freescale Semiconductor. RTAC Americas"); 
  u8SCI_SendChr(USED_PORT, CR);
  u8SCI_SendChr(USED_PORT, LF);
  vfnSCI_SendMsg(USED_PORT,"Communication Protocol on MM/JE Flexis families");
  u8SCI_SendChr(USED_PORT, CR);
  u8SCI_SendChr(USED_PORT, LF);
  vfnSCI_SendMsg(USED_PORT,"8-bit MC9S08JE128 Device");
  sendCR();  
  if(u8IR_RX_init(USED_PORT, (IR_ACTIVE*REFERENCE_LEVEL), RX_INTERRUPT_ENABLED)) for(;;){};  
  
  for(;;) 
  {
    communication_protocol();
  }
}/* loop forever */

/* please make sure that you never leave main */



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



void vfnMGC_init(void)
{
  /* 16MHz external clock source connected. */
  MCGC2 = 0x36;                    // RANGE = 1; HGO = 1; ERCLKEN=1; EREFS = 1; BDIV = 000
  MCGC3 = 0x10;                    // DIV32 =1
  MCGC1 = 0xA0;                    // CLKS = 10; RDIV = 100; IREFS = 0
  while (MCGSC_IREFST){};          // Wait for Reference Status bit to update
  while (MCGSC_CLKST != 0b10){};   // Wait for clock status bits to update 
  MCGC3 = 0x5C;                    // PLLS =1; DIV32 = 1; VDIV = 1001 
  while (!MCGSC_PLLST){};          // Wait for PLL status bit to update
  while (!MCGSC_LOCK){};           // Wait for LOCK bit to set 
  MCGC1 = 0x20;                    // CLKS = 00; RDIV = 100; IREFS = 0
  while (MCGSC_CLKST != 0b11){};   // Wait for clock status bits to update 
}
