

#include "r_typedefs.h"
#include "dr7f701684.dvf.h"

/*-----------------use for RH850_F1KM_S1 --------------------*/

#include "ADC.h"

static uint8_t ADC_Get_Physical_Channel(uint8_t u8ADCPhysicalChannelIndex)
{
	uint8_t u8ADCPhysicalChannel = 0XFFU; /* Error  don't use */
	if (u8ADCPhysicalChannelIndex <= 15U)
	{
		u8ADCPhysicalChannel = u8ADCPhysicalChannelIndex;
	}
	else
	{
		u8ADCPhysicalChannel = 0XFFU;
	}
	return u8ADCPhysicalChannel;
}

static uint16_t ADC_Get_Channel_Result(uint32_t u32ADCVirtualChannel)
{
	uint32_t u32ADCRegisterAddress = 0xFFF20000U + 0x100U + 0X02U * u32ADCVirtualChannel;

	return (*(uint16_t *)u32ADCRegisterAddress);
}

static void ADC_Virtual_Channel_Config(uint32_t u32ADCVirtualChannel, uint8_t u8ADCPhysicalChannel)
{
	uint32_t u32ADCRegisterAddress = 0xFFF20000U + 0X04U * u32ADCVirtualChannel;

	(*(uint16_t *)u32ADCRegisterAddress) = u8ADCPhysicalChannel;
}

void ADC_Init(const uint8_t u8ChList[], uint8_t u8ChNum)
{
	uint8_t i = 0U;

	if ((u8ChList != 0U) && (u8ChNum <= 16U))
	{
		/* Virtual Channel Config */
		for (i = 0U; i < u8ChNum; i++)
		{
			ADC_Virtual_Channel_Config(i, ADC_Get_Physical_Channel(u8ChList[i]));
		}
		/* 12-bit,right align*/
		ADCA0ADCR = 0UL;
		/*sampling time 24 cycles*/
		ADCA0SMPCR = 0x18UL;
		/* Multicycle,interrupt disable,Hardware trigger disable,repeat once*/
		ADCA0SGCR1 = 0x0U; /*0x10U  interrupt enable*/
		/*Start Virtual Channel*/
		ADCA0SGVCSP1 = 0U;
		/* End Virtual Channel*/
		ADCA0SGVCEP1 = u8ChNum - 1U;
		/* Number of scans is 1*/
		ADCA0SGMCYCR1 = 0X0UL;
	}
	else
	{
		i = 0U;
	}
}
/**/
void ADC_DeInit(void)
{
	while (ADCA0SGSTR & 0x200U)
	{
		ADCA0ADHALTR = 0x01UL;
	}

	/*Start Virtual Channel*/
	ADCA0SGVCSP1 = 0U;
	/* End Virtual Channel*/
	ADCA0SGVCEP1 = 0U;
	/*Virtual Channel0 config  AIN0*/
	ADC_Virtual_Channel_Config(0, 0X0U);
}
void ADC_Start_Conversion(void)
{
	/*A/D conversion for SG1 is completed*/
	if ((ADCA0SGSTR & 0x200U) == 0U)
	{
		ADCA0SGSEFCR1 = 0X01UL; /*clear SG1 Scan End Flag*/
		ADCA0SGSTCR1 = 0X01UL;	/*start*/
	}
}
void ADC_Stop_Conversion(void)
{
	if (ADCA0SGSTR & 0x200U)
	{
		ADCA0ADHALTR = 0x01UL;
	}
}
/**************************************************************************/ /**
  * \brief      Get ADC conversion status
  * \retval     0 - ADC is idle
  *             1 - ADC is busy
******************************************************************************/
uint8_t ADC_Get_Conversion_Status(void)
{
	uint8_t u8Status = 0U;

	if (ADCA0SGSTR & 0x200U)
	{
		u8Status = 1U;
	}
	else /*A/D conversion for SG1 is completed*/
	{
		u8Status = 0U;
	}
	return u8Status;
}
void ADC_Get_Conversion_Result(uint16_t *pu16Data, uint8_t u8ChNum)
{
	uint8_t i;

	if ((pu16Data != 0U) && (u8ChNum > 0U) && (u8ChNum <= 16U))
	{
		if (ADC_Get_Conversion_Status() == 0U)
		{
			for (i = 0U; i < u8ChNum; i++)
			{
				pu16Data[i] = ADC_Get_Channel_Result(i);
			}
		}
	}
}
