简体   繁体   English

启用换行符或回车符

[英]Enabling Newline or Carriage return

I am reading some robotic code and i came across something like Newline and Carriage.我正在阅读一些机器人代码,并且遇到了 Newline 和 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)通常表示为转义序列"\n" (换行)和"\r" (回车)

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

https://en.wikipedia.org/wiki/Newline 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.这仍然在计算机中用于移动 cursor 或在读取文本文件时进行换行。

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.您可以从这个片段中学到的唯一一件事就是如何不去做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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