
#include "cspi_defines.h"

#ifndef CSPI_FUNCTIONS_H__ 
#define CSPI_FUNCTIONS_H__  /* Prevent multiple inclusions */


/* 
   Convinience macros for accessing the CSPI registers. In general, the 32 bit
   version should be used, since all CSPI registers are assumed to be 32 bit.

   NOTE: name is the short name of the register CON == CONREG
 */

#define  cspi_read08(name)  (*((U8)(CSPI_REG_##name)))
#define  cspi_read16(name)  (*((U16)(CSPI_REG_##name)))
#define  cspi_read32(name)  (*((U32)(CSPI_REG_##name)))

#define  cspi_write08(name,newvalue) \
         (*((U8)(CSPI_REG_##name)) = (newvalue))
#define  cspi_write16(name,newvalue) \
         (*((U16)(CSPI_REG_##name)) = (newvalue))
#define  cspi_write32(name,newvalue) \
         (*((U32)(CSPI_REG_##name)) = (newvalue))

#define  cspi_compare08(name,expected) \
         PutCheck08(CSPI_REG_##name, (expected));
#define  cspi_compare16(name,expected) \
         PutCheck16(CSPI_REG_##name, (expected));
#define  cspi_compare32(name,expected) \
         PutCheck32(CSPI_REG_##name, (expected));

// Enables CSPI by setting the CONREG'EN bit; all other bits unchanged
#define ENABLE_CSPI reg32setbit(CSPI_REG_CON, CSPI_CON_EN_BP)

// Disables the CSPI by clearing the CONREG'EN bit; all other bits unchanged
#define DISABLE_CSPI reg32clrbit(CSPI_REG_CON, CSPI_CON_EN_BP)

// Writes the corresponding data into the TXDATA register
#define CSPI_SEND_DATA(data)  reg32write(CSPI_REG_TXDATA, (data))

/*
   Polling loop that waits for the TC bit to be set in the STATREG. This bit
    is set when the TXFIFO is empty and the shift register has shifted out
    all bits.
 */

void CSPI_WAIT_TRANSFER_COMPLETE( void )
{
   U32 RegValue;

   do
   {
      RegValue = cspi_read32(STAT);
   }
   while ((RegValue & CSPI_STAT_TC) == 0);
}

/*! Waits for the end of a transmission by polling of the CONREG'XCH bit.
    This bit is cleared when the started transmission is finished.
 */
 
void CSPI_WAIT_EXCHANGE_DONE( void )
{
   U32 RegValue;

   do
   {
      RegValue = cspi_read32(CON);
   }
   while ((RegValue & CSPI_CON_XCH) == 1);
}

/*! Waits until the receiver has received at least one word of data and 
    stored in RxFIFO. This is indicated by setting STATREG'RR to 1.
 */
void CSPI_WAIT_FOR_DATA_IN_RXFIFO( void )
{
   U32 RegValue;

   do
   {
      RegValue = cspi_read32(STAT);
   }
   while ((RegValue & CSPI_STAT_RR) == 0);
}

#endif /* #ifndef CSPI_FUNCTIONS_H__ */

