Code Samples: Arduino HC-05/ESP32 - detect Bluetooth client connect/disconnect

The codes below are for Bluetooth Classic using HC-05 or ESP32.

In your Arduino code often you need to set certain I/O to a specific state, depending on the Bluetooth connection status.

This can be done in many ways, here is the way I do it:

If you are using HC-05, you can do it like this:

hc05

  1. Define a I/O pin to monitor the connection status: const int BtStatus = 2;
  2. Set the BtStatus pin to: pinMode (BtStatus, INPUT);
  3. Connect the STATE pin from the HC-05 to BtStatus pin.
  4. Monitor the connection in the loop().

Example:

const int BtStatus = 2;

void setup() {
  Serial.begin(9600);

  pinMode (BtStatus, INPUT);
}


void loop() {

  if (digitalRead (BtStatus) == 1)
  {
    Serial.println ("Client Connected");
    // Do stuff if connected
  }
  else
  {
    Serial.println ("Client Disconnected");
    // Do stuff if not connected
  }

}

If you are using ESP32, you can do it like this:

  1. Define and register a Bt_Status callback.
  2. Create a Bt_Status callback function.

Example:

#include "BluetoothSerial.h"

#define LED2  2 // Built-in LED

// Bluetooth Serial object
BluetoothSerial SerialBT;


// Bt_Status callback function
void Bt_Status (esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {

  if (event == ESP_SPP_SRV_OPEN_EVT) {
    Serial.println ("Client Connected");
    DigitalWrite (LED2, HIGH);
    // Do stuff if connected
  }

  else if (event == ESP_SPP_CLOSE_EVT ) {
    Serial.println ("Client Disconnected");
    DigitalWrite (LED2, LOW);
    // Do stuff if not connected
  }
}


void setup() {
  Serial.begin (115200);
  PinMode (LED2, OUTPUT);

  // Define the Bt_Status callback
  SerialBT.register_callback (Bt_Status);

  SerialBT.begin ("ESP32");

  Serial.println ();
  Serial.println ("Client Disconnected");
}


void loop() {
  // put your main code here, to run repeatedly:

}

I hope some people find this code useful.

Mike.

2 Likes

Hi... Can we connect HC-05 (Slave) to ESP32 ?
Thanks.