he LED example demonstrates the use of a read-write characteristic to control a LED through a phone app. The canonical source for this example lives at https://github.com/ARMmbed/mbed-os-example-ble/tree/master/BLE_LED

To help you create your own BLE services, we have created this service template. The LED example demonstrates the use of a read-write characteristic to control a LED through a phone app.

The template covers:

  • Setting up advertising and connection states.
  • Assigning UUIDs to the service and its characteristic.
  • Creating an input characteristic: read-write, boolean. This characteristic offers control of the LED.
  • Constructing a service class and adding it to the BLE stack.

Running the application

Requirements

The sample application can be seen on any BLE scanner on a smartphone. If you don't have a scanner on your phone, please install :

- nRF Master Control Panel for Android.

- LightBlue for iPhone.

Hardware requirements are in the main readme.

  • NOTE:* If you have more than a single mbed board (e.g. nrf51dk or mkit) you can run the BLE_LED and BLE_LEDBlinker at the same time. For more information please refer to the BLE_LEDBlinker demo.

Building instructions

Building with mbed CLI

If you'd like to use mbed CLI to build this, then you should refer to the main readme. The instructions here relate to using the developer.mbed.org Online Compiler

In order to build this example in the mbed Online Compiler, first import the example using the ‘Import’ button on the right hand side.

Next, select a platform to build for. This must either be a platform that supports BLE, for example the NRF51-DK, or one of the following:

List of platforms supporting Bluetooth Low Energy

Or you must also add a piece of hardware and the supporting library that includes a Bluetooth Low Energy driver for that hardware, for example the K64F or NUCLEO_F401RE with the X-NUCLEO-IDB05A1

List of components supporting Bluetooth Low Energy.

Once you have selected your platform, compile the example and drag and drop the resulting binary onto your board.

For general instructions on using the mbed Online Compiler, please see the mbed Handbook

Checking for success

Note: Screens captures depicted below show what is expected from this example if the scanner used is nRF Master Control Panel version 4.0.5. If you encounter any difficulties consider trying another scanner or another version of nRF Master Control Panel. Alternative scanners may require reference to their manuals.

  • Build the application and install it on your board as explained in the building instructions.
  • Open the BLE scanner on your phone.
  • Start a scan.

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/start_scan.png

figure 1 How to start scan using nRF Master Control Panel 4.0.5

  • Find your device; it should be named `LED`.

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/scan_results.png

figure 2 Scan results using nRF Master Control Panel 4.0.5

  • Establish a connection with your device.

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/connection.png

figure 3 How to establish a connection using Master Control Panel 4.0.5

  • Discover the services and the characteristics on the device. The *LED service* has the UUID `0xA000` and includes the *LED state characteristic* which has the UUID `0xA001`. Depending on your scanner, non standard 16-bit UUID's can be displayed as 128-bit UUID's. If it is the case the following format will be used: `0000XXXX-0000-1000-8000-00805F9B34FB` where `XXXX` is the hexadecimal representation of the 16-bit UUID value.

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/discovery.png

figure 4 Representation of the Led service using Master Control Panel 4.0.5

  • Open the write pannel of the *LED state* characteristic.

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/write_characteristic.png

figure 5 How to read and write a characteristic value using Master Control Panel 4.0.5

  • The characteristic accept a 1 byte value:

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/write_pannel.png

figure 6 Write characteristic pannel using Master Control Panel 4.0.5

`0x00`: LED ON

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/LED_ON.png

figure 6 Write characteristic pannel to set the LED on using Master Control Panel 4.0.5

`0x01`: LED OFF

https://developer.mbed.org/teams/mbed-os-examples/code/mbed-os-example-ble-LED/raw-file/c6a8f2b3efb6/img/LED_OFF.png

figure 6 Write characteristic pannel to set the LED off using Master Control Panel 4.0.5

  • Toggle the LED characteristic value and see the LED turn ON or turn OFF according to the value you set.

If you can see the characteristic, and the LED is turned on/off as you toggle its value, the application is working properly.

Revision:
74:51fde11a771f
Parent:
44:df8adb3bc797
--- a/source/main.cpp	Fri Dec 14 13:15:42 2018 +0000
+++ b/source/main.cpp	Mon Jan 14 10:45:49 2019 +0000
@@ -18,111 +18,146 @@
 #include <mbed.h>
 #include "ble/BLE.h"
 #include "LEDService.h"
-
-DigitalOut alivenessLED(LED1, 0);
-DigitalOut actuatedLED(LED2, 0);
-
-const static char     DEVICE_NAME[] = "LED";
-static const uint16_t uuid16_list[] = {LEDService::LED_SERVICE_UUID};
+#include "pretty_printer.h"
 
-static EventQueue eventQueue(/* event count */ 10 * EVENTS_EVENT_SIZE);
-
-LEDService *ledServicePtr;
+const static char DEVICE_NAME[] = "LED";
 
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
-{
-    (void) params;
-    BLE::Instance().gap().startAdvertising();
-}
+static EventQueue event_queue(/* event count */ 10 * EVENTS_EVENT_SIZE);
 
-void blinkCallback(void)
-{
-    alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */
-}
+class LEDDemo : ble::Gap::EventHandler {
+public:
+    LEDDemo(BLE &ble, events::EventQueue &event_queue) :
+        _ble(ble),
+        _event_queue(event_queue),
+        _alive_led(LED1, 1),
+        _actuated_led(LED2, 0),
+        _led_uuid(LEDService::LED_SERVICE_UUID),
+        _led_service(NULL),
+        _adv_data_builder(_adv_buffer) { }
 
-/**
- * This callback allows the LEDService to receive updates to the ledState Characteristic.
- *
- * @param[in] params
- *     Information about the characterisitc being updated.
- */
-void onDataWrittenCallback(const GattWriteCallbackParams *params) {
-    if ((params->handle == ledServicePtr->getValueHandle()) && (params->len == 1)) {
-        actuatedLED = *(params->data);
+    ~LEDDemo() {
+        delete _led_service;
     }
-}
 
-/**
- * This function is called when the ble initialization process has failled
- */
-void onBleInitError(BLE &ble, ble_error_t error)
-{
-    /* Initialization error handling should go here */
-}
+    void start() {
+        _ble.gap().setEventHandler(this);
+
+        _ble.init(this, &LEDDemo::on_init_complete);
+
+        _event_queue.call_every(500, this, &LEDDemo::blink);
+
+        _event_queue.dispatch_forever();
+    }
 
-void printMacAddress()
-{
-    /* Print out device MAC address to the console*/
-    Gap::AddressType_t addr_type;
-    Gap::Address_t address;
-    BLE::Instance().gap().getAddress(&addr_type, address);
-    printf("DEVICE MAC ADDRESS: ");
-    for (int i = 5; i >= 1; i--){
-        printf("%02x:", address[i]);
-    }
-    printf("%02x\r\n", address[0]);
-}
+private:
+    /** Callback triggered when the ble initialization process has finished */
+    void on_init_complete(BLE::InitializationCompleteCallbackContext *params) {
+        if (params->error != BLE_ERROR_NONE) {
+            printf("Ble initialization failed.");
+            return;
+        }
 
-/**
- * Callback triggered when the ble initialization process has finished
- */
-void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
-{
-    BLE&        ble   = params->ble;
-    ble_error_t error = params->error;
+        _led_service = new LEDService(_ble, false);
+
+        _ble.gattServer().onDataWritten(this, &LEDDemo::on_data_written);
 
-    if (error != BLE_ERROR_NONE) {
-        /* In case of error, forward the error handling to onBleInitError */
-        onBleInitError(ble, error);
-        return;
+        print_mac_address();
+
+        start_advertising();
     }
 
-    /* Ensure that it is the default instance of BLE */
-    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
-        return;
+    void start_advertising() {
+        /* Create advertising parameters and payload */
+
+        ble::AdvertisingParameters adv_parameters(
+            ble::advertising_type_t::CONNECTABLE_UNDIRECTED,
+            ble::adv_interval_t(ble::millisecond_t(1000))
+        );
+
+        _adv_data_builder.setFlags();
+        _adv_data_builder.setLocalServiceList(mbed::make_Span(&_led_uuid, 1));
+        _adv_data_builder.setName(DEVICE_NAME);
+
+        /* Setup advertising */
+
+        ble_error_t error = _ble.gap().setAdvertisingParameters(
+            ble::LEGACY_ADVERTISING_HANDLE,
+            adv_parameters
+        );
+
+        if (error) {
+            printf("_ble.gap().setAdvertisingParameters() failed\r\n");
+            return;
+        }
+
+        error = _ble.gap().setAdvertisingPayload(
+            ble::LEGACY_ADVERTISING_HANDLE,
+            _adv_data_builder.getAdvertisingData()
+        );
+
+        if (error) {
+            printf("_ble.gap().setAdvertisingPayload() failed\r\n");
+            return;
+        }
+
+        /* Start advertising */
+
+        error = _ble.gap().startAdvertising(ble::LEGACY_ADVERTISING_HANDLE);
+
+        if (error) {
+            printf("_ble.gap().startAdvertising() failed\r\n");
+            return;
+        }
     }
 
-    ble.gap().onDisconnection(disconnectionCallback);
-    ble.gattServer().onDataWritten(onDataWrittenCallback);
+    /**
+     * This callback allows the LEDService to receive updates to the ledState Characteristic.
+     *
+     * @param[in] params Information about the characterisitc being updated.
+     */
+    void on_data_written(const GattWriteCallbackParams *params) {
+        if ((params->handle == _led_service->getValueHandle()) && (params->len == 1)) {
+            _actuated_led = *(params->data);
+        }
+    }
 
-    bool initialValueForLEDCharacteristic = false;
-    ledServicePtr = new LEDService(ble, initialValueForLEDCharacteristic);
+    void blink() {
+        _alive_led = !_alive_led;
+    }
+
+private:
+    /* Event handler */
 
-    /* setup advertising */
-    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
-    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
-    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
-    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
-    ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
-    ble.gap().startAdvertising();
+    void onDisconnectionComplete(const ble::DisconnectionCompleteEvent&) {
+        _ble.gap().startAdvertising(ble::LEGACY_ADVERTISING_HANDLE);
+    }
+
+private:
+    BLE &_ble;
+    events::EventQueue &_event_queue;
+    DigitalOut _alive_led;
+    DigitalOut _actuated_led;
 
-    printMacAddress();
-}
+    UUID _led_uuid;
+    LEDService *_led_service;
 
-void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
-    BLE &ble = BLE::Instance();
-    eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
+    uint8_t _adv_buffer[ble::LEGACY_ADVERTISING_MAX_SIZE];
+    ble::AdvertisingDataBuilder _adv_data_builder;
+};
+
+/** Schedule processing of events from the BLE middleware in the event queue. */
+void schedule_ble_events(BLE::OnEventsToProcessCallbackContext *context) {
+    event_queue.call(Callback<void()>(&context->ble, &BLE::processEvents));
 }
 
 int main()
 {
-    eventQueue.call_every(500, blinkCallback);
+    BLE &ble = BLE::Instance();
+    ble.onEventsToProcess(schedule_ble_events);
 
-    BLE &ble = BLE::Instance();
-    ble.onEventsToProcess(scheduleBleEventsProcessing);
-    ble.init(bleInitComplete);
-
-    eventQueue.dispatch_forever();
+    LEDDemo demo(ble, event_queue);
+    demo.start();
 
     return 0;
 }
+