Showing posts with label BLE. Show all posts
Showing posts with label BLE. Show all posts

Tuesday, 9 October 2018

nRF52832 BLE demo written in C++

Nordic's nRF5xxxxx series chips are very popular BLE chipsets, according to my own experience, comparing to the CSR solution, nRF is more flexible and powerful. For example, the nRF52832, which is used in this demo, is a full functioning Cortex M4 MCU with FPU, if you don't use their SoftDevice, it will just be a Cortex M4 MCU like any other one on the market plus a radio interface, while oh the other hand, the CSR1010 which I had a demo project with it here before is a more dedicated BLE chip with all the BLE stack inside and the user program has to stay in the external serial EEPROM. The user has very limited access to the hardwares inside, the only way is through their APIs.

Despite their chip being a really wonderful product, the nRF SDK is quiet disappointing. The only want you to use their examples and adopt it to your needs, but never tell you how you should use the SoftDevice. I felt very frustrated when I read the code in the examples, I've never read such bad structured C code ever. So many unnecessary macros and function calls, you often have to jump 3 or 4 times among the defined macros to find out which is the final SoftDevice API it calls.

Anyway, I finally figured out how to isolate the SDK code with my own, so then I can write my own code in C++, and don't use their provided peripheral libraries. I really don't like such libraries, you still have to learn how to use it and get yourself familiar with tons of API functions, won't save you any time. On the other side, controlling the hardware via the registers is much more strait forward and simpler.

The demo does a very simple job, it will generate a random value every a few seconds, and if the notification is turned on by the mobile device, the value is pushed to the mobile whenever it gets updated. Meanwhile, the mobile can send a message to the nRF52832, the message will be displayed on the 1602 LCD module when received. It is not necessarily a text message, but I use ascii text here to make it displayable.

Let's see how does it work now:

Here is the source code of the main.cpp:

#include "hd44780.h"
#include "hd44780if_nrf_4bit.h"
#include <nrf52.h> // definitions of nrf52 registers
#include <stdint.h> // definitions of common types such as uint32
#include <stdlib.h>
#include <ble.h>
#include <ble_advertising.h>
#include <ble_gatts.h>
#include <ble_gap.h>
#include <app_timer.h>
#include "start.h"

class Gpio
{
public:
Gpio()
{
NRF_P0->DIR = 0x001fc000; // set p14,15,16,17,18,19,20 output
NRF_P0->PIN_CNF[17] = 0; // connect p17 input
NRF_P0->PIN_CNF[18] = 0;
NRF_P0->PIN_CNF[19] = 0;
NRF_P0->PIN_CNF[20] = 0;
}
};

void update_value(void *p_attr_handle);

ble_gatts_hvx_params_t hvx_param;
uint16_t conn_handle;
APP_TIMER_DEF(user_timer);

Gpio gpio;

Hd44780if_nrf_4bit lcd_nrf_4bit;
Hd44780 lcd(lcd_nrf_4bit);




int main()
{
log_init();
app_timer_init();
app_timer_create(&user_timer, APP_TIMER_MODE_REPEATED, update_value);
    power_management_init();
    ble_stack_init();
    gap_params_init();
    gatt_init();
    conn_params_init();
    services_init();
    advertising_init();
    peer_manager_init();
    advertising_start();

// bt_start();
while (1)
{
idle_state_handle();
}
return 0;
}

extern "C" uint32_t bt_ext_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    uint32_t err_code;
    switch (p_ble_evt->header.evt_id)
    {
case BLE_GATTS_EVT_WRITE:
if (p_ble_evt->evt.gatts_evt.params.write.handle == svc_handles.value_handle)
{
lcd.print_string(40, (char*)p_ble_evt->evt.gatts_evt.params.write.data, p_ble_evt->evt.gatts_evt.params.write.len);
lcd.print_string("                ");
}
break;
case BLE_GAP_EVT_CONNECTED:
lcd.print_string(0, "Connected    ");
lcd.print_string(40, "                ");
conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
app_timer_start(user_timer,150000, &svc_handles2.value_handle);
break;
case BLE_GAP_EVT_DISCONNECTED:
conn_handle = BLE_CONN_HANDLE_INVALID;
app_timer_stop(user_timer);
break;
        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            break;

        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            break;
default:
break;
}
return 0;
}

extern "C" void adv_ext_handler(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;

    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
lcd.print_string(0, "Fast Advertising");
lcd.print_string(40, "Interval 100ms  ");
            break;
case BLE_ADV_EVT_SLOW:
lcd.print_string(0, "Slow Advertising");
lcd.print_string(40, "Interval 500ms  ");
break;
        case BLE_ADV_EVT_IDLE:
lcd.print_string(0, "Idle.           ");
lcd.print_string(40, "                ");
//            sleep_mode_enter();
            break;
        default:
            break;
    }
}

void update_value(void *p_attr_handle)
{
uint16_t len = sizeof(sensor_value);

sensor_value = rand()%0xff;
hvx_param.type = BLE_GATT_HVX_NOTIFICATION;
hvx_param.handle = *(uint16_t*)p_attr_handle;
hvx_param.p_data = &sensor_value;
hvx_param.p_len = &len;
lcd.print_string(12, "0x");
lcd.print_hex(sensor_value);
if (conn_handle != BLE_CONN_HANDLE_INVALID)
{
sd_ble_gatts_hvx(conn_handle, &hvx_param);
}
}

The "Gpio" class initialises the I/O ports, and the important thing: to introduce the bt_ext_handler() and adv_ext_handler() functions to the original main.c (which is renamed as start.c) by the ext_handler.h file, and adopt these 2 event handlers to the BLE stack:

1.  in the ble_stack_init(), add this line to register BLE event handler:
NRF_SDH_BLE_OBSERVER(m_ext_observer, APP_BLE_OBSERVER_PRIO, bt_ext_handler, NULL);

2.  change the line to assign advertising event handler in advertising_init():
init.evt_handler = adv_ext_handler;

The reason to do this is these are the most likely two parts to have interactions with the user code.

Thursday, 7 December 2017

CSR1010 Bluetooth Low Energy (BLE) Demo With Source

There are many Bluetooth Low Energy chips on the market, by a chance I got a CSR development system and did some experiments with it.

CSR1010 is a BLE SoC and the development system is based on C. You don't need to deal with the low level Bluetooth protocols, all you need to do is creating your own service and using the APIs.

To be honest, the CSR development system has only very limited debugging abilities, you can somewhat debug your code doing such as 'stepping' and set break point, but there's no way you can see the values of your variables, so it makes little sense to do the debugging.

Fortunately, my code runs and it seems OK.

Let's describe the functionalities of this simple demo first, besides the basic mandatory BLE services, there is only one user service created, it has 2 characteristics, one is feeding a random data of 1 byte to the client, when the notification is turned on, the Bluetooth board will push the data to the mobile phone every 2 seconds. And the another one is 24-bit and has both read and write properties, this data is used to control the tri-color LED on board. The MSB byte is for the red LED, the LSB is used to control the blue. The number controls the duty cycle of the PWM, 0 is OFF, and set to 0xff you get 100% duty cycle the LED will be in full brightness.

The user service is created like this:

#ifndef JJ_TEST_SERVICE_H
#define JJ_TEST_SERVICE_H

primary_service
{
    uuid : 333f5834-123e-4f2b-9da8-8e863c322e5f,
    name : "JJ_test_service",
    
    characteristic
    {
        uuid : e8069f93-c150-48ef-a02d-589b652e9538,
        name : "RANDOM_NUMBER",
        flags : [FLAG_IRQ, FLAG_ENCR_R],
        properties : [read, notify],
        value : 0x00,
        client_config
        {
            flags : [FLAG_IRQ],
            name : "RANDOM_NUMBER_C_CFG"
        }
    },
    
    characteristic
    {
        uuid : d1dea016-a7fb-4dfa-84c5-b24158669e20,
        name : "LIGHT_CTL",
        flags : [FLAG_IRQ, FLAG_ENCR_R],
        properties : [read, write],
        size_value : 3
    }
}


#endif

This demo is based on the CSR demo application "gatt_server", as the whole source code is too much, I only include the user created part here.

JJ_test_service.c:

/*============================================================================*
 *  SDK Header Files
 *===========================================================================*/

#include <gatt.h>           /* GATT application interface */
#include <buf_utils.h>      /* Buffer functions */
#include <random.h>
#include <pio.h>


/*============================================================================*
 *  Local Header Files
 *===========================================================================*/

#include "gatt_server.h"    /* Definitions used throughout the GATT server */
#include "app_gatt_db.h"    /* GATT database definitions */
#include "JJ_test_service.h"

#define PIO_BUTTON      1          /* PIO connected to the button on CSR10xx */
#define PIO_LED_RED     9          /* PIO connected to the RED on CSR10xx */
#define PIO_LED_GREEN   10           /* PIO connected to the GREEN on CSR10xx */
#define PIO_LED_BLUE    11          /* PIO connected to the BLUE on CSR10xx */

#define PIO_DIR_OUTPUT  TRUE        /* PIO direction configured as output */
#define PIO_DIR_INPUT   FALSE       /* PIO direction configured as input */

gatt_client_config jj_client_cfg;
typedef struct _LIGHT_CTL
{
    uint8   red;
    uint8   green;
    uint8   blue;
} LIGHT_CTL;

LIGHT_CTL jj_light_ctrl;

extern void JJ_Test_InitChipReset(void)
{
    PioSetMode(PIO_LED_RED, pio_mode_pwm3);
    PioSetMode(PIO_LED_GREEN, pio_mode_pwm1);
    PioSetMode(PIO_LED_BLUE, pio_mode_pwm2);
    PioSetDir(PIO_LED_RED, PIO_DIR_OUTPUT);
    PioSetDir(PIO_LED_GREEN, PIO_DIR_OUTPUT);
    PioSetDir(PIO_LED_BLUE, PIO_DIR_OUTPUT);
    PioEnablePWM(1, TRUE);
    PioEnablePWM(2, TRUE);
    PioEnablePWM(3, TRUE);
    PioConfigPWM(3, pio_pwm_mode_inverted_push_pull,
                 0, 255, 0,
                 0, 255, 255, 0);
    PioConfigPWM(1, pio_pwm_mode_inverted_push_pull,
                 0, 255, 0,
                 0, 255, 255, 0);
    PioConfigPWM(2, pio_pwm_mode_inverted_push_pull,
                 0, 255, 255,
                 0, 255, 255, 0);
}

extern void JJ_Test_DataInit(void)
{
    jj_client_cfg = gatt_client_config_none;
}

extern void JJ_Test_ReadDataFromNVM(uint16 *nvm_offset)
{
}

extern bool JJ_Test_CheckHandleRange(uint16 handle)
{
    return ((handle >= HANDLE_JJ_test_service) &&
            (handle <= HANDLE_JJ_test_service_END))
            ? TRUE : FALSE;
}

extern void JJ_Test_HandleAccessRead(GATT_ACCESS_IND_T *p_ind)
{
    sys_status rc = sys_status_success; /* Function status */
    uint16 result;
    switch (p_ind->handle)
    {
        case    HANDLE_RANDOM_NUMBER:
            result = Random16();
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 1, (uint8*)&result);
            break;
        case    HANDLE_RANDOM_NUMBER_C_CFG:
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 2, (uint8*)&jj_client_cfg);
            break;
        case    HANDLE_LIGHT_CTL:
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 3, (uint8*)&jj_light_ctrl);
            break;
        default:
            rc = gatt_status_read_not_permitted;
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 0, NULL);
    }
}

extern void JJ_Test_HandleAccessWrite(GATT_ACCESS_IND_T *p_ind)
{
    sys_status rc = sys_status_success; /* Function status */
    switch (p_ind->handle)
    {
        case    HANDLE_RANDOM_NUMBER_C_CFG:
            jj_client_cfg = BufReadUint16(&p_ind->value);
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 0, NULL);
            break;
        case    HANDLE_LIGHT_CTL:
            jj_light_ctrl = *((LIGHT_CTL*)p_ind->value);
            PioConfigPWM(3, pio_pwm_mode_inverted_push_pull,
                         jj_light_ctrl.red, 255-jj_light_ctrl.red, 0,
                         jj_light_ctrl.red, 255-jj_light_ctrl.red, 255, 0);
            PioConfigPWM(1, pio_pwm_mode_inverted_push_pull,
                         jj_light_ctrl.green, 255-jj_light_ctrl.green, 0,
                         jj_light_ctrl.green, 255-jj_light_ctrl.green, 255, 0);
            PioConfigPWM(2, pio_pwm_mode_inverted_push_pull,
                         jj_light_ctrl.blue, 255-jj_light_ctrl.blue, 0,
                         jj_light_ctrl.blue, 255-jj_light_ctrl.blue, 255, 0);
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 0, NULL);
        default:
            rc = gatt_status_write_not_permitted;
            GattAccessRsp(p_ind->cid, p_ind->handle, rc, 0, NULL);
    }
}

void notificationTimerHandler(timer_id tid)
{
    uint16   temp;
    temp = Random16();
    if (jj_client_cfg == gatt_client_config_notification)
    {
        GattCharValueNotification (GetConnectionID(), HANDLE_RANDOM_NUMBER, 1, (uint8*)&temp);
    }
    TimerCreate(2*SECOND, TRUE, notificationTimerHandler);
}

As CSR is not providing a mobile phone app to be used, I'll use a generic BLE app from Nordic, another Bluetooth chip manufacture. That seems a bit weird but it works.

A video: