Designing A Great Debug Serial Console
Debug serial consoles using UART are the mainstay of embedded programming. Along with step-by-step debugging, they form the two essential tools you need when developing embedded firmware. But what makes a good serial console?
ANSI escape codes allow us to do things:
- Colourize the log data sent from the microcontroller. For example, info message could be the default colour, warnings yellow, and errors red.
- Insert newly received log data “behind” typed in text from the user. This allows you to implement a CLI to control the micro AND receive log messages at the same time, without the logging messages disrupting the commands the user types in.
0x1B
(referred to as ESC
in this document) is the ANSI escape character which starts all escape sequences.
ESC[m
: Reset code
ESC[nD
: Move cursor back n
cells.
ESC[J
: Erase text from cursor to send of screen
To implement the CLI, the MCU should buffer all received characters until it receives a \n
char that indicates the user has pressed enter. At this point the command can be processed. However, if a log message needs to be sent back to the user in between the user entering a character and pressing enter, escape codes can be used to preserve their input.
- Send
ESC[nD
withn
being the number of chars in the receive buffer. This will bring the cursor back to the start of the line. - Send
ESC[J
to clear the text from the cursor position to the end of the screen (i.e. the partial command the user has entered). - Send the log message.
- Re-send the text in the receive buffer back to the user, so it looks like they are still part way through entering the command.
- Done!