From 4aec8ac0ddbb52ec9ada793c068ae98393cd5097 Mon Sep 17 00:00:00 2001
From: cnlohr <lohr85@gmail.com>
Date: Sun, 12 Mar 2023 23:20:27 -0400
Subject: [PATCH] Add timeout to printf.

---
 ch32v003fun/ch32v003fun.c                  | 4 +++-
 examples/debugprintfdemo/debugprintfdemo.c | 5 ++---
 2 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/ch32v003fun/ch32v003fun.c b/ch32v003fun/ch32v003fun.c
index f25595f..3cc57c3 100644
--- a/ch32v003fun/ch32v003fun.c
+++ b/ch32v003fun/ch32v003fun.c
@@ -856,12 +856,14 @@ int _write(int fd, const char *buf, int size)
 
 	char buffer[4] = { 0 };
 	int place = 0;
+	uint32_t timeout = 80000; // Give up after ~20ms
 	while( place < size )
 	{
 		int tosend = size - place;
 		if( tosend > 7 ) tosend = 7;
 
-		while( ((*DMDATA0) & 0x80) );
+		while( ((*DMDATA0) & 0x80) )
+			if( timeout-- == 0 ) return place;
 
 		uint32_t d;
 		int t = 3;
diff --git a/examples/debugprintfdemo/debugprintfdemo.c b/examples/debugprintfdemo/debugprintfdemo.c
index 297d2b8..576f199 100644
--- a/examples/debugprintfdemo/debugprintfdemo.c
+++ b/examples/debugprintfdemo/debugprintfdemo.c
@@ -24,9 +24,8 @@ int main()
 	while(1)
 	{
 		GPIOD->BSHR = 1 | (1<<4);	 // Turn on GPIOD0
-		//Delay_Ms( 50 );
-		GPIOD->BSHR = (1<<16) | ( 1<<(4+16) ); // Turn off GPIOD0
-		//Delay_Ms( 50 );
 		printf( "+%d\n", count++ );
+		GPIOD->BSHR = (1<<16) | ( 1<<(4+16) ); // Turn off GPIOD0
+		printf( "-%d\n", count++ );
 	}
 }
-- 
GitLab