newline & carriage return in Serial.printf()

27 Oct 2009

Any way to swap \n and \r?  Just started playing with the serial ports via Serial.printf() and noticed that mbed is using the DOS equivalents for \n and \r (as opposed to the Unix/Linux defaults). Any way to programmatically change this?

27 Oct 2009 . Edited: 27 Oct 2009

Hi Dave,

Dave Falkenburg wrote:
Any way to swap \n and \r? Just started playing with the serial ports via Serial.printf() and noticed that mbed is using the DOS equivalents for \n and \r (as opposed to the Unix/Linux defaults)

Looking at http://en.wikipedia.org/wiki/Newline, there are 3 (2 common) ways for line endings:

  • LF - Unix, Mac OSX
  • CR+LF - DOS, Windows
  • CR - Old Mac

Our preference in code is to use the Unix/Mac OSX format of just LF (\n) in code. On the Windows platform, most terminal apps can set the line ending to just LF, and many programs use this anyway.

We don't modifying any behaviour here. i.e. LF and CR characters just pass through as per normal. So whilst we recommend you do:

printf("hello\n");   // prefered line ending

and you should just get a LF out, you can also do:

printf("hello\r\n"); // discouraged line ending

you should get CR+LF. As I said, the preference to keep the code the same across platforms is just to use \n, and change the terminal settings on DOS/Windows to recognise that.

Here is a test program I just wrote to play with showing loopback on a serial port, putting out characters using putc and printf, and reading back the raw result. Main aim was to prove no manipulation of line ending characters:

Basically, we try not to do any magic around line endings. If you are seeing different behaviour, or have any ideas/suggestions, please shout.

Thanks,
Simon

27 Oct 2009

Thanks for the detailed reply.  I may have had something misconfigured in my terminal program.