#include "at32f403a_407.h"
#include "spi_common.h"

void common_spi_init(void)
{
    gpio_init_type gpio_initstructure;
    spi_init_type spi_init_struct;
  
    crm_periph_clock_enable(CRM_IOMUX_PERIPH_CLOCK, TRUE);
    crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
    crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
    
    gpio_pin_remap_config(SWJTAG_MUX_010, TRUE);
    gpio_pin_remap_config(SPI3_GMUX_0010, TRUE);
  
    // SCK
    gpio_initstructure.gpio_out_type       = GPIO_OUTPUT_PUSH_PULL;  
    gpio_initstructure.gpio_pull           = GPIO_PULL_DOWN;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_MUX;  
    gpio_initstructure.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
    gpio_initstructure.gpio_pins           = GPIO_PINS_3;
    gpio_init(GPIOB, &gpio_initstructure);
  
    // MISO
    gpio_initstructure.gpio_pull           = GPIO_PULL_UP;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_INPUT;  
    gpio_initstructure.gpio_pins           = GPIO_PINS_4;
    gpio_init(GPIOB, &gpio_initstructure);
    
    // MOSI
    gpio_initstructure.gpio_pull           = GPIO_PULL_UP;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_MUX; 
    gpio_initstructure.gpio_pins           = GPIO_PINS_5;
    gpio_init(GPIOB, &gpio_initstructure);
     
    // CS
    gpio_initstructure.gpio_out_type       = GPIO_OUTPUT_PUSH_PULL;  
    gpio_initstructure.gpio_pull           = GPIO_PULL_UP;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_OUTPUT;  
    gpio_initstructure.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
    gpio_initstructure.gpio_pins           = GPIO_PINS_15;
    gpio_init(GPIOA, &gpio_initstructure);
    
    
    SPI_FLASH_CS_H();

    crm_periph_clock_enable(CRM_SPI3_PERIPH_CLOCK, TRUE);
    
    spi_default_para_init(&spi_init_struct);
    spi_init_struct.transmission_mode = SPI_TRANSMIT_FULL_DUPLEX;
    spi_init_struct.master_slave_mode = SPI_MODE_MASTER;
    spi_init_struct.mclk_freq_division = SPI_MCLK_DIV_2, //SPI_MCLK_DIV_32; //SPI_MCLK_DIV_2;
    spi_init_struct.first_bit_transmission = SPI_FIRST_BIT_MSB;
    spi_init_struct.frame_bit_num = SPI_FRAME_8BIT;
    spi_init_struct.clock_polarity = SPI_CLOCK_POLARITY_HIGH;
    spi_init_struct.clock_phase = SPI_CLOCK_PHASE_2EDGE;
    spi_init_struct.cs_mode_selection = SPI_CS_SOFTWARE_MODE;
    
    spi_init(SPI3, &spi_init_struct);
 
    //spi_hardware_cs_output_enable(SPI3, TRUE);
    
    spi_enable(SPI3, TRUE);
}

void common_spi_send(spi_type *spi, uint16_t data)
{
    while (spi_i2s_flag_get(spi, SPI_I2S_TDBE_FLAG) == RESET);
    spi->dt = data;
}

uint8_t common_spi_receive(spi_type *spi)
{
    while (spi_i2s_flag_get(spi, SPI_I2S_RDBF_FLAG) == RESET);
    return spi->dt;
}

uint8_t common_spi_tx_rx(spi_type *spi, uint8_t data)
{
    while (spi_i2s_flag_get(spi, SPI_I2S_TDBE_FLAG) == RESET);
    spi->dt = data;
  
    while (spi_i2s_flag_get(spi, SPI_I2S_RDBF_FLAG) == RESET);
    return spi->dt;
}
