0

I am reading some robotic code and i came across something like Newline and Carriage. What are those two things? I could not find any useful usage related the code itself. Here is the code

// !! make sure you have enabled Newline or Carriage return
#define _mode 0 // (0) used for calibration and testing, (1) uses serial as input
void handle_serial() {
  //: reads and stores the serial data
  int i = 0; float buff[3] = {0, 0, 0};
  String s_buff = "";
  while (Serial.available()) {
    char c = Serial.read();
    if (c == 13 || c == 32 || c == '\n') {
      buff[i] = s_buff.toFloat();
      s_buff = "";
      i++;
    } else
      s_buff += c;
  }

  if (_mode == 0)
    commands_exe(buff[0], buff[1], buff[2]);
  else if (_mode == 1)
    if (state == 4) {
      _direction = {buff[0], buff[1]};
      turn = buff[2];
    }
}
Belengaz
  • 13
  • 3
  • 2
    You should burn this code. Probably most other code in the project too. – EOF Apr 09 '21 at 21:33
  • why? I don't understand? – Belengaz Apr 09 '21 at 21:37
  • I tried to delete the code and run the program but an error occur. I don't think it is worthless – Belengaz Apr 09 '21 at 21:46
  • If you look at it `13` is `'\r'` and `32` is `' '` (space) and the only character literal shown correctly is `'\n'`. The code says `if (whitespace) { ... } else { add c to s_buff }` There is no validation on whether `s_buff` holds a valid value before calling `s_buff.toFloat()`. In fact, if the first character received was whtespace, it would attempt a conversion on the empty-string. That is just a few of the reasons you were encouraged to start over... – David C. Rankin Apr 09 '21 at 22:05

1 Answers1

3

Newline and Carriage. What are those two things?

That's two control characters. Usually expressed as the escape sequence "\n" (new line) and "\r" (carriage return)

https://en.wikipedia.org/wiki/Carriage_return

https://en.wikipedia.org/wiki/Newline

Both have historic reasons. Carriage return moved the printhead back to the beginning of the line. New line moved to the next line.

This is still used in computers to move the cursor around or to make linebreaks when reading text files.

The idea of it in this code is to read bytes until newline, space or carriage return are received. then the bytes received till then is converted to a float.

But as the comments suggest this implementation is bad for many reasons. mainly it is very error prone.

For example you risk to exceeed the boudnaries of your buffer if you don't receive space, newline or carriage return in time.

It is also often used to terminate serial commands so the computer knows when he received a full command, which at the same time allows to display them nicely in a terminal. It is up to the sender to make sure the correct data is sent which in gerneral is a very bad idea.

The only thing you can learn from this snippet is how not do to do it.

Piglet
  • 27,501
  • 3
  • 20
  • 43