/* 
*******************************************************************************
THIS INFORMATION (or THIS SOFTWARE or THIS DOCUMENT) IS FOR GUIDANCE ONLY. 
ST MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS 
SOFTWARE nor for any infringement of patents or other rights of third parties 
which may result from its use.

ST MICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, INDIRECT 
INCIDENTAL OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING 
IN CONNECTION WITH OR ARISING FROM THE FURNISHING, PERFORMANCE, OR USE 
OF THIS SOFTWARE.

Specifications mentioned in this publication are subject to change without 
notice. This publication supersedes and replaces all information previously 
supplied. STMicroelectronics products are not authorized for use as critical 
components in life support devices or systems without the express written 
approval of STMicroelectronics.  
*******************************************************************************
COPYRIGHT 2003 STMicroelectronics
Source File Name : main.c
Group            : IPSW, CMG - IPDF
Author           : MCD Application Team
Date First Issued: 20/08/2004
********************************Documentation**********************************
General Purpose -Top Level file.This file calls the functions, written in 
     different source directories of ST7 Library.
     -This will run an application including SCI to hyperterminal communication 
      and ADC conversion on channel0.Both applications will run simultaneously.
     -SPI- M95040 EEPROM communication, means writing 10 bytes data on EEPROM 
      and reading data from EEPROM is included.
     -TIMER A will generate the rising edge by enabling output compare on PB6 
      pin. This generated signal is applied to PA0 pin , which is the input 
      capture for PWMART.In the Interrupt subroutine, User to PC communication 
      executed.
*******************************************************************************
Hardware 
    -MDT2 application board to use SPI- M95040 EEPROM.
     Hyperterminal on PC.
     Serial cabel from from serial port to PC communication port.
     PB6 and PA0 pins must be connected together.            
*******************************************************************************     
********************************RevisionHistory********************************
_______________________________________________________________________________
Date : 20/08/2004              	Release:  1.0
******************************************************************************/     
#include "ST7lib_config.h"                               /*Configuration File*/
#include "user.h"                  //contains all user configuarable parameters

/* Buffers Declaration to display messages on the Hyperterminal(PC) with using 
  SCI functions*/
const canuint8 buff2[]= "MSG RCD\n";             //Should be 8 bytes  (DLC = 8)
const unsigned char buff24[]= " CAN Transmission Failed \n\r";
const unsigned char buff25[]= " CAN Transmission Passed \n\r";
const unsigned char buff19[]= "PLEASE ENTER THE DATA(length 8 bytes)YOU WISH\
                                                      TO TRANSMIT THROUGH CAN";
const unsigned char buff26[]= " Wait for DATA from Can-Analyzer\n\r";                                                      
                                                      
const unsigned char buff14[]= "PRESS RESET TO RUN APPLICATION AGAIN\n\r";
const unsigned char buff20[]= "DEMO IS OVER\n\r";
const unsigned char buff21[]= "GOOD DAY";
const unsigned char buff4[]= {"SPI-EEPROM APPLICATION STARTED\n\r"};
const unsigned char buff5[]= {"10 bytes Data is written on EEPROM\n\r"};
const unsigned char buff6[]= {"SPI is reading EEPROM\n\r"};
const unsigned char buff7[]= {"Verifying the Read & Write data\n\r"};
const unsigned char buff8[]= {"SPI WORKING OK\n\r"};
const unsigned char buff9[]= {"TALK TO PC:\n\r"};
const unsigned char buff10[]= {"MESSAGE LENGTH (00-20)\n"};
const unsigned char buff11[]= {"\n\rMESSAGE:"};
    
/* function for applying delay during application*/  
extern void Delay_1(void);
extern void Delay(void);

/*Display function to display ADC converted data on seven segment LED*/
extern void App_Tx_Copy_Data(canuint8 tx_handle,canuint8 *data_ptr);

static unsigned char PC_Buffer[18],length[2];   
static unsigned char len_message=0,length1=0,length2=0;
static unsigned char R_DATA=0,TX_Add_Ret=0,TX_Byte_Ret=0,Read_status2=0;
static unsigned char RX_Byte_Ret=0;
static unsigned char FLAG = 0;/* Flag to check whether PWMART Interrupt Routine
                                                                has occurred */           

typedef struct
{
  canuint16 stdid;
  canuint16 extid;
  canuint8  dlc;
  canuint8  data[8];
}data_buff;

tCanMsgOject user_tx_struct; /* user transmmit structure using CanMsgTransmit()
                                                                     service */   
       
/******************************************************************************
                          MAIN APPLICATION BEGINS
******************************************************************************/
void main(void); 
void main (void)                    
{                                    
    /* Declaration of the variables used in the application*/
    canuint8 ADC_Buffer[10];          /*ADC converted data buffer declaration*/    
    unsigned char SPI_Buffer[10];/*SPI-EEPROM read data stored in this buffer*/                   
    unsigned char i,sub_add=0x00;     
    unsigned char TransFailed = 0, AckFailed = 0;
    canuint8 cnt,rx_handle,tx_handle=0;
    canuint8 user_tx_buffer;
    SCI_RxError_t Err;

/******************************************************************************
    IO Library called to configure PB3(MCO),PB2(SPI Pin),PB6(T16_OCMP1),PB1=
    T8_OCMP1 as o/p and PA0(PWMART interrupt input capture),PB4(Ain0) as i/p 
******************************************************************************/
    
    IO_Init(); 
    IO_Output(IO_PUSH_PULL, IO_PORT_B, IO_PIN_1 | IO_PIN_3 | IO_PIN_2 | IO_PIN_6); 
    IO_Input (IO_FLOATING, IO_PORT_B, IO_PIN_4 ); 
    IO_Input (IO_FLOATING, IO_PORT_A, IO_PIN_0 );
  
/******************************************************************************
    ITC Library called to set the priority, for SCI level 3 and for EI) and 
    PWMART level 2.
******************************************************************************/    

    ITC_Init ();    
    ITC_SetPriority (IT_SCI2, IT_LEVEL_3);
    ITC_SetPriority (IT_ART , IT_LEVEL_2);
    ITC_ConfigureInterrupt (IT_PortA, 0, IT_EDGE_R);/*PWMART INT ON RISING EDGE
                                                            ON THE ARTIC1 PIN */
    
/******************************************************************************
    MCC Library called to initialise PF0 pin for MCO enable and RTC timer
******************************************************************************/

    MCC_Init(MCC_DEFAULT);
    MCC_Init(MCO_ENABLE);
    MCC_RTC_Timer(MCC_RTC_1);  

/******************************************************************************
    SCI Library called to initialise sci peripheral with its parity disable, 
   and baudrate 19200, 8 bit data and 1 bit stop bit.
******************************************************************************/    

    SCI2_Init(SCI_DEFAULT_PARAM1, SCI_DEFAULT_PARAM2);
    SCI2_Select_Baudrate(SCI_PR_13 + SCI_TR_2 + SCI_RR_2);
    EnableInterrupts                        
    SCI2_Mode(SCI_TX_ENABLE);                       /*SCI transmit enable mode*/  

/************CAN Initialization***********************************************/ 
    
    CanInitPowerOn();                       
    CanInit(ZERO);     
    

/*****************Timer8 Initialisation in PWM mode***************************/   

    TIMER8_Init(TIMER8_FCPU_4);    
    TIMER8_PWM_Mode(TIMER8_OUTPUT1_R,TIMER8_OUTPUT2_F,0x40,0x80);
   
/******************************************************************************
    ADC Library called to initialise channel0 to be applied with analog data 
    and speed of conversion
******************************************************************************/    

    ADC_Init(ADC_DEFAULT);        /* Initialisation of the ADC,sets by default,
                                     channel to AIN0, speed to Fcpu/4, ADC off,
                                     amplifier off, interrupt disable and
                                     Continous conversion mode.*/
  
    ADC_Enable();			             /* Switch on the ADC to starts conversion on
                                                        the selected channel.*/
    Delay_1();
    
/******************************************************************************
    CAN and ADC application run simultaneously and store the 8 bytes of 
    conversion in ADC_Buffer[10].
******************************************************************************/
    SCI2_PutBuffer(buff26,sizeof(buff26));   
    while(!(SCI2_IsTransmitCompleted()));          // displays buff 26 on Hyper
    while(  !(Can_Ind_Flags[0] & Ind_Mask[0])  );/* Wait here till some message
                                                     is received on handle 0 */
    /********Send an acknowledge message once the indication flag is set******/
    tx_handle = 0;                              //Transmitting through handle 0
    if(!CanGetStatus())          /* Not to transmit when the controller is into 
                                                         // sleep/busoff state */
    { 
        App_Tx_Copy_Data(tx_handle,buff2);             /* User function copying 
                           the user data into Global Tx Buffer for TxMessage0*/
    }
    Can_Ind_Flags[0] &= (canuint8)(~(Ind_Mask[0])); //clear the indication flag  
    if(CanTransmit(tx_handle)!= KCANTXOK) //Call CanTransmit() service for msg0  
    {
        /* user specific action incase transmission request is not successful*/
        AckFailed = 1;  //set this flag if fail to transmit acknowledge message
        SCI2_PutBuffer(buff24,sizeof(buff24));   
        while(!(SCI2_IsTransmitCompleted()));
        while(1);             // stuck here if there is any transmission error.
    }
   
    for (i=0;i<8;i++)
    {
        while (!(ADC_Test_Conversn_Complete ()));        /* Check for the EOC*/
        ADC_Buffer[i]= (canuint8)ADC_Conversn_Read ();/*Store the converted data*/
    }
    
        
/************ Clear the confirmation flag before starting transmission *******/
    Can_Conf_Flags[0] &= (canuint8)(~(Conf_Mask[0]));      
      
/************ User Transmit Part using CanTransmit() service *****************/
    if(!CanGetStatus())          /* Not to transmit when the controller is into 
                                                          sleep/busoff state */
    {
        App_Tx_Copy_Data(tx_handle,ADC_Buffer);        /* User function copying 
                           the user data into Global Tx Buffer for TxMessage0*/
        if(CanTransmit(tx_handle)!= KCANTXOK)     /* Call CanTransmit() service
                                                               for message 0 */ 
        {
            /* user action incase transmission request is not successful*/
            TransFailed = 1;    //set this flag is transmission fails
            SCI2_PutBuffer(buff24,sizeof(buff24));         
            while(!(SCI2_IsTransmitCompleted()));
            while(1);          // stuck here if there is any transmission error.
        }
    }                                       
    
 
    while(CanSleep()== KCANFAILED);//Put CAN in sleep mode
 
    SCI2_PutBuffer(buff4,sizeof(buff4));   
    while(!(SCI2_IsTransmitCompleted()));          // displays buff 4 on Hyper
/******************************************************************************
                 SPI to EEPROM (95040) APPLICATION STARTS
      Initialise the SPI with CPOL, CPHA, baudrate(fcpu/16) and master mode                 
******************************************************************************/    

    SPI_Init(SPI_DEFAULT | SPI_ENABLE | SPI_BAUDRATE_16 | SPI_CLK_PP_0 , SPI_MSTR_SW);  
    IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_LOW);                /*PB3 pin low*/
    SPI_PutByte((unsigned char)0x01);            /*Access the EEPROM register*/
    while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
    SPI_Clear_Flags();       /*check transmission complete and clear flag set*/
    SPI_PutByte((unsigned char)0xF0);// Clear all flags in the EEPROM registers
    while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
    SPI_Clear_Flags();                                       
    IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_HIGH);              /*set PB3 High*/
    
/******************************************************************************
                    SPI to EEPROM (95040) WRITE OPERATION
******************************************************************************/    

    for (i=0;i<10;i++)
    { 
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_LOW);              /*set PB2 low*/
      SPI_PutByte((unsigned char)0x06);       /*Access the register of EEPROM*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
      SPI_Clear_Flags();             /* Check for the successful transmission*/                          
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_HIGH);            /*set PB2 high*/
    
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_LOW);              /*set PB2 low*/   	     
      SPI_PutByte((unsigned char)0x02);  /*Write in the data memory of EEPROM*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
      SPI_Clear_Flags();             /* Check for the successful transmission*/
      SPI_PutByte(sub_add);                 /* Load the sub address of EEPROM*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
      SPI_Clear_Flags();              /*check for the successful transmission*/
      SPI_PutByte((unsigned char)ADC_Buffer[i]);       /*write data on EEPROM*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
      SPI_Clear_Flags();              /*Check for the successful transmission*/
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_HIGH);            /*Set PB2 high*/
      sub_add++;
    
      do
      {
        IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_LOW);   	     
        SPI_PutByte((unsigned char)0x05);/*Read the status register of EEPROM*/
        while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
        SPI_Clear_Flags();            /*check for the successful transmission*/
        SPI_PutByte((unsigned char)0x01);           /*Generate 8 clock pulses*/
        while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
        SPI_Clear_Flags();            /*check for the successful transmission*/
        IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_HIGH);          /*set PB2 high*/
      } while (SPI_GetByte() & 0x01);        /*check write complete in EEPROM*/
    }
    Delay();
    
    /************DISPLAY MESSAGES FOR SPI WRITE OPERATION OVER****************/
    SCI2_PutBuffer(buff5,(unsigned char)sizeof(buff5));              
    while(!(SCI2_IsTransmitCompleted()));
    Delay();
    SCI2_PutBuffer(buff6,(unsigned char)sizeof(buff6));              
    while(!(SCI2_IsTransmitCompleted()));

/******************************************************************************
                    SPI to EEPROM (95040) READ OPERATION
******************************************************************************/    

    sub_add=0x00;               
    for (i=0;i<10;i++)
    {
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_LOW);   	          /*Set PB2 low*/
      SPI_PutByte((unsigned char)0x03);   /*Set the EEPROM for read operation*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));      	 
      SPI_Clear_Flags();              /*check for the successful transmission*/
      SPI_PutByte(sub_add);                           /*load the read address*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));      	 
      SPI_Clear_Flags();              /*check for the successful transmission*/                         
      SPI_PutByte((unsigned char)0x01);             /*generate 8 clock pulses*/
      while(!(SPI_IsTransmitCompleted()==SPI_TRANSMIT_OK));
      while(!(SPI_IsReceptionCompleted()==SPI_RECEIVE_OK));
      SPI_Buffer[i] = SPI_GetByte();               /*get the data from EEPROM*/
      IO_Write (IO_PORT_B, IO_PIN_2, IO_DATA_HIGH);            /*set PB2 high*/
      sub_add++;
    }                                  
    Delay();
    Delay();

 /********************DISPLAY MESSAGE FOR SPI OPERATION OVER******************/

    SCI2_PutBuffer(buff7,(unsigned char)sizeof(buff7));              
    while(!(SCI2_IsTransmitCompleted()));                          
    
/******************************************************************************
       VERIFY THE DATA FOR SPI to EEPROM (95040) READ AND WRITE OPERATION
******************************************************************************/       

    for (i=0;i<10;i++)
    {
       while (!((unsigned char)ADC_Buffer[i]==SPI_Buffer[i]));
    }
    Delay();
    
    SCI2_PutBuffer(buff8,(unsigned char)sizeof(buff8));              
    while(!(SCI2_IsTransmitCompleted()));  

    CanWakeup();
//send a message asking the user to enter some data in the hyperterminal
    SCI2_PutBuffer(buff19,sizeof(buff19)); 
    // Use CAN Transmit Service to ack the wake up         
    while(!(SCI2_IsTransmitCompleted()));
    
/******************************************************************************
                    Reception of message written by user
******************************************************************************/        
    len_message = 8;
    SCI2_Mode(SCI_RX_ENABLE);
    Err = SCI2_GetBuffer(PC_Buffer,len_message);    
    if(Err == SCI_RECEIVE_OK)                         /*Checks the error status*/
    {
        Nop ;                                                 /* Reception OK*/
    }                                                         
    else                                     /*Error Ocurred during reception*/
    {
        if(Err & SCI_NOISE_ERR)
        {
            SCI2_Forced_Clear_Flag();
        }
        if(Err & SCI_OVERRUN_ERR)
        {
            SCI2_Forced_Clear_Flag();
        }
        if(Err & SCI_FRAMING_ERR)
        {
            SCI2_Forced_Clear_Flag();
        }
        if(Err & SCI_PARITY_ERR)
        {
            SCI2_Forced_Clear_Flag();
        }
    }   

/******************************************************************************
    TIMER A Library called to generate the rising edge at the pin PB6 
******************************************************************************/    

    TIMERA_Init(TIMER_FCPU_8); 
    TIMERA_OCMP_Mode(TIMER_OCMP_1,0xf000,TIMER_OUTPUT_R);

/******************************************************************************
    PWMART Library called to capture the rising edge, generated by TIMER A,
    applied on PA0.
******************************************************************************/ 

    PWMART_Init(PWMART_DEFAULT);
    PWMART_Counter_Enable(PWMART_REG_ARR,0xB0,PWMART_CLK_1);
    PWMART_ICAP_Mode(PWMART_ICAP_1,PWMART_SENSITIVITY_R | PWMART_ICAP1_IT_ENABLE);
     
/******************************************************************************
    Data transmission to Can until PWMART interrupt occurs.
******************************************************************************/
    while(FLAG == 0)   /* keep on Transmitting entered data on CAN till PWMART
                                                            Iinterrupt occurs*/
    {
        TransFailed = 0;


        if(!CanGetStatus())
        {
           /* User Transmit part using CanMsgTransmit() service */  
            user_tx_struct.stdid = MAKE_STD_ID(0x500); /* fill the stdid part */
	          user_tx_struct.extid = 0x0000;
	          user_tx_struct.dlc = 8; /* set the dlc */
            for(cnt=0;cnt<user_tx_struct.dlc;cnt++)
	              user_tx_struct.data[cnt]= PC_Buffer[cnt]; /* copy received data into the tx buffer*/
	          if(CanMsgTransmit(&user_tx_struct)!= KCANTXOK)
            {
                /* user specific action incase transmission request is not successful*/
                TransFailed = 1;
                SCI2_PutBuffer(buff24,sizeof(buff24));     
                while(!(SCI2_IsTransmitCompleted()));
                 
            }
            else
            {
                SCI2_PutBuffer(buff25,sizeof(buff25));     
                while(!(SCI2_IsTransmitCompleted()));
            }       
        }  
    }//while(FLAG == 0 

    while(1)
    { 
        char var1 = 0;
        {
            for (var1=0;var1<6;var1++)
            {  
                Delay_1();
                SCI2_PutBuffer(buff14,sizeof(buff14));
            }
        }  
     WDG_Refresh (0x00);                         /*Generates immediate reset*/   
    }
  
}
/******************************************************************************
                                  END OF MAIN
******************************************************************************/

/******************************************************************************
Interrupt Subroutine for DUMMY
******************************************************************************/
#ifdef _HIWARE_                                  /* test for HIWARE Compiler */
#pragma TRAP_PROC SAVE_REGS            /* additional registers will be saved */
#else
#ifdef _COSMIC_                                  /* test for Cosmic Compiler */
@interrupt                                      /* Cosmic interrupt handling */
#else
#error"Unsupported Compiler!"                 /* Compiler Defines not found! */
#endif
#endif

void DUMMY()
{
    volatile int i;
    for (i = 0; i < 5000; i++)
    {
        Nop
    }   
}  

/******************************************************************************
Interrupt Subroutine for PWMART
******************************************************************************/
#ifdef _HIWARE_                                  /* test for HIWARE Compiler */
#pragma TRAP_PROC SAVE_REGS            /* additional registers will be saved */
#else
#ifdef _COSMIC_                                  /* test for Cosmic Compiler */
@interrupt                                      /* Cosmic interrupt handling */
#else
#error"Unsupported Compiler!"                 /* Compiler Defines not found! */
#endif
#endif

void PWMART_IT_Routine ()
{   
    PWMART_Clear_Flag(PWMART_FLAG_ICF1);
    PWMART_Mode_Disable(PWMART_ICAP1_IT_DISABLE);  /*Disable PWMART Interrupt*/
//    Delay_1();
    FLAG = 1; /*Set a flag to show PWMART interrupt has occurred. Depending on 
    whether this flag is set,           */
}   
    
/******************************************************************************
Interrupt Subroutine for SCI
******************************************************************************/
#ifdef _HIWARE_                                  /* test for HIWARE Compiler */
#pragma TRAP_PROC SAVE_REGS            /* additional registers will be saved */
#else
#ifdef _COSMIC_                                  /* test for Cosmic Compiler */
@interrupt                                      /* Cosmic interrupt handling */
#else
#error"Unsupported Compiler!"                 /* Compiler Defines not found! */
#endif
#endif

void SCI2_IT_Routine()
{  
    SCI2_IT_Function();
}
            
/******************************************************************************
                      USER DEFINED FUNCTIONS
******************************************************************************/

void App_Tx_Copy_Data(canuint8 tx_handle,canuint8 *data_ptr)
{
    canuint8 cnt;
    CanGlobalInterruptDisable();
    for(cnt=0;cnt<Tx_Dlc[tx_handle];cnt++)
    {
        Tx_Data_Ptr[tx_handle][cnt] = *data_ptr++; /* copying the user tx data into 
                                                  global tx buffer */ 
    }
    CanGlobalInterruptRestore();
}

/******************************************************************************
Delay function to apply time delay in the application
******************************************************************************/ 

void Delay(void)
{   
    volatile unsigned char i; volatile int j;
    for (i=0;i<8;i++)
    {
        for (j=0;j<1000;j++)
        {
            Nop
        }
    }
} 


void Delay_1(void)
{   
    volatile char i; volatile int j;
    for (i=0;i<10;i++)
    {
        for (j=0;j<30000;j++); 
    } 
}  


/**** (c) 2003   STMicroelectronics *************************** END OF FILE **/












