ESP32 needs a Reset for Serial Monitor to work properly

Hi guys,

I‘ve got a NodeMCU ESP32 and connected a MH-Z19C Co2 sensor and 1.3" IPS screen to it. Here is the code I'm running:

void setup() {

  Serial.print("Connecting to MH-Z19...");
  Serial2.begin(9600, SERIAL_8N1, RX2, TX2);

  Serial2.write(abc_off, 9);
  Serial.println("Written abc_off to MH-Z19");
  Serial.print("Bytes to read from MH-Z19: ");
  bytesToRead = Serial2.available();

The problem begins when I plug in the ESP to USB: It jumps a lot of lines in the setup-section and the serial monitor doesn't print anything at all. The first print is way below in the loop-section.

The other problem is with the MH-Z19C: When I do a Serial2.available() after asking the sensor to send me 9 bytes of data it sends me 11 bytes instead the first time.

All this strange behaviour is gone when I just reset the ESP32 once. Then the serial monitor shows me every Serial.print from the setup() section correctly and the MH-Z19C sends always 9 bytes as it should.

But still... every first connection to USB it starts by jumping over serial print states and garbage data from the sensor. Is there a way to debug this more?

Edit: putting a delay(500) after the Serial.begin(9600) resolves the missing Serial.prints. The sensor still sends me 11 bytes instead of 9 on the first USB connect. A push on the reset button solves this but should not happen either way.

I do not believe the while(!Serial) works on these boards. This works on the original Arduino boards with native USB. But boards which use UART Serial have no way of knowing whether Serial Monitor was opened.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.