BBC micro:bit

Code it. Connect it. 

Bitty Software - mobile apps for micro:bit and free coding tutorials


Table of Contents


Documentation

The micro:bit Bluetooth Profile - see menu for individual services


Development Tools

pxt.microbit.org - This is the best development tool for beginners wanting to use Bluetooth
https://www.microbit.co.uk/

Hex Files

Hex files are now located at the downloads page of the Bitty Software web site.


micro:bit Blue - The micro:bit Bluetooth demo app for Android

Most of the videos below feature an Android application I wrote to enable the testing and  demonstration of the many Bluetooth capabilities which the BBC micro:bit has. 

You can install it direct from Google Play. Search for it by name or use this URL:

https://play.google.com/store/apps/details?id=com.bluetooth.mwoolley.microbitbledemo

This application will be released as open source in the next few weeks!

Note that to use the application and enjoy your micro:bit's Bluetooth capabilities in full, you need a hex file which contains the full list of Bluetooth "services". The hex file your new micro:bit contains when you unbox it does have all the services but the animation it runs means you cannot set the LED display over Bluetooth.

There are a choice of hex files suitable for use with micro:bit Blue available from the downloads page at the Bitty Software web site


External Resources



Videos

Bitty Software Videos

The Bitty Software web site has videos of its own which are not included in the list below. Well worth checking out:

BBC micro:bit basic Bluetooth capabilities demo




BBC micro:bit Bluetooth profile overview




BBC micro:bit heart rate histogram

I've combined my love of cycling with my love of the micro:bit! Cyclists often use a training technique involving dividing their measured heart rate during a training session into 5 bands or 'zones'. They monitor the distribution of the time their heart rate has spent in each zone as a histogram during training with the aim that it have a certain shape or bias for a given intensity of training. Here's a screenshot from a cycling analytics system I use:


The heart rate zone histogram is on the right of course.

Those 5 zones got me thinking. The micro:bit has a 5 x 5 LED matrix so what if..... I somehow hooked up a heart rate monitor (over Bluetooth of course!) and displayed a real-time histogram on the micro:bit so that I had a small, wearable heart rate zone training monitor? There was only one way to find out...

micro:bit Bluetooth heart rate zone monitor

At the top of the image you can see my Bluetooth Polar heart rate monitor which I strap around my chest. It transmits heart rate measurements approximately once per second to my phone which is running my multi-purpose micro:bit demo to which I've added my new heart rate zone demo. The phone displays a histogram which is updated in real time along with other details and uses the micro:bit's Bluetooth LED Service to mirror the histogram onto the micro:bit LED grid. Simples!


BBC micro:bit heart rate histogram from Martin Woolley on Vimeo.



BBC micro:bit plays Name That Fruit!




BBC micro:bit Temperature Alarm


#include "MicroBit.h"

/*
 * Temperature Alarm
 * Uses the Bluetooth Event Service to inform registered clients whenever the temperature falls below xx or rises above yy
 */
MicroBit uBit;

uint16_t state      = 0; // 0=ok, 1=alarming because it's cold, 2=alarming because it's hot
uint16_t ok         = 0;
uint16_t any        = 0;
uint16_t temp_alarm = 9000;
uint16_t set_lower  = 9001;
uint16_t set_upper  = 9002;
uint16_t cold       = 1;
uint16_t hot        = 2;
uint8_t  upper      = 24;
uint8_t  lower      = 19;
int reading_count   = 0;

void onSetLower(MicroBitEvent e)
{
 lower = e.value;
    uBit.display.scroll("L=");
    uBit.display.scrollAsync(lower);
}

void onSetUpper(MicroBitEvent e)
{
 upper = e.value;
    uBit.display.scroll("U=");
    uBit.display.scrollAsync(upper);
}

void onTemperatureReading(MicroBitEvent e)
{
 int temperature = uBit.thermometer.getTemperature();
 reading_count++;
 if (reading_count == 10) { 
   uBit.display.scrollAsync(temperature);
   reading_count = 0;
 }
 if (temperature > upper && state == ok) {
     MicroBitEvent evt(temp_alarm, hot);
  state = hot;
  return;
 }
 if (temperature < lower && state == ok) {
     MicroBitEvent evt(temp_alarm, cold);
  state = cold;
  return;
 }
 if (temperature >= lower && temperature <= upper && state != ok) {
     MicroBitEvent evt(temp_alarm, ok);
  state = ok;
 }
}

void app_main()
{
  uBit.display.scrollAsync("TEMP ALARM");
  new MicroBitTemperatureService(*uBit.ble, uBit.thermometer);
  // listen for client events which set the upper and lower temperature limits
  uBit.MessageBus.listen(set_lower, any, onSetLower);
  uBit.MessageBus.listen(set_upper, any, onSetUpper);
  // listen to the temperature sensor
  uBit.MessageBus.listen(MICROBIT_ID_THERMOMETER, MICROBIT_THERMOMETER_EVT_UPDATE, onTemperatureReading);
}



BBC micro:bit basic Squirrel Counter



How to pair your BBC micro:bit with an Android phone or tablet



Bluetooth controlled Kitronix micro:bit buggy

Kitronik sell a nice buggy kit which is designed to follow lines on the ground. I reprogrammed it to respond to event messages delivered over Bluetooth from a smartphone application using the Bluetooth Event Service so I could remote control it.

Bluetooth controlled micro:bit buggy from Martin Woolley on Vimeo.

Information about the micro:bit Bluetooth Event Service can be found here:

http://lancaster-university.github.io/microbit-docs/ble/event-service/

And here's the micro:bit code:
/*
/*
The MIT License (MIT)

Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#include "MicroBit.h"

MicroBit uBit;

int pin0, pin8, pin12, pin16 = 0;

int drive = 0;

void onConnected(MicroBitEvent e)
{
    uBit.display.print("C");
}

void onDisconnected(MicroBitEvent e)
{
    uBit.display.scroll("D");
}

void onControllerEvent(MicroBitEvent e)
{
  uBit.serial.printf("event %d\n",e.value); 
  if (e.value == MES_DPAD_BUTTON_1_DOWN) {
      pin12 = 1;
      pin16 = 1;
      drive = 1;
  } else {
    if (e.value == MES_DPAD_BUTTON_1_UP) {
      uBit.serial.printf("2\n"); 
      pin12 = 0;
      pin16 = 0;
      drive = 0;
    }
  }
  
  if (drive == 1) {
      if (e.value == MES_DPAD_BUTTON_C_DOWN) {
          uBit.serial.printf("3\n"); 
          pin12 = 1;
          pin16 = 0;
      } else {
          if (e.value == MES_DPAD_BUTTON_D_DOWN) {
              uBit.serial.printf("4\n"); 
              pin12 = 0;
              pin16 = 1;
          } else {
              if (e.value == MES_DPAD_BUTTON_C_UP || e.value == MES_DPAD_BUTTON_D_UP) {
                  uBit.serial.printf("5\n"); 
                  pin12 = 1;
                  pin16 = 1;
              } else {
                    uBit.serial.printf("6\n"); 
              }
          }
      }
  }

  uBit.io.P0.setDigitalValue(pin0);
  uBit.io.P8.setDigitalValue(pin8);
  uBit.io.P12.setDigitalValue(pin12);
  uBit.io.P16.setDigitalValue(pin16);
  
}

int main()
{
    // Initialise the micro:bit runtime.
    uBit.init();

    uBit.display.scroll("BUGGY!");
    uBit.messageBus.listen(MES_DPAD_CONTROLLER_ID, 0, onControllerEvent); 
    uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
    uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);

    // If main exits, there may still be other fibers running or registered event handlers etc.
    // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
    // sit in the idle task forever, in a power efficient sleep.
    release_fiber();
}

The same application created with PXT

and the corresponding JavaScript:

let pin0 = 0;
let pin8 = 0;
let pin12 = 0;
let pin16 = 0;
let drive = 0;
basic.showString("ROBOT WARS!");
bluetooth.onBluetoothConnected(() => {
    basic.showString("C");
});
bluetooth.onBluetoothDisconnected(() => {
    basic.showString("D");
});
control.onEvent(control.eventSourceId(EventBusSource.MES_DPAD_CONTROLLER_ID), control.eventValueId(EventBusValue.MICROBIT_EVT_ANY), () => {
    if (control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_1_DOWN)) {
        pin12 = 1;
        pin16 = 1;
        drive = 1;
    } else if (control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_1_UP)) {
        pin12 = 0;
        pin16 = 0;
        drive = 0;
    } else { }
    if (drive == 1) {
        if (control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_C_DOWN)) {
            pin12 = 1;
            pin16 = 0;
        } else {
            if (control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_D_DOWN)) {
                pin12 = 0;
                pin16 = 1;
            } else {
                if (control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_C_UP) || control.eventValue() == control.eventValueId(EventBusValue.MES_DPAD_BUTTON_D_UP)) {
                    pin12 = 1;
                    pin16 = 1;
                } else { }
            }
        }
    }
    pins.digitalWritePin(DigitalPin.P0, pin0);
    pins.digitalWritePin(DigitalPin.P8, pin8);
    pins.digitalWritePin(DigitalPin.P12, pin12);
    pins.digitalWritePin(DigitalPin.P16, pin16);
});



The micro:bit Bluetooth Magnetometer (digital compass) Service

micro:bit contains a magnetometer or digital compass. The Bluetooth profile includes a service called the Magnetometer Service and this allows connected devices to obtain the compass bearing of the micro:bit and for it to be updated in real-time. Here's a demo.....

micro:bit Bluetooth Magnetometer (digital compass) Service Demo from Martin Woolley on Vimeo.

Information about the micro:bit Bluetooth Magnetometer Service can be found here:

http://lancaster-university.github.io/microbit-docs/ble/magnetometer-service/

And here's the micro:bit code:

/*
#include "MicroBit.h"
#include "MicroBitSamples.h"

#ifdef MICROBIT_BLE_MAGNETOMETER

MicroBit uBit;

int main()
{
    // Initialise the micro:bit runtime.
    uBit.init();
    
    // Note GATT table size increased from default in MicroBitConfig.h
    // #define MICROBIT_SD_GATT_TABLE_SIZE             0x500
    new MicroBitMagnetometerService(*uBit.ble, uBit.compass); 
    uBit.display.scroll("MAGNETOMETER");

    // If main exits, there may still be other fibers running or registered event handlers etc.
    // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
    // sit in the idle task forever, in a power efficient sleep.
    release_fiber();
}

#endif




micro:bit Animal Vegetable Mineral game using Bluetooth UART service

micro:bit now has a Bluetooth UART service which emulates serial data comms over Bluetooth low energy. I used it to implement the classic two player guessing game Animal Vegetable or Mineral. Simples!

BBC micro:bit Animal Vegetable Mineral game from Martin Woolley on Vimeo.

And here's the micro:bit code:
#include "MicroBit.h"
#include "MicroBitSamples.h"
#include "MicroBitUARTService.h"

#ifdef MICROBIT_UART

MicroBit uBit;
MicroBitUARTService *uart;

int connected = 0;

void onConnected(MicroBitEvent e)
{
    uBit.display.scroll("C");
    
    connected = 1;
    
    // my client will send ASCII strings terminated with the colon character
    ManagedString eom(":");
    
    while(1) {
        ManagedString msg = uart->readUntil(eom);
        uBit.display.scroll(msg);
    }
    
}

void onDisconnected(MicroBitEvent e)
{
    uBit.display.scroll("D");
    connected = 0;
}

void onButtonA(MicroBitEvent e)
{
    if (connected == 0) {
        uBit.display.scroll("NC");
        return;
    }
    uart->send("YES");
    uBit.display.scroll("YES");
}

void onButtonB(MicroBitEvent e)
{
    if (connected == 0) {
        uBit.display.scroll("NC");
        return;
    }
    uart->send("NO");
    uBit.display.scroll("NO");
}

void onButtonAB(MicroBitEvent e)
{
    if (connected == 0) {
        uBit.display.scroll("NC");
        return;
    }
    uart->send("GOT IT!!");
    uBit.display.scroll("GOT IT!!");
}

/*
Recommend disabling the DFU and Event services in MicroBitConfig.h since they are not needed here:

#ifndef MICROBIT_BLE_DFU_SERVICE
#define MICROBIT_BLE_DFU_SERVICE                0
#endif

#ifndef MICROBIT_BLE_EVENT_SERVICE
#define MICROBIT_BLE_EVENT_SERVICE              0
#endif

*/

int main()
{
    // Initialise the micro:bit runtime.
    uBit.init();

    uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
    uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);

       
    // Note GATT table size increased from default in MicroBitConfig.h
    // #define MICROBIT_SD_GATT_TABLE_SIZE             0x500
    uart = new MicroBitUARTService(*uBit.ble, 32, 32); 
    uBit.display.scroll("AVM");

    // If main exits, there may still be other fibers running or registered event handlers etc.
    // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
    // sit in the idle task forever, in a power efficient sleep.
    release_fiber();
}

#endif



Using the ARM mbed IDE to select Bluetooth services to include in your BBC micro:bit application

The BBC micro:bit has a default Bluetooth profile which includes a range of "services". Access to the full set of extensive Bluetooth capabilities on the micro:bit is not currently available if you use the on-line code editors Blocks, Touch Develop or the one from Code Kingdom. No Bluetooth functionality is available from mico:python either. So if you want to exploit Bluetooth on your micro:bit beyond the small number of canned use cases supported by these code editors, it is recommended that you use ARM's mbed IDE. This video shows you how, explains the issues and the workarounds to those issues.


Developing a Bluetooth music player remote control using only a smartphone



How to pair your micro:bit with an iOS device



How to pair your micro:bit with a Windows smartphone



43 comments :

  1. Hi Martin,

    Thanks for posting all this! Please, can you help with 3 further questions I have ...
    1. Do you know if there is an example anywhere to send micro:bit sensor data onto a MQTT server? (I am currently investigating using Android/Evothings as one option)
    2. Can I get a copy of the source for your Android app you developed? (I would like to create new variations of it for various different STEM projects and add the MQTT client to the app to send data onto a MQTT broker)
    3. Is it possible to get a copy of the Bluetooth profile and Bluetooth project for the micro:bit? ( I have a Cassia Hub device and would like to try to extend the range and pairing options for the microbit - To do this I need a copy of the BLE profile for the BBC Microbit to load onto the hub via their SDK so it can push/pull a transparent relay to and from the micro:bit )
    Best wishes, Gary

    ReplyDelete
  2. Hi Gary
    1. No but you'd need a gateway device anyway (for Bluetooth to IP) and so you could use the UART service to send data from attached sensors or other services related to internal sensors and then transform that into MQTT messages at your gateway node. Bluetooth SIG have a gateway implementation for Raspberry Pi. It's not perfect but getting better each release. Might help.... or if your needs are simpler you could just write something in node.js for Pi yourself.
    2. Yes and no. I donated the code to the BBC and they're supposed to be releasing it but have been saying this for months. Last date I was given was 'mid-August'. I'll revisit with them today as I really want it out there.... that was always the intention. That said, the LU documentation I wrote contains code fragments taken directly from the application.
    3. The profile itself is really just a spec and therefore yes. The implementation on micro:bit is in the micro:bit runtime AKA DAL. See https://lancaster-university.github.io/microbit-docs/ble/profile/ for docs and https://github.com/lancaster-university/microbit-dal for code.

    Would love to see what you get up to. Follow me on Twitter so I can follow back and DM you with my email address.

    ReplyDelete
  3. I seem to have fallen at the first hurdle - I loaded the Bluetooth All Services hex file as above and put uBit in pairing mode, but none of the devices I try can see it (iPad, Nexus 7, EE phone) and don't offer to pair. Why?

    ReplyDelete
  4. The only reason I can think that would happen is if the m:b is not really in pairing mode. Did you see PAIRING MODE scroll across the display?

    Try loading the "Most services, no security" hex file. This does not need pairing so you should see it advertising and be able to connect to it right away.

    With the All Services hex file, an Android device should see it when it's in pairing mode, from the Settings/Bluetooth screen.

    ReplyDelete
  5. p.s. if you can't get pairing to work, post a video of you going through the process and I'll see if I can spot any clues.

    ReplyDelete
  6. Yes, it says PAIRING MODE, and in fact it seems I can pair with a Blackberry Z10 but it's still invisible to the other 3 devices I tried. Changing to the no-security hex file makes no difference. Are there flavours of Bluetooth?

    ReplyDelete
  7. I may have answered my own question. I tried the nRF connect app on my Nexus 7 (1st gen) and it says "Device doesn't support Bluetooth Low Energy". So presumably BLE and ordinary Bluetooth aren't interoperable?

    ReplyDelete
  8. Yes, there's Bluetooth low energy (previously known as Bluetooth Smart) which the micro:bit requires and there's Bluetooth BR/EDR which is different and use for things like audio streaming. Most smartphones and tablets today support both. I not the following for Nexus 7 however: http://android.stackexchange.com/questions/70076/does-nexus-7-has-bluetooth-smart-technology

    For Apple devices the pairing process is different. You will not "see" your device in the Settings/Bluetooth page. You have to find it with an application and connect. This should trigger pairing. I use the nRF Connect (AKA nRF Master Control Panel) app. See https://www.youtube.com/watch?v=wslwyAMwMhs

    ReplyDelete
  9. Thanks. After trying various household devices seems only the Blackberry supports BLE, but that doesn't connect to the Play store. Is the APK for the Android app available directly?

    ReplyDelete
  10. Not at present (awaiting BBC). You could write a BlackBerry Qt app though... that would be cool. See https://supportforums.blackberry.com/t5/Native-Development-Knowledge/BlackBerry-10-Bluetooth-LE-resource-index/ta-p/2326147 for some of my work in this area from a former life!

    ReplyDelete
  11. I'm having some trouble with the BITTY datalogger. Th App loads onto my phone and seems to work fine if when I load the .hex file: bdl_v2_pair_max_power.hex onto my micro:bit. However, when I load the other .hex file, or a .hex file compiled from the .PXT blocks you give, the App won't work.

    ReplyDelete
    Replies
    1. Hi Neil, I've determined that there's a problem with PXT at present and this may well account for your problems. The binary code generated does not reserve enough memory for the selected Bluetooth services to be created at run-time. Microsoft are aware and are working on the issue. I expect it will be fixed very soon.

      Let me know in a week or so whether or not you still have problems.

      regards

      Martin

      Delete
    2. Hi Martin

      Thanks for the confirmation that PXT has a bluetooth problem! I was starting to think it was me!!

      Regards

      Neil.

      Delete
  12. Hi Neil, when you load the other hex file, i.e. the hex file which does not require you to pair your phone, make sure you "forget" the micro:bit from the list of Bluetooth paired devices on the phone. Hex files from PCT require pairing at present. After installing a PXT hex file (or any other hex file which requires pairing) you must always "forget" the micro:bit from the Bluetooth paired devices list and pair again, since installing a new hex file will wipe everything off the micro:bit, including Bluetooth pairing data. This latter point is an issue I'm discussing with the micro:bit foundation and Lancaster University in the hope this can be changed so that you don't need to pair again every time you install a new hex file.

    If this doesn't help, make contact through email and I'll see what I can do. Details here:

    http://www.bittysoftware.com/common.html#app_problems

    ReplyDelete
  13. Hey Martin,

    Great stuff here. I just have a quick question.

    I want to use the micro:bit to broadcast a BLE packet which contains some arbitrary data.

    No pairing required, I've got a Raspberry Pi python app "sniffing" and logging all incoming BLE packets: I've set up my config.json to allow this.

    I've had a look through your posts and couldn't find anything for this specific case. Could you direct me to a relevant post if I have missed one?

    Ideally I would just like to transmit one packet then stop, and the services described on the DAL documentation are too specific (i.e. tied to the buttons or on-board temperature sensor). I just want to fire a packet which I can set the payload data manually.

    Any ideas?

    Cheers

    ReplyDelete
  14. Hi

    you can advertise a small amount of arbitrary data in the GAP Manufacturer Data field which you can include in advertising packets. You will find it difficult to advertise just a single packet.... advertising is a periodic process. You might get away with setting the advertising frequency so that packets are sent infrequently, start advertising and then stop as soon to immediately after as you can get. I would suggest the Pi should deal with the case of possible repeated packets though, that would be a much safer approach.

    To do this, you need to work with C/C++ and will need to know your way around the micro:bit DAL. No microbit-specific APIs have been created for this use case so you'll be programming directly against the mbed APIs (which themselves sit on top of the Nordic nRF51 APIs).

    Take a look at this class for examples of setting advertising packet content and starting advertising:

    https://github.com/lancaster-university/microbit-dal/blob/master/source/bluetooth/MicroBitEddystone.cpp

    ReplyDelete
  15. p.s. the Manufacturer Data field and its format is defined in the Bluetooth Core Specification Supplement. Note that its value must start with a company ID which is something that must be registered with the Bluetooth SIG. If you're developing a product then you do need this to be set field properly. See https://www.bluetooth.com/specifications/adopted-specifications

    ReplyDelete
  16. Also see https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers

    ReplyDelete
  17. Hi Martin, is there a way (or windows10 app) to flash the micro:bit via a Bluetooth dongle (BLED112 or Bluetooth 4.0 dongle) on a windows PC?

    ReplyDelete
    Replies
    1. There's no magic way to do this that I know of. You'd need some software to perform the role of the "DFU client" and send the software in the appropriately formatted series of messages so that the DFU service on the micro:bit understands it. It's definitely technically feasible I just don't know of a DFU tool for Windows. Someone should write one! :-)

      Delete
  18. Hi Martin,

    Thanks for your swift reply.

    I'm having some issues with the Eddystone UID example. Specifically I am receiving the following error when trying to build microbit-samples/source/examples/bluetooth-eddystone-uid:

    error: 'class MicroBitBLEManager' has no member named 'advertiseEddystoneUid'

    Here are the steps to recreate the issue (on Linux):

    git clone https://github.com/lancaster-university/microbit-samples
    cd microbit-samples

    yt target bbc-microbit-classic-gcc

    cp source/examples/bluetooth-eddystone-uid/* source

    yt clean
    yt build

    Strange thing is, if I go to microbit-samples/yotta_modules/microbit-dal/source/bluetooth/MicroBitBLEManager.cpp I can quite clearly see MicroBitBLEManager does contain advertiseEddystoneUid.

    This is my first time using the yotta build system so I am unsure if it is an error on my end or something else. I have tried making a new project from scratch and it does the same.

    Do you have any suggestions to the cause of this? Its been ages since I've done C++ so I think it may be an old header file, but I've tried pulling everything from github fresh as above.

    ReplyDelete
  19. Hi

    yes, your cp command is a bit over-enthusiastic. You need to copy the config.json file to the directory above source/. It contains flags which typically drive conditional definition of source code fragments so in your case I believe what's happening is the function you need is not being ifdef'd due to the wrong config.json flags being set.

    Good luck

    Martin

    ReplyDelete
  20. Hey Martin,

    I've done as you have advised and I still get the error. My directory structure is:

    .
    ├── build
    ├── config.json
    ├── module.json
    ├── source
    │   └── main.cpp
    ├── test
    ├── yotta_modules
    └── yotta_targets

    I tried all of the other examples and they work fine, including the Eddystone URL example. It is just the UID example that doesn't work. If I find out what is causing it I'll let you know.

    Thanks for your help!

    ReplyDelete
  21. Weird. Have you tried running "yt clean"?

    ReplyDelete
    Replies
    1. I just went through the procedure and it worked fine for me. Must be an issue local to your environment I think. I recorded the whole thing. See https://youtu.be/OqU-OOkyPlQ

      Delete
  22. I tried it on a separate workstation and it worked fine, must be something to do with my install on my other PC. Thanks for the advice.

    I also solved my original query by working directly with the ble API. I took your advice of setting the advertising interval high and turning off the ble before it can send another packet. It works fine for this application.

    Essentially we have a door with a reed switch attached. We want the microbit the send a packet to the Pi to let it know that the door has been opened (reed switch opened). It works great with the microbit.

    Thanks for your help.

    ReplyDelete
  23. Cool! Sounds like a great project :-)

    ReplyDelete
  24. Hi Martin,
    I'm doing a project with the MicroBit using serial comms. If a button is pressed on the MicroBit, this is relayed to a Python program running on my laptop. Pressing button A sends a "0" and pressing button B sends a "1". Using Python's serial library (pyserial), the Python application reads in these button presses. In essence, the MicroBit acts as a controller for a Python GUI game which I have developed.
    My question is, is it possible to replace this serial comms with Bluetooth in order to have a wireless controller for this game? I can pair the MicroBit with my phone no problem thanks to your videos. Do you know what the process is for pairing the MicroBit with a laptop?
    Thanks,
    Ciarán

    ReplyDelete
  25. Hi Ciaran, yes you can do this with Bluetooth. You could either use the Button Service, which will transmit a value each time a button's state changes (0=released, 1=pressed, 2=long press) or if you must have the values you've selected, you could use the Event Service with some code on the micro:bit to respond to button interactions by transmitting events with the values you've chosen. If that's the only code you'd need to write i.e. you have no other logic you need on the micro:bit, personally I'd use the Button service.

    See https://lancaster-university.github.io/microbit-docs/ble/button-service/

    As for pairing with a Pi, yes you can do this. You don't necessarily have to at all of course. Whether or not you need to pair depends on the hex file you've installed... it's a software issue. Your choices are to use "passkey pairing", "just works pairing" or to not require pairing at all. You can control this choice in either C/C++ in the config.json file used by Yotta or in your project settings (somewhere) with the PXT tool.

    Meanwhile, I just blogged about pairing a Pi with something else using BlueZ. Hope this helps.

    http://bluetooth-mdw.blogspot.co.uk/2017/02/pairing-bbc-microbit-with-raspberry-pi.html

    Regards

    Martin

    ReplyDelete
    Replies
    1. Hi Martin,

      I am not attempting to connect to the Microbit using a Pi, rather my Windows 10 laptop.

      I put the microbit in pairing mode and could see the microbit in the list of nearby devices on my laptop. I clicked "pair" and was then prompted to enter the pairing code which I then entered. On the laptop it showed that I was paired with the MicroBit.

      I have some python code that searches for nearby bluetooth devices. But when I run this code, it does not find my Microbit.

      I'm wondering why this is?

      From looking at some documentation online, I see that there is an Android API for Bluetooth LE. I'm wondering if there is a similar one for Python which I could use with the Microbit?

      Any advice you can provide would be greatly appreciated.
      Regards,
      Ciarán

      Delete
  26. Sorry, no idea where I got that idea from! :-)

    There are several Python libraries for Bluetooth low energy. Most of them seem incomplete or "experimental" though. Google and I'm sure you'll find several. I can't recommend any one in particular however.

    As an alternative to Python you could consider Node.js. There are a couple of good libraries for it (bleno and noble).

    There may be other options.... I don't tend to do much with Bluetooth and Windows other than as a normal user to be honest.

    ReplyDelete
  27. Hi Martin,

    I looked into the node libraries you mentioned and I have been using the following Github projects. I noticed that you are a contributor.

    https://github.com/sandeepmistry/node-bbc-microbit
    https://github.com/sandeepmistry/node-bluetooth-hci-socket

    I have succeeded in running the button-listener.js script and I have successfully connected to my Microbit through Bluetooth using the noble libraries.

    However, when I press buttons on the MicroBit, nothing is reflected in the console. I think the problem is that my MicroBit is staying in "Pairing mode".

    I followed the instructions in the bluetooth-hci-socket README and installed the WinUSB driver as indicated.

    Unfortunately as a result, Bluetooth on my laptop seems to be disabled. Hence, I can't click "Pair" to pair with the MicroBit but I am "connected" to it as evidenced from the following console output:

    Scanning for microbit
    discovered microbit: id = faa3a36e7b8c, address = fa:a3:a3:6e:7b:8c
    connecting to microbit
    connected to microbit
    subscribing to buttons
    subscribed to buttons

    On the MicroBit, the typical pairing pattern is displayed. Previously, this pattern disappeared once I clicked "Pair".

    Is there a way around this? Maybe you have seen this error before.

    Thanks,
    Ciarán

    ReplyDelete
    Replies
    1. I'm not familiar with node-bluetooth-hci-socket or of using these libraries from Windows.

      What makes you think your micro:bit is still in pairing mode? Create a hex file which does not require pairing (easy from pxt.microbit.org) and test again.

      Delete
  28. Hi Martin,

    Glad I stumbled on your blog - you've got some great stuff here! I'm currently working on a book for Make about the microbit, and in one of my introductory chapters I'm testing the range of BLE. The specs read 77m, but I couldn't get any more than 8 m before my communication was lost. Yet I see you were getting upwards of 200m. Is my board defective? How were you able to get such a range? (I was using the 'Find my phone' example from the Blue app).

    Thanks for any suggestions,

    Wolf

    ReplyDelete
    Replies
    1. Hello Wolf

      what's the "Find my phone example" and the "Blue app"?

      Range is going to be a factor of three things:

      1. Transmission power: this is set in code. There's a config property called tx_power in config.json which C/C++ developers can set (or you can set it in MicroBitConfig.h if you use the online mbed editor). Set it to 7 and you have set it to the maximum.

      2. Environment: Physical barriers will attenuate signal strength. Walls. Trees. People. Plastic cases you install your micro:bit in. That said I got over 300 metres in a local park full of people and trees.

      3. Receiver sensitivity: it's just a fact that different phones perform very differently when it comes to receiving Bluetooth, working with the same transmitting micro:bit. I've seen enormous differences such as 30m with a Samsung Edge 7, 40m with an iPhone (I forget the model) and over 200m with a Google Nexus 5. I assume this is due to factors like antenna design but that's just educated guess work.

      So stating the range of a micro:bit is about no more than giving a guideline really as there are quite a few variables and you'll probably only ever have complete control over one of them (the code your micro:bit is running).

      Cheers

      Martin

      Delete
    2. Thanks for your reply, Martin! I misspoke - I was using the micro:bit app available on the Google Play Store, not the microbit:Blue app (also available there.) The 'Find my phone' app just sends a signal from a micro:bit to a paired phone and sets off an alert on the phone to allow you to find your phone. There's no way in the app to set transmission power, so that's probably a big part of the problem. I'll play around with it, and I'll be using the mbed editor and C++ code as well, so I'll keep that in mind. Thanks for the info!

      Wolf

      Delete
  29. Hi Martin.

    I'm struggling to replicate your MostServices mBed web IDE example. I'm starting from scratch, importing the MicroBit library and including its header. I edit MicroBitConfig.h as you recommend re memory, so that pairing goes OK.

    Thereafter, when I use your Android app & connect, it sees the eg accelerometer service but no data is received - I cannot animate the Microbit image on screen.

    I notive the MICROBIT_DAL_VERSION is defined as "unknown" in the header. Changing that to 1.4.8 doesn't help.

    Any ideas?

    Thanks David.

    ReplyDelete
    Replies
    1. Hi David, I'm wondering if there's an issue with how you're creating your project. The MICROBIT_DAL_VERSION constant is not the issue. I just went through the basic process, just creating an app with the accelerometer service included and with no pairing required (for simplicity) and it worked fine for me. I blogged about the process and published the project so you can review. See http://bluetooth-mdw.blogspot.co.uk/2017/04/making-microbit-accelerometer-available.html

      Hope this helps

      Martin

      Delete
    2. Thanks for taking the time to do that Martin. I copied your latest blog post, and have success. But it doesn't work on the first attempt - it behaves just as I had experienced ie "frozen". But if I persist, pressing "back", or changing the accelerometer period, or a combo of both, eventually I get acceleromter data displayed & an animated uBit.

      Went back to my previous hex & that too I can persuade to show acc data if I try hard enough!

      Thanks David.

      Delete
    3. Great, glad you got something working. nRF Connect is good for troubleshooting btw. That's weird behaviour and I can't explain it. Computers are evil though. Never forget this :-)

      Delete