/*
 * mcu_adc.h
 *
 *  Created on: 7/05/2021
 *      Author: alexrayne <alexraynepe196@gmail.com>
 * ------------------------------------------------------------------------------------
 *  renesas RA chip ADC support
 */

#ifndef BSP_CPU_MCU_ADC_H_
#define BSP_CPU_MCU_ADC_H_

#include <mcu-chip.h>



#define __ADC_CAT2(a, b) a##b
#define ADCn(n)  __ADC_CAT2(R_ADC, n)

#define ADC_PORT_IDXSTEP   (R_ADC1_BASE - R_ADC0_BASE)
#define ADC_PORT_NO(port)  ( ( ((uint8_t*)(port)) - R_ADC0_BASE )/ADC_PORT_IDXSTEP)
#define ADC_PORTn(n)       ( (R_ADC0_Type*)( R_ADC0_BASE + ((n)*ADC_PORT_IDXSTEP) ) )



#ifdef __cplusplus
extern "C" {
#endif

typedef R_ADC0_Type     ADC_TypeDef;                    // Base register for this unit
typedef R_ADC0_Type     ADC12_TypeDef;                  // Base register for ADC 12bit

enum ADCChanelIDX {
    ADC_TEMP    = -3,
    ADC_VREF    = -2,
    ADC_DIAG    = -1,
    ADC_CH0     = 0, ADC_CH1     = 1, ADC_CH2     = 2, ADC_CH3     = 3,
    ADC_CH4     = 4, ADC_CH5     = 5, ADC_CH6     = 6, ADC_CH7     = 7,
    ADC_CH8     = 8, ADC_CH9     = 9, ADC_CH10    = 10, ADC_CH11   = 11,
    ADC_CH12    = 12, ADC_CH13   = 13, ADC_CH14   = 11, ADC_CH15   = 12,
    ADC_CH16    = 16, ADC_CH17   = 17, ADC_CH18    = 18, ADC_CH19   = 19,
    ADC_CH20    = 20,
};
typedef enum ADCChanelIDX ADCChanelIDX;

static inline
uint16_t    ADC_value(ADC_TypeDef* adc, ADCChanelIDX regidx){
    return adc->ADDR[regidx];
}

static inline
bool ADC_IsActiveFlag_EOCS (ADC_TypeDef *ADCx){
    // while ADC convertion busy, ADST == 1
    return ADCx->ADCSR_b.ADST == 0;
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////

#if defined(CHIP_FAMILY_RA2L1)
#define ADC_VREFINT_MV      1480u
#endif



///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///                         STM32F4 HAL
//#include "r_adc_api.h"

#ifndef R_ADC_API_H
enum {
    ADC_CHANNEL_0   =   ADC_CH0,
    ADC_CHANNEL_1   =   ADC_CH1,
    ADC_CHANNEL_2   =   ADC_CH2,
    ADC_CHANNEL_3   =   ADC_CH3,
    ADC_CHANNEL_4   =   ADC_CH4,
    ADC_CHANNEL_5   =   ADC_CH5,
    ADC_CHANNEL_6   =   ADC_CH6,
    ADC_CHANNEL_7   =   ADC_CH7,
    ADC_CHANNEL_8   =   ADC_CH8,
    ADC_CHANNEL_9   =   ADC_CH9,
    ADC_CHANNEL_10  =   ADC_CH10,
    ADC_CHANNEL_11  =   ADC_CH11,
    ADC_CHANNEL_12  =   ADC_CH12,
    ADC_CHANNEL_13  =   ADC_CH13,
    ADC_CHANNEL_14  =   ADC_CH14,
    ADC_CHANNEL_15  =   ADC_CH15,
    ADC_CHANNEL_16  =   ADC_CH16,
    ADC_CHANNEL_17  =   ADC_CH17,
    ADC_CHANNEL_18  =   ADC_CH18,
    ADC_CHANNEL_VREFINT = ADC_VREF,
    ADC_CHANNEL_18      = ADC_TEMP,

};

#endif



#ifdef __cplusplus
}
#endif

#endif /* BSP_CPU_MCU_ADC_H_ */
