Skip to content

Commit 8e8f389

Browse files
authored
Merge pull request #1876 from geky/newline-conversion
Add newline conversion for stdout
2 parents abf9850 + 54609f6 commit 8e8f389

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

hal/common/retarget.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ FileHandle::~FileHandle() {
8888
#if DEVICE_SERIAL
8989
extern int stdio_uart_inited;
9090
extern serial_t stdio_uart;
91+
#if MBED_CONF_CORE_STDIO_CONVERT_NEWLINES
92+
static char stdio_in_prev;
93+
static char stdio_out_prev;
94+
#endif
9195
#endif
9296

9397
static void init_serial() {
@@ -226,9 +230,19 @@ extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsign
226230
if (fh < 3) {
227231
#if DEVICE_SERIAL
228232
if (!stdio_uart_inited) init_serial();
233+
#if MBED_CONF_CORE_STDIO_CONVERT_NEWLINES
234+
for (unsigned int i = 0; i < length; i++) {
235+
if (buffer[i] == '\n' && stdio_out_prev != '\r') {
236+
serial_putc(&stdio_uart, '\r');
237+
}
238+
serial_putc(&stdio_uart, buffer[i]);
239+
stdio_out_prev = buffer[i];
240+
}
241+
#else
229242
for (unsigned int i = 0; i < length; i++) {
230243
serial_putc(&stdio_uart, buffer[i]);
231244
}
245+
#endif
232246
#endif
233247
n = length;
234248
} else {
@@ -254,7 +268,28 @@ extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int
254268
// only read a character at a time from stdin
255269
#if DEVICE_SERIAL
256270
if (!stdio_uart_inited) init_serial();
271+
#if MBED_CONF_CORE_STDIO_CONVERT_NEWLINES
272+
while (true) {
273+
char c = serial_getc(&stdio_uart);
274+
if ((c == '\r' && stdio_in_prev != '\n') ||
275+
(c == '\n' && stdio_in_prev != '\r')) {
276+
stdio_in_prev = c;
277+
*buffer = '\n';
278+
break;
279+
} else if ((c == '\r' && stdio_in_prev == '\n') ||
280+
(c == '\n' && stdio_in_prev == '\r')) {
281+
stdio_in_prev = c;
282+
// onto next character
283+
continue;
284+
} else {
285+
stdio_in_prev = c;
286+
*buffer = c;
287+
break;
288+
}
289+
}
290+
#else
257291
*buffer = serial_getc(&stdio_uart);
292+
#endif
258293
#endif
259294
n = 1;
260295
} else {

mbed_lib.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"name": "core",
3+
"config": {
4+
"stdio-convert-newlines": {
5+
"help": "Enable conversion to standard newlines on stdin/stdout",
6+
"value": false
7+
}
8+
}
9+
}

0 commit comments

Comments
 (0)