0
0
Drone-programmingHow-ToBeginner · 3 min read

How to Send Data Using BLE: Simple Guide for Beginners

To send data using BLE, you write data to a characteristic on the peripheral device using writeValue or similar API calls. The central device connects to the peripheral, discovers services and characteristics, then sends data by writing bytes to the chosen characteristic.
📐

Syntax

Sending data over BLE involves these steps:

  • Connect to the BLE peripheral device.
  • Discover the service and characteristic you want to write to.
  • Write data bytes to the characteristic using a write method.

Example syntax in JavaScript Web Bluetooth API:

javascript
await characteristic.writeValue(new Uint8Array([1, 2, 3]));
💻

Example

This example shows how to connect to a BLE device, find a writable characteristic, and send data bytes.

javascript
async function sendData() {
  try {
    const device = await navigator.bluetooth.requestDevice({
      filters: [{ services: ['battery_service'] }]
    });
    const server = await device.gatt.connect();
    const service = await server.getPrimaryService('battery_service');
    const characteristic = await service.getCharacteristic('battery_level');
    const data = new Uint8Array([42]);
    await characteristic.writeValue(data);
    console.log('Data sent:', data);
  } catch (error) {
    console.error('Failed to send data:', error);
  }
}

sendData();
Output
Data sent: Uint8Array(1) [42]
⚠️

Common Pitfalls

  • Not connecting to the device before writing data causes errors.
  • Trying to write to a characteristic that is not writable will fail.
  • Sending data larger than the characteristic's max size can cause truncation or failure.
  • Forgetting to handle asynchronous calls properly leads to unexpected behavior.

Always check device connection and characteristic properties before writing.

javascript
/* Wrong: Writing without connecting */
await characteristic.writeValue(new Uint8Array([1])); // Error: Not connected

/* Right: Connect first */
await device.gatt.connect();
await characteristic.writeValue(new Uint8Array([1]));
📊

Quick Reference

Remember these key points when sending data using BLE:

  • Connect to the device before any data transfer.
  • Discover the correct service and characteristic UUIDs.
  • Use writeValue or equivalent to send data bytes.
  • Handle promises or callbacks to manage asynchronous operations.
  • Check characteristic properties to confirm it supports writing.

Key Takeaways

Always connect and discover services before sending data over BLE.
Write data by sending bytes to a writable characteristic using the appropriate API.
Handle asynchronous calls carefully to avoid errors during communication.
Check characteristic properties to ensure it supports writing data.
Keep data size within the characteristic's limits to prevent failures.