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?

4
  • did you connect the correct pins? ... do not use pin 0 and pin 1 for software serial
    – jsotola
    Commented Jan 27, 2021 at 22:24
  • 1
    @jsotola In this setup, I'm not using software serial. The pinout is displayed with the exception of RX0 now being RX1 on the Mega.
    – Adamelli
    Commented Jan 27, 2021 at 22:34
  • are you missing the GND connection of the LV side of the level shifter?
    – hcheung
    Commented Jan 28, 2021 at 13:28
  • @hcheung They're internally connected.
    – Adamelli
    Commented Jan 28, 2021 at 15:34

1 Answer 1

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.