#include "bsp.h"
#include "n32g45x.h"

void SetSysClock_HSE_PLL(uint32_t pllmul)
{
	__IO uint32_t StartUpCounter = 0, HSEStartUpStatus = 0;

	// It is necessary to initialize the RCC peripheral to the reset state.
	RCC_DeInit();

	// Enable HSE, open external crystal oscillator.
	RCC_ConfigHse(RCC_HSE_ENABLE);

	// Wait for HSE to be stable.
	HSEStartUpStatus = RCC_WaitHseStable();

    // Go on until the HSE is stable.
	if (HSEStartUpStatus == SUCCESS)
	{
		//----------------------------------------------------------------------//
		// Enable flash Prefetch buffer
		FLASH_PrefetchBufSet(FLASH_PrefetchBuf_EN);

		// 0:HCLK <= 32M
		// 1:HCLK <= 64M
		// 2:HCLK <= 96M
		// 3:HCLK <= 128M
		// 4:HCLK <= 144M
		FLASH_SetLatency(FLASH_LATENCY_4);
		//----------------------------------------------------------------------//

		// AHB prescaler factor set to 1,HCLK = SYSCLK = 144M
		RCC_ConfigHclk(RCC_SYSCLK_DIV1);
		// AHB prescaler factor set to 2,PCLK2 = HCLK/2 = 72M
		RCC_ConfigPclk2(RCC_HCLK_DIV2);
		// AHB prescaler factor set to 4,PCLK1 = HCLK/4 = 36M
		RCC_ConfigPclk1(RCC_HCLK_DIV4);

		////-----------------Set PLL clock source as HSE, set PLL frequency multiplication factor.-------------------//
		// PLLCLK = 8MHz * pllmul
		RCC_ConfigPll(RCC_PLL_SRC_HSE_DIV1, pllmul);
		////------------------------------------------------------------------//

		// Enable PLL
		RCC_EnablePll(ENABLE);
		// Wait for PLL to be stable.
		while (RCC_GetFlagStatus(RCC_FLAG_PLLRD) == RESET)
		{
		}
		RCC_ConfigSysclk(RCC_SYSCLK_SRC_PLLCLK);

		// Switch PLL clock to SYSCLK.
		RCC_ConfigSysclk(RCC_SYSCLK_SRC_PLLCLK);

		// Read the clock switch status bit and make sure pllclk is selected as the system clock.
		while (RCC_GetSysclkSrc() != 0x08)
		{
		}
	}
	else
	{ // If HSE fails to open, the program will come here, where the user can add the error code to handle.
      // When HSE fails or breaks down,mcu will automatically set HSI as the system clock.HSI is an internal high speed
      // clock of 8MHz.
		while (1)
		{
		}
	}
}

void key_Init(void)
{
	GPIO_InitType GPIO_InitStructure;
	RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOE,ENABLE);
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IPU;
	GPIO_InitStructure.Pin = GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6;
	GPIO_InitPeripheral(GPIOE, &GPIO_InitStructure);	
}


void BSP_Init(void)
{
    SetSysClock_HSE_PLL(RCC_PLL_MUL_18);    ///配置系统时钟源为外部高速时钟	
	RCC_ConfigPclk1(RCC_HCLK_DIV4);

    SysTick_Config(SystemCoreClock / 1000);
    NVIC_EnableIRQ(SysTick_IRQn);
	
	key_Init();
}

