An example of creating and updating a simple GATT Service using the BLE_API
Dependencies: BLE_API mbed nRF51822
Fork of BLE_BatteryLevel by
Diff: main.cpp
- Revision:
- 12:4024aa3f72b0
- Parent:
- 8:45beed07b093
- Child:
- 13:60e095fe4b45
--- a/main.cpp Wed Nov 05 14:18:56 2014 +0000 +++ b/main.cpp Mon Dec 15 08:10:46 2014 +0000 @@ -1,5 +1,5 @@ /* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited + * Copyright (c) 2006-2014 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,67 +20,48 @@ BLEDevice ble; -DigitalOut led1(LED1); - -#define NEED_CONSOLE_OUTPUT 0 /* Set this if you need debug messages on the console; - * it will have an impact on code-size and power - * consumption. */ - -#if NEED_CONSOLE_OUTPUT -Serial pc(USBTX, USBRX); -#define DEBUG(...) { pc.printf(__VA_ARGS__); } -#else -#define DEBUG(...) /* nothing */ -#endif /* #if NEED_CONSOLE_OUTPUT */ - -BatteryService *batteryServicePtr = NULL; +DigitalOut led1(LED1, 1); +Ticker t; void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason) { - DEBUG("Disconnected handle %u!\n\r", handle); - DEBUG("Restarting the advertising process\n\r"); + printf("Disconnected handle %u!\n\r", handle); + printf("Restarting the advertising process\n\r"); ble.startAdvertising(); } -/** - * Runs once a second in interrupt context triggered by the 'ticker'; updates - * battery level if there is a connection. - */ -void periodicCallback(void) +void blink(void) { - led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */ - - if (ble.getGapState().connected) { - /* Update battery level */ - static uint8_t batt = 50; - batt++; - if (batt > 100) { - batt = 72; - } - batteryServicePtr->updateBatteryLevel(batt); - } + led1 = !led1; } int main(void) { - led1 = 1; - Ticker ticker; - ticker.attach(periodicCallback, 1); + uint8_t batteryLevel = 50; + t.attach(blink, 1.0f); - DEBUG("Initialising the nRF51822\n\r"); + printf("Initialising the nRF51822\n\r"); + ble.init(); ble.onDisconnection(disconnectionCallback); /* setup advertising */ ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED); ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); - ble.setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */ + ble.setAdvertisingInterval(Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000)); /* 1000ms; in multiples of 0.625ms. */ ble.startAdvertising(); - BatteryService batterService(ble); - batteryServicePtr = &batterService; + BatteryService batteryService(ble, batteryLevel); while (true) { - ble.waitForEvent(); + ble.waitForEvent(); // this will return upon any system event (such as an interrupt or a ticker wakeup) + + // the magic battery processing + batteryLevel++; + if (batteryLevel > 100) { + batteryLevel = 20; + } + + batteryService.updateBatteryLevel(batteryLevel); } }