Friday, 19 August 2016

How to switch off the need to pair your micro:bit when using Bluetooth

Pairing is the bedrock of all Bluetooth security. If you pair your micro:bit with your phone, for example, from that point on, only you can connect to and interact with your micro:bit. Imagine you were using your phone with my micro:bit Blue application to drive a  micro:bit controlled Kitronik buggy. You wouldn't want someone else connecting to it and driving it away, would you?

But not all applications need security. And pairing definitely impacts user experience. Furthermore, currently, whenever you flash a new hex file to your micro:bit, the pairing data gets wiped off your micro:bit so you have to 'forget' the pairing details on your phone and go through the entire pairing process again. Not great when you're performing develop/test cycles frequently.

Note: some changes are planned in this area. USB firmware is to be changed so that data on micro:bit, including pairing keys, will persist when new hex files are flashed. I'm also aiming to have a Block in Microsoft's PXT that lets you choose whether you want pairing or not and if you do, whether it should be based on the passkey system or Bluetooth's "Just Works" method. Watch this space for updates on both these developments.

If you're a micro:bit C/C++ developer, you can get under the hood in ways in which users of other tools often cannot. And this includes the ability to create a hex file which will result in your micro:bit not needing to be paired. Here's how.

In your project folder's root, you should have a file called config.json. All you need to do is ensure there's a property of the bluetooth json object called 'open' which has a value of 1. open=1 means 'no security'. Here's the first part of my config.json file:

{
    "microbit-dal": {
        "bluetooth": {
            "enabled": 1,
            "pairing_mode": 1,
            "open": 0,
            "dfu_service": 0,
            "event_service": 0,
            "device_info_service": 1
        },
        "gatt_table_size": "0x700"
    }
}



And that's it! Run 'yt clean' followed by 'yt build' and the resultant hex file will remove the need for your microbit to be paired when using Bluetooth.

Even with applications that need security, this is useful. You can do development and test cycles with pairing switched off, and enable it when you come to do your final testing and release build. The best of both worlds.

Use responsibly! :-)

Code it. Connect it. Bitty Software.

Saturday, 6 August 2016

micro:bit and Bluetooth range testing #2

How far can a BBC micro:bit transmit data using Bluetooth? I still don't know.

Yesterday, I went to a larger local park, primarily because there might be more Pokemon there but also because it would give the opportunity to perform another micro:bit Bluetooth range test.

Once again though I ran out of park.

This time I got to...... <drum roll>........


354 metres and my phone was still receiving data!


Phenomenal.

I stopped when I would have had to turn a corner and go out of line of sight from the micro:bit, held once again by my Trusty Assistant. To be clear.... Bluetooth does not require line of sight. Radio signals pass through objects including walls. But for optimum conditions, line of sight is best and optimum conditions is what you want when investigating maximum range.

I had started to notice that I wasn't getting all data that was being transmitted. Bluetooth accelerometer data was being transmitted by the micro:bit regularly but I could tell from my phone, not all were arriving. So 354 metres is probably close to the maximum range. That said, I walked slightly down hill and then up hill so line of sight to the micro:bit was almost at floor level and there were quite a few people using the path in between me and the micro:bit as well. So I think a bit more range can be squeezed out of the micro:bit in ideal conditions. I'll certainly test again to see if I can find that so far illusive limit.



and just for good measure, here's what I could see of Trusty Assistant at the end of the path 354 metres from me.

Yes, 354 metres is a long way!
More importantly, I caught a couple of Haunters and a few Ghastlys!



The hunt for Pokemon and micro:bit Bluetooth maximum range continues ......

Friday, 5 August 2016

micro:bit and Bluetooth range testing

How far can a BBC micro:bit transmit data using Bluetooth? I don't know. But I intend to find out.

A couple of days ago I was testing code I'd written for a Kitronik buggy which allows me to control it from my Android phone over Bluetooth and took the buggy for a spin on a local road. The changes I'd made to this release of the micro:bit code included the ability to drive in reverse and the automatic stopping of both motors if the Bluetooth connection between the smartphone and micro:bit was lost, for example if the buggy went out of range. I know that the range which Bluetooth can achieve is way further than most people think but ultimately it depends on many factors and will vary considerably from product to product so I didn't know what to expect with the BBC micro:bit.

I set to driving the buggy away from me, steering with my phone. At about 40 metres I couldn't really see the buggy very well anymore and didn't want to cause a horrible accident so I threw it into reverse and brought it back to me. I paced to the spot where I'd abandoned to verify the distance which was just under 40 of my long, approx 1 metre strides. Very scientific, I know!

Spot the buggy. It's there if you look carefully and not yet out of Bluetooth range!
A good test of my new reversing functionality but the question of the micro:bit's maximum Bluetooth range had still not been answered.

Last night my wife and I went for a walk up to our local park. The primary objective and reason for our walk was of course to hunt for Pokemon. The secondary objective was to perform another range test on the sports field in the park. Or was it the other way around? No matter :-)

The sports field is pretty big, plenty big enough for this test. This time I didn't use the buggy. It doesn't drive on grass. So instead I used my micro:bit Blue application and the micro:bit accelerometer. I set the micro:bit to transmit accelerometer data every 640ms (polling frequency set by writing to the Accelerometer Period characteristic) and walked over to one side of the sports field with my wife, or "Trusty Assistant" as I shall now refer to her. Trusty assistant was asked to stand still, holding the micro:bit by the edge connector and to avoid covering the Bluetooth antenna on the other edge. I fired up micro:bit Blue and went into the Accelerometer screen which looks like this (screenshot taken the day after the test):



See my micro:bit Bluetooth capabilities video to see this screen in action by the way.

With Trusty Assistant in position, I started my GPS Sports Watch so I could get it to measure distance for me and proceeded to pace away towards the opposite side of the field, holding my phone so I could see the screen but to the side of my body so it had line of sight to the micro:bit. I used my approx. 1 metre long paces and counted.

At 50 paces I was still receiving accelerometer data, which didn't surprise me.

At 75 paces I was still receiving data. Still not enormously surprised but definitely feeling pleased.

At 100 paces I was pleased and perhaps a little surprised and beginning to wonder if Trusty Assistant's patience might be beginning to wear out! I was also getting funny looks from other people in the park. Not surprising really, given the silly way I was walking. One woman, with her daughter even asked me "What are you doing?!" with a concerned look on her face. "I'm attempting to measure the maximum distance a BBC micro:bit can transmit data using...." (trailing off as I realise what a geek/crazy person I sound like!)  ".....errrr ... Bluetooth". The woman and her daughter noticeably quickened their pace at this point and sped off into the distance without looking back!

I'll cut this short.

At 200 paces I was still receiving data! At that point I was noticed by a bunch of approximately 13 year old girls. "Are you catching Pokemon, mate?!" one asked. "No, actually I'm attempting to...... errrr yes! That's right, I'm catching Pokemon!". I think I got away with it :-)

At more than 200 paces I ran out of park. It becomes woodland at that point and I wanted line of sight for optimum conditions so I stopped. I was still receiving data though.

GPS indicated I'd walked 0.14 miles or 225 metres and I was still receiving data. 

GPS data from my test. 0.14 miles - 225 metres!
The maximum range has therefore not yet been established and I'll return to this another day. But wow, what a result!

Surprised? Amazed? Pretty cool, huh?!

My Trusty Assistant deserves a special commendation for her patience. Here's a photo of her, taken at the 225 metre mark where I'd decided to give up the test.

Yep, 225 metres is a long way. She's over by the tree-line, honest!
When Bluetooth 5 comes along it will quadruple the maximum range by the way!

Oh and as to the primary objective.... amongst other things I did catch a Machop :-)


Technical footnote: The transmission power is one variable in the range which can be achieved. On a BBC micro:bit this can actually be controlled from software. There's a build variable in config.json called "tx_power" which takes a value of 0 (lowest power) to 7 (highest power). A default build produced using one of the editors at microbit.co.uk has tx_power set to 0 (a BBC decision) so you won't get the same range I achieved. A build created using Microsoft's PXT has it set to 6. If you use mbed or Yotta to code in C/C++ you can set it yourself though and of course I had it set to 7.

Code it. Connect it. Bitty Software.

Friday, 29 July 2016

Sending 'commands' from a micro:bit over Bluetooth

I got asked how you might use Bluetooth to send 'commands' from a micro:bit to another Bluetooth enabled device.

First read my blog on what kind of Bluetooth device can 'talk' to what kind of other device.

micro:bit has the concept of "events" which are things we can use as though they are numeric commands. An event has an ID and a value. Each are 16 bits in length so an event is a total of 32 bits long.

The micro:bit has something called the Event Service and this allows events to flow in either direction between the micro:bit and something else like a smartphone.

The Microsoft PXT tool lets you create your own event values and trigger them from anything you like in your code.

So these are our basic ingredients.

Let's walk through an example.

First, check out this application I created in PXT


You can fork the code itself here: https://codethemicrobit.com/bkrakvpxxn

You can see I create an event ID of 9010 and two associated event values of 1 and 2. I also keep track of whether or not we have a Bluetooth connection in a variable called 'connected'

Then, if the user presses button A we create an event with ID 9010 and event value 01. If the user presses button B we create an event with ID 9010 and event value 02.

That's all we need to do on the micro:bit side of things.

On the other device we have to send the micro:bit the event ID and values we're interested in being notified about if they occur.

Here's what the micro:bit Bluetooth Event Service looks like. It will help when we look at how to test this code from a smartphone next.


The blobs are called "characteristics" and they're like data items or variables that have particular purposes. Client Requirements contains a list of one or more event IDs and event values that the client (i.e. the other device) has said it's interested in. MicroBit Event contains the event ID and value of the most recent event that has happened on the micro:bit.

There's a great smartphone app for Android and iOS that lets you explore and test Bluetooth communication called nRF Connect. I'll walk through how I tested my PXT code using screenshots to illustrate:


Note: I've paired my micro:bit and phone. This is essential as at the time of writing both PXT and the microbit.co.uk tools produce code which requires your micro:bit to be paired if you're going to use Bluetooth. Here's how to pair with an iOS device and here's how to pair with Android.

There's nRF Connect on my Android phone. I launch it and it automatically scans for advertising Bluetooth devices and finds my micro:bit.


I click CONNECT to have the phone connect to the micro:bit.This gives me the next screen which shows the Bluetooth services on the micro:bit. Most were custom designed for the micro:bit so nRF Connect does not know their names.


The UUIDs are unique identifiers. The highlighted one is the event service. You can see the UUID shown here is the same as the one in the Event Service graphic above. Selecting the service causes it to expand so we can see its characteristics:


The two we're interested in are highlighted in green. 9775 is the MicroBit Event characteristic. 23C4 is the Client Requirements characteristic. The next job is to write to the Client Requirements characteristic using nRF Connect. This will transmit the value we enter to the micro:bit, effectively saying "Hey, if one of these events happens, please tell me". You start a Write operation by selecting the upwards pointing arrow icon next to the characteristic and this causes a dialogue to appear:


The second field is a drop down data type selector. I have it set to BYTE ARRAY. The value is in hex and needs some explanation. The first two bytes are the event ID of 9010. The second is the event value but 0000 means "any event values with the specified event ID". 9010 is not 0x3223 in hex though, it's 0x2332! micro:bit, in common with many other devices likes its data to arrive or be sent over comms links in 'little endian format'. So the least significant bytes come first as we read left to right and this is why we're sending 0x3223.

Now that the micro:bit knows what we're interested in, we also have to switch on "notifications" relating to the MicroBit Event characteristic. This just tells Bluetooth on the micro:bit to send the phone a message if its value changes. And it will change if one of the events we just said we were interested in happens.


Notifications are enabled by selecting the icon with multiple downward pointing arrows next to the MicroBit Event characteristic as shown.

All that's left now is to test! Pressing first button A and then button B causes the value of the MicroBit Event characteristic to change as the data is received over Bluetooth from the micro:bit. Your own code on a phone or other Central mode Bluetooth device could respond to these events anyway you choose.


That's the result of pressing Button A. Event ID 0x3234 (9010) and Event Value 0x0100 which of course is ID 9010 and value 01 in little endian format.

And button B produces....


the same result but this time the value is 02.

Simples!

Code it. Connect it. Bitty Software.

micro:bit and Bluetooth 'roles'

Bluetooth devices will play one of 4 possible Bluetooth roles as defined by that masterpiece, the Bluetooth core specification. The four roles are called
  1. Peripheral
  2. Central
  3. Broadcaster
  4. Observer
These terms are part of "GAP", the Generic Access Profile, which is a part of the Bluetooth architecture.

A Peripheral advertises, inviting and (perhaps) accepting connections from Central devices. 'Advertising' means transmitting small amounts of data, quite frequently, which other Bluetooth devices can receive and act upon if they think the advertising device is of interest.

A Central device scans, looking for advertising packets and based on their content, may decide to connect to a device it thinks is suitable.

A Broadcaster is like a peripheral in that it advertises but it does not accept connections. It's sole purpose is to advertise.

An Observer scans and processes advertising packets but never tries to connect to another device.

Examples:

The BBC micro:bit is a Peripheral.

A smartphone is typically a Central but some newer devices can also act as Peripherals with the right application software running.

A Bluetooth beacon (iBeacon, AltBeacon, EddyStone and so on) is a Broadcaster.

A beacon application on a smartphone which alerts you to special offers broadcast by beacons for example, is an Observer.

A Peripheral cannot create connections, only accept them. Therefore a Peripheral cannot connect to another Peripheral. A Peripheral cannot scan for advertising packets from other devices, only transmit them. Therefore two Peripherals cannot interact using advertising data only.

The outcome of this is that one micro:bit cannot talk to another micro:bit *directly* using Bluetooth. You'd need a Central mode device acting as a hub and relaying messages between micro:bits.  My Heart Rate Monitor video shows a smartphone acting as a Central hub which is connected to two Peripherals, a BBC micro:bit and a heart rate monitor.

Technically, a device like the BBC micro:bit could have the ability to be either (or both) a Peripheral and a Central but there's just not enough memory available on the micro:bit to squeeze the larger Bluetooth stack that would be required to support both GAP roles. Maybe as and when there's a 32K micro:bit (complete conjecture / wishful thinking!) this will happen.

That's it. An introduction to Bluetooth GAP roles and their relevance to BBC micro:bit. Amaze your friends at your next dinner party ;-)

Code it. Connect it. Bitty Software.

Implementing a Buggy controller using Microsoft's PXT tool

Ages ago I wrote the code needed to control a Kitronix buggy with a micro:bit which is itself being sent commands over Bluetooth from my microbit Blue Android application. You can see it and the C/C++ code here.

Microsoft released their amazing PXT tool fairly recently. It's fantastically flexible and you can fully exploit Bluetooth very easily. I reimplemented by buggy controller code using PXT and the results are here.

In fact I also published the project so if you want to fork it and have play, here's the URL:

https://codethemicrobit.com/rurfubdeav



Saturday, 18 June 2016

micro:bit Blue



One of the things my work with the BBC micro:bit produced is an Android application with which you can experience many of the types of things you can do with Bluetooth on the micro:bit. In the beginning I wrote the initial versions of the application to allow me to test the Bluetooth profile as it was being implemented by Lancaster University. But bit by bit (no pun intended!) it took on a life of its own and I use it all the time now to demonstrate just how much fun you can have with micro:bit and Bluetooth and in fact how much you can learn. I even used it recently as part of a Bluetooth technical training course I was involved in delivering for Bluetooth SIG in Berlin, micro:bit is not just for kids :-)

Today I renamed my application 'micro:bit Blue' and published it in Google Play. If you want to load it onto your Android phone or tablet head over to https://play.google.com/store/apps/details?id=com.bluetooth.mwoolley.microbitbledemo

Each page has a help menu by the way and there's lots of information in there about what you can do and how things work.

Enjoy!

Code it. Connect it. Bitty Software.