/*
 * spi.c
 *
 * Created: 25/09/2016 12:52:51
 *  Author: Ledo
 */ 



#include "spi0.h"

void SPI_init(void) 
{
	
	
 //sysclk_enable_pba_module(SYSCLK_SPI0);
 gpio_enable_module(SPI_GPIO_MAP , sizeof(SPI_GPIO_MAP)/sizeof(SPI_GPIO_MAP[0]));
 
 spi_initMaster(&AVR32_SPI0 , &SPI_OPTIONS);
 
 //spi_setupChipReg(&AVR32_SPI0,&SPI_OPTIONS,sysclk_get_pba_hz());
 //spi_selectionMode(&AVR32_SPI0 ,0 ,0 ,0);
 //spi_enable((&AVR32_SPI0));	
 
 // Enable the clock to the selected example Timer/counter peripheral module.
 sysclk_enable_peripheral_clock(&AVR32_SPI0);
 
 
 //spi_master_init(&AVR32_SPI0);
 spi_master_setup_device(&AVR32_SPI0, &SPI_DEVICE_0, SPI_MODE_0,
 SPI_OPTIONS.baudrate, 0);
 AVR32_SPI0.MR.pcs = 0xE;
 AVR32_SPI0.CSR0.cpol = 0;
 AVR32_SPI0.CSR0.ncpha = 1;

 spi_enable(&AVR32_SPI0);
 
  gpio_configure_pin(POTA_CS,GPIO_DIR_OUTPUT | GPIO_INIT_HIGH);
  gpio_configure_pin(POTB_CS,GPIO_DIR_OUTPUT | GPIO_INIT_HIGH);
  

}




void AjustePot_A(uint8_t ch, uint8_t cursor)
{
	gpio_set_pin_low(POTA_CS);

	// Send the command write byte.
	while (!spi_is_tx_ready(&AVR32_SPI0));
	spi_write_single(&AVR32_SPI0,ch);
	
	// Send the cursor data.
	while (!spi_is_tx_ready(&AVR32_SPI0));
	spi_write_single(&AVR32_SPI0,cursor);
	delay_us(100);
	gpio_set_pin_high(POTA_CS);
}

void AjustePot_B(unsigned char cursor)
{
	gpio_set_pin_low(POTB_CS);

	// Send the command write byte.
	while (!spi_is_tx_ready(&AVR32_SPI0));
    spi_write_single(&AVR32_SPI0,POTA_WR);
	
	// Send the cursor data.
	while (!spi_is_tx_ready(&AVR32_SPI0));
    spi_write_single(&AVR32_SPI0,cursor);
	
	delay_us(100);
	gpio_set_pin_high(POTB_CS);

}





