/*********************************************************************************************
Copyright <2024> <Icore Technology (Nanjing)  Co.,Ltd>
All Rights Reserved,
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided 
with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to 
endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************************/

/*
*********************************************************************************************************
*                                              rx32s61xx
*                                           Library Function
*
*                                   Copyright 2024, RX Tech, Corp.
*                                        All Rights Reserved
*
*
* Project      : rx32s61xx
* File         : main.c
* By           : RX_SD_Team
* Version      : V1.0.0
* Description  : Only rx32s61xx
*********************************************************************************************************
*/
#include "main.h"

/*
*********************************************************************************************************
*                                           Global macro/Structure
*********************************************************************************************************
*/
//#define BreakSource_COMP
/*
*********************************************************************************************************
*                                             Global variable
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*                                           Global Function declaration
*********************************************************************************************************
*/


void Delay_us( uint32_t us )
{
  uint32_t Fsys;
	Fsys=RCC_Get_SystemClock()/1000000;
	if( us*Fsys > SysTick_LOAD_RELOAD_Msk ) return;
	SysTick->CTRL = 0;      //Disable SysTick
	SysTick->LOAD = Fsys*us;//Set count number:72*us, 72 means 1us when SystemCoreClock is 72MHz
	SysTick->VAL  = 0;      //Clear current count number and count flag
	SysTick->CTRL = 5;      //Enable SysTick and Select SystemCoreClock as SysTick clock source
	while((SysTick->CTRL&0x10000)==0);//Wait for count flag set
	SysTick->CTRL = 0;      //Disable SysTick
}

void Delay_ms( uint32_t ms )
{
	uint32_t i;
	for(i=ms;i>0;i--)
	{
		Delay_us(1000);
	}
}

void SystemClock_Config(void)
{
	// set flash lantency
	FLASH_Set_Latency(FLASH_Latency_3);
	
  RCC_Enable_HSI();
  while(RCC_Get_HSIRDY() != 1)
  {
  }
  RCC_Set_PLLMUL(RCC_CFGR_PLLMUL_19x);
  RCC_Enable_PLL();
  while(RCC_Get_PLLRDY() != 1)
  {
  }
  RCC_Set_AHBPrescaler(RCC_CFGR_HPRE_DIV1);
  RCC_Set_APB1Prescaler(RCC_CFGR_PPRE1_DIV2);
  RCC_Set_APB2Prescaler(RCC_CFGR_PPRE2_DIV1);
  RCC_Set_SysClkSource(RCC_CFGR_SW_PLL);
  while(RCC_Get_SysClkSource() != RCC_CFGR_SWS_PLL)
  {
  }
  RCC_Set_ADCClkSource(RCC_CFGR_ADCCLK_SEL_PLL2);
  RCC_Set_ADCPrescaler(RCC_CFGR_ADCPRE_DIV5);
}

void GPIO_Toggle(void)
{
  RCC_Enable_AHBClock(RCC_AHBENR_IOPAEN|RCC_AHBENR_IOPBEN|RCC_AHBENR_IOPCEN|RCC_AHBENR_IOPDEN);
                        
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_PUPDR_Pullup;
  GPIO_InitStruct.Speed = GPIO_OSPEEDR_High;
  GPIO_InitStruct.Alternate = GPIO_AF0;
  GPIO_InitStruct.Pin = GPIO_PIN_3;	
  GPIO_Init(GPIOB,&GPIO_InitStruct);
  GPIO_InitStruct.Pin = GPIO_PIN_4;
  GPIO_Init(GPIOB,&GPIO_InitStruct);
}

void CMP1_GPIO_Config(void)
{
  /*CMP1
  1P: PC0:ANA
  1N: PC1:ANA
  OUT: PA6:AF8
  */
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  GPIO_InitStruct.Pull = GPIO_PUPDR_Floating;
  GPIO_InitStruct.Speed = GPIO_OSPEEDR_High;
  GPIO_InitStruct.Alternate = GPIO_AF0;
  
  GPIO_InitStruct.Pin = GPIO_PIN_0;    //1P
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_Init(GPIOC,&GPIO_InitStruct);
  
  GPIO_InitStruct.Pin = GPIO_PIN_1;    //1N
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_Init(GPIOC,&GPIO_InitStruct);
  
  GPIO_InitStruct.Pin = GPIO_PIN_4;    //OUT
  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Alternate = GPIO_AF2;
  GPIO_Init(GPIOA,&GPIO_InitStruct);

  /*CMP mode config*/
  RCC_Enable_APB2Clock(RCC_APB2ENR_SYSCFGEN);
  CMP_Enable(COMP1);
  COMP1->CR |= 0x07<<4;//1N
  COMP1->CR |= 0x01<<8;//1P 
}

void TIM8_GPIO_Config(void)
{ 
  /*
  TIM8:
  CH1  :PD3_AF1
  CH1N :PD0_AF5
  CH2  :PD2_AF5
  CH2N :PC7_AF5
  CH3  :PD1_AF5 
  CH3N :PC6_AF1
  CH4  :PC5_AF1 
  CH5  :PB1_AF1
  CH6  :PB2_AF1
  ETR  :PC3_AF1
  BKIN :PC5_AF5
  BKIN2:PD5_AF3
  */ 
  GPIO_InitTypeDef        GPIO_InitStruct = {0};
  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull = GPIO_PUPDR_Pulldown;
  GPIO_InitStruct.Speed = GPIO_OSPEEDR_High;
  
  GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_3;											//PD3(AF1)    TIM8CH1
  GPIO_Init(GPIOD,&GPIO_InitStruct);
  
  GPIO_InitStruct.Alternate = GPIO_AF5;
  GPIO_InitStruct.Pin = GPIO_PIN_0;											//PD0(AF5)    TIM8CH1N
  GPIO_Init(GPIOD,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF5;
  GPIO_InitStruct.Pin = GPIO_PIN_2;											//PD2(AF5)    TIM8CH2
  GPIO_Init(GPIOD,&GPIO_InitStruct);
  
  GPIO_InitStruct.Alternate = GPIO_AF5;
  GPIO_InitStruct.Pin = GPIO_PIN_7;											//PC7(AF5)    TIM8CH2N
  GPIO_Init(GPIOC,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF5;
  GPIO_InitStruct.Pin = GPIO_PIN_1;											//PD1(AF5)    TIM8CH3
  GPIO_Init(GPIOD,&GPIO_InitStruct);
  
  GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_6;											//PC6(AF1)    TIM8CH3N
  GPIO_Init(GPIOC,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_5;											//PC5(AF1)    TIM8CH4
  GPIO_Init(GPIOC,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_1;											//PB1(AF1)    TIM8CH5
  GPIO_Init(GPIOB,&GPIO_InitStruct);

	GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_2;											//PB2(AF1)    TIM8CH6
  GPIO_Init(GPIOB,&GPIO_InitStruct);
	
//	GPIO_InitStruct.Alternate = GPIO_AF5;
//  GPIO_InitStruct.Pin = GPIO_PIN_5;											//PC5(AF5)    TIM8BKIN1
//  GPIO_Init(GPIOC,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF3;
  GPIO_InitStruct.Pin = GPIO_PIN_5;											//PD5(AF3)    TIM8BKIN2
  GPIO_Init(GPIOD,&GPIO_InitStruct);
	
	GPIO_InitStruct.Alternate = GPIO_AF1;
  GPIO_InitStruct.Pin = GPIO_PIN_3;											//PC3(AF1)    TIM8ETR
  GPIO_Init(GPIOC,&GPIO_InitStruct);
}

void TIM_initial(TIM_TypeDef *TIMx)
{
  RCC_Enable_APB2Clock(RCC_APB2ENR_TIM8EN);//TIM8 Clock EN 
  TIM8_GPIO_Config();
  
  //SET CNT BASE
  TIM_Set_Prescaler(TIMx, TIM8_Prescaler);
  TIM_Set_AutoReload(TIMx, (TIM8_ARR-1));
  TIM_Set_RepetitionCounter(TIMx,0);
 
 //CH1 / CH1N
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH1, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH1, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH1N, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH1(TIMx, TIM8_CCR); 
  //CH2 / CH2N
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH2, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH2, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH2N, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH2(TIMx, TIM8_CCR); 
  //CH3 / CH3N
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH3, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH3, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH3N, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH3(TIMx, TIM8_CCR);	
  //CH4 / CH4N
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH4, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH4, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH4(TIMx, TIM8_CCR);
  //CH5
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH5, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH5, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH5(TIMx, TIM8_CCR);
  //CH6
  TIM_Set_OC_Mode(TIMx, TIM_CHANNEL_CH6, TIM_OCMODE_PWM1);
  TIM_Set_OC_Polarity(TIMx, TIM_CHANNEL_CH6, TIM_OCPOLARITY_HIGH);
  TIM_Set_OC_CompareCH6(TIMx, TIM8_CCR);
  
  /*  Enable register preload for every output channels */
	TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH1);
	TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH2);
	TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH3);
	TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH4);
	TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH5);
  TIM_Enable_OC_Preload(TIMx, TIM_CHANNEL_CH6);
	TIM_Enable_ARRPreload(TIMx);

   /* Set Deadtime */
  TIM_Set_ClockDivision(TIMx,TIM_CLOCKDIVISION_DIV1);
  TIM_Set_OC_DeadTime(TIMx,0x20);  //deadtime
  /*  BDTR   AF1*/
  #ifdef  BreakSource_COMP
  CMP1_GPIO_Config();
  /*comp1 out high break*/
  TIM_Disable_BreakInputSource(TIMx,TIM_BREAK_INPUT_BKIN,TIM_AF_BKINE); //BKINE=0
  TIM_Set_BreakInputSourcePolarity(TIMx,TIM_BREAK_INPUT_BKIN,TIM_AF_BKCMP1P,TIM_BKIN_POLARITY_NoInvert);//BKCMPxP =0
  TIM_Enable_BreakInputSource(TIMx,TIM_BREAK_INPUT_BKIN,TIM_AF_BKCMP1E); //BKCMPxE=1
  #else 
  /*bkin pin high break*/
  TIM_Set_Break2Polarity(TIM8,TIM_BREAK2_POLARITY_HIGH);
  TIM_Set_BreakInputSourcePolarity(TIMx,TIM_BREAK_INPUT_BKIN2,TIM_BKIN_SOURCE_BKIN,TIM_BKIN_POLARITY_NoInvert);//BKINP =0
  TIM_Enable_BreakInputSource(TIMx,TIM_BREAK_INPUT_BKIN2,TIM_BKIN_SOURCE_BKIN); //BKINE =1
  #endif 
  
  /*The channel pwm output can be selected to be affected by the brake input*/
  TIM_Enable_Break_Control(TIMx);
  TIM_Set_CH4Break_Invalid(TIMx);
  TIM_Set_CH5Break_Invalid(TIMx);
  TIM_Set_CH6Break_Invalid(TIMx);
  
  TIM_Disable_AOE(TIMx);//AOE=0
  TIM_Enable_BRK2(TIMx);//BKE =1   
  TIM_Enable_MOE(TIMx);//MOE=1
  
  /**********************************/
	/* Start output signal generation */
	/**********************************/
	/* Enable outputs OC1, OC1N, OC2, OC2N, OC3 and OC3N */
  TIM_Enable_CC_Channel(TIMx, 
                        TIM_CHANNEL_CH1|TIM_CHANNEL_CH1N|
                        TIM_CHANNEL_CH2|TIM_CHANNEL_CH2N|
                        TIM_CHANNEL_CH3|TIM_CHANNEL_CH3N|
                        TIM_CHANNEL_CH4|
                        TIM_CHANNEL_CH5|TIM_CHANNEL_CH6);
  //Enable CCPC=1
  TIM_Enable_CC_Preload(TIMx);  
  
  TIM_Enable_MOE(TIMx);
  TIM_Enable_CEN(TIMx);

}

void ADC_GPIO_Init(void)
{
	RCC_Enable_AHBClock(RCC_AHBENR_IOPBEN | RCC_AHBENR_IOPCEN);

  GPIO_InitTypeDef  GPIO_InitStruct = {0};
  GPIO_InitStruct.Mode 				= GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull 				= GPIO_PUPDR_Floating;
  GPIO_InitStruct.Speed 			= GPIO_OSPEEDR_High;
	GPIO_InitStruct.Alternate 	= GPIO_AF0;
	
  GPIO_InitStruct.Pin = GPIO_PIN_2;											//PC2    ADC channel 2
  GPIO_Init(GPIOC,&GPIO_InitStruct);	
}

void trig_convert(ADC_TypeDef *ADCx, uint32_t Channel, uint32_t SamplingTime, uint32_t TriggerSource)
{
  __IO uint32_t uhADCxConvertedData;
	
	RCC_Enable_AHBClock(RCC_AHBENR_ADC1EN);
	ADC_GPIO_Init();
	
	ADC_Inj_InitTypeDef  ADC_Inj_InitStruct = {0};
	ADC_INJ_RankInitTypeDef  ADC_INJ_RankInitStruct = {0};
	
	ADC_Inj_InitStruct.TriggerSource  	 		= TriggerSource;
	ADC_Inj_InitStruct.ScanMode    					= ADC_CR1_SCAN_ENABLE;
	ADC_Inj_InitStruct.DataAlignment 				= ADC_CR2_ALIGN_RIGHT;
	ADC_Inj_InitStruct.TrigAuto  						= ADC_CR1_JAUTO_INDEPENDENT;
	ADC_Inj_InitStruct.AnalogWatchDog 			= ADC_CR1_AWD_DISABLE;
	ADC_Inj_InitStruct.InjectDiscont				= ADC_CR1_JDISCEN_DISABLE;
	ADC_Inj_InitStruct.AWDChannelGroup			= ADC_AWD_DISABLE;
	ADC_Inj_InitStruct.EOCOption						= ADC_EOC_OPT_DISABLE;
	ADC_Inj_Init(ADCx, &ADC_Inj_InitStruct);
	
	ADC_INJ_RankInitStruct.Length 								= ADC_JSQRL_SCAN_1RANK;
	ADC_INJ_RankInitStruct.Rank[0].Channel  			= Channel;
	ADC_INJ_RankInitStruct.Rank[0].SamplingTime   = SamplingTime;
	ADC_INJ_RankInit(ADCx, &ADC_INJ_RankInitStruct);
	
  /* Enable ADC */
  ADC_Enable_ADON(ADCx);
	
	Delay_us(200);
	
	/* Run ADC self calibration */
	ADC_Trig_CAL(ADCx);
	while (ADC_Get_CAL(ADCx) != 0);
	
	NVIC_SetPriority(ADC_IRQn, 1);			//�����ж����ȼ�
	NVIC_EnableIRQ(ADC_IRQn);					//ʹ�� ADC �ж�
	
	ADC_Enable_IT(ADC1,ADC_CR1_JEOCIE);//�������ע��ͨ��ת�������ж�
}

void UART2_Init_Async( uint32_t baudrate )
{
	GPIO_InitTypeDef GPIO_InitStruct  = {0};
	UART_InitTypeDef UART_InitStruct = {0};
	
	RCC_Enable_AHBClock(RCC_AHBENR_IOPDEN);
  RCC_Enable_AHBClock(RCC_AHBENR_IOPAEN);
	RCC_Enable_APB1Clock(RCC_APB1ENR_UART2EN);

	UART_InitStruct.BaudRate             = baudrate;
	UART_InitStruct.DataWidth            = UART_DATAWIDTH_8B;
	UART_InitStruct.Parity               = UART_PARITY_NONE;
	UART_InitStruct.StopBits             = UART_STOPBITS_1;
	UART_InitStruct.TransferDirection    = UART_DIRECTION_TX_RX;
	UART_Init(UART2,&UART_InitStruct);

  //PD5  -> UART2_TX
	//PD4  -> UART2_RX
	GPIO_InitStruct.Alternate = GPIO_AF5;
	GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull      = GPIO_PUPDR_Pullup;
	GPIO_InitStruct.Speed     = GPIO_OSPEEDR_High;
	GPIO_InitStruct.Pin       = GPIO_PIN_4;
	GPIO_Init(GPIOD, &GPIO_InitStruct);
	GPIO_InitStruct.Pull      = GPIO_PUPDR_Floating;
	GPIO_InitStruct.Pin       = GPIO_PIN_5;
	GPIO_Init(GPIOD, &GPIO_InitStruct);

	UART_Enable(UART2);
}


int main(void)
{
  SystemClock_Config();
  RCC_Enable_AHBClock(RCC_AHBENR_ADC1EN);
  GPIO_Toggle();
  UART2_Init_Async(115200);
  
  trig_convert(ADC1,ADC_CHANNEL_2,ADC_SAMPLINGTIME_2p5CYCLES,ADC_CR2_JEXTSEL_TIM8_CC4);
  TIM_initial(TIM8);
  
  /*BKIN PIN Connect PB4*/
  Delay_ms(10);
  GPIO_Toggle_Pin(GPIOB,GPIO_PIN_4);
  Delay_ms(10);
  GPIO_Toggle_Pin(GPIOB,GPIO_PIN_4);
  
  while(1)
  {
    
  }
}

