SunFounder ESP32 Starter Kit
(continued from previous page)
// Read data from the serial port and send it to BLE characteristic
if (Serial.available() > 0) {
String str = Serial.readStringUntil('\n');
const char *newValue = str.c_str();
pCharacteristic->setValue(newValue);
pCharacteristic->notify();
}
}
• Callbacks: Two callback classes (MyServerCallbacks and MyCharacteristicCallbacks) are defined to
handle events related to Bluetooth communication. MyServerCallbacks is used to handle events related to
the connection state (connected or disconnected) of the BLE server. MyCharacteristicCallbacks is used to
handle write events on the BLE characteristic, i.e., when a connected device sends a string to the ESP32 over
BLE, it’s captured and stored in receivedText, and the current time is recorded in lastMessageTime.
// Define the BLE server callbacks
class MyServerCallbacks : public BLEServerCallbacks {
// Print the connection message when a client is connected
void onConnect(BLEServer *pServer) {
Serial.println("Connected");
}
// Print the disconnection message when a client is disconnected
void onDisconnect(BLEServer *pServer) {
Serial.println("Disconnected");
}
};
// Define the BLE characteristic callbacks
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
// When data is received, get the data and save it to receivedText,␣
˓→and record the time
std::string value = pCharacteristic->getValue();
receivedText = String(value.c_str());
lastMessageTime = millis();
Serial.print("Received: ");
Serial.println(receivedText);
}
};
• Setup BLE: In the setupBLE() function, the BLE device and server are initialized, the server callbacks are set,
the BLE service is created using the defined UUID, characteristics for sending notifications and receiving data
are created and added to the service, and the characteristic callbacks are set. Finally, the service is started and
the server begins advertising.
// Initialize the Bluetooth BLE
void setupBLE() {
BLEDevice::init(bleName); // Initialize the BLE␣
˓→device
BLEServer *pServer = BLEDevice::createServer(); // Create the BLE␣
˓→server
// Print the error message if the BLE server creation fails
(continues on next page)
140 Chapter 1. For Arduino User