problem with serial

Slave: Arduino uno
Master: Arduino mega

code for uno:

#include <Servo.h>
String state;
String s1open = "s1 open";
String s1close = "s1 close";
Servo servo1;

void setup() {

 Serial.begin(9600);

 servo1.attach(9);
}

void loop() {
 while(Serial.available()==0) {}
 
  state = Serial.readStringUntil('\n');

if(state == s1open){
  servo1.write(180);
}
if(state == s1close){
  servo1.write(0);
}
}

code for Mega:

String state;

void setup() {
Serial1.begin(9600);
Serial.begin(9600);
Serial.println("arduino is ready");

}

void loop() {

while(Serial.available()==0){}

state = Serial.readString();

Serial1.println(state);
Serial.println(state);

}

wireing: TX uno --> Rx1 mega
Rx uno --> Tx1 Mega
common ground
servo--> pin 9 uno

problem:
if i type in s1 close or s1 open in the serial or serial1 monitor of the Arduino mega, it doesnt work
if i type in s1 close or s1 open in the serial, but rewire the wires as:
Tx uno --> Rx0 mega
Rx uno --> Tx0 mega
it does work.

if i rewrite the code a little and i make the uno master and the mega slave it also works fine without rewireing. Can someone tell me where i went wrong making the uno slave and the mega master ? maybe a tip or a correction ?

Why don't you have readStringUntil() in the Mega?

I never use those functions anyway. Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

Also, while it is NOT the cause of your problem, it is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. Just use cstrings - char arrays terminated with 0.

When you connect the Uno to Serial on the Mega it will receive the data direct from the Serial Monitor.

...R

When you connect the Uno to Serial on the Mega it will receive the data direct from the Serial Monitor.

so of i understand correctly, it is not possible to connenct the serial1/2/3 from the mega to the serial of the uno ?

i did some tests and found out that my uno is not recieving anything from my mega/serial 1

PlatoBE:
so of i understand correctly, it is not possible to connenct the serial1/2/3 from the mega to the serial of the uno ?

Sure you can. It's just that if you do that, you can't use the Uno serial to communicate with the USB host.

PlatoBE:
i did some tests and found out that my uno is not recieving anything from my mega/serial 1

...which could mean a million things.