//#############################################################################
//
// FILE:   sci_ex1_echoback.c
//
// TITLE:  SCI Echoback Example.
//
//! \addtogroup bitfield_example_list
//! <h1>SCI Echoback</h1>
//!
//!  This test receives and echo-backs data through the SCI-A port.
//!
//!  A terminal such as 'putty' can be used to view the data from
//!  the SCI and to send information to the SCI. Characters received
//!  by the SCI port are sent back to the host.
//!
//!  \b Running \b the \b Application
//!  Open a COM port with the following settings using a terminal:
//!  -  Find correct COM port
//!  -  Bits per second = 9600
//!  -  Data Bits = 8
//!  -  Parity = None
//!  -  Stop Bits = 1
//!  -  Hardware Control = None
//!
//!  The program will print out a greeting and then ask you to
//!  enter a character which it will echo back to the terminal.
//!
//!  \b Watch \b Variables \n
//!  - loopCounter - the number of characters sent
//!
//! \b External \b Connections \n
//!  Connect the SCI-A port to a PC via a transceiver and cable.
//!  - GPIO28 is SCI_A-RXD (Connect to Pin3, PC-TX, of serial DB9 cable)
//!  - GPIO29 is SCI_A-TXD (Connect to Pin2, PC-RX, of serial DB9 cable)
//!
//
//#############################################################################
//
//
// $Copyright:
// Copyright (C) 2022 Texas Instruments Incorporated - http://www.ti.com/
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions 
// are met:
// 
//   Redistributions of source code must retain the above copyright 
//   notice, this list of conditions and the following disclaimer.
// 
//   Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the 
//   documentation and/or other materials provided with the   
//   distribution.
// 
//   Neither the name of Texas Instruments Incorporated nor the names of
//   its contributors may be used to endorse or promote products derived
//   from this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// $
//#############################################################################

//
// Included Files
//
#include "f28x_project.h"
//#include "mdb_Init.h"
#include "mdb_sci_RX.h"
#include "mdb_sci_TX.h"
#include "mdb_lin_RX.h"
#include "mdb_lin_TX.h"
#include "FunState.h"
#include "math.h"
#include "Init_pwm.h"
#include "sfo_v8.h"
#include "MonitorSci.h"
#include "gpio.h"
#include "cmpss.h"
#include "charger_ecan.h"
#include "charger_ecan.h"
#include "adc.h"
#include "timer.h"
#include "FunState.h"

#include "FaultDetect.h"
//
// Defines
//
// Define AUTOBAUD to use the autobaud lock feature
//#define AUTOBAUD

//
// Globals
//
uint16_t loopCounter = 0;
uint16_t loopCounter1 = 0;
uint16_t uTest_epwmIsr_num = 0;

uint16_t PEROD = 0;
uint16_t PEROD_step = 10;
uint16_t PEROD_cmd = 0;

uint16_t uFaultHard_NUM = 0;

Uint16 status;
//int MEP_ScaleFactor; // Global variable used by the SFO library
//                     // Result can be used for all HRPWM channels
//                     // This variable is also copied to HRMSTEP
//                     // register by SFO() function.
int temp=0;
//
// Function Prototypes
//
void initSCIAEchoback(void);
void transmitSCIAChar(uint16_t a);
void transmitSCIAMessage(unsigned char * msg);
void initSCIAFIFO(void);
void SetupSCI(void);
//void error(void);
void scia_xmit(char Char);
void scia_msg(char *msg);



//void initADCSOC(void);
//void initADC(void);

//
// Main
//
void main(void)
{
//    uint16_t ReceivedChar;
//    unsigned char *msg;


    //
    // Initialize device clock and peripherals
    //
    InitSysCtrl();

    //
    // Initialize GPIO
    //
    InitGpio();

    //
    // For this example, only init the pins for the SCI-A port.
    // GPIO_SetupPinMux() - Sets the GPxMUX1/2 and GPyMUX1/2 register bits
    // GPIO_SetupPinOptions() - Sets the direction and configuration of GPIOs
    // These functions are found in the F28X7x_Gpio.c file.
    //
    GPIO_SetupPinMux(28, GPIO_MUX_CPU1, 1);
    GPIO_SetupPinOptions(28, GPIO_INPUT, GPIO_PUSHPULL);

    GPIO_SetupPinMux(29, GPIO_MUX_CPU1, 1);
    GPIO_SetupPinOptions(29, GPIO_OUTPUT, GPIO_ASYNC);

//    GPIO_SetupPinMux(39, GPIO_MUX_CPU1, 1);
//    GPIO_SetupPinOptions(39, GPIO_INPUT, GPIO_PUSHPULL);

    EALLOW;


    GpioCtrlRegs.GPAPUD.bit.GPIO22 = 0;        // Enable pull-up for GPIO28 (LIN TX)
    GpioCtrlRegs.GPAPUD.bit.GPIO23 = 0;        // Enable pull-up for GPIO29 (LIN RX)
    GpioCtrlRegs.GPAQSEL2.bit.GPIO23 = 3;      // Asynch input GPIO29 (LINRXA)
    GpioCtrlRegs.GPAQSEL2.bit.GPIO23 = 0x01;   // No qualification for all group A GPIO 16-31
    GpioCtrlRegs.GPACTRL.bit.QUALPRD3 = 0x03;
    GpioCtrlRegs.GPAGMUX2.bit.GPIO22 = 2;
    GpioCtrlRegs.GPAMUX2.bit.GPIO22 = 1;       // Configure GPIO28 for LIN TX operation (2-Enable,0-Disable)
    GpioCtrlRegs.GPAGMUX2.bit.GPIO23 = 2;
    GpioCtrlRegs.GPAMUX2.bit.GPIO23 = 1;       // Configure GPIO29 for LIN RX operation (2-Enable,0-Disable)


//    GpioCtrlRegs.GPBPUD.bit.GPIO39 = 0;
//    GpioCtrlRegs.GPBMUX1.bit.GPIO39 = 1;

    GPIO_SetupPinMux(39, GPIO_MUX_CPU1, 0);
    GPIO_SetupPinOptions(39, GPIO_OUTPUT, GPIO_ASYNC);
    GPIO_WritePin(39,0);

    GPIO_SetupPinMux(34, GPIO_MUX_CPU1, 0);
    GPIO_SetupPinOptions(34, GPIO_OUTPUT, GPIO_ASYNC);
    GPIO_WritePin(34,0);

    init_relay_gpio();

    EDIS;
    //
    // Disable CPU interrupts
    //
    DINT;

    //
    // Initialize the PIE control registers to their default state.
    // The default state is all PIE interrupts disabled and flags
    // are cleared.
    //
    InitPieCtrl();

    //
    // Disable CPU interrupts and clear all CPU interrupt flags
    //
    IER = 0x0000;
    IFR = 0x0000;

    //
    // Initialize the PIE vector table with pointers to the shell Interrupt
    // Service Routines (ISR)
    //
    InitPieVectTable();

    EALLOW;
    PieVectTable.ADCA1_INT = &adcA1ISR;     // Function for ADCA interrupt 1
    PieVectTable.EPWM1_INT = &epwm1ReCharISR;     // Function for
    PieVectTable.EPWM2_INT = &epwm2CharISR;     // Function for
    EDIS;
    
    IER |= M_INT1|M_INT3;  // Enable group 1 interrupts

    //
    // Configure the ADC and power it up
    //
//    initADC();
//
//    // Setup the ADC for ePWM triggered conversions on channel 1
//    //
//    initADCSOC();
    ADC_INIT();

    PieCtrlRegs.PIEIER1.bit.INTx1 = 1;

    //
    // Enable global Interrupts and higher priority real-time debug events:
    //
    
    SetupSCI();
    init_can();

    Time_init();

//    PieCtrlRegs.PIEIER1 = 1;
//    initSCIAFIFO();                         // Initialize the SCI FIFO
//    initSCIAEchoback();                     // Initialize SCI for echoback
    
    MonitorSci_System_PeripheralInit();


    // ePWM and HRPWM register initialization
    //
    
    HRPWM_Config(160);   // ePWMx target

	if (EPwm1Regs.ETFLG.bit.INT)
		EPwm1Regs.ETCLR.bit.INT = 1;
		
	if (EPwm2Regs.ETFLG.bit.INT)
		EPwm2Regs.ETCLR.bit.INT = 1;

    PieCtrlRegs.PIEIER3.bit.INTx1 = 0;
    PieCtrlRegs.PIEIER3.bit.INTx2 = 0;

    ////pwm  gpio������
    InitEPwm1Gpio();
    InitEPwm2Gpio();
    InitEPwm3Gpio();
//    InitEPwm4Gpio();

    EINT;
    ERTM;
     MonitorSci_System_AppInit();//³õÊ¼»¯Êý¾Ý


     MonitorSci_System_AppInit_lin();

     ADC_DATA_INIT();
     Fault_DATA_init();

     Fun_Status_init();
     BaseTime_init();
     
//     loopCounter = 0;
//
//     uRunState   = 0;
//     uSofterTime = 0;
//     status = SFO_INCOMPLETE;
//
//     while(status == SFO_INCOMPLETE)
//     {
//         status = SFO();
//         if(status == SFO_ERROR)
//         {
// //            error();   // SFO function returns 2 if an error occurs & # of MEP
//         }              // steps/coarse step exceeds maximum of 255.
//     }

    for(;;)
    {
        vMtimerTreat();

        DELAY_US(1000);

//        GPIO_WritePin(39, 1);
        DELAY_US(1000);

//        GPIO_WritePin(39, 0);
        DELAY_US(1000);
    }
}

//
//  initSCIAEchoback - Initialize SCI-A for echoback
//
void initSCIAEchoback(void)
{
    //
    // Note: Clocks were turned on to the SCIA peripheral
    // in the InitSysCtrl() function
    //
    SciaRegs.SCICCR.all = 0x0007;           // 1 stop bit,  No loopback
                                            // No parity, 8 char bits,
                                            // async mode, idle-line protocol
    SciaRegs.SCICTL1.all = 0x0003;          // enable TX, RX, internal SCICLK,
                                            // Disable RX ERR, SLEEP, TXWAKE
    SciaRegs.SCICTL2.all = 0x0003;
    SciaRegs.SCICTL2.bit.TXINTENA = 1;
    SciaRegs.SCICTL2.bit.RXBKINTENA = 1;

    //
    // SCIA at 9600 baud
    // @LSPCLK = 25 MHz (100 MHz SYSCLK) HBAUD = 0x01  and LBAUD = 0x44.
    //
    SciaRegs.SCIHBAUD.all = 0x0001;
    SciaRegs.SCILBAUD.all = 0x0044;

    SciaRegs.SCICTL1.all = 0x0023;          // Relinquish SCI from Reset
}

//
// transmitSCIAChar - Transmit a character from the SCI
//
void transmitSCIAChar(uint16_t a)
{
//    while (SciaRegs.SCIFFTX.bit.TXFFST != 0)
    while(MonitorSci_SEND_STATUS==0)
    {

    }
    SciaRegs.SCITXBUF.all = a;
}

//
// transmitSCIAMessage - Transmit message via SCIA
//
void transmitSCIAMessage(unsigned char * msg)
{
    int i;
    i = 0;
    while(msg[i] != '\0')
    {
        transmitSCIAChar(msg[i]);
        i++;
    }
}

//
// initSCIAFIFO - Initialize the SCI FIFO
//
void initSCIAFIFO(void)
{
    SciaRegs.SCIFFTX.all = 0xE040;
    SciaRegs.SCIFFRX.all = 0x2044;
    SciaRegs.SCIFFCT.all = 0x0;
}

void 
scia_xmit(char Char)
{
    //
	// Wait for the module to be ready to transmit
    //
	while(LinaRegs.SCIFLR.bit.TXRDY == 0);

    //
	// Begin transmission
    //
	LinaRegs.SCITD.all = Char;
}

//
// scia_msg -
// 
void 
scia_msg(char *msg)
{
	int it;
    it = 0;
    
    while(msg[it] != '\0')
    {
        scia_xmit(msg[it]);
        it++;
    }
}

//
// SetupSCI -
//
void SetupSCI(void)
{
    //
    // Allow write to protected registers
    //
    EALLOW;

    LinaRegs.SCIGCR0.bit.RESET = 0;     // Into reset
    LinaRegs.SCIGCR0.bit.RESET = 1;     // Out of reset

    LinaRegs.SCIGCR1.bit.SWnRST = 0;    // Into software reset

    LinaRegs.SCIPIO0.bit.RXFUNC = 1;
    LinaRegs.SCIPIO0.bit.TXFUNC = 1;
    //
    // SCI Configurations
    //
    LinaRegs.SCIGCR1.bit.COMMMODE = 0;      // Idle-Line Mode
    LinaRegs.SCIGCR1.bit.TIMINGMODE = 1;    // Asynchronous Timing
    LinaRegs.SCIGCR1.bit.PARITYENA = 0;     // No Parity Check
    LinaRegs.SCIGCR1.bit.PARITY = 0;        // Odd Parity
    LinaRegs.SCIGCR1.bit.STOP = 0;          // One Stop Bit
    LinaRegs.SCIGCR1.bit.CLK_MASTER = 1;    // Enable SCI Clock
    LinaRegs.SCIGCR1.bit.LINMODE = 0;       // SCI Mode
    LinaRegs.SCIGCR1.bit.SLEEP = 0;         // Ensure Out of Sleep
    LinaRegs.SCIGCR1.bit.MBUFMODE = 0;      // No Buffers Mode
    LinaRegs.SCIGCR1.bit.LOOPBACK = 0;      // External Loopback
    LinaRegs.SCIGCR1.bit.CONT = 1;          // Continue on Suspend
    LinaRegs.SCIGCR1.bit.RXENA = 1;         // Enable RX
    LinaRegs.SCIGCR1.bit.TXENA = 1;         // Enable TX

    //
    // Ensure IODFT is disabled
    //
    LinaRegs.IODFTCTRL.bit.IODFTENA = 0x0;

    //
    // Set transmission length
    //
    LinaRegs.SCIFORMAT.bit.CHAR = 7;     //Eight bits
    LinaRegs.SCIFORMAT.bit.LENGTH = 0;   //One byte


    //
    // Set baudrate
    //
    LinaRegs.BRSR.bit.SCI_LIN_PSL = 324;          //Baud = 9.6khz
    LinaRegs.BRSR.bit.M = 8;

    LinaRegs.SCIGCR1.bit.SWnRST = 1;  //bring out of software reset

    //
    // Disable write to protected registers
    //
    EDIS;
}




//
// End of file
//
