/** 
 *******************************************************************************
 * @file    main.c
 * @brief   the application functions of Slave demo for the TOSHIBA
 *          'TMPM311' Device Series 
 * @version V0.100
 * @date    2014/10/27
 * 
 * DO NOT USE THIS SOFTWARE WITHOUT THE SOFTWARE LICENSE AGREEMENT.
 * 
 * (C)Copyright TOSHIBA ELECTRONIC DEVICES & STORAGE CORPORATION 2017 All rights reserved
 *******************************************************************************
 */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

uint8_t SIO0_RxBuffer[BufSize] = { 0U };
uint8_t SIO0_TxBuffer[BufSize] = "SlaveToMaster";

volatile uint8_t fSIO0TxOK = 1U;
volatile uint8_t gSIO0RdIndex = 0U;
volatile uint8_t gSIO0WrIndex = 0U;

void SIO_Configure(void);

/**
  * @brief  main  function
  * @param  None
  * @retval int
  */
int main(void)
{
    SIO_InitTypeDef SIO0_Init;

    SCB->VTOR = (unsigned int)0x10000000;
    /*configure the IO port of SIO */
    SIO_Configure();
    /*configure the SIO0 channel */
    SIO_Enable(SIO0);
    /* Selects input clock for prescaler as PhiT0. */
    SIO_SetInputClock(SIO0, SIO_CLOCK_T0);

    /*initialize the SIO0 struct */
    SIO0_Init.InputClkEdge = SIO_SCLKS_TXDF_RXDR;
    SIO0_Init.TIDLE = SIO_TIDLE_HIGH;
    SIO0_Init.TXDEMP = SIO_TXDEMP_HIGH;
    SIO0_Init.EHOLDTime = SIO_EHOLD_FC_64;
    SIO0_Init.TransferMode = SIO_TRANSFER_FULLDPX;
    SIO0_Init.TransferDir = SIO_LSB_FRIST;
    SIO0_Init.Mode = SIO_ENABLE_TX | SIO_ENABLE_RX;
    SIO0_Init.DoubleBuffer = SIO_WBUF_ENABLE;

    SIO_Init(SIO0, SIO_CLK_SCLKINPUT, &SIO0_Init);


    /* enable SIO0 Channel RX interrupt */
    NVIC_EnableIRQ(INTRX0_IRQn);

    /* enable SIO0 Channel TX interrupt */
    NVIC_EnableIRQ(INTTX0_IRQn);

    while (1) {
        /*SIO0 send data from TXD0 */
        if (fSIO0TxOK == 1U) {
            fSIO0TxOK = 0U;
            SIO_SetTxData(SIO0, SIO0_TxBuffer[gSIO0WrIndex++]);
            if (gSIO0WrIndex == (BufSize + 1)) 
                gSIO0WrIndex = 0;
        } else {
            /*Do Nothing */
        }

        /*SIO0 receive data end */
        if (gSIO0RdIndex >= BufSize) {
            SIO_Disable(SIO0);
        } else {
            /*Do Nothing */
        }

    }
}

/**
  * @brief  configure the IO port of SIO
  * @param  None
  * @retval None
  */
void SIO_Configure(void)
{
    /*SET PA6 AS TXD0 */
    TSB_PA->FR1 |= (1U << 6U);
    TSB_PA->CR |= (1U << 6U);

    /*SET PA4 AS SCLK0 */
    TSB_PA->FR1 |= (1U << 4U);
    TSB_PA->IE |= (1U << 4U);

    /*SET PA5 AS RXD0 */
    TSB_PA->FR1 |= (1U << 5U);
    TSB_PA->IE |= (1U << 5U);
}

/**
  * @brief  Deal with the error parameter
  * @param  file: Pointer to the file where the error parameter locates
  * @param  line: Number of the line in which the error parameter locates
  * @retval None
  */
#ifdef DEBUG
void assert_failed(char *file, int32_t line)
{
    while (1) {
        __NOP();
    }
}
#endif
