#include "stdio.h"
#include "OB6621.h"
#include "uart.h"
#include "spi.h"
#include "gpio.h"

void Delay(uint32_t nDelayCount)
{
    while(nDelayCount--);
}

int main(void)
{
    uint32_t nLoop;
    SystemCoreClockUpdate();

    // Open UART
    GPIO_SetPinMFType(OB_GPIO2, GPIO_PIN0, GPIO_MF_UART1_RX);
    GPIO_SetPinMFType(OB_GPIO2, GPIO_PIN1, GPIO_MF_UART1_TX);
    UART_Open(OB_UART1, 19200);

    printf("+----------------------------------------------------------------------+\n\r");
    printf("|                       SPI Driver Sample Code                         |\n\r");
    printf("+----------------------------------------------------------------------+\n\r");
    printf("\n\r");

    /* Setup SPI multi-function pin */
    GPIO_SetPinMFType(OB_GPIO3, GPIO_PIN4, GPIO_MF_SPI_MASTER_SS); //SSP_SS
    GPIO_SetPinMFType(OB_GPIO3, GPIO_PIN5, GPIO_MF_SPI_MASTER_CLK); //SSP_CLK
    GPIO_SetPinMFType(OB_GPIO3, GPIO_PIN6, GPIO_MF_SPI_MASTER_MOSI); //SSP_MOSI
    GPIO_SetPinMFType(OB_GPIO3, GPIO_PIN7, GPIO_MF_SPI_MASTER_MISO); //SSP_MISO

    SPI_MasterOpen(OB_SPI, (SPI_OUT_PHASE_FIRST | SPI_OUT_POLARITY_HI | SPI_SIZE_8BIT ), 1000000);
    SPI_EnableINT(OB_SPI, SPI_INT_RTIM);

    nLoop = 0x100;
    g_SPIRxCounter = 0x00;
    printf(" Rx Data = \n\r");

    while(nLoop--)
    {
        Delay(100);

        // Send Clock to Slave
        OB_SPI->DR = nLoop;

        // Receive the Data from Slave

        g_SPIRxCounter = 0x00;
        while (1)
        {
            if (g_SPIRxCounter >= 1)
            {
                printf(" %02X,\n\r", g_SPIRxData[0]);
                break;
            }
        }
    }
    while(1);
}

