/** 
 *******************************************************************************
 * @file    main.c
 * @brief   the application functions of TEMP demo for the TOSHIBA
 *          'TMPM311' Device Series 
 * @version V0.100
 * @date    2014/10/27
 * 
 * DO NOT USE THIS SOFTWARE WITHOUT THE SOFTWARE LICENSE AGREEMENT.
 * 
 * (C)Copyright TOSHIBA ELECTRONIC DEVICES & STORAGE CORPORATION 2017 All rights reserved
 *******************************************************************************
 */


#include "main.h"

#define TMRB_1MS        0x3E8U  /* fsys = fc = 8MHz, fphiT0 = fperiph = fgear = fc */
                                 /* ftmrb = 1/8fphiT0 = 1/8 * 8 = 1MHz, Ttmrb = 1us, 1000us/1us = 1000 = 0x3E8 */


/**
  * @brief  The main routine of DSADC demo
  * @param  None
  * @retval None
  */
int main(void)
{
    TMRB_InitTypeDef m_tmrb;
    DSADC_InitTypeDef InitStruct;
    uint32_t result = 0U;
    f1ms = 0U;
    f1s = 0U;

    SCB->VTOR = (unsigned int)0x10000000;

    Retarget_Init();

    /*TMRB initial */
    m_tmrb.Mode = TMRB_INTERVAL_TIMER;
    m_tmrb.ClkDiv = TMRB_CLK_DIV_8;
    m_tmrb.TrailingTiming = TMRB_1MS;   /* periodic time is 1ms */
    m_tmrb.UpCntCtrl = TMRB_AUTO_CLEAR;
    m_tmrb.LeadingTiming = TMRB_1MS;    /* periodic time is 1ms */

    TMRB_Enable(TSB_TB0);
    TMRB_Init(TSB_TB0, &m_tmrb);
    NVIC_EnableIRQ(INTTB0_IRQn);
    TMRB_SetRunState(TSB_TB0, TMRB_RUN);

    /* Enable AMP and BGR */
    TEMP_SetBGRState(ENABLE);
    TEMP_SetAMPState(ENABLE);

    /* wait 1 ms to secure the stabilization time */
    while (f1ms != 1U) {
    };
    f1ms = 0U;

    /* initialize DSADC unit D */
    DSADC_SWReset(TSB_DSADD);

    InitStruct.Clk = DSADC_FC_DIVIDE_LEVEL_1;
    InitStruct.BiasEn = ENABLE;
    InitStruct.ModulatorEn = ENABLE;
    InitStruct.SyncMode = DSADC_A_SYNC_MODE;  /* DSADC_A_SYNC_MODE; */
    InitStruct.HardwareFactor = DSADC_HARDWARE_TRIGGER_EXT;
    InitStruct.HardwareEn = DISABLE;

    InitStruct.Repeatmode = DSADC_REPEAT_MODE;      /* Repeat mode */
    InitStruct.AnalogInput = DSADC_ANALOG_INPUT_INT;
    InitStruct.Amplifier = DSADC_GAIN_8x;
    InitStruct.Offset = 0x03U;
    InitStruct.CorrectEn = ENABLE;
    DSADC_Init(TSB_DSADD, &InitStruct);

    /* Enable temperature sensor operation */
    TEMP_SetSensorState(ENABLE);
    /* Start DSADC function */
    DSADC_Start(TSB_DSADD);

    while (1U) {
        if (f1s == 1U) {
            f1s = 0U;
            result = DSADC_GetConvertResult(TSB_DSADD);
            printf("DSADD: %d\r\n", result);
        }
    }
}

#ifdef DEBUG
/**
  * @brief  Deal with the error parameter
  * @param  file: Pointer to the file where the error parameter locates
  * @param  line: Number of the line in which the error parameter locates
  * @retval None
  */
void assert_failed(char *file, int32_t line)
{
    while (1) {
        __NOP();
    }
}
#endif
