Skip to content

Commit 2330dcc

Browse files
committed
Added newline conversion for stdin
stdin converts the following character sequences: \n -> \n \r\n -> \n \r -> \n \n\r -> \n For original behaviour, a serial object can be instantiated explicitly
1 parent 69c3362 commit 2330dcc

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

hal/common/retarget.cpp

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,8 @@ FileHandle::~FileHandle() {
8888
#if DEVICE_SERIAL
8989
extern int stdio_uart_inited;
9090
extern serial_t stdio_uart;
91-
static char stdio_prev;
91+
static char stdio_in_prev;
92+
static char stdio_out_prev;
9293
#endif
9394

9495
static void init_serial() {
@@ -228,11 +229,11 @@ extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsign
228229
#if DEVICE_SERIAL
229230
if (!stdio_uart_inited) init_serial();
230231
for (unsigned int i = 0; i < length; i++) {
231-
if (buffer[i] == '\n' && stdio_prev != '\r') {
232+
if (buffer[i] == '\n' && stdio_out_prev != '\r') {
232233
serial_putc(&stdio_uart, '\r');
233234
}
234235
serial_putc(&stdio_uart, buffer[i]);
235-
stdio_prev = buffer[i];
236+
stdio_out_prev = buffer[i];
236237
}
237238
#endif
238239
n = length;
@@ -259,7 +260,24 @@ extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int
259260
// only read a character at a time from stdin
260261
#if DEVICE_SERIAL
261262
if (!stdio_uart_inited) init_serial();
262-
*buffer = serial_getc(&stdio_uart);
263+
while (true) {
264+
char c = serial_getc(&stdio_uart);
265+
if ((c == '\r' && stdio_in_prev != '\n') ||
266+
(c == '\n' && stdio_in_prev != '\r')) {
267+
stdio_in_prev = c;
268+
*buffer = '\n';
269+
break;
270+
} else if ((c == '\r' && stdio_in_prev == '\n') ||
271+
(c == '\n' && stdio_in_prev == '\r')) {
272+
stdio_in_prev = c;
273+
// onto next character
274+
continue;
275+
} else {
276+
stdio_in_prev = c;
277+
*buffer = c;
278+
break;
279+
}
280+
}
263281
#endif
264282
n = 1;
265283
} else {

0 commit comments

Comments
 (0)