From 397ccb9737cbdba6ce78388786297b3b2fdb73f0 Mon Sep 17 00:00:00 2001
From: Alexander Mandera <alexander@mandera.eu>
Date: Thu, 22 Jun 2023 16:44:23 +0200
Subject: [PATCH] Add SystemInit144HSE

---
 ch32v203fun/ch32v203fun.c   | 23 +++++++++++++++++++++++
 ch32v203fun/ch32v203fun.h   |  1 +
 examples_v203/blink/blink.c |  2 +-
 3 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/ch32v203fun/ch32v203fun.c b/ch32v203fun/ch32v203fun.c
index e95da26..0bc2e88 100644
--- a/ch32v203fun/ch32v203fun.c
+++ b/ch32v203fun/ch32v203fun.c
@@ -927,6 +927,29 @@ void SystemInit144HSI( void )
 	while ((RCC->CFGR0 & (uint32_t)RCC_SWS) != (uint32_t)0x08) {}
 }
 
+void SystemInit144HSE( void )
+{
+	RCC->CTLR |= ((uint32_t)RCC_HSEON);
+	while(!(RCC->CTLR&RCC_HSERDY));
+
+	RCC->CFGR0 = RCC_HPRE_DIV1 | RCC_PPRE2_DIV1 | RCC_PPRE1_DIV2;
+	RCC->CFGR0 &= (uint32_t)((uint32_t)~(RCC_PLLSRC | RCC_PLLXTPRE | RCC_PLLMULL));
+	RCC->CFGR0 |= (uint32_t)(RCC_PLLSRC_HSE | RCC_PLLXTPRE_HSE | RCC_PLLMULL18);
+
+	/* Enable PLL */
+	RCC->CTLR |= RCC_PLLON;
+
+	/* Wait till PLL is ready */
+	while((RCC->CTLR & RCC_PLLRDY) == 0) {}
+
+	/* Select PLL as system clock source */
+	RCC->CFGR0 &= (uint32_t)((uint32_t)~(RCC_SW));
+	RCC->CFGR0 |= (uint32_t)RCC_SW_PLL;
+
+	/* Wait till PLL is used as system clock source */
+	while ((RCC->CFGR0 & (uint32_t)RCC_SWS) != (uint32_t)0x08) {}
+}
+
 void DelaySysTick( uint32_t n )
 {
 	uint32_t targend = SysTick->CNT + n;
diff --git a/ch32v203fun/ch32v203fun.h b/ch32v203fun/ch32v203fun.h
index 17fbddb..d9917a6 100644
--- a/ch32v203fun/ch32v203fun.h
+++ b/ch32v203fun/ch32v203fun.h
@@ -7369,6 +7369,7 @@ void SystemInit(void) __attribute__((used));
 
 // Initialization functions
 void SystemInit144HSI( void );
+void SystemInit144HSE( void );
 
 // TODO: Debug and UART
 
diff --git a/examples_v203/blink/blink.c b/examples_v203/blink/blink.c
index 1b9bf74..11c8b78 100644
--- a/examples_v203/blink/blink.c
+++ b/examples_v203/blink/blink.c
@@ -6,7 +6,7 @@
 
 int main()
 {
-	SystemInit144HSI();
+	SystemInit144HSE();
 
 	// Enable GPIOs
 	//RCC->APB2PCENR |= RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOC;
-- 
GitLab