Saturday, December 19, 2020

ESP32 Bluetooth serial example

It's a simple example of ESP32 Bluetooth serial communication, run on ESP32-DevKitC V4.

The video show how it run, to communicate with Python/Raspberry Pi. The Python code is in my another blog: HelloRaspberryPi - Python (on Raspberry Pi) Bluetooth communicate with ESP32 SerialToSerialBT, using pybluez.

To make the ESP32 examples appear in examples list, you have to choose board of ESP32 first. It's ESP32 Wrover Module in may case.

The example available in Arduino IDE MENU > File > Examples > Bluetooth Serial (under Examples for Wrover Module) > SerialToSerialBT.


I make a little bit modification to display its Bluetooth MAC address.
// ref: Examples > BluetoothSerial > SerialToSerialBT

#include "BluetoothSerial.h"
#include "esp_bt_device.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 printDeviceAddress() {
 
  const uint8_t* point = esp_bt_dev_get_address();
 
  for (int i = 0; i < 6; i++) {
 
    char str[3];
 
    sprintf(str, "%02X", (int)point[i]);
    Serial.print(str);
 
    if (i < 5){
      Serial.print(":");
    }
 
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("\n---Start---");
  SerialBT.begin("ESP32test"); //Bluetooth device name
  
  Serial.println("The device started, now you can pair it with bluetooth!");
  Serial.println("Device Name: ESP32test");
  Serial.print("BT MAC: ");
  printDeviceAddress();
  Serial.println();
}

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

The function printDeviceAddress() is copy from dfrobot ESP32 Arduino: Getting the Bluetooth Device Address.

Next:


No comments:

Post a Comment