ble transmitter

Dependencies:   mbed BLE_API nRF51822

transmitter_main.cpp

Committer:
jzabins2
Date:
2019-04-17
Revision:
8:2d82653c8ffd
Parent:
7:1e93ff891703
Child:
9:aa9d34bbb46c

File content as of revision 8:2d82653c8ffd:

#include "mbed.h"
#include "ble/BLE.h"

Serial pc(USBTX, USBRX);

#define LED_RED     p22
#define LED_GREEN   p21
#define LED_BLUE    p23
#define BUTTON_PIN  p17
#define BATTERY_PIN p1

DigitalOut led1(p21);

struct Packet {
    uint32_t seqNum;
    
    Packet() : seqNum(0) {}
};
uint8_t seqNum2 = 8;

BLE ble;
Packet p;
const static char DEVICE_NAME[] = "JOEY";
static volatile bool  triggerSensorPolling = false;

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising(); // restart advertising
}

void updatePayload(void)
{
//    ble.gap().updateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&p, sizeof(p));
    (p.seqNum)++;
    pc.printf("seq_num: %d\n", p.seqNum);
}

void periodicCallback(void)
{
    led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */
    updatePayload();
    
    /* Note that the periodicCallback() executes in interrupt context, so it is safer to do
     * heavy-weight sensor polling from the main thread. */
    triggerSensorPolling = true;
}

void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE &localble          = params->ble;
    ble_error_t error = params->error;
    
    if (error != BLE_ERROR_NONE) {
        return;
    }
    
    localble.gap().onDisconnection(disconnectionCallback);
    
//    localble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
//    localble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&p, sizeof(p));
    localble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&seqNum2, sizeof(seqNum2));

    
    localble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    localble.gap().setAdvertisingInterval(1000); /* 1000ms */
    localble.gap().startAdvertising();
}

int main(void)
{
    led1 = 1;
    
    Ticker ticker;
    ticker.attach(periodicCallback, 1);
    
    ble.init(bleInitComplete);
    
    /* SpinWait for initialization to complete. This is necessary because the
     * BLE object is used in the main loop below. */
    while (ble.hasInitialized()  == false) { /* spin loop */ }
    
    while (1) {
        // check for trigger from periodicCallback()
        if (triggerSensorPolling && ble.getGapState().connected) {
            triggerSensorPolling = false;
        } else {
            ble.waitForEvent(); // low power wait for event
        }
    }
}