console_uart.c

nRF52840-MDK (boards.json id: nrf52840-mdk) · File : console_uart.c · Language : C · Use case : Afficher des messages sur la console série du debugger

The serial console rides the UART wired to the MDK debugger: lightweight printf, echo of received characters, tick counter. The first debugging tool of any nRF project, no JTAG probe needed.

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 plugged to the PC over its USB (the debugger exposes a serial port).

Wiring

No wiring when keeping the debugger pins; otherwise crossed TX/RX to a 3.3 V USB-serial adapter.

How it works

app_uart sets up the UART (configurable pins and baudrate), print formats on the stack then sends byte by byte; app_uart_get drains the RX FIFO.

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

Switch to UARTE + EasyDMA for real throughput, or redirect printf through _write (newlib) for standard printf.

console_uart.c

// nRF52840-MDK : console UART via le debugger intégré (puce J-Link/CP210x).
// Broches SDK par défaut (custom_board) : TX P0.06 / RX P0.08 — adapter si besoin.
#include <stdio.h>
#include <stdarg.h>
#include "nrf_drv_uart.h"
#include "app_uart.h"

static void uart_init(void) {
  nrf_drv_uart_config_t cfg = NRF_DRV_UART_DEFAULT_CONFIG;
  cfg.pseltxd = 6;          // TX : vérifier le schéma de la carte
  cfg.pselrxd = 8;          // RX
  cfg.baudrate = NRF_UART_BAUDRATE_115200;
  app_uart_init(&cfg);
}

static void print(const char *fmt, ...) {
  char buf[128];
  va_list ap; va_start(ap, fmt);
  int n = vsnprintf(buf, sizeof buf, fmt, ap);
  va_end(ap);
  for (int i = 0; i < n; i++) app_uart_putc(buf[i]);
}

int main(void) {
  uart_init();
  print("\nnRF52840-MDK — console OK\n");
  uint32_t n = 0;
  for (;;) {
    uint8_t octet;
    while (app_uart_get(&octet) == NRF_SUCCESS) {   // écho RX
      app_uart_putc(octet);
      print("[recu 0x%02X]\n", octet);
    }
    if (++n % 500000 == 0) print("tick %u\n", n / 500000);
  }
}

← Back to the board