Example Code for Arduino-Bluetooth

Last revision 2026/02/05

This article provides a comprehensive guide on establishing Bluetooth communication using Arduino and ESP32 boards. It includes sample codes for setting up Bluetooth connections between host and slave devices, as well as BLE server configurations for data transfer and notifications.

1. Bluetooth Basic Tutorial

ESP32 has Bluetooth functionality, and this example will demonstrate the use of two FireBeetle 2 ESP32-E boards for Bluetooth communication. One ESP32 board will send data to the other ESP32 board, which is the most basic model for using Bluetooth wireless communication.

Hardware Preparation

Sample Code

Program: Use one FireBeetle 2 ESP32-E as the host and the other as the slave to establish a Bluetooth wireless communication, where the host sends data to the slave.

The programs for the host and slave are created in separate windows, and should be compiled and uploaded separately. Otherwise, it will not be possible to open two serial ports.

Program for Slave:

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32_one");       //Bluetooth device name 
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

**Program for host: **

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

String MACadd = "AA:BB:CC:11:22:33";
uint8_t address[6]  = {0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33};
String name = "ESP32_one";
const char *pin = "1234";  //<- Standard pin will be provided by default
bool connected;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test", true);   
  Serial.println("The device started in master mode, make sure remote BT device is on!");

  // Connecting using the address provides a faster connection (up to 10 seconds), while connecting using the name can take longer (up to 30 seconds)
  // It first parses the name to an address, but it allows connecting to different devices with the same name.
  // Set CoreDebugLevel to Info to see the device Bluetooth address and device name
  connected = SerialBT.connect(name);
  if(connected) {
    Serial.println("Connected Succesfully!");
  } else {
    while(!SerialBT.connected(10000)) {
      Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app."); 
    }
  }
  // disconnect() may take up to 10 seconds
  if (SerialBT.disconnect()) {
    Serial.println("Disconnected Succesfully!");
  }
  // This will reconnect to the name (if parsed, it will use the address) or the address (name/address) used with connect.
  SerialBT.connect();
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

Result

Open two serial monitor windows simultaneously, edit the message to be sent in the "Send" column of one of the serial monitor windows, and the message should be displayed in the other serial monitor window, which proves that the Bluetooth communication between the two FireBeetle 2 ESP32-E development boards is successful.

DFR0654-BLE result

2. Bluetooth Server

Hardware Preparation

Other Preparation Work

BLEDevice

  • init() Description: Create a BLE device
  • createServer() Description: Create a BLE server

BLEServer

  • createService() Description: Create a BLE service
  • setCallbacks() Description: Create server callbacks
  • start() Description: Start the server
  • getAdvertising() Description: Configure advertising function

BLEService

  • createCharacteristic() Description: Create characteristic of the service

BLECharacteristic

  • setCallbacks() Description: Set callbacks for characteristic
  • setValue() Description: Set the value of the characteristic
  • getValue() Description: Get the value of the characteristic
  • notify() Description: Send notification

BLEAdvertising

  • start() Description: Start advertising

Sample Code

Establish a BLE server that can provide data and send notifications to clients. When the server receives data from a client, it sends the received data to the client as a notification.

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#define SERVICE_UUID             "DFCD0001-36E1-4688-B7F5-EA07361B26A8"
#define CHARACTERISTIC1_UUID     "DFCD000A-36E1-4688-B7F5-EA07361B26A8"
bool deviceConnected = false;
BLEServer *pServer;
BLEService *pService;
BLECharacteristic* pCharacteristic;

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};
class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string value = pCharacteristic->getValue();

      if (value.length() > 0) {
        Serial.println("*********");
        Serial.print("New value: ");
        for (int i = 0; i < value.length(); i++){
          Serial.print(value[i]);
        }
        Serial.println();
        Serial.println("*********");
        pCharacteristic->notify();
      }
    }
};
void setupBLE()
{
  BLEDevice::init("DFRobot_ESP32");   //Create BLE device
  pServer = BLEDevice::createServer();   //Create BLE server
  pServer->setCallbacks(new MyServerCallbacks());   //Set the server's callback function
  pService = pServer->createService(SERVICE_UUID); //Create BLE service
  pCharacteristic = pService->createCharacteristic(
                                                 CHARACTERISTIC1_UUID,
                                                 BLECharacteristic::PROPERTY_READ|
                                                 BLECharacteristic::PROPERTY_NOTIFY|
                                                 BLECharacteristic::PROPERTY_WRITE);   //Create characteristic for the service
  pCharacteristic->setCallbacks(new MyCallbacks());    //Set the callback function for the characteristic
  pCharacteristic->addDescriptor(new BLE2902());
  pCharacteristic->setValue("Hello DFRobot");
  pService->start();
  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}
void setup() {
  Serial.begin(115200);
  setupBLE();
}

void loop() {
   delay(3000);
}

Result

Using FireBeetle 2 ESP32-E as a BLE server, the client can be a mobile phone. Install the Bluetooth helper LightBlue from the app store on the phone and establish a BLE connection with the ESP32-E module. Here, we will demonstrate the operations provided by Light Blue on an iPhone. Similar Bluetooth software helpers are also available for Android phones.

Operation on Mobile client are as follows:

  1. Step 1. Connect to DFRobot_ESP32.
    DFR0654-BLE Result 2

  2. Step 2. Click on the icon as shown in the figure.
    DFR0654-BLE Result 3

  3. Step 3. Send data to the server.
    DFR0654-BLE Result 4

  4. Step 4. The transmitted data can be viewed.
    DFR0654-BLE Result 5

  5. Step 5. The received data will be viewed on serial port.
    DFR0654-BLE Result 6

Was this article helpful?

TOP