/***************************************************************
copyright from private LiuXiao
if you have any question,you can contact me by email 461445092@qq.com
2022-10-05 17:56:24.020233
***************************************************************/

#include   <string.h>
#include   ".\SA51024.h"
#include   "../config/mcal/peripheral/tc/plib_tc0.h"
#include   "../config/mcal/peripheral/port/plib_port.h"

extern STATE_UINT16       speaker_cycle_u16;

void  SA51024_MainTask(void);


void TC0_CallBack_Function (TC_TIMER_STATUS status, uintptr_t context)
{ 
   if ((DAC_IsReady(DAC_CHANNEL_0) == true))
    {
		SA51024_MainTask();
	}
}


/*
sa51024 related var init
*/
void  SA51024_Init(void)
{
	uint16 index = 0;

	sa51024_state = SA51024_IDLE;
	sa51024_strength= SA51024_STRENGTH_LEVEL0;
	sa51024_wave_index = 0;

	for(index =0; index < NUM_ELEMENTS; index++)
	{
		sa51024_wave_tbl_u16_new[index] = (uint16)((Raw_data[index]/16.0) + 2048);
	}
	
	//TC0_TimerCallbackRegister(TC0_CallBack_Function, 0);
    //TC0_TimerStart();
}


/*100us task*/
void  SA51024_MainTask(void)
{
	/*output sin wave*/
	if(SA51024_WORKING == SA51024_WAVE_STATE )
	{
		SA51024_WAVE_INDEX++;
		if(SA51024_WAVE_INDEX>=SA51024_WAVE_MAX_NUM)
        // if(SA51024_WAVE_INDEX>500)
		{
			SA51024_WAVE_INDEX = 0;
			//speaker_cycle_u16 = SA51024_WAVE_MAX_NUM;
            // SA51024_WAVE_STATE = SA51024_STOP;
		}
        /*
        if (SA51024_WAVE_INDEX < 64)
        {
            SA51024_TRIG_ADC(SA51024_WAVE_TABLE[0]/64*SA51024_WAVE_INDEX);
        }
        else if (SA51024_WAVE_INDEX >= (SA51024_WAVE_MAX_ID + 64))
        {
            SA51024_TRIG_ADC(SA51024_WAVE_TABLE[SA51024_WAVE_MAX_ID]/64*(SA51024_WAVE_MAX_NUM - SA51024_WAVE_INDEX));
        }
        else
        {
            SA51024_TRIG_ADC(SA51024_WAVE_TABLE[SA51024_WAVE_INDEX - 64]);
        }
        */
        SA51024_TRIG_ADC(SA51024_WAVE_TABLE[SA51024_WAVE_INDEX]);
		
	}
	else if(SA51024_STOP == SA51024_WAVE_STATE )
	{/*output 0V*/
		SA51024_WAVE_INDEX = 0;
		//SA51024_TRIG_ADC(2048);
		SA51024_WAVE_STATE = SA51024_IDLE;
	}
    else{
        //SA51024_TRIG_ADC(2048);
    }
}

/*
set sa51024 control state
para state woking->vibrate
para level ->vibrate strenght
*/
void  SA51024_Set_State(FA51024_main_e_typ state,FA51024_ctrl_e_typ level)
{
	if(SA51024_WORKING == state)
	{
		SA51024_WAVE_STATE = SA51024_WORKING;
	}
	else
	{
		SA51024_WAVE_STATE = SA51024_STOP;
	}
}
