Saturday, April 06, 2013

Raspberry Pi and TI CC2541 SensorTag


Texas Instruments have yet another low cost development kit.  The SensorTag is a Bluetooth Low Energy (BLE) key fob filled with the sorts of sensors that you'll find in the latest smartphone - pressure, temperature, humidity, accelerometer, gyroscope and magnetometer. See the SensorTag User Guide for full details.

If you're interested in experimenting with the SensorTag and you've got one of the latest iPhones, or iPads, then there's no need for you to be reading this,  pop over to Texas Instruments SensorTag page and the ByteWorks blog.  For Raspberry Pi and other Linux users I'll describe what I've figured out so far.

What you'll need

The hardware is really simple, in addition to the SensorTag which can be bought direct from TI post free, you'll need a BLE (aka Bluetooth 4.0) capable dongle.  I'm using a Plugable USB-BT4LE which can be bought on Amazon.  A PC running Linux - Ubuntu 12.10 seems to have everything needed as standard, and it was by testing on a laptop with the Plugable dongle I was able to prove to myself that the dongle and SensorTag both worked and would communicate.   However,  the rest of this post will be about using the RaspberryPi, because that's what I set out to make work.

Software

This is my first RaspberryPi project so I started with a standard Raspbian "wheezy" image.

Testing

Finding the SensorTag
$ sudo hcitool lescan

LE Scan ...
90:59:AF:0A:A8:4E (unknown)
90:59:AF:0A:A8:4E SensorTag
ctrl c

Connect to the discovered tag
$ sudo hcitool lecc 90:59:AF:0A:A8:4E

Switch on a sensor and read its value
$ gatttool -b 90:59:AF:0A:A8:4E --interactive


[   ][90:59:AF:0A:A8:4E][LE]> connect
[CON][90:59:AF:0A:A8:4E][LE]> char-read-hnd 0x25
[CON][90:59:AF:0A:A8:4E][LE]>
Characteristic value/descriptor: 00 00 00 00
[CON][90:59:AF:0A:A8:4E][LE]> char-write-cmd 0x29 01
[CON][90:59:AF:0A:A8:4E][LE]> char-read-hnd 0x25
[CON][90:59:AF:0A:A8:4E][LE]>
Characteristic value/descriptor: a3 ff 7c 06
[   ][90:59:AF:0A:A8:4E][LE]>

The values 0x25 and 0x29 are "handles" that we either read from (0x25 holds the thermometer reading) or write to (0x29 must be set to a value of 01 to turn on the thermometer)

See http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Gatt_Server for details of the sensor handles.  We can also ask the sensors to send a continuous stream of readings.  To do this enter "char-write-cmd 0x26 0100", a value of 0000 will turn the stream off.

A working program

Having figured that out I wrote a simple python script that uses pexpect to drive gatttool.  Grab a copy from github if you're interested.

Building gatttool

I had to build my own copy of gatttool as the version included in wheezy wasn't able to write values to the sensor. To build bluez-5.2 you need to "apt-get install" the following - libglib2.0-dev libdbus-1-dev libusb-dev libudev-dev libical-dev systemd libreadline-dev

See comment from Klaus Seiler on how to build.