Read from Serial and write to Bluetooth sometimes crashes

Hi
I have a GPS Module connected to the M5Core2. I read continuously the GPS and send it to the serial and over bluetooth. After I disconnect and reconnect the bluetooth device, the M5Core2 hangs, the loop is not runing anymore. But I can see the Client connected/disconnected messages. Seems, that the callback works, but loop does not.

#include <Arduino.h>
#include <M5Core2.h>
#include "BluetoothSerial.h"
#include <sys/time.h>

BluetoothSerial ESP_BT;
int gpsChar;

void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){
  if(event == ESP_SPP_CLOSE_EVT ) {
    Serial.println("Client disconnected");
  }
  if(event == ESP_SPP_SRV_OPEN_EVT){
    Serial.println("Client connected");
  }
}

void setup() {
  M5.begin(true, true, true, false);
  M5.Lcd.fillScreen(TFT_BLACK);
  ESP_BT.register_callback(callback);
  ESP_BT.begin("M5Core2");
  Serial.println("Bluetooth Device is Ready to Pair");
  Serial2.begin(38400);
}

void loop() {
  while(Serial2.available()) {
    gpsChar = Serial2.read();
    if (gpsChar >= 0) {
      char c = (char)gpsChar;
      ESP_BT.write(c);
      Serial.print(c);
    }
  }
  Serial.print(".");
  delay(20);
}

The output after it crashed and i connect and disconnect the bluetooth device:

$GNGLL,4816.01200,N,00855.97770,E,154688.00,A,A*7B
.......................Client connected
.............$GNRMC,154629.00,A,4816.01201,NClient disconnected
Client connected
Client disconnected
Client connected
Client disconnected
Client connected
Client disconnected

What can I do, that this works properly?
Thank you
Marco

Please post your code using the code button </>

so it looks like this

I can’t read your coloured text

See How to get the best out of the Forum

…R

better?

Hi, where do you check on the loop if you are actually connected or not to the bluetooth before trying to send something?

Why you have serial and serial2?

If serial2 is the bluetooth, try to delay a bit after checking if avaliable.. try delay(500) and then reduce it if it works untill crashing