//###########################################################################
//
// FILE:    Example_2837xDScic_FFDLB.c
//
// TITLE:   SCI FIFO Digital Loop Back Test.
//
//! \addtogroup cpu01_example_list
//! <h1>SCI FIFO Digital Loop Back Test (sci_looback)</h1>
//!
//!  This program uses the internal loop back test mode of the peripheral.
//!  Other then boot mode pin configuration, no other hardware configuration
//!  is required.
//!
//!  This test uses the loopback test mode of the SCI module to send
//!  characters starting with 0x00 through 0xFF.  The test will send
//!  a character and then check the receive buffer for a correct match.
//!
//!  \b Watch \b Variables \n
//!  - \b LoopCount - Number of characters sent
//!  - \b ErrorCount - Number of errors detected
//!  - \b SendChar - Character sent
//!  - \b ReceivedChar - Character received
//!
//
//###########################################################################
// $TI Release: F2837xD Support Library v3.11.00.00 $
// $Release Date: Sun Oct  4 15:55:24 IST 2020 $
// $Copyright:
// Copyright (C) 2013-2020 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 "F2837xD_Device.h"
#include "math.h"

//
// GY953
//
void spi_xmit(void);
void spi_receive(void);
void gy953_init(void);
void spi_fifo_init(void);
void spi_gpio_setting(void);

unsigned char data[7];  ///////////////////////or unsigned char
int16_t pitch,roll,yaw;
double PITCH=-179.25431,ROLL=12.135213,YAW=153.2315;
float distance = 123;
//
// ESP32-1 byte trans
//
void Scic_loopback_init(void);
void Scic_fifo_init(void);
void Scic_xmit(void);
void DECtoBIN(void);
void transfer(void);


int p3,p4,r3,r4,y3,y4;
__interrupt void cpu_timer0_isr(void);
__interrupt void cpu_timer1_isr(void);


int BIN[13];
    //include /null

int c = 1,cc = 1,flag = 0;
//
// Main
//
void main(void)
{

//
// Step 1. Initialize System Control registers, PLL, WatchDog, Clocks to
// default state:
// This function is found in the F2837xD_SysCtrl.c file.
//
   InitSysCtrl();

//
// Step 2. Initialize GPIO:
// This example function is found in the F2837xD_Gpio.c file and
// illustrates how to set the GPIO to it's default state.
//
   InitGpio();
   InitSpiaGpio();
   spi_gpio_setting();
//
// 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 the GPIOS
// These functions are found in the F2837xD_Gpio.c file.
//
   GPIO_SetupPinMux(139, GPIO_MUX_CPU1, 6);
   GPIO_SetupPinOptions(139, GPIO_INPUT, GPIO_PUSHPULL);
   GPIO_SetupPinMux(56, GPIO_MUX_CPU1, 6);
   GPIO_SetupPinOptions(56, GPIO_OUTPUT, GPIO_ASYNC);


//
// Step 3. Initialize PIE vector table:
// The PIE vector table is initialized with pointers to shell Interrupt
// Service Routines (ISR).  The shell routines are found in F2837xD_DefaultIsr.c.
// Insert user specific ISR code in the appropriate shell ISR routine in
// the F2837xD_DefaultIsr.c file.
//

//
// Disable and clear all CPU __interrupts:
//
    DINT;

    InitPieCtrl();

    IER = 0x0000;
    IFR = 0x0000;

//
// Initialize Pie Control Registers To Default State:
// This function is found in the F2837xD_PieCtrl.c file.
//
// InitPieCtrl();  //PIE is not used for this example

//
// Initialize the PIE Vector Table To a Known State:
// This function is found in F2837xD_PieVect.c.
// This function populates the PIE vector table with pointers
// to the shell ISR functions found in F2837xD_DefaultIsr.c.
//
    InitPieVectTable();

//
// Enable CPU and PIE __interrupts
// This example function is found in the F2837xD_PieCtrl.c file.
//
    EALLOW;  // This is needed to write to EALLOW protected registers
    PieVectTable.TIMER0_INT = &cpu_timer0_isr;
    PieVectTable.TIMER1_INT = &cpu_timer1_isr;
    EDIS;
//
// Step 4. User specific functions, Reassign vectors (optional),
// Enable Interrupts:
//
    InitCpuTimers();

    ConfigCpuTimer(&CpuTimer0, 200, 2000);
    ConfigCpuTimer(&CpuTimer1, 200, 5000);

    CpuTimer0Regs.TCR.all = 0x4000;
    CpuTimer1Regs.TCR.all = 0x4000;


    IER |= M_INT1;
    IER |= M_INT13;

    PieCtrlRegs.PIEIER1.bit.INTx7 = 1;

    EINT;  // Enable Global interrupt INTM
    ERTM;  // Enable Global realtime interrupt DBGM


    Scic_fifo_init();       // Initialize the SCI FIFO
    Scic_loopback_init();  // Initialize SCI for digital loop back
    spi_fifo_init();     // Initialize the SPI FIFO
    gy953_init();
    //
    // Note: Autobaud lock is not required for this example
    //

//
// Send a character starting with 0
//


//
// Step 5. Send Characters forever starting with 0x00 and going through
// 0xFF.  After sending each, check the receive buffer for the correct value
//
    for(;;)
    {

    }
}
void spi_gpio_setting(){
    GPIO_SetupPinMux(24, GPIO_MUX_CPU1, 6); //SIMO pin34
    GPIO_SetupPinMux(25, GPIO_MUX_CPU1, 6); //SOMI pin51
    GPIO_SetupPinMux(26, GPIO_MUX_CPU1, 6); //SCLK pin53
    GPIO_SetupPinMux(27, GPIO_MUX_CPU1, 6); //SS   pin52
}
void spi_xmit()
{
    int i;
    SpibRegs.SPICTL.bit.TALK = 1; // Enable Transmit path
    for(i=0;i<6;i++){
        if(i == 0){
            SpibRegs.SPITXBUF = 0x95;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }
        if(i == 1){
            SpibRegs.SPITXBUF = 0x96;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }
        if(i == 2){
            SpibRegs.SPITXBUF = 0x97;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }
        if(i == 3){
            SpibRegs.SPITXBUF = 0x98;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }
        if(i == 4){
            SpibRegs.SPITXBUF = 0x99;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }
        if(i == 5){
            SpibRegs.SPITXBUF = 0x9A;
            if(SpibRegs.SPIFFRX.bit.RXFFST != 0){
                data[i] = (unsigned char)SpibRegs.SPIRXBUF;
            }
        }

    }

}
void spi_receive()
{
    roll = (int16_t)(data[0] << 8 | data[1]);
    pitch = (int16_t)(data[2] << 8 | data[3]);
    yaw = (int16_t)(data[4] << 8 | data[5]);

    ROLL = (double)roll/100.0;
    PITCH = (double)pitch/100.0;
    YAW = (double)yaw/100.0;

}
void gy953_init()
{
    SpibRegs.SPICTL.bit.TALK = 1;
    //Configure registor
    SpibRegs.SPITXBUF = 0x41;
    SpibRegs.SPITXBUF = 0x7D;
    //Control registor
    SpibRegs.SPITXBUF = 0x42;
    SpibRegs.SPITXBUF = 0x9D;

    DELAY_US(3000);

}


//
// spi_fifo_init - Initialize Spib FIFO
//
void spi_fifo_init()
{
    //
    // Initialize SPI FIFO registers
    //
    SpibRegs.SPIFFTX.all = 0xE040;
    SpibRegs.SPIFFRX.all = 0x2044;
    SpibRegs.SPIFFCT.all = 0x0;

    //
    // Initialize core SPI registers
    //
    InitSpi();
}
//
// Scic_loopback_init - Configure Scic settings
//
void Scic_loopback_init()
{
    //
    // Note: Clocks were turned on to the Scic peripheral
    // in the InitSysCtrl() function
    //

    ScicRegs.SCICCR.all = 0x0007;  // 1 stop bit,  No loopback
                                   // No parity,8 char bits,
                                   // async mode, idle-line protocol
    ScicRegs.SCICTL1.all = 0x0003; // enable TX, RX, internal SCICLK,
                                   // Disable RX ERR, SLEEP, TXWAKE
    ScicRegs.SCICTL2.all = 0x0003;
    ScicRegs.SCICTL2.bit.TXINTENA = 1;
    ScicRegs.SCICTL2.bit.RXBKINTENA = 1;
    ScicRegs.SCIHBAUD.all = 0x0000;//00;  //250000 baud
    ScicRegs.SCILBAUD.all = 0x0036;//19;
    ScicRegs.SCICCR.bit.LOOPBKENA = 0; // Enable loop back
    ScicRegs.SCICTL1.all = 0x0023;     // Relinquish SCI from Reset
}

//
// Scic_xmit - Transmit a character from the SCI
//
void Scic_xmit()
{
    int a,b;

    for(a=0;a<12;a++){
        ScicRegs.SCITXBUF.all = BIN[a];     //1 bytes transmit 16 times (include '/0')
        DELAY_US(100);  //important delay
          if(a == 10){
               c = 1;
               cc = 1;
               for(b=0;b<11;b++){
                   BIN[b] = 0;
               }

          }
    }
}

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

void transfer()
{
    double p1,p2,r1,r2,y1,y2;
    if(cc == 1){
      cc = 0;
      p2 = modf(PITCH,&p1);
      p4 = (int)(p2*100);
      p3 = (int)p1;

      r2 = modf(ROLL,&r1);
      r4 = (int)(r2*100);
      r3 = (int)r1;

      y2 = modf(YAW,&y1);
      y4 = (int)(y2*100);
      y3 = (int)y1;
    }

}

void DECtoBIN(){
    int pitch,roll,yaw,height;
    int i;

    if(c == 1){
        pitch = p3;
        roll = r3;
        yaw = y3;
        height = distance;
        c = 0;

        //pitch
        if(pitch == 0 && p4 == 0){
            BIN[0] = 0x5A;
            for(i=1;i<4;i++){
                BIN[i] = 0;
            }

        }else if(pitch > 0){
            BIN[0] = 0x5A;
            BIN[1] = 0;
            BIN[2] = p3;
            BIN[3] = p4;

        }else if(pitch < 0){
            BIN[0] = 0x5A;
            BIN[1] = 1;
            BIN[2] = (-1)*p3;
            BIN[3] = (-1)*p4;
            flag = 1;
        }
         //roll
        if(roll == 0 && r4 == 0){
            for(i=4;i<7;i++){
                BIN[i] = 0;
            }

        }else if(roll > 0){
            BIN[4] = 0;
            BIN[5] = r3;
            BIN[6] = r4;

        }else if(roll < 0){
            BIN[4] = 1;
            BIN[5] = (-1)*r3;
            BIN[6] = (-1)*r4;
        }
         //yaw
        if(yaw == 0 && y4 == 0){
            for(i=7;i<10;i++){
                BIN[i] = 0;
            }

        }else if(yaw > 0){
            BIN[7] = 0;
            BIN[8] = y3;
            BIN[9] = y4;

        }else if(yaw < 0){
            BIN[7] = 1;
            BIN[8] = (-1)*y3;
            BIN[9] = (-1)*y4;
        }
         //height
        if(height > 255){
            height = 255;
            BIN[10] = height;
            BIN[11] = 0x5A;
        }else{
            BIN[10] = height;
            BIN[11] = 0x5A;
        }
    }
}

__interrupt void cpu_timer0_isr(void)
{
   CpuTimer0.InterruptCount++;

   spi_xmit();
   spi_receive();

   //
   // Acknowledge this interrupt to receive more interrupts from group 1
   //
   PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
}
__interrupt void cpu_timer1_isr(void)
{
   CpuTimer1.InterruptCount++;
   transfer();
   DECtoBIN();
   Scic_xmit();


}

//
// End of file
//
