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

					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 "71x_lib.h"
#include "REvaLib.h"

//------------------------------------------------------------------
// utility functions
//------------------------------------------------------------------
#if USE_UTILS

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



#endif

#if USE_IO
//------------------------------------------------------------------
// Digital functions
//------------------------------------------------------------------
void init_IO() {
   /* I/O Port initialization */
   /*   Configure P1.4-6 - P1.8-10 as Output Push-Pull */
   GPIO_Config(GPIO1, 0x0770, GPIO_OUT_PP);
   /*   Configure P0.0-1 as Output Push-Pull */
   GPIO_Config(GPIO0, 0x0003, GPIO_OUT_PP); 
}

void writeIO(unsigned char number){
  u8 tempChar = number & 0x03;
  u8 tempVal1 = (u8)(((u16)number << 2)& 0x0070);
  u8 tempVal2 = (u8)((((u16)number << 3)& 0x0700)>>8);
  GPIO_ByteWrite(GPIO0, GPIO_LSB, tempChar);
  GPIO_ByteWrite(GPIO1, GPIO_LSB, tempVal1);
  GPIO_ByteWrite(GPIO1, GPIO_MSB, tempVal2);
}

unsigned char readIO(){
  unsigned char result = 0x00;
  u16 tempVal = GPIO0->PD >> 10;
  result = (unsigned char)tempVal & 0x3F;
  return(result);
}
#endif

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

//this is needed for letting time to the ADC to perform some actions
void dummy_fct()
{	;	}
void delay ( int n )
{
	int i;
	while (n--)
		{
		for ( i = 0 ; i < 10000 ; i++ )
			dummy_fct();
		}
}


#define referencemv 2500 //voltage reference for the ADC (highest value in mV)
#define offset 0x9ab   // digital value for the 0 volt (min)
#define vref 0x600  // digital value for the 2.5 volt (max)

// using calibration offer the possibility to have the value of the tension conversted.
u32 ADC12_Calib(u16 Conv_Res)
{
  static u32 result;
  u32 temp1, temp2,temp3,temp4;
  	 
  if ((Conv_Res>offset)&&(Conv_Res<=0xfff)) 
   return referencemv*(Conv_Res-offset)/(0xfff-offset+vref);
  else if (Conv_Res<0x7ff)
   return referencemv*(0xfff+Conv_Res-offset)/(0xfff-offset+vref);
  else 
   return 0;
}

//initialize the ADC chanels
int init_adc( void ) 
	{
   /*  Configure the used analog input channel to HI_AIN_TRI */
   GPIO_Config (GPIO1, 0x000F, GPIO_HI_AIN_TRI);
   /* ADC12 peripheral configuration  ----------------------------------------*/
   /*  Initialize the converter register. */
   ADC12_Init();
   delay ( 1 );
   /*  Configure the prescaler register using the configured PCLK with
    a sampling frequency=50Hz */
   ADC12_PrescalerConfig(50);
   
   /*  Select the conversion mode=single channel */
   ADC12_ModeConfig (ADC12_ROUND);
}

//that's the maximum value for the PWM register.
#define MAX_PWM_VAL (0x7FFF)
#define T1_OCMP_A 0x80
void init_PWM() {
   // Configure the GPIO1 Port
   // Timer 1 Output Compare function pin (P1.7) configured as Alternate
   // function pushpull.
   GPIO_Config (GPIO1 , T1_OCMP_A , GPIO_AF_PP );
   // Initialize the Timer
   TIM_Init ( TIM1 );
   // Configure the TIM Prescaler
   TIM_PrescalerConfig ( TIM1, 0x1 );
}

//this function reads an analogic value on one of the ADC inputs
// it is not exported out of this file,
// but is called from the other analog functions below

static u16 AnaRead(char channel)
{
	u16 TempRead = 0x0;
	
	switch(channel) {
	 case 0:
	 default:
      // Select the channel 0 to be converted
      ADC12_ChannelSelect(ADC12_CHANNEL0);
	 break;
	 case 1:
      // Select the channel 1 to be converted
      ADC12_ChannelSelect(ADC12_CHANNEL1);
	 break;
	 case 2:
      // Select the channel 2 to be converted
      ADC12_ChannelSelect(ADC12_CHANNEL2);
	 break;
	 case 3:
      // Select the channel 3 to be converted
      ADC12_ChannelSelect(ADC12_CHANNEL3);
	 break;	 
	}
   delay ( 1 );    	// Start the Converter
   ADC12_ConversionStart();
   delay ( 1 );	//stabilisation	
   switch(channel) {
	 case 0:
	 default:
   	// Wait until the availabiliy of data in the specific flags
   	while (ADC12_FlagStatus (ADC12_DA0)==RESET);
   	// Get the conversion result from the correponding Data register
	   TempRead = ADC12_ConversionValue(ADC12_CHANNEL0);
	 break;
	 case 1:
   	// Wait until the availabiliy of data in the specific flags
   	while (ADC12_FlagStatus (ADC12_DA1)==RESET);
   	// Get the conversion result from the correponding Data register
	   TempRead = ADC12_ConversionValue(ADC12_CHANNEL1);
	 break;
	 case 2:
   	// Wait until the availabiliy of data in the specific flags
   	while (ADC12_FlagStatus (ADC12_DA2)==RESET);
   	// Get the conversion result from the correponding Data register
	   TempRead = ADC12_ConversionValue(ADC12_CHANNEL2);
	 break;
	 case 3:
   	// Wait until the availabiliy of data in the specific flags
   	while (ADC12_FlagStatus (ADC12_DA3)==RESET);
   	// Get the conversion result from the correponding Data register
	   TempRead = ADC12_ConversionValue(ADC12_CHANNEL3);
	 break;
	 
	}
  	// Disable the converter
  	ADC12_ConversionStop(); 

	//return value
	return TempRead;
}

#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=AnaRead(3);
	value=ADC12_Calib(TempRead);
	
	//convert it into tenth of Celcius degrees
	value -= 1;
	
	//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 2.
	TempRead = AnaRead(2);
	value=ADC12_Calib(TempRead);
	//convert in percentage
	value *= (u16)100;
	value /= referencemv; //2500 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 0. no conversion needed
	TempRead = AnaRead(0);
	value=ADC12_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 1. no conversion needed
	TempRead = AnaRead(1);
	value=ADC12_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 0x7FFF
	TempWrite /= VDDmV;
	
  // Generate a PWM Signal :
  TIM_PWMOModeConfig ( TIM1, TempWrite, TIM_HIGH, 0x7FFF, TIM_LOW );

  // Start The Counter
  TIM_CounterConfig ( TIM1, TIM_START );		
}
#endif

//------------------------------------------------------------------
// EEPROM access functions through I2C
//------------------------------------------------------------------
#if USE_EEPROM
#define I2C0_SCL 0x2000
#define I2C0_SDA 0x4000
#define I2C1_SCL 0x0004
#define I2C1_SDA 0x0008

#define EEPROM_ADDR 0xA0
#define MAXBUFEEPROM 20

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

void init_I2C() {
   //configure the SDA and the SCL pin of the I2C1 as master(*)
   GPIO_Config(GPIO0,I2C1_SCL,GPIO_AF_OD);
   GPIO_Config(GPIO0,I2C1_SDA,GPIO_AF_OD);

   //initialise the I2C1
   I2C_Init(I2C1);
   //configure le frequence de clk
   I2C_FCLKConfig (I2C1);
   //enable the peripheral of the I2C1
   I2C_OnOffConfig (I2C1, ENABLE);
   //Configure the I2C1 speed
   I2C_SpeedConfig (I2C1, 10000);
  	//configure the I2C1 address
	I2C_AddressConfig ( I2C1, 0xC0, I2C_Mode7);
	//Enable the Acknowledge
   I2C_AcknowledgeConfig (I2C1, ENABLE);
   // Enable the interrupt generation
   I2C_ITConfig (I2C1, ENABLE);
}

I2C_Tx_Status SendResult;
//this function writes data from the ST7 memory to the EEPROM
void WriteEEPROM(unsigned char addr, unsigned char cnt, unsigned char *buf)
  {
	vu8 Register_Value;
	u8 sendBytes = 0;
   //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 (I2C1, I2C_BUSY);
  
  	//Generate Start
	I2C_STARTGenerate(I2C1, ENABLE);
   while (I2C_FlagStatus (I2C1,DIRECT,I2C_SB)==RESET);


	//Transmit the address of the EEPROM as write mode
   I2C_AddressSend(I2C1,EEPROM_ADDR,I2C_Mode7,I2C_TX);
   
   //Register_Value =I2C_RegisterRead(I2C1,I2C_SR2);

	//Test the end of address transmission
	while (I2C_FlagStatus (I2C1,DIRECT,I2C_ENDAD)==RESET);	

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

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


//_this function reads data from the EEPROM to the ST7 memory 
void ReadEEPROM(unsigned char addr, unsigned char cnt, unsigned char *buf)
	{
	u8 Address;
	//Generate Start
	I2C_STARTGenerate(I2C1, ENABLE);
   while (I2C_FlagStatus (I2C1,DIRECT,I2C_SB)==RESET);

	//Transmit the address as write mode
   I2C_AddressSend (I2C1,EEPROM_ADDR,I2C_Mode7,I2C_TX);

	//Test the end of address transmission
	while (I2C_FlagStatus (I2C1,DIRECT,I2C_ENDAD)==RESET);

	//Transmit the address de memory
   SendResult=I2C_BufferSend (I2C1, &addr,1);
   //I2C_ByteSend(I2C1,&addr);
   
	//Generate Start
	I2C_STARTGenerate(I2C1, ENABLE);
   while (I2C_FlagStatus (I2C1,DIRECT,I2C_SB )==RESET);

	//Transmit the address as read mode
   I2C_AddressSend (I2C1,EEPROM_ADDR,I2C_Mode7,I2C_RX);

	//Test the end of address transmission
	while (I2C_FlagStatus (I2C1,DIRECT,I2C_ENDAD)==RESET);

	//Receive the data
	SendResult=I2C_BufferReceive (I2C1,buf,cnt);

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

#endif






