/** \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

#define OLED_VBAT 0x20
#define OLED_VDD 0x10;
#define OLED_RESET_B 0x08
#define OLED_DATA_COMMAND_B 0x04
#define OLED_SDIN 0x02
#define OLED_SCLK 0x01

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

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("*");
}

int SpiRW( u32 unPeripheralAddressSPI, unsigned int unCPHA, unsigned int unCPOL,
		u8* auchWriteBuf, u8* auchReadBuf, int unNumBytes, u8 uchCsActiveHigh )
/**
* \brief       Perform a SPI read or write.
* \par         Details
*              This function provides a combination SPI Read and Write to the chosen SPI port in the design
*              CPHA and CPOL can be set to 0 or 1
*              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
*              uchCsActiveHigh==TRUE allows SS configurations to be used
*              uchCsActiveHigh==FALSE allows SS# configurations to be used
*
* \param[in]   unPeripheralAddressSPI         - @help
* \param[in]   unCPHA             - phase of SCK (edge to trigger on). 0=Leading edge, 1=Trailing edge
* \param[in]   unCPOL             - polarity of SCK. 0=Active high, 1=Active low
* \param[in]   auchWriteBuf       - pointer to write data buffer
* \param[in]   auchReadBuf        - pointer to read data buffer
* \param[in]   unNumBytes         - number of bytes to transfer
* \param[in]   uchCsActiveHigh    - polarity of slave select 0=active low, 1=active high
*
* \retval      Always returns 0
*/
{
	int i;
	unsigned int unControlData = 0x00000186;

	//If CPHA or CPOL = 1, we need to set the corresponding bits in the control register
	unControlData = unControlData | (unCPHA << 4);
	unControlData = unControlData | (unCPOL << 3);

	//Write config data to SPICR.  We need the inhibit bit=1.
	XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

	//Deassert CS to 1 to ensure SPI slave is inactive
	if( uchCsActiveHigh )
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);
	else
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);

	for( i = 0; i < unNumBytes; i++)
	{
		if( auchWriteBuf != 0 )
		{
			//Write data to SPIDTR.  This is the data that will be transferred to the SPI slave.
			XSpi_WriteReg(unPeripheralAddressSPI, 0x68, auchWriteBuf[ i ]);
			//Debug//printf( "Write %02x; ", auchWriteBuf[i]);
		}
		else
		{
			//Write data to SPIDTR.  This is the data that will be transferred to the SPI slave.
			XSpi_WriteReg(unPeripheralAddressSPI, 0x68, 0x00);
		}

		//Write config data to SPICR.  We need the inhibit bit=1.
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

		//Assert CS for our PMOD part
		if( uchCsActiveHigh )
			XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);
		else
			XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);

		//Un-inhibit our SPI master to transfer the data
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData & 0xFFFFFEFF);

		//Wait for transaction to complete.  Check to see if Tx_Empty flag is set before proceeding.
		while( !(XSpi_ReadReg( unPeripheralAddressSPI, 0x64 ) & 0x00000004) )
			;

		//Inhibit SPI master to prevent further action
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

		//Read received data
		if( (auchReadBuf != 0) )
		{
			auchReadBuf[ i ] = XSpi_ReadReg(unPeripheralAddressSPI, 0x6C);
			//Debug//printf( "Read %02x\r\n", auchReadBuf[i]);
		}
	}
	if( uchCsActiveHigh )
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);
	else
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);
	return 0;
}

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;
	}
}

void led_knight_rider(XGpio *pLED_GPIO, int nNumberOfTimes)
/**
* \brief       Blink a row of LEDs nNumberOfTimes times.
* \par         Details
*              The Digilent NEXYS-3 and Zedboard have 8 green LEDs located above the toggle switches.
*              This function blinks them back/forth (a bit like the KITT car from Knight Rider)
*
* \param[in]   *pLED_GPIO    - address of the GPIO peripheral driving the LEDs in MicroBlaze memory map
*
* \retval      None
*/
{
	int i=0;
	int j=0;
	u8 uchLedStatus=0;

	// Blink the LEDs back and forth nNumberOfTimes
	for(i=0;i<nNumberOfTimes;i++)
	{
		for(j=0;j<8;j++)  // Scroll the LEDs up
		{
			uchLedStatus = 1 << j;
			XGpio_DiscreteWrite(pLED_GPIO, 1, uchLedStatus);
			delay(ABOUT_ONE_SECOND / 15);
		}

		for(j=0;j<8;j++)  // Scroll the LEDs up
		{
			uchLedStatus = 8 >> j;
				XGpio_DiscreteWrite(pLED_GPIO, 1, uchLedStatus);
				delay(ABOUT_ONE_SECOND / 15);
		}
	}
}
/* MTS
void max_set_PMOD_port(int nPortNumber, u8 uchPortType)
/**
* \brief       Configure driving peripherals on each Pmod port.
* \par         Details
*              The Maxim HDL hardware design for the Nexys 3 includes a multiplexer on each PMOD port to allow I2C,
*              SPI, GPIO, and UART functionality to be selected on each port.
*
*              This function should be called any time a new PMOD type is plugged into a PMOD.
*              Valid settings for uchPortType follow:
* \n           PMOD_PORT_TYPE_UART, PMOD_PORT_TYPE_SPI, PMOD_PORT_TYPE_GPIO, PMOD_PORT_TYPE_I2C
*
* \param[in]   nPortNumber    -  integer number of the port to set (0=A, 1=B, 2=C, 3=D)
* \param[in]   uchPortType    -  u8 number to set type of PMOD port

*/
{
	if(nPortNumber>=0 && nPortNumber<=3)
	{
		g_auchPortType[nPortNumber]=uchPortType;
	}
	max_configure_PMOD_port(g_auchPortType[0],g_auchPortType[1],g_auchPortType[2],g_auchPortType[3]);
	delay(ABOUT_ONE_SECOND / 10);
}

void max_configure_PMOD_port(u8 uchPmodPortA, u8 uchPmodPortB, u8 uchPmodPortC, u8 uchPmodPortD)
/**
* \brief       Configure driving peripherals on each Pmod port.
* \par         Details
*              The Maxim HDL hardware design for the Nexys 3 includes a multiplexer on each PMOD port to allow I2C,
*              SPI, GPIO, and UART functionality to be selected on each port.
*              The standard configuration is (PortA = I2C, PortB = SPI, PortC = GPIO, PortD = UART)
*              This function is used to set the standard configuration in the main() function, as well as to
*              optionally change the port config.  The 2-bit number used to define the port configuration is
*              encoded as follows:
* \n           00=UART, 01=SPI, 10=GPIO and 11=I2C
*
* \param[in]   uchPmodPortA    -  2-bit number to define configuration for Pmod port A
* \param[in]   uchPmodPortB    -  2-bit number to define configuration for Pmod port B
* \param[in]   uchPmodPortC    -  2-bit number to define configuration for Pmod port C
* \param[in]   uchPmodPortD    -  2-bit number to define configuration for Pmod port D
*
* \retval      TRUE if operation succeeded
*/
{
	u8 uchPmodPortSelectBits=0;
	// The PMOD ports are configured with an 8 bit word sent to GPIO2
	// Bits 1:0 are for port #A
	// Bits 3:2 are for port #B
	// Bits 5:4 are for port #C
	// Bits 7:6 are for Port #D

	 //S = 2'b00   	=> UART active 	(PMOD_PORT_TYPE_UART)
	 //S=  2'b01   	=> SPI active 	(PMOD_PORT_TYPE_SPI)
	 //S = 2'b10  	=> GPIO active	(PMOD_PORT_TYPE_GPIO)
	 //S = 2'b11	=> I2C active 	(PMOD_PORT_TYPE_I2C)

	uchPmodPortSelectBits = (uchPmodPortD << 6) + (uchPmodPortC << 4) + (uchPmodPortB << 2) + uchPmodPortA;
	XGpio_DiscreteWrite(&g_xGpioPmodPortMuxIO, 1, uchPmodPortSelectBits);
}
int check_if_i2c_device_is_present(int nPMODPortNumber)
/**
* \brief       Test for SDA and SCL pullups.
* \par         Details
*              This function places the PMOD port into GPIO mode briefly in order to sample the SDA and SCL lines
*              If they are high, then this implies that a pull-up is present, and hence a PMOD board is likely present
*
* \param       None
*
* \retval      TRUE if pull-ups present, FALSE if pullups not present
*/
{
	unsigned int unGpioPortData = 0;
	int nReturnVal=FALSE;
	int i;
	unsigned char auchTempPortType[4];
	XGpio *pPortGPIO;

	// Make a temp/backup copy of the (present) port type assignments
	for(i=0;i<4;i++)
		auchTempPortType[i] = g_auchPortType[i];

	// Configure Port n to be GPIO
	if(nPMODPortNumber>=0 && nPMODPortNumber<=3)
	{
		switch(nPMODPortNumber)
		{
			case 0:
				pPortGPIO=&g_xGpioPmodPortA;
				break;
			case 1:
				pPortGPIO=&g_xGpioPmodPortB;
				break;
			case 2:
				pPortGPIO=&g_xGpioPmodPortC;
				break;
			case 3:
				pPortGPIO=&g_xGpioPmodPortD;
				break;
		}

		// Pre-set the GPIO on the active port to be inputs
		// This is pins SCL and SDA
		XGpio_SetDataDirection(pPortGPIO, 1, 0x0C);  // Set the all pins to outputs, except pins SDA (pin3) and SCL (pin2)

		max_set_PMOD_port(nPMODPortNumber, PMOD_PORT_TYPE_GPIO);
		delay(ABOUT_ONE_SECOND / 10);

		// Read the value of the GPIO pins
		unGpioPortData = XGpio_DiscreteRead(pPortGPIO, 1);
		XGpio_SetDataDirection(pPortGPIO, 1, 0xFF);  // Set the all pins on this GPIO port back to inputs
		if(((unGpioPortData >> 2) & 0x03)==0x03)
		{
			printf("I2C Device is present\r\n");
			nReturnVal=TRUE;
		}
		else
		{
			nReturnVal=FALSE;
			print_asterisks(74);
			printf("******WARNING: Could not find pull-ups on SDA nor SCL ********************\r\n");
			printf("******Attempts to read/write may hang CPU ********************************\r\n");
			printf("******Recommend to go back to main menu and double-check I2C device.******\r\n");
			print_asterisks(74);
			delay(ABOUT_ONE_SECOND * 3);
		}
	}

	delay(ABOUT_ONE_SECOND / 10);
	// Set the ports back to the original configuration
	max_configure_PMOD_port(auchTempPortType[0],auchTempPortType[1],auchTempPortType[2],auchTempPortType[3]);
	delay(ABOUT_ONE_SECOND / 10);

return(nReturnVal);
}

int 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;
	int nValue=0;
	if(nExponent==0)
		nValue=1;
	else
	{
		nValue = nBase;
		for(i=1;i<nExponent;i++)
		{
			nValue = nValue * nBase;
		}
	}
	return(nValue);
}

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
*/
{
	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(checkUartEmpty(unUartAddress) && (j < nTimeoutInTenthsOfSeconds))
	{
		j++;
		delay(ABOUT_ONE_SECOND/10);
	}

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

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

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
*/
{
	u8 uchInputChar = 0;
	unsigned int unInputStringIndex = 0;

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

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

void printf_temp(float fTemp, u8 uchPrintCelsius, u8 uchAddCarriageReturn)
/**
* \brief       Print temperature as xx.x as degrees F or C
* \par         Details
*              This function prints the temperature with .1 degree resolution in either degrees
* \n           Celsius (uchPrintCelsius==TRUE) -or- Fahrenheit (uchPrintCelsius==FALSE)
*
* \param[in]   fTemp                   - temperature to print in celsius
* \param[in]   uchPrintCelsius         - true = print as celsius, false = print as fahrenheit
* \param[in]   uchAddCarriageReturn    - true = add a carriage return
*
* \retval      None
*/
{
	if(uchPrintCelsius==TRUE)
		printf("%.1f deg C",fTemp);
	else
		printf("%.1f deg F",((fTemp*1.8f)+32.0f));
	if(uchAddCarriageReturn==TRUE)
		printf("\r\n");
}
*/


void sendOLEDSPI(u8 uchDataToWrite)
/**
* \brief       Bit bang routine for Zedboard SPI OLED interface
* \par         Details
*              This function sends an (unsigned) byte (msb first) to the OLED SPI port
*
* \param[in]   uchDataToWrite          - u8 value to be written to OLED SPI
* \retval      None
*/
{
	int i;

	for(i=7;i>=0;i--)
	{
		// Set the OLED_SDIN bit
		if(((uchDataToWrite >> i) & 0x01)==0x01)
			g_structureOLED.portStatus |= OLED_SDIN;
		else
			g_structureOLED.portStatus &= ~OLED_SDIN;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);

		// Clock in the data via a rising edge of SCLK
		g_structureOLED.portStatus |= OLED_SCLK;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);
		g_structureOLED.portStatus &= ~OLED_SCLK;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);
	}
}

void initializeOLED(u8 *pFont)
/**
* \brief       Initializes the OLED display
* \par         Details
*              This function initializes the OLED display and the global data structure that holds the OLED display buffer and font.
*
* \param[in]   *pFont          - pointer to an u8 array containing the ASCII display font
* \retval      None
*/
{
	// First, initialize the global structure that represents the OLED device

	//GPIO that manages the bit-banged SPI interface to the OLED
	//XGpio_Initialize(&g_structureOLED.xgpioPort, XPAR_AXI_GPIO_OLED_DEVICE_ID);
	XGpio_Initialize(&g_structureOLED.xgpioPort, XPAR_AXI_GPIO_OLED_DEVICE_ID);
	XGpio_SetDataDirection(&g_structureOLED.xgpioPort, 1, 0x00);	// Set the OLED peripheral to outputs
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, 0x00);		// Set all values to zero
	delay(100);

	// Set the font in the OLED structure
	g_structureOLED.font = pFont;

	// Init the global variable that represents the OLED bit-bang pins
	g_structureOLED.portStatus = 0x00;

	// Init and clear the display buffer and the invertered/flipped buffer
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	clearOLEDBuffer(g_structureOLED.flippedBuffer);

	// Now, Initialize the OLED display (hardware)

	// Disable VBAT power supply to the OLED integrated switcher
	// Note:  These bits control the Gate voltage on a P-Channel MOSFET
	g_structureOLED.portStatus |= OLED_VBAT;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	//Enable VDD power supply to digital logic within OLED
	g_structureOLED.portStatus |= OLED_VDD;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	// Disable reset
	g_structureOLED.portStatus |= OLED_RESET_B;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	// Set Display Off
	sendOLEDSPI(0xAE);
	delay(100);

	// Set Display Clock Divide Ratio.  Oscillator Frequency
	sendOLEDSPI(0xD5);
	delay(100);
	sendOLEDSPI(0x80);
	delay(100);

	// Set Multiplex Ratio
	sendOLEDSPI(0xA8);
	delay(100);
	sendOLEDSPI(0x1F);
	delay(100);

	// Set Display Offset
	sendOLEDSPI(0xD3);
	delay(100);
	sendOLEDSPI(0x00);
	delay(100);

	// Set Display Start Line
	sendOLEDSPI(0x40);
	delay(100);

	// Set Charge Pump
	sendOLEDSPI(0x8D);
	delay(100);
	sendOLEDSPI(0x14);
	delay(100);

	// Set Segment Re-Map
	sendOLEDSPI(0xA1);
	delay(100);

	// Set COM Output Scan Direction
	sendOLEDSPI(0xC8);
	delay(100);

	// Set Com Pins Hardware Configuration
	sendOLEDSPI(0xDA);
	delay(100);
	sendOLEDSPI(0x02);
	delay(100);

	// Set Contrast Control
	sendOLEDSPI(0x81);
	delay(100);
	sendOLEDSPI(0x8F);
	delay(100);

	// Set Pre-Charge Period
	sendOLEDSPI(0xD9);
	delay(100);
	sendOLEDSPI(0xF1);
	delay(100);

	// Set VCOMH Deselect Level
	sendOLEDSPI(0xDB);
	delay(100);
	sendOLEDSPI(0x40);
	delay(100);

	// Set Entire Display On
	sendOLEDSPI(0xA4);
	delay(100);

	// Set Normal/Inverse Display
	sendOLEDSPI(0xA6);
	delay(100);

	// Enable the VBAT power supply (which is used for the OLED)
	g_structureOLED.portStatus &= ~OLED_VBAT;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/2);	// Long delay for internal OLED switcher to stabilize

	// Set Display On
	sendOLEDSPI(0xAF);
	delay(100);
}

void clearOLEDBuffer(u8 *pauchBuffer)
/**
* \brief       Clears the OLED display buffer
* \par         Details
*              This function clears the display buffer by setting all pixels to zero.
*
* \param[in]   *pauchBuffer          - pointer to an u8 array used for the OLED pixel buffer
* \retval      None
*/
{
	int i;

	for(i=0;i<512;i++)
		pauchBuffer[i] = 0x00;

}

void displayOLEDBuffer(u8 *pauchBuffer)
/**
* \brief       Copies the display buffer into the OLED display
* \par         Details
*              This function writes the the display buffer into the OLED display using the page mode setting.
* \n           Note:  The Zedboard OLED display contains a Solomon SSD1306 display controller.
*
* \param[in]   *pauchBuffer          - pointer to an u8 array used for the OLED pixel buffer
* \retval      None
*/
{
	int column=0;
	int page=0;
	u8 *p;
	u8 uchPixelValue=0;

	// Set the display mode to page based transfers
	sendOLEDSPI(0x20);
	delay(100);
	sendOLEDSPI(0x02);
	delay(100);

	// Set the page pointer lower nibble to 0x0
	sendOLEDSPI(0x00);
	delay(100);

	// Set the page pointer upper nibble to 0x0
	sendOLEDSPI(0x10);
	delay(100);

	// Write 4 pages worth of data
	// Note that the SSD1306 controller can handle 128x64 displays, but the OLED
	// used on zedboard is only 128x32.  Data is provided to the display as (4) pages of 128 bytes each.
	p = pauchBuffer;
	for(page=0;page<4;page++)
	{
		// Enable Command Mode (shut off data mode)
		g_structureOLED.portStatus &= ~OLED_DATA_COMMAND_B;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
		delay(100);	// Long delay for internal OLED switcher to stabilize

		// Set the page command by issuing 0xB0 (page0), 0xB1 (page1) etc.
		sendOLEDSPI((0xB0+page));

		// Enable the Data mode (shut off command mode)
		g_structureOLED.portStatus |= OLED_DATA_COMMAND_B;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
		delay(100);	// Long delay for internal OLED switcher to stabilize

		for(column=0;column<128;column++)
		{
			uchPixelValue = *p;
			sendOLEDSPI(uchPixelValue); // change this to zero
			p++;
		}
	}

	// Enable Command Mode (shut off data mode)
	g_structureOLED.portStatus &= ~OLED_DATA_COMMAND_B;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(100);	// Long delay for internal OLED switcher to stabilize
}

void putCharOLED(int x, int y, char chCharacter)
/**
* \brief       Places a single ASCII character into the OLED display buffer
* \par         Details
*              This function copies an ASCII character from the font table into the OLED display buffer (configured as a 16x4 character display).
*
* \param[in]   x          - The x position of the character location
* \param[in]   y          - The y position of the character location
* \param[in]   chCharacter          - ASCII character to be printed (ex:  0x41 = 'A')
* \retval      None
*/
{
	int i;
	int nDisplayBufferIndex=0;
	int nFontIndex=0;

	// Create the index location for the character into the display memory
	nDisplayBufferIndex = (x * 8) + (y * 16 * 8);

	// Make sure the character has a valid value, else ignore
	if(chCharacter >=0 && chCharacter<128)
	{
		nFontIndex = chCharacter * 8;

		for(i=nDisplayBufferIndex;i<nDisplayBufferIndex+8;i++)
		{
			g_structureOLED.writeBuffer[i] = g_structureOLED.font[nFontIndex];
			nFontIndex++;
		}
	}
}

void printfToBufferOLED(int x, int y,char *chString)
/**
* \brief       Printf-like function to copy an ASCII string into the OLED display buffer
* \par         Details
*              This function copies a pre-formatted ASCII string into the OLED display buffer, but does not take any action to display the buffer
*
* \param[in]   x          - The starting position of string within the 16x4 character display
* \param[in]   y          - The starting position of string within the 16x4 character display
* \param[in]   *chString          - pointer to an null terminated character string.  Should be generated with sprintf (or similar).
* \retval      None
*/
{
	int nStringLength;
	int nInitialDisplayLocation;
	int nRemainingDisplayLength;
	int i;
	int xIndex=0;
	int yIndex=0;
	nStringLength = strlen(chString);

	// Will the string fit on the display?  If not, truncate the length
	nInitialDisplayLocation = y*16 + x;
	nRemainingDisplayLength = 64 - nInitialDisplayLocation;
	if(nStringLength > nRemainingDisplayLength)
		nStringLength = nRemainingDisplayLength;

	xIndex = x;
	yIndex = y;
	for(i=0;i<nStringLength;i++)
	{
		putCharOLED(xIndex,yIndex,chString[i]);
		xIndex++;
		if(xIndex==16)
		{
			xIndex=0;
			yIndex++;
		}
	}
}

void printfToOLED(int x, int y,char *chString)
/**
* \brief       Printf-like function to copy an ASCII string into the OLED display buffer
* \par         Details
*              This function copies a pre-formatted ASCII string into the OLED display buffer,
*              flips/rotates the display pixels, and then sends the buffer to the OLED display
*
* \param[in]   x          - The starting position of string within the 16x4 character display
* \param[in]   y          - The starting position of string within the 16x4 character display
* \param[in]   *chString          - pointer to an null terminated character string.  Should be generated with sprintf (or similar).
* \retval      None
*/
{
	printfToBufferOLED(x,y,chString);
	flipAndCopyDisplayBuffer(g_structureOLED.writeBuffer, g_structureOLED.flippedBuffer);
	displayOLEDBuffer(g_structureOLED.flippedBuffer);
}


void flipAndCopyDisplayBuffer(u8 *pauchSourceBuffer, u8 *pauchDestinationBuffer)
/**
* \brief       Copies the pixels from the source display buffer, into the destination buffer, flipping their location 180 degrees.
* \par         Details
*              The (0,0) pixel location on the OLED display is in the bottom right corner.
*              This function flips the display so that the (0,0) is in the top left corner and (131,31) is in the bottom right.
*
* \param[in]   *pauchSourceBuffer          - pointer to an u8 buffer used as the source display buffer
* \param[in]   *pauchDestinationBuffer     - pointer to an u8 buffer used as the destination display buffer
* \retval      None
*/
{
	int i,x,y;
	u8 uchTempWord1;
	u8 uchTempWord2;
	u8 uchTempWord3;

	for(y=0;y<4;y++)
	{
		for(x=0;x<128;x++)
		{
			uchTempWord1 = pauchSourceBuffer[511-((y*128)+x)];
			uchTempWord3 = 0;
			for(i=0;i<8;i++)
			{
				uchTempWord2 = (uchTempWord1 >> (7-i)) & 0x01;  // shift the bit to the bit0 location and mask off
				uchTempWord2 = uchTempWord2 << i;				// shift the bit back to the desired location.
				uchTempWord3 += uchTempWord2;
			}
			pauchDestinationBuffer[((y*128)+x)] = uchTempWord3;
		}
	}
}

void printOLED_31855(float fInternalTemp,float fProbeTemp, int displayCelsius)
/**
* \brief       Prints the MAX31855 temperature to the OLED.
* \par         Details
*              Uses the printfToOLED function to print the 31855 temperature values to the OLED
*
* \param[in]   fInternalTemp  - floating point value representing the internal temperature of the MAX31855
* \param[in]   fProbeTemp     - floating point value representing the probe temperature of the MAX31855
* \param[in]   displayCelsius - TRUE if the value is to be displayed in Celsius, FALSE for Fahrenheit
* \retval      None
*/
{
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	sprintf(g_tempString,"MAX31855 Temp");
	printfToOLED(0,0,g_tempString);
	if(displayCelsius==TRUE)
	{
		sprintf(g_tempString,"Int: %.1f(C)",fInternalTemp);
		printfToOLED(0,2,g_tempString);
		sprintf(g_tempString,"Probe: %.1f(C)",fProbeTemp);
		printfToOLED(0,3,g_tempString);
	}
	else
	{
		sprintf(g_tempString,"Int: %.1f(F)",(fInternalTemp*1.8f)+32);
		printfToOLED(0,2,g_tempString);
		sprintf(g_tempString,"Probe: %.1f(F)",(fProbeTemp*1.8f)+32);
		printfToOLED(0,3,g_tempString);
	}
}

void printOLED_31723(float fTemp)
/**
* \brief       Prints the MAX31723 temperature to the OLED.
* \par         Details
*              Uses the printfToOLED function to print the 31723 temperature value to the OLED
*
* \param[in]   fTemp  - floating point value representing the internal temperature of the MAX31723
* \retval      None
*/
{
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	sprintf(g_tempString,"MAX31723 Temp");
	printfToOLED(0,0,g_tempString);
	sprintf(g_tempString,"%.1f(C) %.1f(F)",fTemp,(fTemp*1.8f)+32);
	printfToOLED(0,2,g_tempString);
}

void printOLED_3231M(struct maximDateTime t, float fTemp)
/**
* \brief       Prints the MAX3231M data to the OLED
* \par         Details
*              Uses the printfToOLED function to print the MAX3231M data to the OLED
*
* \param[in]   maximDateTime t  - structure containing the date and time results from the MAX3231M
* \param[in]   fTemp  - floating point value representing the internal temperature of the MAX3231M
* \retval      None
*/
{
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	sprintf(g_tempString," %d/%d/%d",t.uchMonth,t.uchDate,(t.uchYear+2000));
	printfToOLED(0,0,g_tempString);
	sprintf(g_tempString,"%02d:%02d:%02d\r\n",t.uchHour,t.uchMinute,t.uchSecond);
	printfToOLED(0,1,g_tempString);
	sprintf(g_tempString,"%.1f(C) %.1f(F)",fTemp,(fTemp*1.8f)+32);
	printfToOLED(0,3,g_tempString);
}

void printOLED_44000Lux(float fLuxReading)
/**
* \brief       Prints the MAX44000 Lux data to the OLED
* \par         Details
*              Uses the printfToOLED function to print the MAX44000 lux data to the OLED
*
* \param[in]   fLuxReading - floating point value representing the lux reading
* \retval      None
*/
{
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	sprintf(g_tempString,"Ambient Light:");
	printfToOLED(0,0,g_tempString);
	sprintf(g_tempString,"%.1f (Lux)",fLuxReading);
	printfToOLED(0,1,g_tempString);
}

void printOLED_44000Prox(float fProxReading)
/**
* \brief       Prints the MAX44000 Proximity data to the OLED
* \par         Details
*              Uses the printfToOLED function to print the MAX44000 prox data to the OLED
*
* \param[in]   fProxReading - floating point value representing the prox reading
* \retval      None
*/
{
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	sprintf(g_tempString,"Proximity Val:");
	printfToOLED(0,0,g_tempString);
	sprintf(g_tempString,"%.1f",fProxReading);
	printfToOLED(0,1,g_tempString);
}


