Skip to content

Commit 58de57d

Browse files
committed
bricks/_common/mphalport: Print exceptions on a new line.
Fixes pybricks/support#870
1 parent 6a07abf commit 58de57d

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

bricks/_common/micropython.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ bool pbsys_main_stdin_event(uint8_t c) {
7878

7979
// Prints the exception that ended the program.
8080
static void print_final_exception(mp_obj_t exc, int ret) {
81+
82+
// Ensure exception prints on new line.
83+
mp_hal_stdout_tx_flush();
84+
8185
nlr_buf_t nlr;
8286
nlr.ret_val = NULL;
8387

bricks/_common/mphalport.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
// Contains the MicroPython HAL for STM32-based Pybricks ports.
66

77
#include <stdint.h>
8-
9-
#include <contiki.h>
8+
#include <string.h>
109

1110
#include <pbdrv/clock.h>
1211
#include <pbdrv/config.h>
@@ -55,6 +54,8 @@ int mp_hal_stdin_rx_chr(void) {
5554
return c;
5655
}
5756

57+
static bool ended_on_new_line = true;
58+
5859
// Send string of given length
5960
mp_uint_t mp_hal_stdout_tx_strn(const char *str, size_t len) {
6061
size_t remaining = len;
@@ -63,6 +64,7 @@ mp_uint_t mp_hal_stdout_tx_strn(const char *str, size_t len) {
6364
uint32_t size = remaining;
6465
pbio_error_t err = pbsys_host_stdout_write((const uint8_t *)str, &size);
6566
if (err == PBIO_SUCCESS) {
67+
ended_on_new_line = str[size - 1] == '\n';
6668
str += size;
6769
remaining -= size;
6870
} else if (err != PBIO_ERROR_AGAIN) {
@@ -85,4 +87,15 @@ void mp_hal_stdout_tx_flush(void) {
8587
while (!pbsys_host_tx_is_idle()) {
8688
MICROPY_VM_HOOK_LOOP;
8789
}
90+
91+
// A program may be interrupted in the middle of a long print, or the user
92+
// may have printed without a newline. Ensure we end on a new line.
93+
if (!ended_on_new_line) {
94+
const char *eol = "\r\n";
95+
uint32_t size = strlen(eol);
96+
pbsys_host_stdout_write((const uint8_t *)eol, &size);
97+
while (!pbsys_host_tx_is_idle()) {
98+
MICROPY_VM_HOOK_LOOP;
99+
}
100+
}
88101
}

0 commit comments

Comments
 (0)