Convert serial.read() into a useable string using Arduino?

后端 未结 15 1129
盖世英雄少女心
盖世英雄少女心 2020-11-29 15:27

I\'m using two Arduinos to sent plain text strings to each other using newsoftserial and an RF transceiver.

Each string is perhaps 20-30 characters in length. How do

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 16:07

    If you want to read messages from the serial port and you need to deal with every single message separately I suggest separating messages into parts using a separator like this:

    String getMessage()
    {
      String msg=""; //the message starts empty
      byte ch; // the character that you use to construct the Message 
      byte d='#';// the separating symbol 
    
      if(Serial.available())// checks if there is a new message;
      {
        while(Serial.available() && Serial.peek()!=d)// while the message did not finish
        {
          ch=Serial.read();// get the character
          msg+=(char)ch;//add the character to the message
          delay(1);//wait for the next character
        }
      ch=Serial.read();// pop the '#' from the buffer
      if(ch==d) // id finished
      return msg;
      else
      return "NA";
      }
    else
    return "NA"; // return "NA" if no message;
    }
    

    This way you will get a single message every time you use the function.

提交回复
热议问题