简体   繁体   中英

Enabling Newline or Carriage return

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];
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM