From 089f9163e7f2373dac26100479f231ddf07040e0 Mon Sep 17 00:00:00 2001
From: Antti Huhtala <antti.huhtala@iki.fi>
Date: Sat, 3 Feb 2024 11:28:58 +0200
Subject: [PATCH] Simplify UART_BRR calculation. Fix for #271.

---
 ch32v003fun/ch32v003fun.h | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/ch32v003fun/ch32v003fun.h b/ch32v003fun/ch32v003fun.h
index 86c511e..fc69058 100644
--- a/ch32v003fun/ch32v003fun.h
+++ b/ch32v003fun/ch32v003fun.h
@@ -5225,10 +5225,9 @@ void SystemInit(void);
 #else
 	#define UART_BAUD_RATE 115200
 #endif
-#define OVER4DIV 4
-#define INTEGER_DIVIDER (((25 * (FUNCONF_SYSTEM_CORE_CLOCK)) / ((OVER4DIV) * (UART_BAUD_RATE))))
-#define FRACTIONAL_DIVIDER ((INTEGER_DIVIDER)%100)
-#define UART_BRR ((((INTEGER_DIVIDER) / 100) << 4) | (((((FRACTIONAL_DIVIDER) * ((OVER4DIV)*4)) + 50)/100)&15))
+// Debug UART baud rate register calculation. Works assuming HCLK prescaler is off.
+// Computes UART_BRR = CORE_CLOCK / BAUD_RATE with rounding to closest integer
+#define UART_BRR (((FUNCONF_SYSTEM_CORE_CLOCK) + (UART_BAUD_RATE)/2) / (UART_BAUD_RATE))
 // Put an output debug UART on Pin D5.
 // You can write to this with printf(...) or puts(...)
 
-- 
GitLab