Table of Contents

Here’s a simple ESP32 Bluetooth Classic example that demonstrates how to set up an ESP32 as a Bluetooth Classic Serial Server. This example uses the Bluetooth Serial library to communicate with a Bluetooth Classic client (e.g., a smartphone or PC).

Code for ESP32 (Bluetooth Classic Serial Server)

#include <BluetoothSerial.h>

// Create BluetoothSerial object
BluetoothSerial SerialBT;

void setup() {
  // Start Serial Monitor for debugging
  Serial.begin(115200);
  Serial.println("Starting Bluetooth Classic Server...");

  // Initialize Bluetooth Serial
  if (!SerialBT.begin("Lonely_Binary_ESP32")) {  // ESP32 Bluetooth device name
    Serial.println("Bluetooth initialization failed!");
    return;
  }
  Serial.println("Bluetooth initialized. Waiting for client to connect...");
}

void loop() {
  // Check if data is available from the Bluetooth client
  if (SerialBT.available()) {
    // Read data from Bluetooth and print to Serial Monitor
    char receivedChar = SerialBT.read();
    Serial.print("Received: ");
    Serial.println(receivedChar);
  }

  // Send a message to the Bluetooth client (optional)
  SerialBT.println("Hello from ESP32 Bluetooth server!");

  delay(1000);
}
C++

Explanation:

  1. BluetoothSerial: The BluetoothSerial class is used to create a Bluetooth Classic serial connection.
  2. SerialBT.begin(“Lonely_Binary_ESP32”): This initializes the Bluetooth module with a name (ESP32_BT_Server) that will be used by clients to identify the device.
  3. SerialBT.available(): This checks if data is available from the connected Bluetooth client.
  4. SerialBT.read(): Reads data from the Bluetooth client and prints it to the Serial Monitor.
  5. SerialBT.println(): Sends a message to the Bluetooth client. In this case, the ESP32 will send “Hello from ESP32 Bluetooth server!” every second.

How to Test:

  1. Upload the code to your ESP32.
  2. Enable Bluetooth on your PC and search for Bluetooth devices.
  3. You should see Lonely_Binary_ESP32 in the list of available devices. Pair with it.
  1. Use a Bluetooth Terminal app for Android or a Termius App on your PC to connect to the ESP32.
  1. Once connected, the app should display messages like “Hello from ESP32 Bluetooth server!” from the ESP32.
  1. You can also send data from the app to the ESP32, and it will be printed in the Serial Monitor.

Categorized in:

Bluetooth Classic,

Tagged in: