/********************************************************************************

					REva Library
			Copyright (c), RAISONANCE

+-------------------------------------------------------------------------------+
 The present source code which is for guidance only aims at providing
 customers with information regarding their products in order for them to
 save time. As a result, RAISONANCE shall not be held liable for any
 direct indirect or consequential damages with respect to any claims arising
 from the content of such a source code and/or the use made by customers of 
 the information contained herein in connection with their products.
+-------------------------------------------------------------------------------+*/
   
//this file implements the functions for easy handling of the REva board


//WARNING: all these functions assume that the associated peripherals are correctly initialized

#include "73x_lib.h"
#include "REvaLib.h"

//------------------------------------------------------------------
// utility functions
//------------------------------------------------------------------

//this function converts a hex number from ascii to binary
unsigned char readhex(char car)
{
	if( (car>='a') && (car<='f') )
		return car-'a'+10;

	if( (car>='A') && (car<='F') )
		return car-'A'+10;

	if( (car>='0') && (car<='9') )
		return car-'0';

	return 0xff;
}


#if USE_IO
//------------------------------------------------------------------
// Digital functions
//------------------------------------------------------------------
void init_IO() {
   // I/O Port initialization
   GPIO_InitTypeDef gpio_init ;
   
   CFG_PeripheralClockConfig(CFG_CLK_GPIO2 , ENABLE);
  	CFG_PeripheralClockConfig(CFG_CLK_GPIO5 , ENABLE);
  	
   // Configure P2.0-7 as Output Push-Pull for REva LEDs
   gpio_init.GPIO_Pins = 0x00FF ;
   gpio_init.GPIO_Mode = GPIO_Mode_OUT_PP ;
   GPIO_Init(GPIO2, &gpio_init) ;
   
   // Configure P5.8-9, P5.12-15 as standard input for REva buttons and switches
   gpio_init.GPIO_Pins = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15 ;
   gpio_init.GPIO_Mode = GPIO_Mode_IN_TRI_TTL ;
   GPIO_Init(GPIO5, &gpio_init) ;
}

void writeIO(unsigned char number){
  GPIO_ByteWrite(GPIO2, GPIO_LSB, number);
}

unsigned char readIO(){
  return ((GPIO5->PD&0x0300)>>4)|((GPIO5->PD&0xF000)>>12) ;
}
#endif

//------------------------------------------------------------------
// Analog functions
//------------------------------------------------------------------
#if USE_ANALOG

#define referencemv (5000) // voltage reference for the ADC (highest value in mV)
#define offset (0x000) 		// digital value for the 0 volt (min)
#define vref (0x3FF)  		// digital value for the 5 volt (max)

// Converts the digital value (between 0x000 and 0x3FF) into the corresponding value in mV
u32 ADC_Calib(u16 Conv_Res)
{
	if(!Conv_Res)
		return 0 ;
	
	return (((u32)Conv_Res*referencemv)/vref)&(0x003FFFFF) ;
}

//initialize the ADC chanels
void init_adc( void ) 
	{
	GPIO_InitTypeDef gpio_init ;
	ADC_InitTypeDef adc_init ;
	
	// ADC Clock Enable
  	CFG_PeripheralClockConfig(CFG_CLK_ADC, ENABLE);
  
   // Configure the used analog input channel to HI_AIN_TRI
   // GPIO3 Clock Enable
  	CFG_PeripheralClockConfig(CFG_CLK_GPIO3, ENABLE);
  	gpio_init.GPIO_Pins = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 ;
   gpio_init.GPIO_Mode = GPIO_Mode_HI_AIN_TRI ;
   GPIO_Init (GPIO3, &gpio_init);
   
   // ADC peripheral configuration
   // Initialize the converter register.   
   ADC_StructInit(&adc_init) ;  
   adc_init.ADC_Calibration = ADC_Calibration_ON;
   adc_init.ADC_SamplingPrescaler = 0x7;
   adc_init.ADC_ConversionPrescaler = 0x0;
   adc_init.ADC_FirstChannel = ADC_CHANNEL0;
   adc_init.ADC_ChannelNumber = 5;
   adc_init.ADC_CalibAverage = ADC_CalibAverage_Enable;
   adc_init.ADC_AutoClockOff = ADC_AutoClockOff_Disable;
   adc_init.ADC_ConversionMode = ADC_ConversionMode_Scan;  
   ADC_Init (&adc_init);
  
	// Enable ADC
  	ADC_Cmd(ENABLE);	
  	// Start ADC conversion
  	ADC_ConversionCmd (ADC_ConversionStart);
}

//that's the maximum value for the PWM register.
#define MAX_PWM_VAL (0xFFFF)

void init_PWM() {
	GPIO_InitTypeDef GPIO_InitStructure ;
	PWM_InitTypeDef PWM_InitStructure ;
	 
	CFG_PeripheralClockConfig(CFG_CLK_GPIO2 , ENABLE);
	CFG_PeripheralClockConfig(CFG_CLK_PWM0 , ENABLE);
	 
	// GPIO2 Configuration
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  	GPIO_InitStructure.GPIO_Pins = GPIO_PIN_0;  
  	GPIO_Init (GPIO2, &GPIO_InitStructure);

	// PWM structure Initialization
  	PWM_DeInit (PWM0);
  	PWM_StructInit(&PWM_InitStructure);

	// PWM0 Configuration
  	PWM_InitStructure.PWM_Prescaler0 = 0x2 ;
  	PWM_InitStructure.PWM_Prescaler1 = 0x1;
  	PWM_InitStructure.PWM_DutyCycle = 0x7FFF;
  	PWM_InitStructure.PWM_Period = 0xFFFF;
  	PWM_InitStructure.PWM_Polarity_Level = PWM_POLARITY_High;

  	PWM_Init (PWM0, &PWM_InitStructure);
	
	// Start PWM0
	PWM_Cmd(PWM0, ENABLE);
}

#define MAX_ADC_VAL 0x3ff
//this function reads the value from the temperature sensor (in tenth of Celcius degrees)
signed short ReadTemp(unsigned short VDDmV)
{
	unsigned long TempRead = 0;
	u32 value = 0;

	//read the value from the Temp sensor	
	TempRead=ADC_GetConversionValue(4);
	value=ADC_Calib(TempRead);
	
	//convert it into tenth of Celcius degrees ( U(mV) = 10*(T(C)+1) ) -> ( T(C/10) = U(mV) - 10 )
	value -= 10;
	
	//return the value
	return value;
	
}

//this function reads the value from the potentiometer (as a percentage)
unsigned char ReadPot()
{
	u16 TempRead;
	u32 value;
	
	//read value on channel 3.
	TempRead = ADC_GetConversionValue(3);

	//convert in mV		
	value=ADC_Calib(TempRead);
	
	//convert in percentage
	value *= (u16)100;
	value /= referencemv; //5000 mV for 100%
	return (unsigned char)(value);
}

//this function reads the value from the analog input IN1 (in mV)
unsigned short ReadI1(unsigned short VDDmV)
{
	unsigned long TempRead;
	u32 value;
	//read value on channel 1. no conversion needed
	TempRead = ADC_GetConversionValue(1);
	value=ADC_Calib(TempRead);
	return (unsigned short)(value);
}

//this function reads the value from the analog input IN2 (in mV)
unsigned short ReadI2(unsigned short VDDmV)
{
	unsigned long TempRead;
	u32 value;
	//read value on channel 2. no conversion needed
	TempRead = ADC_GetConversionValue(2);
	value=ADC_Calib(TempRead);
	return (unsigned short)(value);
}

//this function sets Vout at NewVal (in mV)
void SetOUT(unsigned short NewVal, unsigned short VDDmV)
{
	unsigned long TempWrite=NewVal;
	
	//convert it from mV
	TempWrite *= MAX_PWM_VAL; //max value is 0xFFFF
	TempWrite /= VDDmV;
	
	// Generate a PWM Signal :
	PWM_SetDutyCycle(PWM0, TempWrite);
}
#endif

//------------------------------------------------------------------
// EEPROM access functions through I2C
//------------------------------------------------------------------
#if USE_EEPROM

#define EEPROM_ADDR 0xA0
#define MAXBUFEEPROM 20

//definie localbuf in the EEPROM
unsigned char localbuf [MAXBUFEEPROM+1];
int i;

void init_I2C() {
   
	GPIO_InitTypeDef GPIO_InitStructure;
	I2C_InitTypeDef I2C_InitStructure;	
  	/* enable  GPIO2 clock */
  	CFG_PeripheralClockConfig(CFG_CLK_GPIO2, ENABLE); 
  	/* enable I2C0 clock */
  	CFG_PeripheralClockConfig(CFG_CLK_I2C0, ENABLE);
  
  	/* I2C0 pins Configuration */
  	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
  	GPIO_InitStructure.GPIO_Pins = GPIO_PIN_14 | GPIO_PIN_15 ;
  	GPIO_Init (GPIO2, &GPIO_InitStructure);

   /* I2C initialization */
  	I2C_InitStructure.I2C_GeneralCall = I2C_GeneralCallDisable;
  	I2C_InitStructure.I2C_Ack = I2C_AckEnable;
  	I2C_InitStructure.I2C_CLKSpeed = 10000;
  	I2C_InitStructure.I2C_OwnAddress = EEPROM_ADDR;
  
  	I2C_Cmd (I2C0, ENABLE);
  	I2C_Init(I2C0, &I2C_InitStructure);   
}

ErrorStatus SendResult;

// this function writes data from the STR730 memory to the EEPROM
void WriteEEPROM(unsigned char addr, unsigned char cnt, unsigned char *buf)
  {
	
   // the buffer limits the number of bytes to be written
	if ( cnt > MAXBUFEEPROM )
		cnt = MAXBUFEEPROM;
		
	localbuf[0] = addr;
	// copy the data in the localbuf into a new array buf
	for ( i = 0; i < cnt ; i++ )
		localbuf[i+1] = buf[i] ;	
		
   // clean the flag of the SB
   I2C_FlagClear (I2C0, I2C_FLAG_BUSY);
  
  	// Generate Start
	I2C_STARTGenerate(I2C0, ENABLE);
	// test on EV5 and clear it
   while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECT));

	// Transmit the address as write mode
   I2C_AddressSend( I2C0, EEPROM_ADDR, I2C_MODE_ADDRESS7, I2C_MODE_TRANSMITTER );

  	// test on EV6 and clear it
  	while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECTED));  
  	// clear EV6 by setting again the PE bit
  	I2C_Cmd(I2C0, ENABLE);

	// Transmit the data
   SendResult = I2C_BufferSend( I2C0, localbuf, cnt+1 );

	// Generate Stop
	I2C_STOPGenerate( I2C0, ENABLE );
	}


// this function reads data from the EEPROM to the STR730 memory 
void ReadEEPROM(unsigned char addr, unsigned char cnt, unsigned char *buf)
	{

	// Generate Start
	I2C_STARTGenerate(I2C0, ENABLE);
	// test on EV5 and clear it
   while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECT));

	// Transmit the address as write mode
   I2C_AddressSend( I2C0, EEPROM_ADDR, I2C_MODE_ADDRESS7, I2C_MODE_TRANSMITTER );

  	// test on EV6 and clear it
  	while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECTED));  
  	// clear EV6 by setting again the PE bit
  	I2C_Cmd(I2C0, ENABLE);

	// send the EEPROM's internal address to write to
  I2C_ByteSend(I2C0, addr);
   
   // test on EV8 and clear it
  	while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
  
	// Generate Start
	I2C_STARTGenerate(I2C0, ENABLE);
   // test on EV5 and clear it
  	while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECT));

	// Transmit the address as read mode
   I2C_AddressSend( I2C0, EEPROM_ADDR, I2C_MODE_ADDRESS7, I2C_MODE_RECEIVER );

	// test on EV6 and clear it
  	while(! I2C_EventCheck(I2C0, I2C_EVENT_MASTER_MODE_SELECTED));
	// clear EV6 by setting again the PE bit
  	I2C_Cmd(I2C0, ENABLE);
  	
	while(cnt)  // while there is data to be read
  	{
 		// test on EV7 and clear it
    	if(I2C_EventCheck(I2C0, I2C_EVENT_MASTER_BYTE_RECEIVED))  
    	{
      	if(cnt == 2)
	      {
	        	I2C_AcknowledgeConfig(I2C0, DISABLE);
	      }
	
	      if(cnt == 1)
	      {
	        // send STOP Condition
	        I2C_STOPGenerate(I2C0, ENABLE);
	      }
	      
	      // read a byte from the EEPROM
	      *buf = I2C_ByteReceive(I2C0);
	
	      // point to the next location where the byte read will be saved
	      buf++; 
	      
	      cnt--;    
	   }  
  	}
  	
	// enable acknowledge
	I2C_AcknowledgeConfig(I2C0, ENABLE);
	}

#endif








