Skip to content

Commit c0728ac

Browse files
committed
Retarget - stdio serial lazy initialization
We provide mbed::get_serial_stdio() to get a reference for stdio Serial object. We should discourage to use Serial pc(USBTX, USBRX)
1 parent 67e764d commit c0728ac

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

mbed-drivers/Serial.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ class Serial : public SerialBase, public Stream {
6767
virtual int _putc(int c);
6868
};
6969

70+
/** Get the stdio Serial object, which is lazy instantiated.
71+
*
72+
* @returns stdio object
73+
*/
74+
Serial& get_stdio_serial();
75+
7076
} // namespace mbed
7177

7278
#endif

source/retarget.cpp

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -102,16 +102,29 @@ FileHandle::~FileHandle() {
102102
}
103103

104104
#if DEVICE_SERIAL
105+
106+
#include "mbed-drivers/Serial.h"
107+
105108
static int stdio_uart_inited;
106-
static serial_t stdio_uart;
109+
110+
namespace mbed {
111+
112+
Serial& get_stdio_serial()
113+
{
114+
static Serial stdio_serial(STDIO_UART_TX, STDIO_UART_RX);
115+
if (stdio_uart_inited == 0) {
116+
stdio_serial.baud(STDIO_DEFAULT_BAUD);
117+
stdio_uart_inited = 1;
118+
}
119+
return stdio_serial;
120+
}
121+
122+
}
107123
#endif
108124

109125
static void init_serial() {
110126
#if DEVICE_SERIAL
111-
if (stdio_uart_inited) return;
112-
serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX);
113-
serial_baud(&stdio_uart, STDIO_DEFAULT_BAUD);
114-
stdio_uart_inited = 1;
127+
get_stdio_serial();
115128
#endif
116129
}
117130

@@ -243,9 +256,8 @@ extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsign
243256
int n; // n is the number of bytes written
244257
if (fh < 3) {
245258
#if DEVICE_SERIAL
246-
if (!stdio_uart_inited) init_serial();
247259
for (unsigned int i = 0; i < length; i++) {
248-
serial_putc(&stdio_uart, buffer[i]);
260+
get_stdio_serial().putc(buffer[i]);
249261
}
250262
#endif
251263
n = length;
@@ -281,8 +293,7 @@ extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int
281293
if (fh < 3) {
282294
// only read a character at a time from stdin
283295
#if DEVICE_SERIAL
284-
if (!stdio_uart_inited) init_serial();
285-
*buffer = serial_getc(&stdio_uart);
296+
*buffer = get_stdio_serial().getc();
286297
#endif
287298
n = 1;
288299
} else {
@@ -493,8 +504,6 @@ extern "C" void __iar_argc_argv() {
493504
// the user should set up their application in app_start
494505
extern void app_start(int, char**);
495506
extern "C" int main(void) {
496-
// init serial if it has not been invoked prior main
497-
init_serial();
498507
minar::Scheduler::postCallback(
499508
mbed::util::FunctionPointer2<void, int, char**>(&app_start).bind(0, NULL)
500509
);

0 commit comments

Comments
 (0)