From dd3c7db0ad1f116d7e32e07ab0943bc41ba2e0d2 Mon Sep 17 00:00:00 2001
From: recallmenot <104343143+recallmenot@users.noreply.github.com>
Date: Fri, 9 Jun 2023 05:57:53 +0000
Subject: [PATCH] GPIO branchless PWM flicker (#157)

* one GPIO library to rule them all

* GPIO example makefile transfer

* GPIO README.md video upload

* Update README.md

* Update README.md

* GPIO library path recitified

* GPIO pretty paths please

* platformio.ini removed GPIO_analogRead test

* GPIO removed implementation block (unused)

* restoring blink.bin #1

* restoring blink.bin #2

* GPIO_branchless added branching digitalWrite (sometimes necessary)

* GPIO fixed PWM fade flicker

---------

Co-authored-by: recallmenot <edmund.raile@proton.me>
---
 extralibs/ch32v003_GPIO_branchless.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/extralibs/ch32v003_GPIO_branchless.h b/extralibs/ch32v003_GPIO_branchless.h
index 455716b..728ee00 100644
--- a/extralibs/ch32v003_GPIO_branchless.h
+++ b/extralibs/ch32v003_GPIO_branchless.h
@@ -80,6 +80,10 @@ This puts the defaults at an inaudible 23.4kHz.
 The higher the frequency, the greater the EMI radiation will be.
 With low frequencies, say below 1000Hz, LEDs may exhibit perceivable flicker.
 
+Since this library enables compare capture preload (OCxPE of CHCTLRy), writing a value into the compare register using analogWrite will automatically apply it (=load into shadow register) when the timer starts its next cycle.
+This avoids a bug whereby writing a compare value lower than the current counter value, the output will glitch high for the next cycle, resulting in flickery updates.
+Writing `TIMx->SWEVGR |= TIM_UG` will immediately update the shadow register and cause the same issue.
+
 */
 
 
@@ -463,12 +467,10 @@ static inline void GPIO_tim2_init() {
 #undef GPIO_tim1_analogWrite
 #define GPIO_tim1_analogWrite(channel, value) ({				\
 	TIM1->GPIO_timer_CVR(channel) = value;					\
-	TIM1->SWEVGR |= TIM_UG;							\
 })
 #undef GPIO_tim2_analogWrite
 #define GPIO_tim2_analogWrite(channel, value) ({				\
 	TIM2->GPIO_timer_CVR(channel) = value;					\
-	TIM2->SWEVGR |= TIM_UG;							\
 })
 
 #endif // CH32V003_GPIO_BR_H
-- 
GitLab