#include <stdio.h>
#include <stdint.h>

#include "FreeRTOS.h"
#include "task.h"

#include "n32g45x.h"
#include "LCD.h"

#include "LVGL_TaskHand.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)
		{
		}
	}
}


TaskHandle_t StarTaskHandle;
#define starTask_SckDep 	60
#define starTask_Prior		(configMAX_PRIORITIES - 1)
void SystemStar_Init(void)
{
	SetSysClock_HSE_PLL(RCC_PLL_MUL_18);    ///配置系统时钟源为外部高速时钟	
	RCC_ConfigPclk1(RCC_HCLK_DIV4);
	
	ILI9341_Init();
	lcd_fill(COLOR_YELLOW);
	vTaskDelete(StarTaskHandle);
}

TaskHandle_t Task1_TFTColorFill;
#define Task1_SckDep 	100
#define Task1_Prior		3
void TFTColorFill()
{
	for(;;)
	{
		lcd_fill(COLOR_YELLOW);
		vTaskDelay(1000);
		lcd_fill(COLOR_RED);
		vTaskDelay(1000);
	}
}


int main(void)
{
	xTaskCreate((TaskFunction_t)SystemStar_Init,"StarTask",starTask_SckDep,NULL,starTask_Prior,&StarTaskHandle);
	//xTaskCreate((TaskFunction_t)TFTColorFill,"Task1",Task1_SckDep,NULL,Task1_Prior,&Task1_TFTColorFill);
	Creat_LVGLTask();
	vTaskStartScheduler();
	
	while(1)
		;	
}

