BLE radio support

This commit is contained in:
cpq committed 2026-11-25 13:58:07 +00:00
1 parent a8d6573ccc
commit 76fbf3c713
82 files changed
+7047 -4893

No files matched your search

-67
View File
@@ -1,67 +0,0 @@
# XIAO nRF52840: USB Ethernet and serial with Mongoose
One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM
serial port that carries the Mongoose log. The nRF52840 USB device controller
is driven directly: no TinyUSB, SoftDevice, Ethernet PHY, or lwIP. Mongoose
provides TCP/IP, a DHCP server, and HTTP/HTTPS servers.
The USB code is a Mongoose driver, `src/drivers/usb_nrf52.c`. In
`mongoose_config.h`, `MG_ENABLE_DRIVER_USB_NRF52` selects it, and
`MG_ENABLE_USB_ETHERNET` and `MG_ENABLE_USB_SERIAL` turn on its two
functions. Mongoose runs it from `mg_mgr_init()` and `mg_mgr_poll()`, so
`main.c` only sets up the clock, the LED, and the HTTP listeners.
## Build and flash
Install the Arm GNU toolchain and `adafruit-nrfutil`
(`pip install adafruit-nrfutil`). The first build fetches CMSIS and Nordic's
nrfx, for the device headers and the startup code.
```sh
make
make flash PORT=/dev/cu.usbmodemXXXX
```
The board keeps its Adafruit bootloader. The application starts at 0x27000,
above the area reserved for the SoftDevice, which is not used. `make flash`
opens the serial port at 1200 baud, which reboots the firmware into the
bootloader, then uploads over serial DFU. If no firmware with a USB serial
port is running, double-tap RESET to enter the bootloader first.
## Use on macOS
Connect with a USB data cable. macOS creates an Ethernet service and a
`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory
if prompted, and leave the network service set to DHCP.
`mongoose_config.h` gives the device a static address, and the driver serves
DHCP to the host:
* Device: `192.168.7.1/24`
* HTTP: <http://192.168.7.1/>
* HTTPS: <https://192.168.7.1/> (self-signed demonstration certificate)
* JSON tick: <http://192.168.7.1/api/tick>
Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another
network. Remove them to make the board a DHCP client instead, for example
behind macOS Internet Sharing.
```sh
curl --noproxy '*' http://192.168.7.1/api/tick
curl --noproxy '*' -k https://192.168.7.1/api/tick
screen /dev/cu.usbmodemXXXX 115200
```
The baud rate is ignored, except that 1200 baud followed by DTR dropping
reboots into the bootloader. The serial port is an output console; received
bytes are discarded.
## Implementation
* `main.c`: LED blink task and the HTTP/HTTPS handler.
* `hal.h`, `hal.c`: clock, SysTick, RNG, LED, newlib stubs.
* `../../../../src/drivers/usb_nrf52.c`: nRF52840 USB device controller,
polled. EasyDMA moves each 64-byte packet, one transfer at a time.
Applies Nordic's errata 171, 187 and 199 workarounds.
* `../../../../src/drivers/usb.c`: controller independent NCM + ACM, shared
with the RP2040/RP2350 and SAMD21 drivers.
@@ -74,9 +74,10 @@ int main(void) {
hal_rng_init();
hal_gpio_write(LED1, true);
hal_gpio_output(LED1);
mg_usb_init(NULL, &mg_usb_hw_nrf52); // USB serial log console
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Also starts the radio and the USB log console
mg_mgr_init(&mgr); // Also starts the radio
mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL);
mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL);
mg_mqtt_init(&mgr);
@@ -87,6 +88,7 @@ int main(void) {
for (;;) {
mg_mgr_poll(&mgr, 0);
mg_usb_poll(NULL, false);
mg_mqtt_poll(&mgr);
blink_task();
}
@@ -2,19 +2,21 @@
#include "nrf.h"
#define MG_ARCH MG_ARCH_ARMGCC
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_NRF52 1 // 802.15.4 radio: the network interface
#define MG_ENABLE_DRIVER_NRF52 1 // Radio: the network interface
#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode
#define MG_USB_REBOOT() \
do { \
NRF_POWER->GPREGRET = 0x57; \
NVIC_SystemReset(); \
} while (0)
#define MG_ENABLE_TCPIP_TCPRTX 1
#define MG_ENABLE_CUSTOM_MICROS 1
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_TLS MG_TLS_BUILTIN
#define MQTT_CLIENT_ID "xiao-nrf52840"
#ifndef MQTT_SERVER_URL
#define MQTT_SERVER_URL "mqtt://broker.emqx.io:1883"
#endif
// Stable, locally administered MAC derived from the factory device ID.
#define MG_SET_MAC_ADDRESS(mac) \
do { \
@@ -0,0 +1,51 @@
# Seeed XIAO nRF52840: USB Ethernet to BLE mesh bridge, no TinyUSB.
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
MGDIR = ../../../..
# Flash over USB: the board's Adafruit bootloader does serial DFU. The
# firmware reboots into it on a 1200 baud touch. PORT: the board's USB serial
# port. adafruit-nrfutil: pip install adafruit-nrfutil
PORT ?= /dev/cu.usbmodem11301
NRFUTIL ?= adafruit-nrfutil
CFLAGS = -W -Wall -Wextra -Werror -Wshadow -Wdouble-promotion
CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Inrfx/mdk
CFLAGS += -DNRF52840_XXAA -D__STARTUP_CLEAR_BSS -D__START=main -D__HEAP_SIZE=0
CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
CFLAGS += $(CFLAGS_EXTRA)
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc
LDFLAGS += -Wl,--gc-sections -Wl,-Map=$@.map
SOURCES = hal.c main.c $(MGDIR)/mongoose.c
SOURCES += nrfx/mdk/system_nrf52840.c nrfx/mdk/gcc_startup_nrf52840.S
all build: firmware.hex
firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
arm-none-eabi-size --format=berkeley $@
firmware.hex: firmware.elf
arm-none-eabi-objcopy -O ihex $< $@
firmware.zip: firmware.hex
$(NRFUTIL) dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $< $@
flash: firmware.zip
$(NRFUTIL) dfu serial --package $< -p $(PORT) -b 115200 --singlebank --touch 1200
cmsis_core:
git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@
# nRF52840 device headers, SystemInit() and the startup code
nrfx:
git clone -q -c advice.detachedHead=false --depth 1 -b v2.11.0 https://github.com/NordicSemiconductor/nrfx $@
clean:
rm -rf firmware.* cmsis_core nrfx
.PHONY: all build flash clean
@@ -0,0 +1,129 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include "hal.h"
#include <string.h>
static volatile uint64_t s_ticks; // Milliseconds since boot
void SysTick_Handler(void) { // SysTick IRQ handler, triggered every 1ms
s_ticks++;
}
uint64_t hal_get_tick(void) {
return s_ticks;
}
// Mongoose time source, see MG_ENABLE_CUSTOM_MILLIS
uint64_t mg_millis(void) {
return s_ticks;
}
// Mongoose microsecond time source for the mesh, see MG_ENABLE_CUSTOM_MICROS.
// SysTick runs at the core clock and reloads every millisecond. Sample the
// tick counter and the sub-millisecond counter in one critical section
uint64_t mg_micros(void) {
uint32_t primask = __get_PRIMASK(), val, pending;
uint64_t ms;
__disable_irq();
ms = s_ticks;
pending = SCB->ICSR & SCB_ICSR_PENDSTSET_Msk;
val = SysTick->VAL;
if (pending != (SCB->ICSR & SCB_ICSR_PENDSTSET_Msk)) {
pending = SCB_ICSR_PENDSTSET_Msk;
val = SysTick->VAL;
}
__set_PRIMASK(primask);
if (pending != 0 && val != 0) ms++;
return ms * 1000 + ((uint64_t) (SysTick->LOAD - val) * 1000) /
(SysTick->LOAD + 1);
}
// Mongoose random source, see MG_ENABLE_CUSTOM_RANDOM
bool mg_random(void *buf, size_t len) {
for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
uint32_t r = hal_rng_read();
memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r));
}
return true;
}
// Avoid pulling printf and friends in through assert()
void __assert_func(const char *s, int line, const char *fn, const char *expr) {
(void) s, (void) line, (void) fn, (void) expr;
for (;;) (void) 0;
}
extern unsigned char _end[]; // End of data section, start of heap. See link.ld
static unsigned char *s_current_heap_end = _end;
size_t hal_ram_used(void) {
return (size_t) (s_current_heap_end - _end);
}
size_t hal_ram_free(void) {
unsigned char endofstack;
return (size_t) (&endofstack - s_current_heap_end);
}
void *_sbrk(int incr) {
unsigned char *prev_heap;
unsigned char *heap_end = (unsigned char *) ((size_t) &heap_end - 256);
prev_heap = s_current_heap_end;
// Check how much space we got from the heap end to the stack end
if (s_current_heap_end + incr > heap_end) return (void *) -1;
s_current_heap_end += incr;
return prev_heap;
}
// Newlib stubs
struct stat;
int _fstat(int fd, struct stat *st) {
(void) fd, (void) st;
return -1;
}
int _open(const char *path) {
(void) path;
return -1;
}
int _close(int fd) {
(void) fd;
return -1;
}
int _isatty(int fd) {
(void) fd;
return 1;
}
int _lseek(int fd, int ptr, int dir) {
(void) fd, (void) ptr, (void) dir;
return 0;
}
void _exit(int status) {
(void) status;
for (;;) asm volatile("BKPT #0");
}
void _kill(int pid, int sig) {
(void) pid, (void) sig;
}
int _getpid(void) {
return -1;
}
int _write(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
int _read(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
void _init(void) {
}
@@ -0,0 +1,70 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
//
// USB to BLE bridge. The USB Ethernet interface is the LAN, the radio
// carries the mesh over BLE 2 Mbit/s frames. The bridge runs the mesh: it
// admits nodes and gives each one a turn to send
#include "hal.h"
#include "mongoose.h"
static uint64_t s_frames_up, s_frames_down; // Up: radio to USB
// LAN side: count Ethernet frames forwarded from the radio to the USB host
static size_t usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
size_t sent = mg_tcpip_driver_usb_nrf52.tx(buf, len, ifp);
if (sent != 0) s_frames_up++;
return sent;
}
// Mesh side: count Ethernet frames from the USB host queued for the radio
static size_t radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
size_t queued = mg_tcpip_driver_nrf52.tx(buf, len, ifp);
if (queued != 0) s_frames_down++;
return queued;
}
int main(void) {
static struct mg_tcpip_if usb, radio;
static struct mg_tcpip_driver usb_driver;
static char usb_queue[8192];
static struct mg_tcpip_driver radio_driver;
uint64_t blink_timer = 0, stats_timer = 0;
hal_system_init();
hal_rng_init();
hal_gpio_write(LED, true); // Off
hal_gpio_output(LED);
mg_usb_init(NULL, &mg_usb_hw_nrf52); // USB first: the log goes there
radio_driver = mg_tcpip_driver_nrf52;
radio_driver.tx = radio_tx;
radio.driver = &radio_driver;
MG_SET_MAC_ADDRESS(radio.mac);
if (!radio.driver->init(&radio)) return 1;
usb_driver = mg_tcpip_driver_usb_nrf52;
usb_driver.tx = usb_tx;
usb.driver = &usb_driver;
memcpy(usb.mac, radio.mac, sizeof(usb.mac));
mg_queue_init(&usb.recv_queue, usb_queue, sizeof(usb_queue));
if (!usb.driver->init(&usb)) return 1;
mg_radio_bridge(&radio, &usb); // Forward between radio and USB
MG_INFO(("USB to BLE bridge, channel %d, MAC %M", MG_RADIO_CHANNEL,
mg_print_mac, radio.mac));
for (;;) {
uint64_t now = mg_millis();
usb.driver->poll(&usb, false);
radio.driver->poll(&radio, false);
if (mg_timer_expired(&blink_timer, 500, now)) hal_gpio_toggle(LED);
if (mg_timer_expired(&stats_timer, 5000, now)) {
MG_INFO(("Ethernet frames up/down: %llu/%llu, dropped USB/radio: %u/%u",
s_frames_up, s_frames_down, (unsigned) usb.ndrop,
(unsigned) radio.ndrop));
}
}
return 0;
}
@@ -0,0 +1,29 @@
#pragma once
#include "nrf.h"
#define MG_ARCH MG_ARCH_ARMGCC
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_TCPIP_DRIVER_INIT 0 // main.c sets up both interfaces
#define MG_ENABLE_IPV6 0
#define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_MICROS 1
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_ENABLE_DRIVER_NRF52 1 // Radio: the mesh side
#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller: the LAN side
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode
#define MG_USB_REBOOT() \
do { \
NRF_POWER->GPREGRET = 0x57; \
NVIC_SystemReset(); \
} while (0)
// Stable, locally administered MAC derived from the factory device ID
#define MG_SET_MAC_ADDRESS(mac) \
do { \
uint32_t id_[2] = {NRF_FICR->DEVICEID[0], NRF_FICR->DEVICEID[1]}; \
uint8_t hash_[32]; \
mg_sha256(hash_, (uint8_t *) id_, sizeof(id_)); \
memcpy(mac, hash_, 6); \
(mac)[0] = ((mac)[0] & 0xfc) | 2; \
} while (0)
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "nrf.h"
#define BIT(x) (1UL << (x))
#define PIN(port, num) (((port) << 5) | (num))
#define PINNO(pin) ((pin) & 31)
#define PINPORT(pin) ((pin) >> 5)
#define LED PIN(0, 26) // P0.26, red user LED, active low
uint64_t hal_get_tick(void);
size_t hal_ram_used(void);
size_t hal_ram_free(void);
static inline NRF_GPIO_Type *hal_gpio_bank(uint16_t pin) {
return PINPORT(pin) == 0 ? NRF_P0 : NRF_P1;
}
static inline void hal_gpio_write(uint16_t pin, bool val) {
NRF_GPIO_Type *gpio = hal_gpio_bank(pin);
if (val) {
gpio->OUTSET = BIT(PINNO(pin));
} else {
gpio->OUTCLR = BIT(PINNO(pin));
}
}
static inline void hal_gpio_toggle(uint16_t pin) {
hal_gpio_write(pin, (hal_gpio_bank(pin)->OUT & BIT(PINNO(pin))) == 0);
}
static inline void hal_gpio_output(uint16_t pin) {
hal_gpio_bank(pin)->PIN_CNF[PINNO(pin)] =
(GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) |
(GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos);
}
// Vectors above the bootloader, 64 MHz crystal clock, 1 ms SysTick
static inline void hal_system_init(void) {
extern uint32_t __isr_vector[];
SCB->VTOR = (uint32_t) __isr_vector;
__DSB();
__ISB();
__enable_irq();
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (!NRF_CLOCK->EVENTS_HFCLKSTARTED) (void) 0;
SystemCoreClockUpdate();
SysTick_Config(SystemCoreClock / 1000);
}
static inline void hal_rng_init(void) {
NRF_RNG->CONFIG = 1; // Bias correction
NRF_RNG->TASKS_START = 1;
}
static inline uint32_t hal_rng_read(void) {
uint32_t value = 0;
for (unsigned i = 0; i < 4; i++) {
while (!NRF_RNG->EVENTS_VALRDY) (void) 0;
value |= (uint32_t) NRF_RNG->VALUE << (i * 8);
NRF_RNG->EVENTS_VALRDY = 0;
}
return value;
}
@@ -0,0 +1,62 @@
/* nRF52840 on the XIAO nRF52840, with the Adafruit UF2 bootloader. Flash:
* MBR and SoftDevice S140 below 0x27000, the bootloader from 0xED000 up: the
* application in between. The SoftDevice is not enabled, so all RAM is ours,
* except the first 24k it would take: kept free, as the Arduino core does */
ENTRY(Reset_Handler);
MEMORY {
flash(rx) : ORIGIN = 0x00027000, LENGTH = 0xC6000
sram(rwx) : ORIGIN = 0x20006000, LENGTH = 0x3A000
}
SECTIONS {
.vectors : { KEEP(*(.isr_vector)) . = ALIGN(4); } > flash
.text : { *(.text* .text.*) } > flash
.rodata : { *(.rodata*) . = ALIGN(4); } > flash
.data : {
_sdata = .;
*(.first_data)
*(.iram .iram.*) /* Mongoose MG_IRAM functions */
*(.data SORT(.data.*))
. = ALIGN(4);
_edata = .;
} > sram AT > flash
__data_start = _sdata;
__data_end = _edata;
__data_load_start = LOADADDR(.data);
/* Unused data regions expected by Nordic's standard startup. */
__sdata_start = _edata;
__sdata_end = _edata;
__sdata_load_start = _edata;
__tdata_start = _edata;
__tdata_end = _edata;
__tdata_load_start = _edata;
__fast_start = _edata;
__fast_end = _edata;
__fast_load_start = _edata;
.bss : {
_sbss = .;
*(.bss SORT(.bss.*) COMMON)
. = ALIGN(4);
_ebss = .;
} > sram
__bss_start__ = _sbss;
__bss_end__ = _ebss;
__tbss_start__ = _ebss;
__tbss_end__ = _ebss;
__sbss_start__ = _ebss;
__sbss_end__ = _ebss;
/* Health record, see MG_HEALTH_RAM: not cleared, survives a warm reset */
.mg_health (NOLOAD) : { KEEP(*(.mg_health .mg_health*)) } > sram
. = ALIGN(8);
_end = .; /* Start of heap, see _sbrk() in hal.c */
/* Nordic startup reserves its default 16 KiB stack at the top of RAM. */
.stack ORIGIN(sram) + LENGTH(sram) - 0x4000 (NOLOAD) : {
KEEP(*(.stack))
} > sram
ASSERT(_end <= __StackLimit, "RAM sections overlap the stack")
}
@@ -1,4 +1,5 @@
#pragma once
#define MG_ARCH MG_ARCH_ARMGCC
#define MG_TLS MG_TLS_BUILTIN
#define MG_ENABLE_TCPIP 1
@@ -8,6 +9,15 @@
#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode
#include "nrf.h"
#define MG_USB_REBOOT() \
do { \
NRF_POWER->GPREGRET = 0x57; \
NVIC_SystemReset(); \
} while (0)
// Static device address; the driver serves DHCP to the USB host. Remove
// these to get an address over DHCP instead, e.g. from Internet Sharing
#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1)