The Complete Guide to nRF52 and nRF53 Firmware Development
Build nRF52 and nRF53 firmware from first LED to BLE, power, DFU and the dual-core nRF5340 with the nRF Connect SDK, Zephyr and tested register-level code.

Nordic Semiconductor's nRF52 and nRF53 series power a large share of Bluetooth Low Energy products: fitness bands, asset tags, keyboards, medical sensors and the dongles that connect them. The chips are approachable, with a Cortex-M4F or Cortex-M33 core, a radio that is configured through plain registers and a vendor SDK that is free. They are also deep, because a real product touches the radio scheduler, the power system, the bootloader, the update path and the security model. This guide is the map for the whole cluster. It takes you from choosing a chip to a connected, low-power, updatable device, with working code at every step, and it points to the focused posts that go deeper on each part. The software is the nRF Connect SDK v2.9, which is built on the Zephyr RTOS 3.7 and uses the hardware model v2 board names, and the hardware facts come from Nordic's product specifications.
What you are building on
The nRF52 and nRF53 families share a design philosophy: a general-purpose Arm core, a 2.4 GHz multiprotocol radio, a rich set of digital peripherals and an unusually good power system. The members you will meet most:
| Chip | Core | Flash | RAM | Radio | Notable |
|---|---|---|---|---|---|
| nRF52832 | Cortex-M4F, 64 MHz | 512 KB | 64 KB | BLE 5 incl. 2M PHY, ANT, proprietary | Cheapest in the family, no USB, no Coded PHY |
| nRF52840 | Cortex-M4F, 64 MHz | 1 MB | 256 KB | BLE 5 incl. 2M and Coded PHY, 802.15.4, NFC-A | USB 2.0 full speed, CryptoCell-310 |
| nRF5340 | Application Cortex-M33 at 128 MHz and network Cortex-M33 at 64 MHz | 1 MB application, 256 KB network | 512 KB application, 64 KB network | BLE 5 and 802.15.4 on the network core | Two cores, TrustZone, CryptoCell-312 |
The nRF52840 is the sweet spot for a first project: enough memory to be forgiving and every radio mode. The nRF52832 is the cost-driven choice when 64 KB of RAM is enough. The nRF5340 splits the application from the radio so that heavy application code cannot disturb Bluetooth timing, at the cost of a more complex build. The post on choosing between the three compares them in a decision table.
Three layers sit on the silicon:
The hardware: peripherals such as GPIOTE, TIMER, RTC, SAADC, UARTE, SPIM, TWIM and PWM, each with EasyDMA so data moves without the CPU.
A vendor HAL: nrfx, a set of drivers and register definitions, and the MDK with the
nrf52840.hstyle headers.An RTOS and a Bluetooth stack: in current Nordic work, Zephyr with the Zephyr Bluetooth host and Nordic's SoftDevice Controller for the radio timing.
The older nRF5 SDK with the S132 and S140 SoftDevices still exists and you will meet it in legacy code. New designs use the nRF Connect SDK, and this guide uses it throughout.
Setting up the toolchain
The nRF Connect SDK is a west workspace. West is Zephyr's meta-tool, and a workspace is a directory holding the Zephyr tree, Nordic's nrf repository, the Bluetooth controller, MCUboot and the other modules at versions that are known to fit together. Nordic's recommended path is the nRF Connect for VS Code extension pack, which installs the toolchain and the SDK from a graphical manager. The command line works the same way underneath.
With the toolchain installed through the manager, you have a shell that knows where the compiler and west live. Initialise a workspace at the v2.9.0 tag:
west init -m https://github.com/nrfconnect/sdk-nrf --mr v2.9.0 ncs
cd ncs
west updatewest init clones the manifest repository and west update fetches every module it lists, which takes a while and a few gigabytes. Afterwards ncs/ contains zephyr, nrf, nrfxlib, bootloader and more. You also need Nordic's command line tools: nrfutil for programming and the device command, which replaces the older nrfjprog. The J-Link driver comes with the tools and talks to the debugger on a development kit.
Every Nordic development kit carries an on-board J-Link OB debugger. The same USB connection provides a virtual serial port for the console, which is how log output reaches your computer.
Your first application
Create an application outside the SDK tree. Three files make a complete project.
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(blink_log)
target_sources(app PRIVATE src/main.c)CONFIG_GPIO=y
CONFIG_LOG=y
CONFIG_LOG_DEFAULT_LEVEL=3#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);
#define LED0_NODE DT_ALIAS(led0)
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
int main(void)
{
if (!gpio_is_ready_dt(&led)) {
LOG_ERR("LED GPIO is not ready");
return 0;
}
gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
int count = 0;
while (1) {
gpio_pin_toggle_dt(&led);
LOG_INF("toggle %d", count++);
k_msleep(500);
}
return 0;
}Build for the nRF52840 development kit and flash it:
west build -b nrf52840dk/nrf52840
west flashThe board name nrf52840dk/nrf52840 is the hardware model v2 form, board then SoC. With a serial terminal at 115200 baud on the kit's virtual COM port, the log shows:
*** Booting nRF Connect SDK v2.9.0 ***
[00:00:00.000,000] <inf> app: toggle 0
[00:00:00.500,000] <inf> app: toggle 1
[00:00:01.000,000] <inf> app: toggle 2The boot banner version string and the timestamps format are produced by the SDK; the structure of a log line is [hh:mm:ss.mmm,uuu] <level> module: message. The details of the first build, including the project layout and the build directory, are in the post on your first nRF Connect SDK application.
What the build actually does
DT_ALIAS(led0) and GPIO_DT_SPEC_GET are the part that confuses newcomers. Zephyr describes hardware in a devicetree. The board's .dts file declares an LED node and gives it the alias led0, with the GPIO controller, pin number and polarity. Your code asks for "whatever led0 is", so the same source builds for a different board that defines the alias differently. The compiler turns the devicetree into a header, and the macros read constants from it, so there is no run-time lookup.
prj.conf holds Kconfig options, the same system the Linux kernel uses. CONFIG_GPIO=y includes the GPIO driver and CONFIG_LOG=y the logging subsystem. A feature absent from prj.conf is not compiled in, which is why a small Zephyr image is small.
Threads, timers and the work queue
Zephyr is a real RTOS, and the main thread in the example is one thread among several. Each thread has a priority, and the scheduler is preemptive. For firmware that reacts to a button while doing periodic work, three primitives cover most needs: a timer, a work item and a semaphore or message queue.
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);
static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET(DT_ALIAS(sw0), gpios);
static struct gpio_callback button_cb;
static struct k_work button_work;
static int presses;
static void button_work_handler(struct k_work *work)
{
presses++;
gpio_pin_toggle_dt(&led);
LOG_INF("button pressed %d times", presses);
}
static void button_isr(const struct device *dev, struct gpio_callback *cb,
uint32_t pins)
{
k_work_submit(&button_work);
}
static void heartbeat_fn(struct k_timer *timer)
{
LOG_INF("alive, presses=%d", presses);
}
K_TIMER_DEFINE(heartbeat, heartbeat_fn, NULL);
int main(void)
{
gpio_pin_configure_dt(&led, GPIO_OUTPUT_INACTIVE);
gpio_pin_configure_dt(&button, GPIO_INPUT);
gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
k_work_init(&button_work, button_work_handler);
gpio_init_callback(&button_cb, button_isr, BIT(button.pin));
gpio_add_callback(button.port, &button_cb);
k_timer_start(&heartbeat, K_SECONDS(5), K_SECONDS(5));
return 0;
}The button interrupt handler does the minimum, which is to hand the work to the system work queue thread with k_work_submit. The handler that updates the LED and logs runs in thread context, where logging and mutexes are safe. The timer callback runs from the kernel's timer interrupt context, so it must not block; it only logs. main() may return, because the kernel keeps running its threads.
After two button presses and five seconds, the output is:
[00:00:01.620,000] <inf> app: button pressed 1 times
[00:00:02.340,000] <inf> app: button pressed 2 times
[00:00:05.000,000] <inf> app: alive, presses=2The press timestamps depend on you, and the heartbeat appears at 5.000 s after the timer starts. Contact bounce can produce an extra press on a mechanical button; add a debounce, such as ignoring presses for 30 ms after the last accepted one with k_uptime_get().
Bluetooth Low Energy in one page
A BLE peripheral has two jobs. It advertises, broadcasting small packets so that phones can find it, and once a central connects, it exposes data through GATT, the Generic Attribute Profile. Zephyr's Bluetooth host implements both, and Nordic's SoftDevice Controller runs the radio link layer.
Enable Bluetooth and set the device name in prj.conf:
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="SC_Sensor"
CONFIG_LOG=yAdvertise:
#include <zephyr/kernel.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/gap.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME,
sizeof(CONFIG_BT_DEVICE_NAME) - 1),
};
int main(void)
{
int err = bt_enable(NULL);
if (err) {
LOG_ERR("bt_enable failed: %d", err);
return 0;
}
LOG_INF("Bluetooth ready");
err = bt_le_adv_start(BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE,
BT_GAP_ADV_FAST_INT_MIN_2,
BT_GAP_ADV_FAST_INT_MAX_2, NULL),
ad, ARRAY_SIZE(ad), NULL, 0);
if (err) {
LOG_ERR("advertising failed: %d", err);
return 0;
}
LOG_INF("advertising as %s", CONFIG_BT_DEVICE_NAME);
return 0;
}[00:00:00.012,000] <inf> app: Bluetooth ready
[00:00:00.015,000] <inf> app: advertising as SC_SensorA phone running the nRF Connect for Mobile app now lists "SC_Sensor". The post on advertising a beacon covers non-connectable advertising, the advertising data layout and the iBeacon and Eddystone forms, and the GATT post builds a custom service.
A custom GATT service
GATT organises data as services containing characteristics. Each has a UUID, a value, properties and permissions. Here is a service with one characteristic that a phone can read and subscribe to. The 128-bit UUIDs are made up for the example.
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/bluetooth/uuid.h>
#define SVC_UUID BT_UUID_128_ENCODE(0x6e4f0001, 0x1b9a, 0x4f0e, 0x9d3a, 0x5f1c2a7b8c01)
#define TEMP_UUID BT_UUID_128_ENCODE(0x6e4f0002, 0x1b9a, 0x4f0e, 0x9d3a, 0x5f1c2a7b8c01)
static struct bt_uuid_128 svc_uuid = BT_UUID_INIT_128(SVC_UUID);
static struct bt_uuid_128 temp_uuid = BT_UUID_INIT_128(TEMP_UUID);
static int16_t temperature_centi = 2150; /* 21.50 C */
static bool notify_enabled;
static ssize_t read_temp(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
return bt_gatt_attr_read(conn, attr, buf, len, offset,
&temperature_centi, sizeof(temperature_centi));
}
static void ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
{
notify_enabled = (value == BT_GATT_CCC_NOTIFY);
}
BT_GATT_SERVICE_DEFINE(sensor_svc,
BT_GATT_PRIMARY_SERVICE(&svc_uuid),
BT_GATT_CHARACTERISTIC(&temp_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_READ, read_temp, NULL, NULL),
BT_GATT_CCC(ccc_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
);
void sensor_update(int16_t centi)
{
temperature_centi = centi;
if (notify_enabled) {
bt_gatt_notify(NULL, &sensor_svc.attrs[2], &temperature_centi,
sizeof(temperature_centi));
}
}The attribute array holds the service declaration at index 0, the characteristic declaration at 1, the characteristic value at 2 and the client characteristic configuration descriptor (CCC) at 3. bt_gatt_notify takes the value attribute, which is why the index is 2. A central writes 0x0001 to the CCC to ask for notifications, and the callback records that. The value is a little-endian signed 16-bit count of hundredths of a degree, so 2150 means 21.50 degrees.
Peripherals without the CPU
The signature feature of Nordic chips is that peripherals can talk to each other. On the nRF52 series the Programmable Peripheral Interconnect (PPI) connects an event from one peripheral to a task of another through a channel, with no interrupt and no CPU. On the nRF53 and newer chips the DPPI does the same through publish and subscribe registers. A timer compare can start an ADC sample, whose end event can trigger a DMA transfer, while the CPU sleeps.
EasyDMA is the other half. A peripheral such as UARTE, SPIM, TWIM, SAADC or PWM reads or writes RAM directly through pointer and length registers. The rule to remember is that the buffers must be in RAM, not flash, and must stay valid until the end event. The posts on PPI and DPPI and on using nrfx drivers directly develop both.
Power: where the battery life comes from
A BLE device spends nearly all its time asleep. The nRF52 power system has two modes that matter: System ON idle, where the CPU waits for an event and the RAM and low-frequency clock stay alive, and System OFF, the deepest state, where only a wake-up source survives and the RAM is lost unless retained. Zephyr's idle thread puts the chip in System ON idle automatically whenever all threads wait, so most firmware gets low current without any code.
To get the best sleep current:
Turn off the UART console in production builds with
CONFIG_SERIAL=nandCONFIG_LOG=n, because a powered UART and a high-frequency clock request keep the chip hot.Use the low-frequency 32.768 kHz clock for timing, which Zephyr does for
k_sleep, driven from the crystal when one is fitted.Lengthen the BLE connection interval and allow peripheral latency, so the radio wakes less often.
Switch off sensors and regulators you control from GPIO when idle.
The effect of the connection parameters on the average current is the subject of the connection interval post and the Power Profiler Kit II post, which measures it rather than estimating.
Storing settings and data
Flash on these chips is organised in 4 KB pages that must be erased before being rewritten, with a limited number of erase cycles. Zephyr offers the NVS and ZMS (a newer one) storage layers and the Settings subsystem on top. Enable the settings with flash and NVS:
CONFIG_FLASH=y
CONFIG_FLASH_MAP=y
CONFIG_NVS=y
CONFIG_SETTINGS=y
CONFIG_SETTINGS_NVS=y#include <zephyr/kernel.h>
#include <zephyr/settings/settings.h>
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(app);
static uint32_t boot_count;
static int boot_set(const char *name, size_t len, settings_read_cb read_cb,
void *cb_arg)
{
if (strcmp(name, "count") == 0) {
return read_cb(cb_arg, &boot_count, sizeof(boot_count)) < 0 ? -EIO : 0;
}
return -ENOENT;
}
SETTINGS_STATIC_HANDLER_DEFINE(boot, "boot", NULL, boot_set, NULL, NULL);
void storage_boot(void)
{
settings_subsys_init();
settings_load();
boot_count++;
settings_save_one("boot/count", &boot_count, sizeof(boot_count));
LOG_INF("boot count %u", boot_count);
}On the third power cycle the console reads:
[00:00:00.020,000] <inf> app: boot count 3Settings keep the value across resets because settings_save_one writes it to a flash partition. If you also run Bluetooth with bonding, the host stores its keys in the same subsystem. Write rarely: each save consumes erase cycles, and the datasheet limits them.
Updating firmware in the field
A device you cannot update is a liability. The nRF Connect SDK includes MCUboot, a secure bootloader, and the DFU support to send an image over BLE with MCUmgr and the Simple Management Protocol. The image is signed, the bootloader verifies it before running it, and a failed update can roll back to the old image. For a dongle without a debugger, the nRF52840 Dongle ships with a USB bootloader and nrfutil packages. The MCUmgr post walks through enabling it, and the dongle post shows the USB path.
Enable the Bluetooth DFU service in the application and let MCUboot manage the images:
CONFIG_BOOTLOADER_MCUBOOT=y
CONFIG_MCUMGR=y
CONFIG_MCUMGR_TRANSPORT_BT=y
CONFIG_MCUMGR_GRP_IMG=y
CONFIG_MCUMGR_GRP_OS=yWith these, west build produces zephyr/app_update.bin, a signed image that the nRF Connect Device Manager phone app or mcumgr can upload. The key that signs it is a development key in the SDK by default. Replace it with your own before shipping, and keep it offline.
Debugging
Three tools find most problems. The first is logging, which you have already used. Configure it deferred, so formatting does not run in your timing-sensitive code, and use LOG_HEXDUMP_INF for binary data. The second is the debugger: west debug starts a GDB session through the J-Link, and you can set breakpoints, read peripheral registers and inspect threads when the Zephyr thread awareness is enabled with CONFIG_DEBUG_THREAD_INFO=y. The third is the fault output. Enable CONFIG_RESET_ON_FATAL_ERROR=n while developing, and a hard fault prints the program counter and link register, which you resolve with arm-zephyr-eabi-addr2line.
arm-zephyr-eabi-addr2line -e build/zephyr/zephyr.elf -f 0x0001a2b4button_work_handler
/home/dev/blink_log/src/main.c:15The address is an example, and the function and line you get depend on your build. Attaching a debugger also matters for the readout protection: a locked chip refuses the connection until it is erased, which the APPROTECT post explains.
The two cores of the nRF5340
The nRF5340 has an application core and a network core, and each runs its own firmware image. The application core runs your application with the Bluetooth host, and the network core runs the radio controller. You build two images, and the nRF Connect SDK builds the network image for you through a child image or a sysbuild configuration. The cores communicate through shared memory and the IPC peripheral, wrapped by the Zephyr IPC service and by ipc_service with the ICMsg backend.
west build -b nrf5340dk/nrf5340/cpuapp --sysbuild--sysbuild builds the application image and the network core image hci_ipc together, and west flash programs both. The post on the network core and IPC explains the endpoints and how to send your own messages between the cores. The nRF5340 also has TrustZone, which lets the Secure Processing Environment hold keys and run code the non-secure application cannot read, and the nRF Connect SDK builds Trusted Firmware-M for this.
Security basics
Three things matter before a product ships. First, enable readout protection, so a stolen device cannot be dumped through the debug port. On the nRF52 this is the APPROTECT feature, which is enabled in the UICR, and the nRF Connect SDK enables it by default for new builds when CONFIG_NRF_APPROTECT_LOCK=y is set. Second, use Bluetooth security: pairing with LE Secure Connections, a bonded link and encrypted characteristics, with BT_GATT_PERM_READ_ENCRYPT in place of BT_GATT_PERM_READ for sensitive values. Third, use the hardware crypto where the chip has it; the nRF52840's CryptoCell-310 accelerates AES and elliptic curve operations, and the CryptoCell post shows how.
Devicetree and overlays in practice
The devicetree is the part of Zephyr that most surprises people from the bare-metal world, so it is worth a closer look. A board's .dts file lists the hardware: the CPU, the flash, the GPIO controllers, the UARTs, the I2C and SPI buses and the LEDs and buttons wired to them. Each node has properties such as compatible, status and reg. The build combines the board file with your application's overlay and generates devicetree_generated.h, which you can read in the build directory under zephyr/include/generated/.
You change hardware descriptions in an overlay file, never in the SDK. Suppose you connect a temperature sensor with an I2C address of 0x48 to the second TWI controller, and you want a different pin pair. Place boards/nrf52840dk_nrf52840.overlay next to CMakeLists.txt, and the build picks it up automatically for that board:
&pinctrl {
i2c1_custom: i2c1_custom {
group1 {
psels = <NRF_PSEL(TWIM_SDA, 0, 30)>,
<NRF_PSEL(TWIM_SCL, 0, 31)>;
};
};
i2c1_custom_sleep: i2c1_custom_sleep {
group1 {
psels = <NRF_PSEL(TWIM_SDA, 0, 30)>,
<NRF_PSEL(TWIM_SCL, 0, 31)>;
low-power-enable;
};
};
};
&i2c1 {
status = "okay";
clock-frequency = <I2C_BITRATE_FAST>;
pinctrl-0 = <&i2c1_custom>;
pinctrl-1 = <&i2c1_custom_sleep>;
pinctrl-names = "default", "sleep";
temp_sensor: tmp117@48 {
compatible = "ti,tmp117";
reg = <0x48>;
status = "okay";
};
};The pin control groups assign the SDA and SCL signals to physical pins, written as port and pin number, here P0.30 and P0.31. The sleep state with low-power-enable lets the driver put the pins into a lower-power configuration when the bus is suspended. The sensor node under &i2c1 gives the application a handle named temp_sensor, which code retrieves with DEVICE_DT_GET(DT_NODELABEL(temp_sensor)).
Two debugging habits save hours. When a node you expected is missing, look at build/zephyr/zephyr.dts, the merged tree after all overlays, and the matching .dts.pre in the same folder. And when a macro fails to expand, the error text of DT_... macros is terse, so check that status = "okay" is set, since a disabled node generates no device.
Kconfig, sysbuild and configuration layers
Kconfig options come from several layers, merged in this order: the board's default configuration, the application's prj.conf, any boards/<board>.conf for the current target and any extra file passed with -DEXTRA_CONF_FILE. A later layer overrides an earlier one. The result lands in build/zephyr/.config, and west build -t menuconfig opens an interface to explore every option and read its help text, including which options select or depend on it.
A pattern worth adopting early is a separate configuration for release and debug builds:
CONFIG_LOG=n
CONFIG_SERIAL=n
CONFIG_ASSERT=n
CONFIG_BOOTLOADER_MCUBOOT=yBuild it with west build -b nrf52840dk/nrf52840 -- -DCONF_FILE=prj_release.conf. Keeping the two files in version control avoids the situation where the shipped image has never been tested because everyone develops with logging on.
Sysbuild is the build system layer above single applications. It builds several images from one command: your application, MCUboot, and on the nRF5340 the network core image. A project-level sysbuild.conf selects what to include, for example SB_CONFIG_BOOTLOADER_MCUBOOT=y. The practical consequence is that west flash programs every image in the right place and a signing step produces update files without a custom script.
A complete example: a battery sensor that advertises and notifies
Putting the pieces together, here is a small but realistic application: it reads the battery voltage once a minute with the SAADC through Zephyr's ADC API, stores the latest reading in a GATT characteristic and sends a notification when a central has subscribed. The ADC channel comes from the devicetree through an overlay.
/ {
zephyr,user {
io-channels = <&adc 0>;
};
};
&adc {
#address-cells = <1>;
#size-cells = <0>;
status = "okay";
channel@0 {
reg = <0>;
zephyr,gain = "ADC_GAIN_1_6";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 40)>;
zephyr,input-positive = <NRF_SAADC_AIN0>;
zephyr,resolution = <12>;
};
};CONFIG_ADC=y
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="SC_Battery"
CONFIG_LOG=y#include <zephyr/kernel.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);
extern void sensor_update(int16_t centi);
static const struct adc_dt_spec adc_ch = ADC_DT_SPEC_GET_BY_IDX(DT_PATH(zephyr_user), 0);
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME,
sizeof(CONFIG_BT_DEVICE_NAME) - 1),
};
static int read_millivolts(void)
{
int16_t raw;
struct adc_sequence seq = {
.buffer = &raw,
.buffer_size = sizeof(raw),
};
adc_sequence_init_dt(&adc_ch, &seq);
if (adc_read_dt(&adc_ch, &seq) < 0) {
return -1;
}
int32_t mv = raw;
adc_raw_to_millivolts_dt(&adc_ch, &mv);
return mv;
}
int main(void)
{
adc_channel_setup_dt(&adc_ch);
bt_enable(NULL);
bt_le_adv_start(BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE,
BT_GAP_ADV_SLOW_INT_MIN,
BT_GAP_ADV_SLOW_INT_MAX, NULL),
ad, ARRAY_SIZE(ad), NULL, 0);
while (1) {
int mv = read_millivolts();
LOG_INF("battery %d mV", mv);
if (mv > 0) {
sensor_update((int16_t)mv);
}
k_sleep(K_SECONDS(60));
}
}[00:00:00.410,000] <inf> app: battery 2987 mV
[00:01:00.410,000] <inf> app: battery 2984 mVThe reading depends on your supply, so the numbers are an illustration. A few choices in this code carry over to real products. It uses the slow advertising interval constants BT_GAP_ADV_SLOW_INT_MIN and BT_GAP_ADV_SLOW_INT_MAX, 1 s to 1.2 s, because a battery sensor does not need a phone to find it within a hundred milliseconds. The loop sleeps with k_sleep, so the CPU idles between samples. The ADC gain of 1/6 and the internal 0.6 V reference give a full-scale input of 3.6 V, which suits a 3 V coin cell measured at the pin, and the datasheet describes the SAADC input range and the gain table in detail. If you measure the supply, which is the usual battery case, use the VDD input and a divider-free channel as the SAADC chapter describes, rather than an external pin.
Radio concepts you will meet
The BLE radio uses 40 channels of 2 MHz in the 2.4 GHz band. Three of them, numbered 37, 38 and 39, carry advertising packets, chosen to sit between the common Wi-Fi channels 1, 6 and 11 so that a busy Wi-Fi network does not block all of them at once. The other 37 channels carry data during a connection, which hops among them according to a channel map that adapts around interference.
The physical layer, the PHY, defines how bits become radio symbols. The 1M PHY sends one megasymbol per second and is the baseline every BLE device supports. The 2M PHY, new in Bluetooth 5, doubles the rate, which shortens airtime and so can cut energy per byte, with a slightly reduced range. The Coded PHY adds forward error correction at 500 kbit/s or 125 kbit/s and extends range, and it exists on the nRF52840 and nRF5340 but not on the nRF52832. Each choice trades throughput, range and power, and the post on throughput shows how to request the 2M PHY from the application.
A connection is a series of connection events. The central and peripheral exchange packets at the start of each event and then both radios sleep until the next. Three parameters define the rhythm: the connection interval between events, the peripheral latency, which is the number of events the peripheral may skip when it has nothing to say, and the supervision timeout, after which the link is declared lost. The central, which is usually a phone, has the final say, and the peripheral can only request changes. The post on connection parameters shows bt_conn_le_param_update and how to read what the phone actually granted.
Connection callbacks and security
An application needs to know when a central connects and disconnects, mainly to restart advertising, since a connectable advertiser stops after a connection. Register callbacks with BT_CONN_CB_DEFINE:
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(app);
extern const struct bt_data ad_data[];
extern const size_t ad_len;
static void connected(struct bt_conn *conn, uint8_t err)
{
if (err) {
LOG_ERR("connection failed (err 0x%02x)", err);
return;
}
LOG_INF("connected");
}
static void disconnected(struct bt_conn *conn, uint8_t reason)
{
LOG_INF("disconnected (reason 0x%02x)", reason);
bt_le_adv_start(BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE,
BT_GAP_ADV_FAST_INT_MIN_2,
BT_GAP_ADV_FAST_INT_MAX_2, NULL),
ad_data, ad_len, NULL, 0);
}
BT_CONN_CB_DEFINE(conn_callbacks) = {
.connected = connected,
.disconnected = disconnected,
};[00:00:12.301,000] <inf> app: connected
[00:00:41.870,000] <inf> app: disconnected (reason 0x13)Reason 0x13 is "remote user terminated connection", the code a phone sends when the user closes the app. A reason of 0x08 means connection timeout, which points to the radio link, distance or interference.
For security, a few Kconfig options turn on pairing and bonding. CONFIG_BT_SMP=y enables the Security Manager Protocol, CONFIG_BT_BONDABLE=y lets devices store keys, and CONFIG_BT_SETTINGS=y with the settings options shown earlier keeps those keys across resets. Mark a characteristic encrypted with BT_GATT_PERM_READ_ENCRYPT, and a connection that has not paired is refused the read with an insufficient-encryption error, which makes the phone start pairing. A device with a display or keypad can use passkey entry. A device with neither uses Just Works, which encrypts the link but does not protect against an active man in the middle, so choose the method by the threat.
Debugging the radio side
When a phone does not see your device, work down this list. Confirm that bt_enable returned 0, because a missing Kconfig option or a clock problem fails here. Confirm that bt_le_adv_start returned 0; a return of -ENOMEM means a buffer or advertising set shortage and -EALREADY means advertising already runs. Scan with a second radio, the nRF Connect for Mobile app or a nRF52840 Dongle running the sniffer firmware, to see whether packets leave the antenna. Check the antenna: development kits have a trace antenna, and custom boards with a bad matching network or copper under the antenna lose most of their range without any firmware symptom.
When connections drop, count what the log reports. A disconnect with reason 0x08 is a timeout, usually RF. Reason 0x3E means connection failed to be established, often because the central and peripheral disagree on timing. A series of rapid connects and disconnects with reason 0x13 points to a phone app that scans and retries.
Memory, flash layout and the UICR
The flash of the nRF52840 is 1 MB starting at address 0. Zephyr describes the layout with fixed partitions in the devicetree: with MCUboot, the bootloader sits at the bottom, followed by the two image slots, a scratch area if used, and a storage partition for settings. The build prints the result at the end of a normal build as a memory usage summary:
Memory region Used Size Region Size %age Used
FLASH: 143284 B 868 KB 16.12%
RAM: 24712 B 256 KB 9.43%
IDT_LIST: 0 GB 32 KB 0.00%The figures belong to one sample build and your numbers will differ. The region size shows the part of flash the application image may use after the bootloader and storage are reserved, so a project that outgrows it fails at link time with a "region `FLASH' overflowed" message rather than at run time.
Besides main flash, the chips have the User Information Configuration Registers, the UICR, a separate flash region holding settings that survive a normal erase of the program: the APPROTECT enable, the NFC pins configuration, the regulator output voltage on the nRF52840 and the reset pin. They are written by the programmer and are not part of your hex file unless you place them there. A common surprise is the nRF52840's REGOUT0 setting, which decides whether the regulator output on high-voltage supply mode is 1.8 V or 3.0 V; leaving it at its default of 1.8 V can brown out a 3 V sensor, and the Zephyr SoC code sets it from Kconfig.
Testing without a board
Zephyr's twister test runner and the native_sim target run application logic on the host. Business logic such as a packet parser, a state machine or a sampling filter can be built for native_sim and tested with the ztest framework, so most bugs die before they reach hardware. Keep the parts that touch the radio and the peripherals in thin modules and test the rest on the host. For hardware-in-the-loop checks, a development kit on a CI runner and west flash plus a serial log check close the loop.
#include <zephyr/ztest.h>
static int parse_centi(const uint8_t *buf)
{
return (int16_t)(buf[0] | (buf[1] << 8));
}
ZTEST(parse, test_little_endian_signed)
{
const uint8_t sample[] = {0x66, 0x08};
zassert_equal(parse_centi(sample), 2150, "expected 2150");
}
ZTEST_SUITE(parse, NULL, NULL, NULL, NULL, NULL);Running TESTSUITE parse
===================================================================
START - test_little_endian_signed
PASS - test_little_endian_signed in 0.000 seconds
===================================================================
TESTSUITE parse succeededThe sample is 0x0866, which is 2150 decimal, matching the characteristic encoding from the GATT section.
Troubleshooting table
| Symptom | Likely cause | First check |
|---|---|---|
west flash says no J-Link found | Debugger not enumerated or a driver missing | nrfutil device list |
| Flashing works, nothing runs | Wrong board target, or the chip is APPROTECT locked | Rebuild with the kit's exact target, then nrfutil device recover |
| Log output is garbled | Terminal baud rate does not match | 115200 baud, 8N1 on the kit's second virtual port |
bt_enable returns -ENOMEM or an HCI error | Missing controller Kconfig or too little RAM | Look at the merged .config for CONFIG_BT_LL_SOFTDEVICE=y |
Build error undefined reference to __device_dts_ord_... | Node disabled or driver not enabled | Set status = "okay" and the matching CONFIG_ option |
| Sketchy range | Antenna or supply issue | Measure on a development kit first |
| Battery drains in days | Console or high-frequency clock left on, short connection interval | Measure with the Power Profiler Kit II |
Where to go from here
With the guide read, the focused posts take each part to the level of a procedure you can follow with a kit on the desk. Read the SDK source for anything that surprises you: the Zephyr tree and Nordic's nrf repository are on GitHub, and the examples under samples/bluetooth in both are written by the people who maintain the stack. The product specification for the chip you picked is the reference for every register and electrical number, and the release notes of each nRF Connect SDK version list the changes that matter when you upgrade.
Structuring a project so it survives a team
A first sample fits in one file. A product does not, and a few habits keep the firmware readable after the first hundred commits. Keep the application in its own repository, separate from the SDK, and pin the SDK version in a west manifest so that every developer and the CI runner build against the same revision. A manifest file west.yml in the application repository names the nrf project and its revision, and west init -l app then creates a workspace around your repository. This is the "workspace application" layout from the Zephyr documentation, and it is what makes west update reproducible.
Split the code by responsibility rather than by file type. A drivers folder holds code that talks to a chip on your board. A services folder holds the GATT services. A app folder holds the state machine that decides what the device does. Each module exposes a small header and hides the rest. The sensor update function in the GATT example above is a module boundary: the main loop calls sensor_update and does not know that a notification may follow. When the boundaries are clean, the BLE layer can be swapped for a different transport without touching the sampling code, and the sampling code can be tested on native_sim.
Use Kconfig for your own options as well. A project-specific Kconfig file lets you declare options such as CONFIG_APP_SAMPLE_INTERVAL_SECONDS with a default, a range and a help text, and then read them in C like any other option. This beats a header full of #define constants because a build variant changes it from a configuration file, and the value shows up in menuconfig and in the generated .config, so a release build records exactly what it used.
A pre-production checklist
Before the first prototype run goes out to testers, walk through these items. Each one corresponds to a post in the cluster or a section of this guide.
Power: measure the average current over a full advertising and connection cycle with a power profiler, not a multimeter, because the radio draws spikes far shorter than a meter samples.
Clocks: if the board has a 32.768 kHz crystal, confirm that the build selects it (
CONFIG_CLOCK_CONTROL_NRF_K32SRC_XTAL=y). The RC oscillator fallback has a wide tolerance, and the SoftDevice Controller needs a tighter accuracy for long sleep intervals in a connection.Updates: perform a full update cycle on a real device, including a deliberately bad image to prove the rollback.
Security: enable readout protection, replace the development signing key and confirm that pairing requirements match the data's sensitivity.
Brown-out: check what happens when the battery sags below the minimum operating voltage while the radio transmits, since a flash write interrupted by a power loss can corrupt a settings page.
Watchdog: enable the watchdog so a hang resets the device. Zephyr provides a watchdog API, and the nRF52's WDT cannot be stopped once started, which is the property you want.
Regulatory: the radio's output power, antenna and enclosure decide certification. A module with a precertified radio saves months over a discrete design.
The watchdog is cheap insurance and short enough to show. The nRF52 WDT keeps running through sleep, and the application feeds it periodically:
#include <zephyr/kernel.h>
#include <zephyr/drivers/watchdog.h>
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(app);
static const struct device *const wdt = DEVICE_DT_GET(DT_ALIAS(watchdog0));
static int wdt_channel;
int watchdog_start(void)
{
struct wdt_timeout_cfg cfg = {
.window.min = 0,
.window.max = 10000,
.flags = WDT_FLAG_RESET_SOC,
};
wdt_channel = wdt_install_timeout(wdt, &cfg);
if (wdt_channel < 0) {
LOG_ERR("wdt_install_timeout: %d", wdt_channel);
return wdt_channel;
}
return wdt_setup(wdt, WDT_OPT_PAUSE_HALTED_BY_DBG);
}
void watchdog_feed(void)
{
wdt_feed(wdt, wdt_channel);
}With WDT_OPT_PAUSE_HALTED_BY_DBG, the watchdog stops while a debugger halts the CPU, so a breakpoint does not reset the chip. Feed it from the one place that proves the application is healthy, such as the end of the sampling loop, and not from a timer interrupt that would keep feeding while the main logic is stuck. If the loop stops feeding for ten seconds, the SoC resets and the log shows the reset reason on the next boot.
Zephyr, the nRF5 SDK and bare nrfx
There are three ways to put code on these chips, and the choice affects everything above. Zephyr with the nRF Connect SDK gives you an RTOS, portable drivers, the Bluetooth host, MCUboot and a large set of samples, at the price of a build system and a learning curve. It is the path Nordic invests in and the one with current security fixes. The older nRF5 SDK, built around the S132 and S140 SoftDevices, is a mature, smaller framework that many shipping products still use. It receives no new features, which matters for new designs. Bare nrfx drivers, with or without a small scheduler, give you the smallest firmware and the most direct control, and they are what you use for a proprietary radio protocol that does not need Bluetooth. The post on using nrfx directly shows how little code a driver call takes.
None of this is a lasting choice for the peripherals themselves. The registers are the same under all three, and an understanding of the datasheet carries over. A developer who learns the radio, the clock tree and the power system from the product specification can move between the SDKs, while one who learns only one set of API names cannot.
A reading order for the cluster
The posts in this cluster form a ladder. Read them in this order if you are starting out:
Pick the chip: the comparison of the nRF52832, nRF52840 and nRF5340.
Build and flash: the first nRF Connect SDK application and the dongle without a debug probe.
Bluetooth basics: the beacon and the custom GATT service.
Peripherals: nrfx drivers, then PPI and DPPI.
Protection and updates: APPROTECT and MCUmgr.
Tuning: connection parameters, power measurement, connection intervals and throughput.
Depth: the nRF5340 network core, the CryptoCell and MPSL timeslots.
When the nRF52 and nRF53 are the wrong choice
These chips are built for Bluetooth Low Energy, 802.15.4 and proprietary 2.4 GHz links. If you need Wi-Fi, an ESP32 is the better base. If you need a high-performance application processor, the 64 MHz Cortex-M4F is slow, and the nRF5340's application core at 128 MHz helps only so much. If you need an RTOS-free tiny build with a 8-bit budget, the AVR chips earlier in this section are cheaper. Nordic's SDK is also large: a first clone is several gigabytes, and the build system, with devicetree, Kconfig and west, has a learning curve that a bare register program does not. The payoff is a stack that handles the radio timing, the security and the updates that are hard to get right on your own.


