Bluetooth Low Energy (BLE) beacon with nRF24L01(+). Data is received and displayed by Android device (Android app source code is attached).

Dependencies:   DS1820 mbed

nRF24L01 as Bluetooth Low Energy (BLE) Broadcaster/Beacon

Temperature measured by a DS1820 sensor is broadcasted by a nRF24L01(+) module as Bluetooth Low Energy signal. Data is then received and displayed on an Android device (smartphone/tablet) with Bluetooth Low Energy (Bluetooth Smart) enabled. In order to have Bluetooth LE available your device should run Android 4.3 or more recent.

Needed parts:

Zoom in /media/uploads/hudakz/img_20150314_115402.jpg
Figure 1: The hookup and the Android app in action

It was Dmitry Grinberg who figured out how to use nRF24L01 for BLE.
Read his amazing "Bit-banging" Bluetooth Low Energy. Thank you Dmitry!
I ported the code to mbed from Lijun's repository. Read his very neat article on the topic. Thank you Lijun!


It takes just few steps to build a Temperature Beacon

  1. Connect the nRF24L01(+) module and the DS1820 sensor to the mbed board according to the pin assignment defined in main.cpp. Don't forget to connect a 4.7k Ohm resistor between the DS1820's data pin and the +3.3V pin.

    /media/uploads/hudakz/nrf24l01.png
    Figure 2: nRF24L01(+) pinout

  2. Compile the project and save the binary file to your mbed module.
  3. Enable Bluetooth on the Android device.
  4. To view the raw data, install Nordic's nRF Master Control Panel (available at Google Play for free) to your Android device. Run the app and wait until a new nRF24L01 device is found. Do not tap the CONNECT button. This device is a broadcaster and enables only one way data flow (from the mbed to the Android). To see more details, tap the found nRF24L01 device on the left side of the screen and then the small RAW button which appears on the right side just below the CONNECT button. Now you should be able to see and check the raw bytes received from the mbed.
  5. Install the Android app:
    - Download the TemperatureBeacon app to your computer's folder of choice.
    - Open the folder and copy (send via Bluetooth or USB cable) the downloaded file to your Android device.
    - To install the app, open the folder on the Android with the file downloaded in the previous step and tap it.
  6. Once the app is installed and running:
    - After a while you should see the temperature displayed on Android (See in Figure 1).
    - Data is periodically updated. To verify that, touch the DS1820 sensor and you should see some new values.

If you'd like to adapt the Android app to your taste

  • Install Android Studio onto your computer (Window, Mac, Linux). It's a fantastic IDE from Google for free.
  • Download the Android app project to your computer's folder of choice and unzip.
  • Start Android Studio, open the project downloaded in the previous step and have fun.

I have learnt a lot about Android and Bluetooth Low Energy here:
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html,
https://thenewcircle.com/s/post/1553/bluetooth_smart_le_android_tutorial

The Android app is based on:
https://github.com/devunwired/accessory-samples/tree/master/BluetoothGatt.
Thank you Dave!

Revision:
0:6f3139e3410e
Child:
1:ef3cc9be1f60
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Sat Mar 14 07:34:03 2015 +0000
@@ -0,0 +1,377 @@
+/*
+nRF24L01+ as a Bluetooth Low Energy Broadcaster/Beacon
+by hacking an nRF24L01+ module (which is under $1 per unit on eBay).
+
+Note: It works also with the older nRF24L01 modules (without the +).
+
+In this example we broadcast temperature readings measured by a DS1820 chip.
+(You can easily modify the code to broadcast some other custom data.
+ Only make sure not to exceed the 32 bytes packet length.)
+ 
+The data can be received and displayed on an Android device (smartphone/tablet)
+with Bluetooth Low Energy (Bluetooth Smart) enabled. 
+In order to have Bluetooth 4.0 available (which implements Bluetooth LE)
+your device should run Android 4.3 or later.
+
+I ported this code to mbed from Lijun's repository <https://github.com/lijunxyz/nRF24_BLE>
+Read his very neat article on the topic <http://wiki.lijun.xyz/misc-nrf24-ble.html>
+and notice the nRF24L01(+) module pinout.
+Thank you Lijun.
+
+However, it all began with Dmitry Ginsberg's amazing "Bit-banging" Bluetooth Low Energy
+<http://dmitry.gr/index.php?r=05.Projects&proj=11.%20Bluetooth%20LE%20fakery>
+Thank you Dmitry.
+
+After programming the mbed, enable Bluetooth on the Android device (smartphone/tablet). 
+To view the custom data, install "nRF Master Control Panel" from Nordic (available at Google Play Store).
+Run the app and wait until a new device "nRF24L01" is found. Do not tap the "CONNECT" button. 
+This device is an advertiser and enables only one way data flow (from the mbed to the Android).
+To see more details, tap the found device "nRF24L01" on the left side of the screen
+and then the small "RAW" button which appears on the right side just below the "CONNECT" button. 
+Then you should be able to see and check the raw bytes received from the mbed.
+That's nice. But if you would like to have more fun and see the temperature readings
+then download "Temperature Beacon" from Google Play Store or to have even bigger fun you better build your own Android app.
+It's easy (as everithing, once you know how :)
+    - Install "Android Studio" onto your PC/Mac (it's a fantastic IDE from Google for free)
+    - Download the app project from "..." to your PC/Mac folder of choice
+    - Start "Android Studio" and open the project downloaded in the previous step
+    - Connect your Android device to the PC/Mac via USB (make sure that the USB driver is installed on your PC/Mac
+      and "USB debugging" is enabled in "Developer Options" on your Android device)
+    - Run the project in "Android Studio". When you are asked, choose your Android device (phone/tablet) from the list as running device
+    - Once the app is installed and running, after a few seconds you should see on your Android the temperature readings 
+    - The data is periodically updated to have the illusion of a connected device
+    - To verify that, touch the DS1820 sensor with your finger and you should see some new readings...
+    
+I have learnt a lot from:
+<https://developer.android.com/guide/topics/connectivity/bluetooth-le.html>
+<https://thenewcircle.com/s/post/1553/bluetooth_smart_le_android_tutorial>
+and borrowed the code for Android from here:
+<https://github.com/devunwired/accessory-samples/tree/master/BluetoothGatt>
+Thank you Dave.
+ 
+ */
+
+
+#include "mbed.h"
+#include "DS1820.h"
+
+Serial serial(USBTX, USBRX);
+
+// The MAC address of BLE advertizer -- just make one up
+// If you decide to ceate more Beacons make sure that MAC address (MY_MAC) is unique (differs)
+
+#define MY_MAC_0    0x11
+#define MY_MAC_1    0x12
+#define MY_MAC_2    0x33
+#define MY_MAC_3    0x44
+#define MY_MAC_4    0x55
+#define MY_MAC_5    0x66
+
+#if defined(TARGET_LPC1768)
+SPI         spi(p11, p12, p13);     // MOSI, MISO, SCK
+DigitalOut  cs(p8);                 // CSN  (select SPI chip/slave)
+DigitalOut  ce(p14);                // CE   (enable nRF24L01+ chip)
+DS1820      ds1820(p15);
+#elif defined(TARGET_NUCLEO_F103RB)
+SPI         spi(PB_5, PB_4, PB_3);  // MOSI, MISO, SCK
+DigitalOut  cs(PB_10);              // CSN  (select SPI chip/slave)
+DigitalOut  ce(PA_8);               // CE   (enable nRF24L01+ chip)
+DS1820      ds1820(PA_9);
+#elif defined(TARGET_NUCLEO_F401RE)
+SPI         spi(PB_5, PB_4, PB_3);  // MOSI, MISO, SCK
+DigitalOut  cs(PB_10);              // CSN  (select SPI chip/slave)
+DigitalOut  ce(PA_8);               // CE   (enable nRF24L01+ chip)
+DS1820      ds1820(PA_9);
+#elif defined(TARGET_NUCLEO_F411RE)
+SPI         spi(PB_5, PB_4, PB_3);  // MOSI, MISO, SCK
+DigitalOut  cs(PB_10);              // CSN  (select SPI chip/slave)
+DigitalOut  ce(PA_8);               // CE   (enable nRF24L01+ chip)
+DS1820      ds1820(PA_9);
+
+// If your board/plaform is not present yet then uncomment
+// the following four lines and replace TARGET_YOUR_BOARD and CE_PIN as appropriate.
+
+//#elif defined(TARGET_YOUR_BOARD)
+//SPI         spi(SPI_MOSI, SPI_MISO, SPI_SCK);
+//DigitalOut  cs(SPI_CS);             // CSN  (select SPI chip/slave)
+//DigitalOut  cs(CE_PIN);             // CE   (enable nRF24L01+ chip)
+//DS1820      ds1820(DS1820_PIN);
+
+#endif
+
+uint8_t     buf[32];
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void bleCRC(const uint8_t* data, uint8_t len, uint8_t* dst) {
+
+    // implementing CRC with LFSR
+    uint8_t v, t, d;
+
+    while(len--) {
+        d = *data++;
+        for(v = 0; v < 8; v++, d >>= 1) {
+            t = dst[0] >> 7;
+            dst[0] <<= 1;
+            if(dst[1] & 0x80)
+                dst[0] |= 1;
+            dst[1] <<= 1;
+            if(dst[2] & 0x80)
+                dst[1] |= 1;
+            dst[2] <<= 1;
+
+            if(t != (d & 1)) {
+                dst[2] ^= 0x5B;
+                dst[1] ^= 0x06;
+            }
+        }
+    }
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+uint8_t swapBits(uint8_t a) {
+
+    // reverse the bit order in a single byte
+    uint8_t v = 0;
+    if(a & 0x80)
+        v |= 0x01;
+    if(a & 0x40)
+        v |= 0x02;
+    if(a & 0x20)
+        v |= 0x04;
+    if(a & 0x10)
+        v |= 0x08;
+    if(a & 0x08)
+        v |= 0x10;
+    if(a & 0x04)
+        v |= 0x20;
+    if(a & 0x02)
+        v |= 0x40;
+    if(a & 0x01)
+        v |= 0x80;
+    return v;
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void bleWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff) {
+
+    // Implementing whitening with LFSR
+    uint8_t m;
+    while(len--) {
+        for(m = 1; m; m <<= 1) {
+            if(whitenCoeff & 0x80) {
+                whitenCoeff ^= 0x11;
+                (*data) ^= m;
+            }
+
+            whitenCoeff <<= 1;
+        }
+
+        data++;
+    }
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+static inline uint8_t bleWhitenStart(uint8_t chan) {
+
+    //the value we actually use is what BT'd use left shifted one...makes our life easier
+
+    return swapBits(chan) | 2;
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void blePacketEncode(uint8_t* packet, uint8_t len, uint8_t chan) {
+
+    // Assemble the packet to be transmitted
+
+    // Length is of packet, including crc. pre-populate crc in packet with initial crc value!
+    uint8_t i, dataLen = len - 3;
+    bleCRC(packet, dataLen, packet + dataLen);
+    for(i = 0; i < 3; i++, dataLen++)
+        packet[dataLen] = swapBits(packet[dataLen]);
+    bleWhiten(packet, len, bleWhitenStart(chan));
+    for(i = 0; i < len; i++)
+        packet[i] = swapBits(packet[i]);    // the byte order of the packet should be reversed as well
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void nrfCmd(uint8_t cmd, uint8_t data) {
+
+    // Write to nRF24's register
+
+    cs = 0;
+    spi.write(cmd);
+    spi.write(data);
+    cs = 1;
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void nrfWriteByte(uint8_t cmd) {
+    // transfer only one byte
+    cs = 0;
+    spi.write(cmd);
+    cs = 1;
+}
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+void nrfWriteBytes(uint8_t* data, uint8_t len) {
+    // transfer several bytes in a row
+    cs = 0;
+    do
+    {
+        spi.write(*data++);
+    } while(--len);
+    cs = 1;
+}
+
+int main() {
+    uint8_t data[4];  
+    float*  temp = reinterpret_cast < float * > (&data[0]);
+    
+    // Chip must be deselected
+    cs = 1;
+ 
+    // Setup the spi for 8 bit data, high steady state clock,
+    // second edge capture, with a 10MHz clock rate
+    spi.format(8,0);
+    spi.frequency(10000000);
+ 
+    cs = 1;
+    ce = 0;
+
+    // Initialize nRF24L01+, setting general parameters
+    nrfCmd(0x20, 0x12);    // on, no crc, int on RX/TX done
+    nrfCmd(0x21, 0x00);    // no auto-acknowledge
+    nrfCmd(0x22, 0x00);    // no RX
+    nrfCmd(0x23, 0x02);    // 4-byte address
+    nrfCmd(0x24, 0x00);    // no auto-retransmit
+    nrfCmd(0x26, 0x06);    // 1MBps at 0dBm
+    nrfCmd(0x27, 0x3E);    // clear various flags
+    nrfCmd(0x3C, 0x00);    // no dynamic payloads
+    nrfCmd(0x3D, 0x00);    // no features
+    nrfCmd(0x31, 32);      // always RX 32 bytes
+    nrfCmd(0x22, 0x01);    // RX on pipe 0
+
+    // Set access addresses (TX address in nRF24L01) to BLE advertising 0x8E89BED6
+    // Remember that both bit and byte orders are reversed for BLE packet format
+    buf[0] = 0x30;
+    buf[1] = swapBits(0x8E);
+    buf[2] = swapBits(0x89);
+    buf[3] = swapBits(0xBE);
+    buf[4] = swapBits(0xD6);
+    nrfWriteBytes(buf, 5);
+    buf[0] = 0x2A;          // set RX address in nRF24L01, doesn't matter because RX is ignored in this case
+    nrfWriteBytes(buf, 5);
+    ds1820.begin();
+    
+    while(1) {
+        static const uint8_t    chRf[] = { 2, 26, 80 };
+        static const uint8_t    chLe[] = { 37, 38, 39 };
+        uint8_t                 i = 0;
+        uint8_t                 j = 0;
+        uint8_t                 ch = 0;
+ 
+        *temp = ds1820.read();
+        
+//        serial.printf("temp = %3.1f'C\r\n", *temp); 
+   
+        buf[i++] = 0x42;            // PDU type, given address is random; 0x42 for Android and 0x40 for iPhone
+        buf[i++] = 25;              // number of following data bytes, max 29  (CRC is not included)
+        
+        //----------------------------
+        buf[i++] = MY_MAC_0;
+        buf[i++] = MY_MAC_1;
+        buf[i++] = MY_MAC_2;
+        buf[i++] = MY_MAC_3;
+        buf[i++] = MY_MAC_4;
+        buf[i++] = MY_MAC_5;
+    
+        buf[i++] = 2;               // flags (LE-only, limited discovery mode)
+        buf[i++] = 0x01;
+        buf[i++] = 0x05;
+    
+        buf[i++] = 9;               // length of the name, including type byte
+        buf[i++] = 0x08;            // TYPE_NAME_SHORT
+        buf[i++] = 'n';
+        buf[i++] = 'R';
+        buf[i++] = 'F';
+        buf[i++] = '2';
+        buf[i++] = '4';
+        buf[i++] = 'L';
+        buf[i++] = '0';
+        buf[i++] = '1';
+    
+        buf[i++] = 5;               // length of custom data, including type byte
+        buf[i++] = 0xff;            // TYPE_CUSTOMDATA
+
+        buf[i++] = data[0];         // temperature floating point value (four bytes)
+        buf[i++] = data[1];         
+        buf[i++] = data[2];         
+        buf[i++] = data[3];         
+        //----------------------------
+        
+        buf[i++] = 0x55;            // CRC start value: 0x555555
+        buf[i++] = 0x55;
+        buf[i++] = 0x55;
+    
+        // Channel hopping
+        if(++ch == sizeof(chRf))
+            ch = 0;
+        nrfCmd(0x25, chRf[ch]);
+        nrfCmd(0x27, 0x6E);         // Clear flags
+        blePacketEncode(buf, i, chLe[ch]);
+        nrfWriteByte(0xE2);         // Clear RX Fifo
+        nrfWriteByte(0xE1);         // Clear TX Fifo
+        cs = 0;
+        spi.write(0xA0);
+        for(j = 0; j < i; j++)
+            spi.write(buf[j]);
+        cs = 1;
+    
+        nrfCmd(0x20, 0x12);         // TX on
+        ce = 1;                     // Enable Chip
+        wait_ms(50);    
+        ce = 0;                     // (in preparation of switching to RX quickly)
+        ds1820.startConversion();   // Start temperature conversion
+        wait(1);                    // Broadcasting interval (change to your needs)
+    }
+}