ble_nus.c

nRF52840-MDK (boards.json id: nrf52840-mdk) · File : ble_nus.c · Language : C · Use case : Diffuser un service BLE et envoyer des mesures

BLE is the nRF52840's reason to exist: this sketch advertises a name, exposes the Nordic UART Service and pushes text frames to the nRF Connect app. The starting template of any low-power connected object.

Hardware

An nRF52840-MDK board (Nordic nRF52840, Cortex-M4F @ 64 MHz, 1 MB flash / 256 KB RAM, BLE 5 + 802.15.4) with onboard debugger, programmed in C with nRF5 SDK v17 and the S140 SoftDevice. nRF52840-MDK + a phone with the free nRF Connect app (Android/iOS).

Wiring

No wiring: the radio is onboard, the MDK carries a ceramic antenna.

How it works

The S140 SoftDevice owns the link layer; the advert carries name + service data, NUS adds RX/TX characteristics, ble_nus_string_send notifies the connected client.

Running it

Open the matching nRF5 SDK v17 example (custom_board target), paste this code into main.c, build with Segger Embedded Studio or the gcc Makefile, then flash through the onboard debugger.

Variants

Move to connectable + pairing, add the Battery Service (SAADC reading), or extend range with the Coded PHY (long-range BLE).

ble_nus.c

// nRF52840-MDK : peripheral BLE avec Nordic UART Service (NUS) sous SoftDevice S140.
// L'app "nRF Connect" voit "MDK-Capteur" et reçoit les notifications.
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "ble_advdata.h"
#include "nrf_ble_gatt.h"
#include "ble_nus.h"
#include "app_timer.h"

#define MANIFEST "MDK-Capteur"
NRF_BLE_GATT_DEF(m_gatt);
BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT);
static uint8_t trame[] = "t=21.5C";

static void conn_handle(ble_evt_t const *p, void *ctx) {
  switch (p->header.evt_id) {
    case BLE_GAP_EVT_CONNECTED:  // un client est connecté
      break;
    case BLE_GAP_EVT_DISCONNECTED:
      (void)ble_advertising_start();      // reprendre la publicité
      break;
  }
}

int main(void) {
  nrf_sdh_enable_request();
  app_timer_init();
  uint32_t ram = nrf_sdh_ble_default_cfg_set(1, NULL);
  nrf_sdh_ble_enable(&ram);
  nrf_ble_gatt_init(&m_gatt, NULL);
  ble_nus_init(&m_nus, NULL);
  ble_radio_notification_init(3, 0, NULL, false);

  ble_advdata_t adv = { .name_type = BLE_ADV_DATA_NAME_COMPLETE,
                        .p_name = MANIFEST };
  ble_advdata_service_data_t sd = { .service_uuid = BLE_NUS_UUID,
                                    .data = { .p_data = trame,
                                              .size = sizeof(trame) - 1 } };
  adv.p_service_data = &sd; adv.service_count = 1;
  ble_advertising_start(BLE_ADV_MODE_FAST);

  for (;;) {
    app_sleep();                       // le SoftDevice gère les connexions
    ble_nus_string_send(&m_nus, trame, sizeof(trame) - 1);
  }
}

← Back to the board