## Group Work 2026 – Communication between XIAO ESP32C3 and XIAO ESP32S3 Using BLE

**Assignment:** Send a message between two microcontroller projects and control an output device wirelessly.

In this group work, we used Bluetooth Low Energy (BLE) to establish wireless communication between a Seeed Studio XIAO ESP32C3 and a XIAO ESP32S3. The ESP32C3 was connected to an HC-SR04 ultrasonic distance sensor, while the ESP32S3 controlled an external LED. The sensor detected the distance to an object and the ESP32C3 transmitted an LED command to the ESP32S3. This replaced the wired UART communication used in the earlier assignment.

### Materials Needed

- 1 × Seeed Studio XIAO ESP32C3 (sensor board and BLE server)
- 1 × Seeed Studio XIAO ESP32S3 (LED board and BLE client)
- 1 × HC-SR04 ultrasonic sensor
- 1 × LED and 220 Ω current-limiting resistor
- Resistors for an appropriate 5 V-to-3.3 V Echo level divider (or a suitable logic-level shifter)
- Breadboard, jumper wires, and two USB cables
- Arduino IDE with ESP32 board support (Arduino ESP32 Core 3.1.3 for the supplied code)

### Circuit Setup

**Board 1 – XIAO ESP32C3 (Ultrasonic Sensor / BLE Sender)**

| HC-SR04 connection | XIAO ESP32C3 connection |
|---|---|
| VCC | 5 V supply (if required by the sensor module) |
| GND | GND (common ground with sensor supply) |
| TRIG | D0 |
| ECHO | D1 **through a 5 V-to-3.3 V level shifter or resistor divider** |

**Important:** The HC-SR04 commonly uses a 5 V Echo signal. XIAO ESP32 GPIO inputs are 3.3 V devices, so the Echo signal must not be connected directly at 5 V. If the sensor uses an external 5 V supply, connect its ground to the ESP32C3 ground.

**Board 2 – XIAO ESP32S3 (LED / BLE Receiver)**

| Component | XIAO ESP32S3 connection |
|---|---|
| LED anode (+) | D1 through a 220 Ω resistor |
| LED cathode (−) | GND |

Both boards were powered separately by USB. No wired TX/RX connection between the boards was necessary because data was transferred via BLE.

### How BLE Communication Works

The ESP32C3 operates as the **BLE server** and advertises the name `XIAO_C3`. It provides a BLE service and a readable/notifiable characteristic. The ESP32S3 operates as the **BLE client**, scans for the ESP32C3, connects, locates the characteristic, and subscribes to notifications. The C3 transmits the character `1` to request LED ON and `0` to request LED OFF.

The two sketches use the same identifiers:

```cpp
#define SERVICE_UUID "a12b34c5-d678-40ef-9123-456789abcdef"
#define CHAR_UUID    "a12b34c5-d678-40ef-9123-456789abcde0"
```

### Ultrasonic Sensor and LED Control Logic

The ESP32C3 sends a 10 µs trigger pulse to the HC-SR04 and measures the duration of the returning Echo pulse using `pulseIn()` with a 25,000 µs timeout. The approximate distance is calculated as:

\[
\text{Distance (cm)} = \frac{\text{Echo duration (µs)} \times 0.0343}{2}
\]

The program checks the sensor approximately every **180 ms**. The supplied sender code applies the following logic:

| Measured condition | BLE command | LED result |
|---|---|---|
| Distance ≤ 15 cm | `1` | ON |
| 15 cm < Distance < 20 cm | Previous command | Previous state retained |
| Distance ≥ 20 cm | `0` | OFF |
| No valid Echo reading | `0` | OFF |

The gap between 15 cm and 20 cm provides **hysteresis**, preventing the LED from rapidly switching when the object is close to a single threshold.

### Sender Code – XIAO ESP32C3

The following is the code used for the ESP32C3 board, taken from our 2026 experiment.

```cpp
/* XIAO ESP32C3 / Arduino ESP32 Core 3.1.3
 * HC-SR04 TRIG=D0, ECHO=D1 (ECHO MUST be shifted to 3.3 V)
 * <=15 cm ON; >=20 cm OFF; invalid measurement OFF.
 */
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <BLEAdvertising.h>

#define TRIG_PIN D0
#define ECHO_PIN D1
#define SERVICE_UUID "a12b34c5-d678-40ef-9123-456789abcdef"
#define CHAR_UUID    "a12b34c5-d678-40ef-9123-456789abcde0"

BLEServer* bleServer = nullptr;
BLECharacteristic* stateChar = nullptr;
volatile bool bleConnected = false;
bool wasConnected = false;
bool ledRequest = false;
unsigned long lastSample = 0;

class ServerCB : public BLEServerCallbacks {
  void onConnect(BLEServer* s) override {
    bleConnected = true;
    Serial.println("[BLE] Client connected");
  }
  void onDisconnect(BLEServer* s) override {
    bleConnected = false;
    Serial.println("[BLE] Client disconnected");
  }
};

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL);
  if (us == 0) return -1.0f;
  return us * 0.0343f * 0.5f;
}

void setup() {
  Serial.begin(115200);
  delay(700);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);
  Serial.println("\n=== XIAO ESP32C3 BLE SENDER ===");

  BLEDevice::init("XIAO_C3");
  bleServer = BLEDevice::createServer();
  bleServer->setCallbacks(new ServerCB());
  BLEService* service = bleServer->createService(SERVICE_UUID);
  stateChar = service->createCharacteristic(
      CHAR_UUID,
      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
  stateChar->addDescriptor(new BLE2902());
  stateChar->setValue("0");
  service->start();

  BLEAdvertising* adv = BLEDevice::getAdvertising();
  // A 128-bit UUID + complete name can exceed the 31-byte advertisement limit.
  // Put the name in primary advertising and the service UUID in scan response.
  BLEAdvertisementData primary;
  primary.setFlags(0x06);
  primary.setName("XIAO_C3");
  BLEAdvertisementData response;
  response.setCompleteServices(BLEUUID(SERVICE_UUID));
  adv->setAdvertisementData(primary);  // returns void in Core 3.1.3
  adv->setScanResponseData(response);
  adv->setScanResponse(true);
  BLEDevice::startAdvertising();
  Serial.println("[BLE] Advertising XIAO_C3 (UUID in scan response)");
}

void loop() {
  if (millis() - lastSample >= 180) {
    lastSample = millis();
    float cm = readDistanceCm();
    if (cm < 0) ledRequest = false;
    else if (cm <= 15.0f) ledRequest = true;
    else if (cm >= 20.0f) ledRequest = false;

    stateChar->setValue(ledRequest ? "1" : "0");
    if (bleConnected) stateChar->notify();

    Serial.print("[SENSOR] ");
    if (cm < 0) Serial.print("Invalid");
    else { Serial.print(cm, 1); Serial.print(" cm"); }
    Serial.print(" | LED request: ");
    Serial.print(ledRequest ? "ON" : "OFF");
    Serial.print(" | BLE: ");
    Serial.println(bleConnected ? "Connected" : "Waiting");
  }

  if (!bleConnected && wasConnected) {
    delay(150);
    BLEDevice::startAdvertising();
    Serial.println("[BLE] Advertising restarted");
  }
  wasConnected = bleConnected;
  delay(10);
}
```

The sender advertises its BLE name and service, reads the sensor, updates the characteristic value, and sends notifications when the receiver is connected. If the connection is lost, advertising restarts so the receiver can reconnect.

### Receiver Code – XIAO ESP32S3

The following is the receiver code used in our 2026 experiment. The LED is connected to **D1**.

```cpp

/*
 * XIAO ESP32S3 - BLE LED Receiver
 * Arduino ESP32 Core 3.1.3
 *
 * BLE Server: XIAO ESP32C3
 * BLE Client: XIAO ESP32S3
 *
 * Receive "1" -> LED ON
 * Receive "0" -> LED OFF
 *
 * Signal timeout: 1500ms
 * Auto reconnect
 */

#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEClient.h>
#include <BLERemoteService.h>
#include <BLERemoteCharacteristic.h>

// ==========================
// Configuration
// ==========================

#define LED_PIN D1

#define SIGNAL_TIMEOUT 1500
#define SCAN_TIME 4

#define TARGET_NAME "XIAO_C3"

#define SERVICE_UUID \
  "a12b34c5-d678-40ef-9123-456789abcdef"

#define CHAR_UUID \
  "a12b34c5-d678-40ef-9123-456789abcde0"

// ==========================
// BLE UUID
// ==========================

BLEUUID serviceUUID(SERVICE_UUID);
BLEUUID charUUID(CHAR_UUID);

// ==========================
// BLE global variables
// ==========================

BLEClient* client = nullptr;
BLEScan* scanner = nullptr;

BLERemoteCharacteristic* remoteChar = nullptr;

volatile unsigned long lastRx = 0;
volatile char receivedCommand = '0';

bool currentLED = false;
volatile bool notificationReady = false;

// ==========================
// LED control
// ==========================

void updateLED(bool on) {

  digitalWrite(
    LED_PIN,
    on ? HIGH : LOW
  );

  if (currentLED != on) {

    currentLED = on;

    Serial.println(
      on ? "[LED] ON" : "[LED] OFF"
    );
  }
}

// ==========================
// BLE notification callback
// ==========================

void notifyCallback(
  BLERemoteCharacteristic* pChar,
  uint8_t* data,
  size_t length,
  bool isNotify
) {

  if (length == 0 || data == nullptr) {
    return;
  }

  char cmd = (char)data[0];

  if (cmd == '0' || cmd == '1') {

    receivedCommand = cmd;
    lastRx = millis();

    Serial.print("[RX] Command: ");
    Serial.println(cmd);
  }
}

// ==========================
// BLE client callbacks
// ==========================

class ClientCallbacks : public BLEClientCallbacks {

  void onConnect(BLEClient* pClient) override {

    Serial.println("[BLE] Link connected");
  }

  void onDisconnect(BLEClient* pClient) override {

    notificationReady = false;

    receivedCommand = '0';
    lastRx = 0;

    Serial.println("[BLE] Disconnected");
  }
};

// ==========================
// Connect to the target device
// ==========================

bool connectToC3(
  BLEAddress address,
  esp_ble_addr_type_t addressType
) {

  Serial.println();
  Serial.println("[BLE] Connecting to C3...");

  notificationReady = false;
  remoteChar = nullptr;

  // Clear the previous connection
  if (client->isConnected()) {

    client->disconnect();
    delay(200);
  }

  // Connect using the address type obtained from the scan
  bool success = client->connect(
    address,
    addressType
  );

  if (!success) {

    Serial.println("[ERROR] BLE connection failed");

    return false;
  }

  Serial.println("[BLE] Physical link established");

  // ========================
  // Find the service
  // ========================

  BLERemoteService* service =
      client->getService(serviceUUID);

  if (service == nullptr) {

    Serial.println("[ERROR] Service UUID not found");

    client->disconnect();

    return false;
  }

  Serial.println("[BLE] Service found");

  // ========================
  // Find the characteristic
  // ========================

  remoteChar =
      service->getCharacteristic(charUUID);

  if (remoteChar == nullptr) {

    Serial.println("[ERROR] Characteristic not found");

    client->disconnect();

    return false;
  }

  Serial.println("[BLE] Characteristic found");

  // ========================
  // Check notification support
  // ========================

  if (!remoteChar->canNotify()) {

    Serial.println("[ERROR] Notify not supported");

    client->disconnect();

    return false;
  }

  // ========================
  // Register for notifications
  // ESP32 Core 3.1.3
  // registerForNotify returns void
  // ========================

  Serial.println("[BLE] Registering notifications...");

  remoteChar->registerForNotify(
    notifyCallback
  );

  Serial.println("[BLE] Notification registration requested");

  // ========================
  // Initialize the receive state
  // ========================

  receivedCommand = '0';
  lastRx = 0;

  // ========================
  // Read the initial state
  // ========================

  if (remoteChar->canRead()) {

    String value = remoteChar->readValue();

    if (value.length() > 0) {

      char cmd = value[0];

      if (cmd == '0' || cmd == '1') {

        receivedCommand = cmd;
        lastRx = millis();

        Serial.print("[BLE] Initial value: ");
        Serial.println(cmd);
      }
    }
  }

  notificationReady = true;

  Serial.println("[BLE] Ready to receive");

  return true;
}

// ==========================
// Scan and connect
// ==========================

void scanAndConnect() {

  Serial.println();
  Serial.println("==========================");
  Serial.println("[SCAN] Searching for C3...");
  Serial.println("==========================");

  // Clear previous scan results
  scanner->clearResults();

  BLEScanResults* results =
      scanner->start(SCAN_TIME, false);

  if (results == nullptr) {

    Serial.println("[ERROR] Scan failed");

    return;
  }

  int count = results->getCount();

  Serial.printf(
    "[SCAN] Found %d device(s)\n",
    count
  );

  bool targetFound = false;

  BLEAddress targetAddress(
    "00:00:00:00:00:00"
  );

  esp_ble_addr_type_t targetAddressType =
      BLE_ADDR_TYPE_PUBLIC;

  // ========================
  // Iterate through the scan results
  // ========================

  for (int i = 0; i < count; i++) {

    BLEAdvertisedDevice device =
        results->getDevice(i);

    String name = device.getName();

    Serial.printf(
      "[DEVICE %d] Name: %s | MAC: %s | RSSI: %d\n",
      i,
      name.length() ? name.c_str() : "(unknown)",
      device.getAddress().toString().c_str(),
      device.getRSSI()
    );

    // Match the device name
    bool nameMatched =
      name == TARGET_NAME ||
      name == "XIAO_C3_SENSOR";

    // Match the service UUID
    bool uuidMatched =
      device.haveServiceUUID() &&
      device.isAdvertisingService(serviceUUID);

    if (nameMatched || uuidMatched) {

      Serial.println("[SCAN] Target C3 found!");

      Serial.print("[SCAN] Match: ");

      if (uuidMatched) {
        Serial.println("Service UUID");
      } else {
        Serial.println("Device Name");
      }

      targetAddress = device.getAddress();

      targetAddressType =
          device.getAddressType();

      targetFound = true;

      break;
    }
  }

  // ========================
  // Stop scanning
  // ========================

  scanner->stop();

  scanner->clearResults();

  delay(200);

  // ========================
  // Connect to the target
  // ========================

  if (targetFound) {

    Serial.print("[BLE] Target MAC: ");

    Serial.println(
      targetAddress.toString().c_str()
    );

    bool connected =
        connectToC3(
          targetAddress,
          targetAddressType
        );

    if (!connected) {

      Serial.println(
        "[BLE] Connection failed, retry later"
      );
    }

  } else {

    Serial.println("[SCAN] Target not found");
  }
}

// ==========================
// Initialization
// ==========================

void setup() {

  Serial.begin(115200);

  delay(1500);

  // ========================
  // Initialize the LED
  // ========================

  pinMode(LED_PIN, OUTPUT);

  digitalWrite(LED_PIN, LOW);

  Serial.println();
  Serial.println("==========================");
  Serial.println(" XIAO ESP32S3 BLE RECEIVER");
  Serial.println("==========================");

  // ========================
  // Initialize BLE
  // ========================

  BLEDevice::init("XIAO_S3_LED");

  // Create the BLE client
  client = BLEDevice::createClient();

  client->setClientCallbacks(
    new ClientCallbacks()
  );

  // ========================
  // Configure BLE scanning
  // ========================

  scanner = BLEDevice::getScan();

  // Active scanning
  scanner->setActiveScan(true);

  scanner->setInterval(100);
  scanner->setWindow(90);

  Serial.println("[BLE] Scanner initialized");
  Serial.println("[BLE] Waiting for C3...");
}

// ==========================
// Main loop
// ==========================

void loop() {

  // ========================
  // Connected
  // ========================

  if (client->isConnected()) {

    // Notifications are not ready yet
    if (!notificationReady) {

      updateLED(false);

      delay(50);

      return;
    }

    // Check for signal timeout
    unsigned long now = millis();

    bool signalValid =
      lastRx != 0 &&
      (now - lastRx < SIGNAL_TIMEOUT);

    // LED state
    bool shouldOn =
      signalValid &&
      receivedCommand == '1';

    updateLED(shouldOn);

    delay(30);

    return;
  }

  // ========================
  // Disconnected
  // ========================

  updateLED(false);

  notificationReady = false;

  receivedCommand = '0';
  lastRx = 0;

  // ========================
  // Automatically scan again
  // ========================

  scanAndConnect();

  delay(500);
}
```

The receiver scans for `XIAO_C3` (or a matching BLE service UUID), connects to the server, and registers for notifications. Upon receiving `1`, the LED turns on; upon receiving `0`, it turns off. If the connection drops or no valid command is received for **1,500 ms**, the LED is turned off as a safety measure. The ESP32S3 then automatically scans again to restore the connection.

### Steps to Execute

1. Connect the ultrasonic sensor to the XIAO ESP32C3 using D0 for TRIG and D1 for ECHO, with suitable Echo voltage level shifting.
2. Connect the external LED and current-limiting resistor to D1 and GND on the XIAO ESP32S3.
3. Select the correct board and port in Arduino IDE. Upload the sender sketch to the ESP32C3 and the receiver sketch to the ESP32S3.
4. Power both boards and open their Serial Monitors at **115200 baud** if diagnostic output is required.
5. Wait for the ESP32S3 to discover `XIAO_C3`, connect, and register for BLE notifications.
6. Move an object to within **15 cm** of the ultrasonic sensor and check that the LED turns on.
7. Move the object to at least **20 cm** away and check that the LED turns off.
8. Optionally disconnect the sender's power to observe the LED switching off and the receiver attempting to reconnect.

### Results and Observations

The intended behavior of the uploaded programs is to control the LED on the ESP32S3 wirelessly based on the distance measured by the ESP32C3. The ESP32C3 Serial Monitor reports distance, requested LED state, and BLE connection status. The ESP32S3 Serial Monitor reports scanning, connection events, received commands, and LED state changes.

The test can be documented using photographs of both circuit boards, Serial Monitor screenshots, and a video demonstrating the LED turning on when an object approaches and off when it moves away. **Actual measurement screenshots and video should be inserted here; they are not included in the supplied files.**

<video src="\1.mp4" controls></video>

During our BLE communication experiment, we found that antenna configuration had a significant impact on the connection between the XIAO ESP32S3 and XIAO ESP32C3.

For the XIAO ESP32S3, connecting the external 2.4 GHz antenna was essential for reliable BLE communication. Without the antenna, the board was unable to discover the BLE signal transmitted by the ESP32C3 during our tests. After connecting the antenna, the ESP32S3 could successfully detect and connect to the ESP32C3.

In comparison, the antenna had a much smaller observable impact on the XIAO ESP32C3 in our experimental setup. The ESP32C3 was able to transmit BLE signals over a short distance, although using the antenna can improve signal strength, communication range, and connection stability.

This experiment demonstrated that antenna configuration is an important factor affecting wireless communication performance. In particular, properly connecting the external antenna to the XIAO ESP32S3 was necessary to establish a reliable BLE connection in our setup.


### Conclusion

This experiment demonstrates wireless communication between two different XIAO ESP32 development boards using Bluetooth Low Energy. The XIAO ESP32C3 acts as a sensor-equipped BLE server, while the XIAO ESP32S3 receives the commands and controls an LED. Unlike the earlier wired UART exercise, the boards communicate without a direct data cable. The use of distance thresholds, BLE notifications, automatic reconnection, and a communication timeout makes the system more stable and suitable as a simple example of distributed sensor–actuator control.
