/** \file utilities.c ********************************************************
 * 
 *             Project: Maxim Plug-in Peripheral Modules
 *            Filename: utilities.c
 *         Description: This module contains a collection of general utility
 *                      functions which are not specific to any particular
 *                      module.
 * 
 *    Revision History:
 *\n       4-13-12 Rev 1.0 Seth Messimer   Initial Release
 *\n       7-20-12 Rev 1.4 Nathan Young    Additional functions
 * 
 *  --------------------------------------------------------------------
 * 
 *    This code follows the following naming conventions.
 * 
 * 	  char                   chPmodValue
 * 	  char (array)           sPmodString[16]
 * 	  float                  fPmodValue
 * 	  int                    nPmodValue
 * 	  int (array)            anPmodValue[16]
 * 	  u16                    uPmodValue
 * 	  u8                     uchPmodValue
 * 	  u8 (array)             auchPmodBuffer[16]
 * 	  unsigned int           unPmodValue
 * 	  int *                  punPmodValue
 * 
 * ------------------------------------------------------------------------- */
/*
 * Copyright (C) 2012 Maxim Integrated Products, All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL MAXIM INTEGRATED PRODUCTS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of Maxim Integrated Products
 * shall not be used except as stated in the Maxim Integrated Products
 * Branding Policy.
 *
 * The mere transfer of this software does not imply any licenses
 * of trade secrets, proprietary technology, copyrights, patents,
 * trademarks, maskwork rights, or any other form of intellectual
 * property whatsoever. Maxim Integrated Products retains all ownership rights.
 *
 ***************************************************************************/

#include "xparameters.h"	/* EDK generated parameters */
#include "xspips_hw.h"		/* SPI device driver */
#include "stdio.h"

#include "utilities.h"
#include "MAXREFDES5.h"

#define UART_BASEADDR		XPAR_XUARTPS_0_BASEADDR

int ARMSpi4ByteRW( unsigned int unPeripheralAddressSPI, unsigned int* auchWriteBuf, unsigned int* auchReadBuf)
/**
* \brief       Perform a fixed 4 byte SPI read/write to optimize for speed.
* \par         Details
*              This function provides a combination SPI Read and Write to the chosen ARM SPI port in the design
*              CPHA and CPOL are permanently set to 0 0 right now.
*              Pointers are provided to u8 buffers containing the data to be written and received
*              Data in the auchWriteBuf will be clocked out (MSB first) onto the MOSI pin
*              Data from the MISO pin will be placed into the auchReadBuf
               SS0 is active low and only option right now.
*
* \param[in]   unBaseAddr         - @help
* \param[in]   auchWriteBuf       - pointer to write data buffer
* \param[out]  auchReadBuf        - pointer to read data buffer
*
* \retval      Always returns 0
*/
{
	//Enable manual start, enable manual CS mode, no slave selected
	//Buad rate = clk / 64, CPOL=0 CPHA=0, enable master mode
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x0,0xFC21);//0xFC21

	//Enable the SPI peripheral, and the SS0 pin goes high
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x14,0x1);


	//Write a value to the Tx_Data_reg
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x1C,auchWriteBuf[0]);

	//Write a value to the Tx_Data_reg
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x1C,auchWriteBuf[1]);

	//Write a value to the Tx_Data_reg
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x1C,auchWriteBuf[2]);

	//Write a value to the Tx_Data_reg
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x1C,auchWriteBuf[3]);

	//Assert SS1 pin, SS0 goes low
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x0,0xC421);//0xC421

	//start the SPI transaction by writing a 1 to the Man_start_com bit
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x0,0x1c421);//0x1c421

	while((XSpiPs_ReadReg(unPeripheralAddressSPI,0x4)&0x4)==0);

	//SS1 goes high
	XSpiPs_WriteReg(unPeripheralAddressSPI,0x0,0xFC21);//0xFC21

	//Read the Rx_Data_reg
	auchReadBuf[0]=XSpiPs_ReadReg(unPeripheralAddressSPI,0x20);

	//Read the Rx_Data_reg
	auchReadBuf[1]=XSpiPs_ReadReg(unPeripheralAddressSPI,0x20);

	//Read the Rx_Data_reg
	auchReadBuf[2]=XSpiPs_ReadReg(unPeripheralAddressSPI,0x20);
	auchReadBuf[2]=auchReadBuf[2]<<8;

	//Read the Rx_Data_reg
	auchReadBuf[3]= auchReadBuf[2] + XSpiPs_ReadReg(unPeripheralAddressSPI,0x20);

	return 0;
}


void print_asterisks(int nQuantity)
/**
* \brief       Print nQuantity of asterisks to the default Hyperterminal UART
*
* \param[in]   nQuantity    - number of asterisks to print
*
* \retval      None
*/
{
	int i=0;
	for(i=0;i<nQuantity;i++)
		printf("*");
}

void delay(int nStopValue)
/**
* \brief       Loop for nStopValue iterations to provide a delay.
* \par         Details
*              It is commonly used with the constant 'ABOUT_ONE_SECOND' defined in maximPMOD.h for
*              setting approximate delays
*
* \param[in]   nStopValue    - number of iterations to loop
*
* \retval      None
*/
{
	int i=0;
	int a=0;

	for(i=0;i<nStopValue;i++)
	{
		a=i;
	}
}

unsigned long number_raised_to_power(int nBase, int nExponent)
/**
* \brief       Raise nBase to the nExponent power (operates with integers only).
* \par         Details
*              Many Microblaze applications will not have math.h included due to limited memory space.
*              This is a simple functions to implement (nBase ^ nExponent)
*              Some Maxim devices (such as MAX44009) return values in mantissa + (power of 2) exponent format.
*
* \param[in]   nBase             - base
* \param[in]   nExponent         - exponent
*
* \retval      Base^Exponent
*/
{
	int i=0;
	unsigned long nValue=0;
	if(nExponent==0)
		nValue=1;
	else
	{
		nValue = nBase;
		for(i=1;i<nExponent;i++)
		{
			nValue = nValue * nBase;
		}
	}
	return(nValue);
}

// MTS int receive_byte_with_timeout(u32 unUartAddress, int nTimeoutInTenthsOfSeconds, u8 *uchRxData)
/**
* \brief       Receive a byte from the UART located at *pUartAddress
*
* \param[in]   unUartAddress                - address of the UART peripheral in MicroBlaze memory map @help
* \param[in]   nTimeoutInTenthsOfSeconds    - amount of time to allow before TIMEOUT
* \param[out]  *uchRxData                   - received data is stored at uchRxData
*
* \retval      TRUE if operation succeeded
*/
/*MTS{
	int j=0;
	int nReturnVal = TRUE;
	u8 uchInput = 0;

	// Check if there is a character in the UART Rx buffer
	// Continue checking every 10th of a second for nTimeoutInSeconds
	while(XUartLite_IsReceiveEmpty(unUartAddress) && (j < nTimeoutInTenthsOfSeconds))
	{
		j++;
		delay(ABOUT_ONE_SECOND/10);
	}

	if(XUartLite_IsReceiveEmpty(unUartAddress))
			nReturnVal = FALSE;
	else
	{
		uchInput = XUartLite_RecvByte(unUartAddress);
		// Check if it is an escape sequence
		if(uchInput==27)  // Escape sequence (likely an arrow key)
		{
			if(XUartLite_IsReceiveEmpty(unUartAddress))
				nReturnVal = FALSE;
			else
			{
				uchInput = XUartLite_RecvByte(unUartAddress);
				if(uchInput==91)  // Left bracket (part #2 of the 3 part escape sequence)
				{
					if(XUartLite_IsReceiveEmpty(unUartAddress))
						nReturnVal = FALSE;
					else
					{
						uchInput = XUartLite_RecvByte(unUartAddress);
						if(uchInput==75)
							uchInput = 244;  // We have defined KEYPRESS_END as 244
					}
				}
			}

		}
		*uchRxData = uchInput;
		nReturnVal = TRUE;
	}
	return(nReturnVal);
} */ //MTS

//MTS int GetLine( char* sInputString, unsigned int unMaxSize )
/**
* \brief       Retrieve a line of characters from the default Hyperterminal UART (DEFAULT_HYPERTERMINAL_UART).
* \par         Details
*              Maximum number of characters can be specified.  Function will timeout after 10 seconds.
*
* \param[in]   sInputString       - pointer to buffer for input string
* \param[in]   unMaxSize          - maximum number of characters to input
*
* \retval      TRUE if operation succeeded
*/
/*MTS{
	u8 uchInputChar = 0;
	unsigned int unInputStringIndex = 0;

	receive_byte_with_timeout(UART_BASEADDR, 10, &uchInputChar);
	while( (uchInputChar != '\r') && (uchInputChar != '\n') && (unInputStringIndex < unMaxSize-1) )
	{
		sInputString[ unInputStringIndex ] = (char)uchInputChar;
		unInputStringIndex++;
		receive_byte_with_timeout(UART_BASEADDR, 10, &uchInputChar);
	}
	sInputString[ unInputStringIndex ] = '\0';

	return (unInputStringIndex < unMaxSize) ? unInputStringIndex : -1;
} */ //MTS

