Search code examples
stringarduinosend

How to send and read String over serial between two Arduinos?


Good morning/afternoon/evening. I'm trying to build this project and I have two arduinos (Emitter & Receiver) and they're gonna comunicate using RF control. The emitter/controller reads 2 different analog inputs with potentiometers connected, creates an String called "parametro" with the values of both potentiometers (Ex: "05120512" - 50%/50% - "10231023" - 100%/100%) and send this String via serial to the receiver using Serial.print(parametro). It works just fine.

The problem is: how to read that String as a String on the other Arduino. I've tried to read each byte of the String and create a char array with the values, and then, convert it back to String. However, there are some bug I can't explain. I tried to change the delay() time and it worked at first, but then, the numbers got random or something. I left the potenciometers on the middle position, so when I use Serial.print(parametro) to send data from the controller straight to the serial monitor it works as expected: "05120512051205120512...."

But when I try to send it from the receiver using Serial.println(parametro), it gives me something like:

  • 05120512
  • 05120512
  • 05120512
  • 05120512
  • 05120052
  • 05205105
  • 10510510
  • 51051051

As you can see, at that point the numbers start to get messed up and I don't understand why. Can anyone show me another solution or tell me what I did wrong?

By the way, here are the codes of the receiver. The emitter works fine, as I said:

  //      READING FUNCTION
String lerString(){
String conteudo = "";
char caracteres[8];
// WHILE RECEIVING
for(int i=0;i<=7;i++){
  caracteres[i] = Serial.read();
  delay(10);
  conteudo.concat(caracteres[i]);
}
return conteudo;
}


void loop() {

  //      SERIAL READ
  if(Serial.available() > 0){
    parametro = lerString(); 
  }
  Serial.println(parametro);

}


Solution

  • You would get a more robust implementation if you use a delimiter and implement a simple state machine to walk you through the parsing (ie. string -> "#05120512" that way your receiving function could look like:

    void loop () {
       if (Serial.available) {
          byte = Serial.read();
          if (byte == '#') {
              // got delimiter: start receiving data
              leState = RECEIVING_DATA
              count = 0;
          } else if (leState == RECEVING_DATA){
              count++;
              data[count] = byte;
              if (count == 7) {
                  // print data
                  ...
                  // reset state machine
                  leState = WAITING_FOR_DELIMITER;
              }
          }
       }
    
    }
    

    Warning: untested code - proceed with caution