/*
 * w25q128.c
 *
 * Created: 12/06/2018 16:26:13
 *  Author: Ledo
 */ 

//#include "sam4e.h"

#include "asf.h"
#include <spi.h>


//#define chip_select()     {spi_set_peripheral_chip_select_value(SPI, 0x0E);}
//#define chip_deselect()   {spi_set_peripheral_chip_select_value(SPI, 0x0F);}
#define chip_select()     {pio_set_pin_low(PIO_PA11_IDX);}
#define chip_deselect()   {pio_set_pin_high(PIO_PA11_IDX);}



uint8_t tx_buff[2];

void SPI_init(void);
uint8_t spi_master_transfer(uint8_t byte);

void SPI_init(void)
{
	//miso Pin
	ioport_set_pin_mode(PIO_PA12_IDX, IOPORT_MODE_MUX_A);
	ioport_disable_pin(PIO_PA12_IDX);
	//mosi Pin
	ioport_set_pin_mode(PIO_PA13_IDX, IOPORT_MODE_MUX_A);
	ioport_disable_pin(PIO_PA13_IDX);
	//spck Pin Pin
	ioport_set_pin_mode(PIO_PA14_IDX, IOPORT_MODE_MUX_A);
	ioport_disable_pin(PIO_PA14_IDX);

	//NPCS0 Pin (WIZNET chip select)
	//ioport_set_pin_mode(PIO_PA11_IDX, IOPORT_MODE_MUX_A);
	//ioport_disable_pin(PIO_PA11_IDX);
    pio_set_output(PIOA,(1<<11),1,0,0);
	
	//NPCS1 Pin (DAC LTC1448 chip select)
	//ioport_set_pin_mode(PIO_PA9_IDX, IOPORT_MODE_MUX_A);
	//ioport_disable_pin(PIO_PA9_IDX);
	pio_set_output(PIOA,(1<<9),1,0,0);
	
	//NPCS2 Pin (EXT SPI chip select)
	//ioport_set_pin_mode(PIO_PA10_IDX, IOPORT_MODE_MUX_A);
	//ioport_disable_pin(PIO_PA10_IDX);
	pio_set_output(PIOA,(1<<10),1,0,0);
	
	spi_enable_clock(SPI);
	spi_disable(SPI);
	spi_reset(SPI);
	spi_set_lastxfer(SPI);
	spi_set_master_mode(SPI);
	spi_disable_mode_fault_detect(SPI);
	spi_disable_loopback(SPI);
	spi_set_peripheral_chip_select_value(SPI, spi_get_pcs(0));
	spi_set_fixed_peripheral_select(SPI);
	spi_disable_peripheral_select_decode(SPI);
	spi_set_delay_between_chip_select(SPI, 0);
	
    int16_t baud_div = spi_calc_baudrate_div(1000000, sysclk_get_peripheral_hz());
    spi_set_transfer_delay(SPI, 0, 0,0);
    spi_set_bits_per_transfer(SPI, 0,SPI_CSR_BITS_8_BIT);
    spi_set_baudrate_div(SPI, 0, baud_div);
    spi_configure_cs_behavior(SPI, 0, SPI_CS_KEEP_LOW);
    spi_set_clock_polarity(SPI, 0, SPI_MODE_0 >> 1);
    spi_set_clock_phase(SPI, 0, ((SPI_MODE_0 & 0x1) ^ 0x1));	

	spi_enable(SPI);
}

/**
 * \brief Perform SPI master transfer.
 *
 */
uint8_t spi_master_transfer(uint8_t byte)
{
	uint8_t uc_pcs;
	uint16_t data;
	//SPIe.transfer(byte);
	spi_write(SPI, byte, 0, 0);
	/* Wait transfer done. */
	while ((spi_read_status(SPI) & SPI_SR_RDRF) == 0);
	spi_read(SPI, &data, &uc_pcs);
    return data;
}


