使用Arduino将serial.read()转换为可用的字符串?

Joe*_*Joe 68 arduino

我正在使用两个Arduinos使用newsoftserial和RF收发器相互发送纯文本字符串.

每个字符串的长度可能是20-30个字符.如何转换Serial.read()为字符串,以便我可以做if x == "testing statements"等等?

小智 111

无限的字符串readed

  String content = "";
  char character;

  while(Serial.available()) {
      character = Serial.read();
      content.concat(character);
  }

  if (content != "") {
    Serial.println(content);
  }
Run Code Online (Sandbox Code Playgroud)

  • 非常有用和简单.虽然,我发现我必须在每个字符的读取之间稍微延迟 - 否则它将每个字符打印在一个单独的行而不是连接在一起.`void setup(){Serial.begin(9600); //初始化串口} void loop(){String content =""; 字符; while(Serial.available()){character = Serial.read(); content.concat(字符); 延迟(10); } if(content!=""){Serial.println(content); } (22认同)
  • 如果你想把这个代码移到一个从`loop()`调用的单独函数中,那么你返回(内容);`而不是`Serial.println()`非常重要.否则,您将进入无限循环,因为它将捕获函数打印到Serial的任何内容,并尝试重新处理它. (4认同)
  • 您必须在打印后清除内容,否则即使没有到达新的串行数据,if块也会再次执行。 (2认同)

mag*_*gma 60

帮助Serial.Read()获取字符串:

char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                   // there you know there is data
    {
        if(index < 19) // One less than the size of the array
        {
            inChar = Serial.read(); // Read a character
            inData[index] = inChar; // Store it
            index++; // Increment where to write next
            inData[index] = '\0'; // Null terminate the string
        }
    }

    if (strcmp(inData,This)  == 0) {
        for (int i=0;i<19;i++) {
            inData[i]=0;
        }
        index=0;
        return(0);
    }
    else {
        return(1);
    }
}

void loop()
{
    if (Comp("m1 on")==0) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")==0) {
        Serial.write("Motor 1 -> Offline\n");
    }
}
Run Code Online (Sandbox Code Playgroud)


Iha*_*ajj 52

您可以使用Serial.readString()Serial.readStringUntil()解析Arduino上Serial的字符串.

您还可以使用Serial.parseInt()从串行读取整数值.

int x;
String str;

void loop() 
{
    if(Serial.available() > 0)
    {
        str = Serial.readStringUntil('\n');
        x = Serial.parseInt();
    }
}
Run Code Online (Sandbox Code Playgroud)

通过串行发送的值将是my string\n5,结果将是str = "my string"x = 5

  • 当我尝试手动将串行输入读入字符缓冲区时,我遇到了奇怪的电压波动,但使用`Serial.readStringUntil()`为我修复了所有这些,并使代码更具可读性!谢谢! (2认同)
  • 我测试了,是的,它更容易。然而,与字符缓冲区相比,此操作需要更多的时间和延迟。 (2认同)

lad*_*las 11

我自己也在问同样的问题,经过一些研究,我发现了类似的东西.

它对我来说就像一个魅力.我用它来远程控制我的Arduino.

// Buffer to store incoming commands from serial port
String inData;

void setup() {
    Serial.begin(9600);
    Serial.println("Serial conection started, waiting for instructions...");
}

void loop() {
    while (Serial.available() > 0)
    {
        char recieved = Serial.read();
        inData += recieved; 

        // Process message when new line character is recieved
        if (recieved == '\n')
        {
            Serial.print("Arduino Received: ");
            Serial.print(inData);

            // You can put some if and else here to process the message juste like that:

            if(inData == "+++\n"){ // DON'T forget to add "\n" at the end of the string.
              Serial.println("OK. Press h for help.");
            }   


            inData = ""; // Clear recieved buffer
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


mrv*_*mrv 5

这会更容易:

char data [21];
int number_of_bytes_received;

if(Serial.available() > 0)
{
    number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
    data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
} 

bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp


if (result == 0)
{
   Serial.println("data matches whatever");
} 
else 
{
   Serial.println("data does not match whatever");
}
Run Code Online (Sandbox Code Playgroud)