/*
 * software_spi.c
 *
 * Created: 19/08/2018 13:59:25
 *  Author: Ledo
 */ 

#include "software_spi.h"

 
 
 
 #if SPI_MSBFIRST
 unsigned char msk[] = {0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1};
 #define PCK() (bits[0] << 7 | bits[1] << 6 | bits[2] << 5 | bits[3] << 4 | bits[4] << 3 | bits[5] << 2 | bits[6] << 1 | bits[7])
 #else
 unsigned char msk[] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
 #define PCK() (bits[0]  | bits[1] << 1 | bits[2] << 2 | bits[3] << 3 | bits[4] << 4 | bits[5] << 5 | bits[6] << 6 | bits[7]<<7)
 #endif
 
 
 
 void soft_spi_init()
 {
	 //miso Pin
	 pio_set_input(PIOA,PIO_PA12,PIO_INPUT);
	 //mosi Pin
	 pio_set_output(PIOA,PIO_PA13,1,0,0);
	 //spck Pin Pin
	 pio_set_output(PIOA,PIO_PA14,1,0,0);
	 //NPCS1 Pin (DAC LTC1448 chip select)
	 pio_set_output(PIOA,PIO_PA9,1,0,0);

	 SPI_CLK_LOW();
 }
 
 
 
 void soft_spi_transfer(uint8_t b)
 {
	 
	 for(uint8_t _bit = 0;_bit < 8;_bit++)
	 {
		
		 SPI_CLK_LOW();  // change this to LOW for CPOL=1
		 delay_us(DELAY_T0);//DELAY_CYCLES_P0
		 
		 ///digitalWrite(_MOSI, !!(b & msk[_bit]));
		 SPI_MOSI_LEVEL((b & msk[_bit]));
		 delay_us(DELAY_T1); //  propagation
		 SPI_CLK_HIGH();
		 delay_us(DELAY_T2); //DELAY_CYCLES_C0// holding low, so there is enough time for data preparation and changing
	     SPI_MOSI_LEVEL(false);
		 delay_us(DELAY_T3); // there is a requirement of LOW and HIGH have identical interval!
		 
	 }
	 
	 SPI_CLK_LOW(); 
 }
 
  