/**************************************************************************//**
 * @file     main.c
 * @brief    Main program body
 * @version  V1.1.0
 * @date     14-Feb-2019
 *
 * @note
 * Copyright (C) 2019 Spintrol Limited Corporation. All rights reserved.
 *
 * @attention
 * THIS SOFTWARE JUST PROVIDES CUSTOMERS WITH CODING INFORMATION REGARDING 
 * THEIR PRODUCTS, WHICH AIMS AT SAVING TIME FOR THEM. SPINTROL SHALL NOT BE
 * LIABLE FOR THE USE OF THE SOFTWARE. SPINTROL DOES NOT GUARANTEE THE 
 * CORRECTNESS OF THIS SOFTWARE AND RESERVES THE RIGHT TO MODIFY THE SOFTWARE 
 * WITHOUT NOTIFICATION.
 *
 ******************************************************************************/

#include "spd1178.h"
#include "spc1168.h"
#include <stdio.h>

#define ADC_SAMPLE_TIME_NS 	6400	//If ADC moudle work 40MHz, then the max sample we can set is 6.4us.

/* As descripted below, ADC result convert to voltage can calculate as the follow */
#define				 CodeToVoltage(x)					 ((((float)(x) * 3657) / 8192) /1000)
#define        VoltageToTemperatue(x)		 (((0.654f - (float)(x)) / 0.002f) + 27.0f)

int16_t             				i16VSP 																			 = 0;
float												vol;
float												temperature;
ErrorStatus                 eErrorState;
uint8_t                     u8PREDRIID                                   = 0;                   /* PRE-DRIVER mode ID */
uint8_t                     u8PREDRIDATA;                                                       /* Data read from PRE-DRIVER */
uint32_t                    u32SSPBaundrate                              = 100000;             /* The baundrate of SSP communicating with PRE-DRIVER mode */
uint32_t                    u32Timeout                                   = 500;                 /* The number of times try to get PRE-DRIVER mode ID */
uint8_t                     Count;


/*************************************************************************************************************************
 *
 * @brief      This case show how to measure the high voltage part (PRE-DRIVER) temperature.
 *
 *             Key point:
 *						 Measure High voltage part temperature include steps below,
 *																							<1> Connect ATEST to MCU (low voltage part) bus.																				
 *																							<2> Config ADC to measure ATEST.
 *																							<3> In the ATEST measurement mode, ADC module must keep slow speed to meet
 *																								  the time requred by the ATEST to be stable(commonly 6 us is ok).
 *             PRE-DRIVER init include two steps,
 *                                              <4> Init the communication circuits(SSP circyits) with MCU, we call this
 *																									step 'Init PRE-DRIVER module'.
 *                                              <5> Init PRE-DRIVER socket itself, we call this step 'Power up PRE-DRIVER
 *																								  mode'.
 *
 *************************************************************************************************************************/


int main(void)
{
  FLASH_WALLOW();
  FLASH_SetTiming(200000000);
  /* Disable flash write access after flash operation had done */
  FLASH_WDIS();

  CLOCK_InitWithRCO(CLOCK_HCLK_200MHZ);

  Delay_Init();

  /*
   * Init the UART
   *
   * 1.Set the GPIO34/35 as UART FUNC
   *
   * 2.Enable the UART CLK
   *
   * 3.Set the rest para
   */
  GPIO_SetPinChannel(GPIO_34,GPIO34_UART_TXD);
  GPIO_SetPinChannel(GPIO_35,GPIO35_UART_RXD);
  CLOCK_EnableModule(UART_MODULE);
  UART_Init(UART,38400);

  /* Init PRE-DRIVER module(this step means 'Init PRE-DRIVER module') and get the ID */
  eErrorState = HV_Init(u32SSPBaundrate, &u8PREDRIID, u32Timeout);
  if(eErrorState == ERROR)
  {
    printf("Init PRE-DRIVER mode FAIL\n");
    return 0;
  }
  else
  {
    printf("Init PRE-DRIVER mode SUCCESS[ID:%d]\n",u8PREDRIID);
  }

	/* Step1: */
	/* Connect ATEST of high voltage part to MCU bus */
	HV_ConnectAnalogTestToADC();
	
	/* Config ATEST function of high voltage part */
	HV_ConnectTSensorToAnalogTest();

	/*
	 * There is no need to enable the pre-driver.
	*/
	
	/* Step 2: */
	/* Iinit ADC module to measure the ATEST voltage */
	ADC_EasyInit1(ADC_SOC_0,ADCx_ATEST,ADCTRIG_Software);
	
	/* 
	 * Step 3:
	 * Set ADC module clock 40MHz and set the ADC sample time as 6.4us(ATEST need long time to be stable).
	 * Keep in mind:
	 *						ADC sample time count num is 256, If ADC clock is too fast(eg. 200MHz), even if
	 *						the max sample count is set(256), the sample is also too shot(if ADC clock is 
	 *						200MHz, max sample time is 1000000000/200000000 * 256 ns= 5 *256ns = 1280ns = 1.28us,
	 *						1.28ns is too shot for ATEST measurement, the min time is 5~6 us, so we must slow
	 *						down ADC module clock).
	 */
	CLOCK_SetModuleDiv(ADC_MODULE, 5);
	ADC_SetSampleAndConvertTime(ADC_SOC_0, ADC_SAMPLE_TIME_NS, ADC_DEFAULT_CONVERSION_TIME_NS);
	
	/* set ADC result average count max to make sure the result is stable */
	ADC_SetAverageCnt(ADC_SOC_0, ADCSOCCTL0_BIT_AVGCNT_AVG_128);
	
  while(1)
  {
    /* Use software to trigger ADC SOC0 start to work */
    ADC_SoftwareTrigger(ADC_SOC_0);

    /* Wait until ADC conversion finished (Interrupt flag was set) */
    while(!ADC_GetIntFlag(ADC_SOC_0));

    /* Get result */ 
    i16VSP = ADC_GetResult(ADC_SOC_0);
		printf("ADC sample code is [%d]\n",i16VSP);
    /* Clear ADC SOC0 INT flag */
    ADC_ClearInt(ADC_SOC_0);
		
		/* Calculate the voltage value */
		vol = CodeToVoltage(i16VSP);
    printf("ADC measure voltage is [%f]V\n", vol);
		
		/* Calculate the temperature */
		temperature = VoltageToTemperatue(vol);
		printf("High voltage part (PRE-DRIVER) temperature is [%f]\n",temperature);
		printf("\n");
		
    Delay_Ms(2000);
  }
}
