3

I'm trying to send a string from an ESP32 to an Arduino. I'm using a level shifter, where the Uno is now the Mega (since I couldn't get the Uno to work).

enter image description here

RX0 is now RX1, connected to UART2 of ESP32.

// Master sender ESP32

#include <HardwareSerial.h>
 
void setup() {
  // Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  delay(100);
}
    
void loop() {
  String shape = "1,2,3";
  Serial2.println(shape);
  delay(500);
}

//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readString();
    Serial.println(received);
  }
}

Is there something in either sketch that should be changed?

ocrdu
  • 1,673
  • 2
  • 9
  • 22
Adamelli
  • 93
  • 9

1 Answers1

2

readStringUntil('\n')

//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readStringUntil('\n');
    Serial.println(received);
  }
}

It's about how Serial.readString() works: it reads from the serial port forever in this case. It stops reading if the serial interface is given a time-out. There are two possibilities:

  • use readStringUntil() on the receiver
  • call mySerial.setTimeout(300); (from setup()) to set a 300ms (for instance, as long as it's significantly less than 1000) time out on the receiver — it defaults to one second!
Adamelli
  • 93
  • 9