Read from Serial and write to Bluetooth sometimes crashes

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);
  Serial.println("Bluetooth Device is Ready to Pair");

void loop() {
  while(Serial2.available()) {
    gpsChar =;
    if (gpsChar >= 0) {
      char c = (char)gpsChar;

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

.......................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

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



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