sending commands between two arduinos via serial

Hello,

I am using to arduinos MEGA, and trying to send a simple command from one to another, using serial port 1. The code for TX and RX are bellow:

//TRANSMITTING ARDUINO

char command;

void setup() {
  Serial.begin(9600,SERIAL_8E1);
  Serial1.begin(9600,SERIAL_8E1); 
}

void loop() {

  command = Serial.read();
  if(command == '1')
  {
  Serial.println("sending test1"); 
  Serial1.println("test1"); 
  }
  else if(command == '2')
  {
  Serial.println("sending test2"); 
  Serial1.println("test2");
  }

}
//RECEIVING ARDUINO

String mystr;

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600,SERIAL_8E1);
  Serial1.begin(9600,SERIAL_8E1);
}

void loop() {
 

  while (Serial1.available()>0){
  mystr = Serial1.readString();

    if(mystr == 'test1'){
      Serial.println(mystr);
      Serial.println("Executing test1");
    }
    
    else if(mystr == 'test2'){
      Serial.println(mystr);
      Serial.println("Executing test22");
    }

  }


 
}

The problem is that when I send the command for test2, it executes whatever is on test1 , even though it received the string ‘test2’.

The serial monitor print is attached. Any clue on whats happening?
thanks

problem.png

mystr == 'test1'

The fixed text that you are comparing with should be in double quotes. Single quotes are for single chars

When I use double quotes it prints nothing on the serial monitor of the receiving arduino :frowning:

You are trying to read from the serial port before checking if anything is in the buffer to be read in the transmit code.

Search this site to Robin2’s serial input basics tutorial. It show simple and robust ways to do serial communication.

lauraagouvea:
When I use double quotes it prints nothing on the serial monitor of the receiving arduino :frowning:

Print the value of mystr before you test it. So that you can see whether it contains anything and to reveal any hidden characters before and after it print “>” before it and “<” after it

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

The technique in the 3rd example will be the most reliable. It is what I use for Arduino to Arduino and Arduino to PC communication.

You can send data in a compatible format with code like this (or the equivalent in any other programming language)

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

…R