When writing Arduino sketches that parse HTTP requests, you come across code like this:
if (c == '\n' && currentLineIsBlank) { client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
In this code, there's a special character: "\n".
This special character is a line feed.
In some cases, you may also see the Carriage Return ("\r") special character.
In this article, I will discuss Line Feed and Carriage Return because they seem to be causing a lot of confusion to learners.
In a nutshell:
In modern computers (as opposed to mechanical typewriters where these operators find their roots), how exactly LF and CR work depend on the operating system.
In Unix and Unix like systems, like Mac OS X and Linux, an LF creates a new line and returns the cursor to the start of the line.
In Windows, to achieve the same outcome, you must combine CR with LF. This will result in, first, the generation of a new line, and then, the return of the cursor to the start of the line.
Which of these special characters should you use in your Arduino sketches?
Well, it depends on the application (you probably expected this).
For example, if the application involves the parsing of a web page, which is encoded in an HTTP message, and we want to know when the header has been received, then we can look for a CR + LF combination. We search for CR + LF because this is required by the HTTP standard.
But here's a simple trick: because in HTTP messages, CR and LF almost always appear together, we can reduce the workload of the Arduino by trying to detect one or the other. This realisation cuts not only the workload, but also the complexity of the parsing code.
Another thing to consider is that the HTTP standard is tolerant regarding the use a line feed (LF) to mark the end of a line; this is not strictly correct, but it is widespread and works just fine. This is why in Arduino sketches that parse HTTP messages (like the one in the top of this article), you see that the code will try to detect line feeds (LF, "\n"), and ignore carriage returns (CR).