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

@@ -8,7 +8,8 @@
#define MQTT_CLIENT_ID "esp32c6" // For tutorials/mqtt/mqtt-client
#define MG_ENABLE_TCPIP 1 // Built-in TCP/IP stack, not lwIP
#define MG_ENABLE_DRIVER_ESP32_802154 1 // ESP32-C6 802.15.4 radio
#define MG_ENABLE_DRIVER_ESP32 1 // ESP32-C6 802.15.4 radio
#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only
#define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit
// Stable MAC, so the DHCP address stays the same across reboots: the factory
@@ -0,0 +1,4 @@
cmake_minimum_required(VERSION 3.16)
set(IDF_TARGET esp32c6)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(mongoose-wifi-to-802154-bridge)
@@ -0,0 +1,22 @@
# Build: ESP-IDF from the espressif/idf Docker image. Flash: esptool
# Wi-Fi credentials: make WIFI_NAME=... WIFI_PASS=... build, or set them in
# the environment. Unset, the defaults in main/main.c apply
THISDIR = $(realpath $(CURDIR))
ROOTDIR = $(realpath $(CURDIR)/../../..)
DOCKER ?= docker run --rm -e WIFI_NAME -e WIFI_PASS -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf
PORT ?= /dev/cu.usbmodem101
all build:
$(DOCKER) idf.py reconfigure build # reconfigure picks up WIFI_* changes
flash: build
cd build && esptool --chip esp32c6 -p $(PORT) -b 460800 write-flash @flash_args
menuconfig:
docker run --rm -it -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf idf.py menuconfig
clean:
test -d build && rm -rf build sdkconfig || true
.PHONY: all build flash menuconfig clean
@@ -0,0 +1,12 @@
idf_component_register(SRCS "main.c" "../../../../mongoose.c"
INCLUDE_DIRS "." "../../../.."
REQUIRES esp_wifi esp_netif esp_event esp_timer esp_coex
ieee802154 nvs_flash lwip app_update esp_driver_gpio)
# WIFI_NAME and WIFI_PASS environment variables override the defaults in
# main.c. They are read when CMake configures: run "idf.py reconfigure" after
# changing them
foreach(var WIFI_NAME WIFI_PASS)
if(NOT "$ENV{${var}}" STREQUAL "")
target_compile_definitions(${COMPONENT_LIB} PRIVATE ${var}="$ENV{${var}}")
endif()
endforeach()
@@ -0,0 +1,16 @@
menu "Wi-Fi to 802.15.4 bridge"
config BRIDGE_XIAO_ESP32C6
bool "Seeed XIAO ESP32-C6 antenna switch"
default y
help
Power the RF switch through GPIO3 and select the antenna on GPIO14.
Disable on boards without this switch.
config BRIDGE_XIAO_EXTERNAL_ANTENNA
bool "Use the XIAO's external antenna"
depends on BRIDGE_XIAO_ESP32C6
default n
config BRIDGE_RADIO_CHANNEL
int "802.15.4 channel, must match the radio nodes"
range 11 26
default 15
endmenu
@@ -0,0 +1,476 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
// IPv4 Wi-Fi station <-> Mongoose Ethernet-over-802.15.4 radio bridge.
//
// LAN / DHCP server <-- Wi-Fi --> ESP32-C6 <-- 802.15.4 --> radio nodes
//
// The radio side is Mongoose's esp32 driver acting as the bridge for the
// radio nodes, like tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge.
// The radio driver reads LAN frames from the Wi-Fi interface's recv_queue and
// sends frames to the LAN with that interface's driver tx(). Here the LAN
// interface is a thin wrapper around the Wi-Fi station.
//
// A Wi-Fi station can only send with its own MAC address, so unlike Ethernet
// the frames are translated, see translate(): upstream, node MACs are replaced
// with the station MAC; downstream, the node MAC is restored by IP address.
// Each node gets its own LAN IP from DHCP. The bridge gets one too, for its
// own Mongoose: GET / on port 80 returns the bridge's status as JSON.
//
// Threads: wifi_input() runs in the Wi-Fi task and only queues a copy. All
// the rest, radio, translation and Wi-Fi transmit, runs in app_main's loop.
#include "driver/gpio.h"
#include "esp_coexist.h"
#include "esp_event.h"
#include "esp_ieee802154.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_netif_net_stack.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_wifi_default.h"
#include "freertos/FreeRTOS.h"
#include "lwip/esp_netif_net_stack.h"
#include "mongoose.h"
#include "nvs_flash.h"
#if !CONFIG_IDF_TARGET_ESP32C6
#error This tutorial requires ESP32-C6
#endif
// Override with WIFI_NAME and WIFI_PASS environment variables at build time
#ifndef WIFI_NAME
#define WIFI_NAME "WIFI_NAME"
#endif
#ifndef WIFI_PASS
#define WIFI_PASS "WIFI_PASS"
#endif
#define FRAME_SIZE 1514 // Ethernet header + 1500, no FCS
#define NODE_COUNT 16 // Radio nodes the bridge tracks
#define NODE_TIMEOUT_MS (30UL * 60 * 1000) // Forget a node idle this long
// A radio node, learned from its frames to Wi-Fi
struct node {
uint64_t expires; // Expiry, milliseconds since boot; zero: unused
uint8_t mac[6], ip[4]; // The node's own MAC, and its LAN IPv4 address
};
static uint8_t s_mac[6]; // Wi-Fi station MAC, used by all nodes
static struct node s_nodes[NODE_COUNT]; // Radio nodes, see translate()
static esp_netif_t *s_netif; // Wi-Fi station, raw Ethernet I/O
static volatile bool s_wifi_up; // Associated with the access point
static struct mg_tcpip_if s_wifi; // The radio's LAN interface
static struct mg_tcpip_if s_radio; // 802.15.4 radio interface
static struct mg_tcpip_if s_local; // The bridge's own IP, for the status
// Cumulative totals. Up: radio -> Wi-Fi; down: Wi-Fi -> radio; bridge: Wi-Fi
// -> the bridge's own IP
static unsigned s_frames_up, s_frames_down, s_frames_local, s_wifi_drops;
static unsigned s_frames_bridge, s_radio_sent, s_radio_received;
// Is a an IPv4 address worth learning: not 0.x, loopback or multicast
static bool is_host_ip(const uint8_t *a) {
return a[0] != 0 && a[0] != 127 && a[0] < 224;
}
// Translate an Ethernet frame in place and update s_nodes. Returns false if
// the frame must be dropped. IPv4 and ARP only; IPs and ports stay intact.
// To Wi-Fi: learn the sending node and replace its MAC with the station MAC.
// DHCP keeps the node's chaddr, so each node gets its own LAN IP.
// To radio: find the node by destination IP, or by DHCP chaddr, and restore
// its MAC. Broadcasts pass, unknown unicasts drop
static bool translate(uint8_t *f, size_t len, bool to_radio, uint64_t now) {
uint8_t *ip = NULL, *a = NULL, *bootp = NULL, *udp = NULL;
struct node *n = NULL, *free_node = NULL;
const uint8_t *addr;
bool by_mac;
size_t i;
if (len < 14 || len > FRAME_SIZE || memcmp(f + 6, s_mac, 6) == 0) {
return false;
}
if (!to_radio && ((f[6] & 1) || memcmp(f + 6, "\0\0\0\0\0\0", 6) == 0)) {
return false;
}
if (f[12] == 8 && f[13] == 6) { // ARP for Ethernet/IPv4, request or reply
a = f + 14;
if (len < 42 || memcmp(a, "\x00\x01\x08\x00\x06\x04", 6) != 0 ||
a[6] != 0 || (a[7] != 1 && a[7] != 2) ||
(!to_radio && memcmp(a + 8, f + 6, 6) != 0)) {
return false;
}
} else if (f[12] == 8 && f[13] == 0 && len >= 34) { // IPv4, with options
size_t hlen, total;
ip = f + 14;
hlen = (ip[0] & 15) * 4U, total = ip[2] * 256U + ip[3];
if ((ip[0] >> 4) != 4 || hlen < 20 || total < hlen || total > len - 14) {
return false;
}
// DHCP: UDP ports 67/68, BOOTP and the magic cookie. Only complete,
// unfragmented packets
udp = ip + hlen;
if (ip[9] == 17 && !(ip[6] & 0x3f) && ip[7] == 0 && total >= hlen + 248) {
uint8_t *p = udp + 8;
size_t ulen = udp[4] * 256U + udp[5];
if (udp[0] == 0 && udp[1] == (to_radio ? 67 : 68) && udp[2] == 0 &&
udp[3] == (to_radio ? 68 : 67) && ulen >= 248 &&
ulen <= total - hlen && p[0] == (to_radio ? 2 : 1) && p[1] == 1 &&
p[2] == 6 && memcmp(p + 236, "\x63\x82\x53\x63", 4) == 0) {
bootp = p;
}
}
} else {
return false;
}
// The node: to Wi-Fi, by source MAC; to radio, by DHCP chaddr, else by
// destination IP. Expire old nodes and find a free slot in the same pass
by_mac = !to_radio || bootp != NULL;
addr = !to_radio ? f + 6
: bootp != NULL ? bootp + 28
: ip != NULL ? ip + 16
: a + 24;
for (i = 0; i < NODE_COUNT; i++) {
struct node *p = &s_nodes[i];
if (p->expires != 0 && now > p->expires) p->expires = 0;
if (p->expires == 0) {
if (free_node == NULL) free_node = p;
} else if (n == NULL && (by_mac || is_host_ip(addr)) &&
memcmp(by_mac ? p->mac : p->ip, addr, by_mac ? 6 : 4) == 0) {
n = p;
}
}
if (!to_radio) {
if (bootp != NULL && memcmp(bootp + 28, f + 6, 6) != 0) return false;
if (n == NULL) {
if ((n = free_node) == NULL) return false; // Table full
memset(n, 0, sizeof(*n));
memcpy(n->mac, f + 6, 6);
}
n->expires = now + NODE_TIMEOUT_MS;
addr = ip != NULL ? ip + 12 : a + 14; // Sender IP
if (is_host_ip(addr)) memcpy(n->ip, addr, 4);
if (a != NULL) memcpy(a + 8, s_mac, 6); // ARP sender MAC
if (bootp != NULL) {
bootp[10] |= 0x80; // Ask for broadcast replies: no node IP yet
udp[6] = udp[7] = 0; // No UDP checksum, IPv4 allows that
}
memcpy(f + 6, s_mac, 6);
return true;
}
if (bootp != NULL) {
if (n == NULL) return false; // Another LAN client's DHCP reply
if (is_host_ip(bootp + 16)) memcpy(n->ip, bootp + 16, 4); // yiaddr
}
if (n == NULL) return (f[0] & 1) != 0; // Broadcast passes, unicast drops
memcpy(f, n->mac, 6);
if (a != NULL && a[7] == 2) memcpy(a + 18, n->mac, 6); // ARP reply target
return true;
}
// Is mac a radio node, learned by translate()
static bool is_node(const uint8_t *mac, uint64_t now) {
size_t i;
for (i = 0; i < NODE_COUNT; i++) {
if (s_nodes[i].expires > now && memcmp(s_nodes[i].mac, mac, 6) == 0) {
return true;
}
}
return false;
}
// Radio events: count radio frames, and give each its Wi-Fi coexistence
// priority before it goes out. Wi-Fi and 802.15.4 share one antenna. The
// bridge's unicast frames give a node its turn, and the node answers right
// after: send those at high priority, so the radio keeps the antenna until
// the answer is in. The broadcast beacons go at low priority, and Wi-Fi gets
// the antenna between turns. ESP-IDF applies the priority when the next
// transmission or reception starts
static void radio_fn(struct mg_tcpip_if *ifp, int ev, void *ev_data) {
if (ev == MG_TCPIP_EV_PHY_RX) s_radio_received++;
if (ev == MG_TCPIP_EV_PHY_TX) {
struct mg_str *f = (struct mg_str *) ev_data; // MAC header: dst at 5..6
const uint8_t *frame = (const uint8_t *) f->buf;
bool bcast = f->len < 7 || (frame[5] == 0xff && frame[6] == 0xff);
ieee802154_coex_event_t want = bcast ? IEEE802154_LOW : IEEE802154_HIGH;
esp_ieee802154_coex_config_t coex = esp_ieee802154_get_coex_config();
s_radio_sent++;
if (coex.txrx != want) {
coex.txrx = want;
esp_ieee802154_set_coex_config(coex);
}
}
(void) ifp;
}
// ESP-NETIF custom stack input: Ethernet frames from Wi-Fi, before lwIP.
// Runs in the Wi-Fi task. The queue has one producer, this function, and
// one consumer, the radio driver in app_main, so it needs no lock
static esp_err_t wifi_input(void *netif, void *buf, size_t len, void *eb) {
char *dst;
if (s_wifi_up && len >= 14 && len <= FRAME_SIZE &&
mg_queue_book(&s_wifi.recv_queue, &dst, len) >= len) {
memcpy(dst, buf, len);
mg_queue_add(&s_wifi.recv_queue, len);
} else {
s_wifi_drops++;
}
esp_netif_free_rx_buffer(esp_netif_get_handle_from_netif_impl(netif), eb);
return ESP_OK;
}
// Send an Ethernet frame over Wi-Fi. Returns len, or 0 on failure
static size_t wifi_send(void *buf, size_t len) {
return s_wifi_up && esp_netif_transmit(s_netif, buf, len) == ESP_OK ? len : 0;
}
// LAN driver tx: the radio driver hands over an Ethernet frame from a radio
// node. A unicast to another node goes back to the radio, untranslated.
// Anything else is translated and sent over Wi-Fi
static size_t wifi_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
uint8_t *frame = (uint8_t *) buf; // The radio's receive buffer, writable
uint64_t now = mg_millis();
(void) ifp;
if (len >= 14 && (frame[0] & 1) == 0 && is_node(frame, now)) {
if (mg_tcpip_driver_esp32.tx(buf, len, &s_radio) == 0) return 0;
s_frames_local++;
return len;
}
if (!translate(frame, len, false, now) || wifi_send(frame, len) == 0) {
return 0;
}
s_frames_up++;
return len;
}
// Is a Wi-Fi frame for the bridge itself: an ARP or IPv4 packet to its IP, or
// a DHCP reply to its MAC, before it has an IP
static bool for_bridge(const uint8_t *f, size_t len) {
uint32_t ip = s_local.ip;
size_t hlen = len > 14 ? (size_t) (f[14] & 15) * 4 : 0;
const uint8_t *udp = f + 14 + hlen;
if (len >= 42 && f[12] == 8 && f[13] == 6) { // ARP: target IP at 38
return ip != 0 && memcmp(f + 38, &ip, 4) == 0;
}
if (len < 34 || f[12] != 8 || f[13] != 0) return false; // IPv4 only
if (ip != 0 && memcmp(f + 30, &ip, 4) == 0) return true; // Destination
return hlen >= 20 && len >= 14 + hlen + 8 + 34 && f[23] == 17 &&
udp[0] == 0 && udp[1] == 67 && udp[2] == 0 && udp[3] == 68 &&
memcmp(udp + 8 + 28, s_local.mac, 6) == 0; // DHCP chaddr
}
// Hand a Wi-Fi frame to the bridge's own TCP/IP stack
static void to_bridge(const void *buf, size_t len) {
char *p;
if (mg_queue_book(&s_local.recv_queue, &p, len) >= len) {
memcpy(p, buf, len);
mg_queue_add(&s_local.recv_queue, len);
s_frames_bridge++;
}
}
// Radio driver tx, called with frames from the Wi-Fi interface's recv_queue:
// restore the node's MAC, then queue the frame for the radio. Frames for the
// bridge itself go to its own stack; broadcasts go to both
static size_t radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
uint8_t *frame = (uint8_t *) buf; // Points into the recv_queue, writable
bool bcast = len >= 14 && (frame[0] & 1);
if (bcast || for_bridge(frame, len)) {
to_bridge(buf, len);
if (!bcast) return len;
}
if (!translate(frame, len, true, mg_millis())) return 0;
len = mg_tcpip_driver_esp32.tx(buf, len, ifp);
if (len != 0) s_frames_down++;
return len;
}
// The bridge's own interface sends straight to Wi-Fi, under the station MAC
static size_t local_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
(void) ifp;
return wifi_send((void *) buf, len);
}
// The bridge's own interface is up while Wi-Fi is associated
static bool local_poll(struct mg_tcpip_if *ifp, bool s1) {
(void) ifp, (void) s1;
return s_wifi_up;
}
// Print the node table as a JSON array, for %M
static size_t print_nodes(mg_pfn_t out, void *arg, va_list *ap) {
uint64_t now = mg_millis();
size_t i, n = mg_xprintf(out, arg, "[");
const char *comma = "";
(void) ap;
for (i = 0; i < NODE_COUNT; i++) {
const struct node *p = &s_nodes[i];
uint32_t ip;
if (p->expires <= now) continue;
memcpy(&ip, p->ip, sizeof(ip));
n += mg_xprintf(out, arg, "%s{\"mac\":\"%M\",\"ip\":\"%M\",\"idle_ms\":%llu}",
comma, mg_print_mac, p->mac, mg_print_ip4, &ip,
(unsigned long long) (now + NODE_TIMEOUT_MS - p->expires));
comma = ",";
}
return n + mg_xprintf(out, arg, "]");
}
// GET /: the bridge's status, as JSON
static void http_ev(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
wifi_ap_record_t ap = {0};
bool assoc = esp_wifi_sta_get_ap_info(&ap) == ESP_OK;
mg_http_reply(
c, 200, "Content-Type: application/json\r\n",
"{\"uptime_ms\":%llu,\"free_heap\":%lu,\"ip\":\"%M\","
"\"wifi\":{\"up\":%s,\"ssid\":%m,\"rssi\":%d,\"channel\":%u,"
"\"rx_drops\":%u},"
"\"radio\":{\"channel\":%d,\"frames_sent\":%u,\"frames_received\":%u,"
"\"rx_drops\":%u,\"tx_errors\":%u},"
"\"frames\":{\"up\":%u,\"down\":%u,\"node_to_node\":%u,\"bridge\":%u},"
"\"nodes\":%M}\n",
(unsigned long long) mg_millis(),
(unsigned long) esp_get_free_heap_size(), mg_print_ip4, &s_local.ip,
s_wifi_up ? "true" : "false",
MG_ESC(assoc ? (const char *) ap.ssid : ""), assoc ? ap.rssi : 0,
assoc ? ap.primary : 0, s_wifi_drops, MG_RADIO_CHANNEL,
s_radio_sent, s_radio_received, (unsigned) s_radio.ndrop,
(unsigned) s_radio.nerr, s_frames_up, s_frames_down, s_frames_local,
s_frames_bridge, print_nodes);
}
(void) ev_data;
}
// Wi-Fi association state; the bridge's own IP comes from Mongoose's DHCP.
// app_main retries the connection, so this handler only tracks state
static void wifi_event(void *arg, esp_event_base_t base, int32_t id,
void *data) {
if (id == WIFI_EVENT_STA_CONNECTED) {
s_wifi_up = true;
MG_INFO(("Wi-Fi connected"));
} else if (id == WIFI_EVENT_STA_DISCONNECTED) {
const wifi_event_sta_disconnected_t *e = data;
s_wifi_up = false;
MG_INFO(("Wi-Fi disconnected, reason %u", e->reason));
}
(void) arg, (void) base;
}
// XIAO RF switch: GPIO3 low powers it, GPIO14 selects the antenna
static void antenna_init(void) {
#ifdef CONFIG_BRIDGE_XIAO_ESP32C6
ESP_ERROR_CHECK(gpio_set_direction(GPIO_NUM_3, GPIO_MODE_OUTPUT));
ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_3, 0));
vTaskDelay(pdMS_TO_TICKS(100));
ESP_ERROR_CHECK(gpio_set_direction(GPIO_NUM_14, GPIO_MODE_OUTPUT));
#ifdef CONFIG_BRIDGE_XIAO_EXTERNAL_ANTENNA
ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_14, 1));
#else
ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_14, 0));
#endif
#endif
}
// Wi-Fi station whose received frames go to wifi_input(), not to lwIP. The
// bridge's own IP is Mongoose's, see s_local
static void wifi_init(void) {
esp_netif_inherent_config_t base = ESP_NETIF_INHERENT_DEFAULT_WIFI_STA();
const esp_netif_netstack_config_t stack = {
.lwip = {.init_fn = wlanif_init_sta, .input_fn = wifi_input}};
const esp_netif_config_t cfg = {.base = &base, .stack = &stack};
wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
wifi_config_t wifi = {
.sta = {.ssid = WIFI_NAME,
.password = WIFI_PASS,
.scan_method = WIFI_ALL_CHANNEL_SCAN,
.sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
.threshold = {.rssi = -127, .authmode = WIFI_AUTH_OPEN}}};
esp_err_t err = nvs_flash_init(); // Wi-Fi needs NVS, even with RAM storage
if (err == ESP_ERR_NVS_NO_FREE_PAGES ||
err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
base.flags = ESP_NETIF_FLAG_AUTOUP; // No IP, DHCP, GARP or IPv6
s_netif = esp_netif_new(&cfg);
if (s_netif == NULL) ESP_ERROR_CHECK(ESP_ERR_NO_MEM);
ESP_ERROR_CHECK(esp_netif_attach_wifi_station(s_netif));
ESP_ERROR_CHECK(esp_wifi_set_default_wifi_sta_handlers());
ESP_ERROR_CHECK(esp_wifi_init(&init));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_event, NULL));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi));
ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, s_mac));
}
void app_main(void) {
static struct mg_tcpip_driver wifi_driver;
static struct mg_tcpip_driver radio_driver;
static struct mg_tcpip_driver local_driver;
static struct mg_mgr mgr;
static char wifi_queue[8192];
uint64_t retry_timer = 0, stats_timer = 0;
antenna_init();
wifi_init();
// The radio uses a locally administered variant of the station MAC
memcpy(s_radio.mac, s_mac, 6);
s_radio.mac[0] = (uint8_t) ((s_radio.mac[0] | 2) & 0xfe);
s_radio.mac[5] ^= 0x80;
radio_driver = mg_tcpip_driver_esp32;
radio_driver.tx = radio_tx;
s_radio.driver = &radio_driver;
s_radio.fn = radio_fn; // Send at coexistence priority
if (!s_radio.driver->init(&s_radio)) ESP_ERROR_CHECK(ESP_FAIL);
// The LAN interface: the radio driver only uses its recv_queue and tx
wifi_driver.tx = wifi_tx;
s_wifi.driver = &wifi_driver;
memcpy(s_wifi.mac, s_mac, 6);
mg_queue_init(&s_wifi.recv_queue, wifi_queue, sizeof(wifi_queue));
mg_radio_bridge(&s_radio, &s_wifi);
// The bridge's own interface, under the station MAC, with an IP from DHCP:
// GET / on port 80 returns the bridge's status
local_driver.tx = local_tx;
local_driver.poll = local_poll;
s_local.driver = &local_driver;
memcpy(s_local.mac, s_mac, 6);
mg_snprintf(s_local.dhcp_name, sizeof(s_local.dhcp_name), "radio-bridge");
mg_mgr_init(&mgr);
mg_tcpip_init(&mgr, &s_local);
mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev, NULL);
// Start the radio before Wi-Fi, then enable coexistence. Wi-Fi power
// saving gives the arbiter time slots for 802.15.4
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_coex_wifi_i154_enable());
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_MAX_MODEM));
ESP_ERROR_CHECK(esp_wifi_connect());
MG_INFO(
("Wi-Fi/radio bridge, SSID %s, channel %u", WIFI_NAME, MG_RADIO_CHANNEL));
// Busy loop: radio turns are timed in microseconds, a FreeRTOS tick is much
// longer. Wi-Fi tasks have higher priority and preempt it. The idle task
// starves, so sdkconfig.defaults turns off the idle task watchdog check
for (;;) {
uint64_t now = mg_millis();
s_radio.driver->poll(&s_radio, false);
mg_mgr_poll(&mgr, 0);
if (!s_wifi_up && mg_timer_expired(&retry_timer, 5000, now)) {
(void) esp_wifi_connect();
}
if (mg_timer_expired(&stats_timer, 5000, now)) {
MG_INFO(("Frames up/down/node-to-node %u/%u/%u, Wi-Fi RX drops %u",
s_frames_up, s_frames_down, s_frames_local, s_wifi_drops));
}
}
}
@@ -0,0 +1,9 @@
#pragma once
#include "sdkconfig.h"
#define MG_ARCH MG_ARCH_ESP32
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_TCPIP_DRIVER_INIT 0
#define MG_ENABLE_DRIVER_ESP32 1
#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only
#define MG_TLS MG_TLS_NONE
#define MG_RADIO_CHANNEL CONFIG_BRIDGE_RADIO_CHANNEL
@@ -0,0 +1,10 @@
CONFIG_IDF_TARGET="esp32c6"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
CONFIG_ESP_COEX_SW_COEXIST_ENABLE=y
CONFIG_IEEE802154_ENABLED=y
CONFIG_ESP_MAIN_TASK_STACK_SIZE=6144
# The main task busy-loops the radio, so the idle task does not run
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=n
# The netif is used for raw Wi-Fi I/O, not for an IPv6 stack
CONFIG_LWIP_IPV6=n
-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)
+63 -7
View File
@@ -4,14 +4,60 @@
#include "hal.h"
#include "mongoose.h"
#if MG_RADIO == MG_RADIO_BLE
// NXP release/25.06.00, gen45: gfsk_bt_0p5_h_0p5_1mbps_full_config.
// The alternate data-rate bank is 2 Mbit/s, selected by GENFSK ENH_FEATURE.
// Copyright 2016 Freescale Semiconductor, Inc.; 2018-2023 NXP.
// SPDX-License-Identifier: BSD-3-Clause
// These are the differences from the 802.15.4 setup in hal.h. Both use
// xcvr_ble_uncoded_config for RBME (CRC and whitening).
static const struct w71_radio_reg s_ble_regs[] = {
{&XCVR_MISC->IPS_FO_ADDR[0], 0x0000332c},
{&XCVR_MISC->IPS_FO_ADDR[1], 0x00000034},
{&XCVR_MISC->IPS_FO_DRS0_DATA[0], 0x20ff0000},
{&XCVR_MISC->IPS_FO_DRS1_DATA[0], 0x10ff0000},
{&XCVR_MISC->XCVR_CTRL, 0x00030140},
{&XCVR_PLL_DIG->CHAN_MAP, 0x00000000},
{&XCVR_PLL_DIG->DELAY_MATCH, 0x00040103},
{&XCVR_PLL_DIG->HPMCAL_CTRL, 0x00000000},
{&XCVR_PLL_DIG->HPM_BUMP, 0x00440122},
{&XCVR_PLL_DIG->HPM_SDM_RES, 0x20ff0000},
{&XCVR_RX_DIG->ACQ_FILT_0_3, 0x757a0202},
{&XCVR_RX_DIG->ACQ_FILT_0_3_DRS, 0x09023e3e},
{&XCVR_RX_DIG->ACQ_FILT_10_11, 0x00de0068},
{&XCVR_RX_DIG->ACQ_FILT_10_11_DRS, 0x00a1006e},
{&XCVR_RX_DIG->ACQ_FILT_4_7, 0xeb171801},
{&XCVR_RX_DIG->ACQ_FILT_4_7_DRS, 0xdeeb000b},
{&XCVR_RX_DIG->ACQ_FILT_8_9, 0x01e901c2},
{&XCVR_RX_DIG->ACQ_FILT_8_9_DRS, 0x002601f0},
{&XCVR_RX_DIG->AGC_IDX11_GAIN_CFG, 0x02047e03},
{&XCVR_RX_DIG->AGC_IDX11_GAIN_VAL, 0x006014fa},
{&XCVR_RX_DIG->CTRL0, 0x60063083},
{&XCVR_RX_DIG->CTRL0_DRS, 0x000020c0},
{&XCVR_RX_DIG->DEMOD_FILT_0_1_DRS, 0x01fe01fd},
{&XCVR_RX_DIG->DEMOD_FILT_2_4, 0x0bc20c24},
{&XCVR_RX_DIG->DEMOD_FILT_2_4_DRS, 0x0bc20c23},
{&XCVR_RX_DIG->RCCAL_CTRL0, 0x0000001a},
{&XCVR_RX_DIG->RSSI_GLOBAL_CTRL, 0x80008310},
{&XCVR_TX_DIG->DATARATE_CONFIG_FSK_CTRL, 0x00000000},
{&XCVR_TX_DIG->DATARATE_CONFIG_GFSK_CTRL, 0x00000830},
{&XCVR_TX_DIG->DATA_PADDING_CTRL, 0x00001010},
{&XCVR_TX_DIG->DATA_PADDING_CTRL_1, 0x00001404},
{&XCVR_TX_DIG->DATA_PADDING_CTRL_2, 0x04001c00},
{&XCVR_TX_DIG->GFSK_CTRL, 0x00000400},
{&XCVR_TX_DIG->PA_CTRL, 0x00010126},
{&XCVR_TX_DIG->TXDIG_CTRL, 0x00000000},
};
#endif
// Initialise the transceiver the way NXP XCVR_Init() does it: start the RF
// oscillator, wait for the radio to wake up, enable its clocks and load the
// 802.15.4 register setup. Then select the legacy 802.15.4 demodulator and
// CCA from RX digital. See PhyHwInit() in NXP ieee_802_15_4 PHY sources,
// PhyPacketProcessor.c
// register setup for the selected PHY. For 802.15.4, select the legacy
// demodulator and CCA from RX digital. See PhyHwInit() in NXP ieee_802_15_4 PHY
// sources, PhyPacketProcessor.c
void hal_radio_init(void) {
uint32_t stat = RFMC_RF2P4GHZ_STAT_RST_STAT_MASK |
RFMC_RF2P4GHZ_STAT_LP_ACK_STAT_MASK;
uint32_t stat =
RFMC_RF2P4GHZ_STAT_RST_STAT_MASK | RFMC_RF2P4GHZ_STAT_LP_ACK_STAT_MASK;
size_t i, n = 1000000;
RFMC->CTRL &= ~RFMC_CTRL_RFMC_RST_MASK; // RFMC out of reset
RFMC->RF2P4GHZ_CTRL |= RFMC_RF2P4GHZ_CTRL_XO_EN_MASK; // Start RF oscillator
@@ -31,9 +77,19 @@ void hal_radio_init(void) {
for (i = 0; i < sizeof(s_radio_regs) / sizeof(s_radio_regs[0]); i++) {
*s_radio_regs[i].reg = s_radio_regs[i].val;
}
#if MG_RADIO == MG_RADIO_BLE
for (i = 0; i < sizeof(s_ble_regs) / sizeof(s_ble_regs[0]); i++) {
*s_ble_regs[i].reg = s_ble_regs[i].val;
}
RADIO_CTRL->LL_CTRL = RADIO_CTRL_LL_CTRL_ACTIVE_LL(2); // GENFSK engine
// NXP GENFSK_SetBleWhitenInit(): BLE channel index with bit 6 set.
RBME->WHITEN_CFG = (RBME->WHITEN_CFG & ~RBME_WHITEN_CFG_WHITEN_INIT_MASK) |
RBME_WHITEN_CFG_WHITEN_INIT(MG_RADIO_CHANNEL | 0x40);
#else
XCVR_MISC->XCVR_CTRL &= ~XCVR_MISC_XCVR_CTRL_DEMOD_SEL_MASK;
XCVR_MISC->XCVR_CTRL |= XCVR_MISC_XCVR_CTRL_DEMOD_SEL(2);
XCVR_ZBDEMOD->CCA_LQI_SRC |= XCVR_ZBDEMOD_CCA_LQI_SRC_CCA1_FROM_RX_DIG(1);
#endif
}
// Random 32 bits, for mg_random(). Entropy is radio noise: receiver RSSI,
@@ -99,8 +155,8 @@ uint64_t mg_micros(void) {
}
__set_PRIMASK(primask);
if (pending != 0 && val != 0) ms++;
return ms * 1000 + ((uint64_t) (SysTick->LOAD - val) * 1000) /
(SysTick->LOAD + 1);
return ms * 1000 +
((uint64_t) (SysTick->LOAD - val) * 1000) / (SysTick->LOAD + 1);
}
uint32_t SystemCoreClock;
+1 -1
View File
@@ -17,7 +17,7 @@ uint64_t hal_get_tick(void);
bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now);
size_t hal_ram_used(void);
size_t hal_ram_free(void);
void hal_radio_init(void); // Set up the 2.4 GHz transceiver for 802.15.4
void hal_radio_init(void); // Set up the 2.4 GHz transceiver for MG_RADIO
uint32_t hal_rng_read(void); // Random 32 bits, radio noise. See hal.c
extern uint32_t SystemCoreClock; // CPU clock, Hz. Set by hal_clock_init()
@@ -9,6 +9,9 @@
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_MCXW71 1
#ifndef MG_RADIO
#define MG_RADIO MG_RADIO_BLE // Raw BLE 2M; or MG_RADIO_802154
#endif
#define MG_ENABLE_CUSTOM_MICROS 1
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit
@@ -13,12 +13,15 @@ static uint64_t s_radio_led_until;
// Cumulative totals. Up: radio -> LAN; down: LAN -> radio queue.
static uint64_t s_frames_up, s_frames_down, s_bytes_up, s_bytes_down;
static uint64_t s_radio_sent, s_radio_received;
static size_t (*s_radio_tx)(struct mg_tcpip_if *, const void *, size_t);
static size_t radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) {
size_t sent = s_radio_tx(ifp, buf, len);
if (sent != 0) s_radio_sent++;
return sent;
// Radio interface events: count radio frames, blink on reception
static void radio_fn(struct mg_tcpip_if *ifp, int ev, void *ev_data) {
if (ev == MG_TCPIP_EV_PHY_TX) s_radio_sent++;
if (ev == MG_TCPIP_EV_PHY_RX) {
s_radio_received++;
s_radio_led_until = mg_millis() + 2;
}
(void) ifp, (void) ev_data;
}
static size_t eth_up(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
@@ -27,31 +30,23 @@ static size_t eth_up(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
return sent;
}
static size_t eth_down(struct mg_mesh_node *node, const void *buf, size_t len) {
size_t queued = mg_mesh_default.tx(node, buf, len);
static size_t eth_down(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
size_t queued = mg_tcpip_driver_rw612w.tx(buf, len, ifp);
if (queued != 0) s_frames_down++, s_bytes_down += queued;
return queued;
}
static void radio_rx(struct mg_mesh_node *node, void *buf, size_t len) {
s_radio_received++;
s_radio_led_until = mg_millis() + 2;
mg_mesh_default.rx(node, buf, len);
}
static void log_fn(char ch, void *arg) {
hal_uart_write_buf(arg, &ch, 1);
}
int main(void) {
static struct mg_tcpip_driver_rw612_data eth_data;
static struct mg_tcpip_if eth;
static struct mg_tcpip_driver eth_driver;
static char eth_queue[8192];
static struct mg_tcpip_driver_rw612w_data radio_data;
static struct mg_tcpip_if radio;
static struct mg_mesh mesh;
static struct mg_tcpip_driver radio_driver;
uint32_t lan_received = 0;
uint64_t lan_led_until = 0;
uint64_t link_timer = 0, stats_timer = 0;
@@ -68,15 +63,11 @@ int main(void) {
mg_log_set_fn(log_fn, USART3);
hal_ethernet_init();
mesh = mg_mesh_default;
mesh.tx = eth_down;
mesh.rx = radio_rx; // Observe radio reception without modifying the driver.
radio_data.strategy = &mesh;
radio.driver = &mg_tcpip_driver_rw612w;
radio.driver_data = &radio_data;
radio_driver = mg_tcpip_driver_rw612w;
radio_driver.tx = eth_down;
radio.driver = &radio_driver;
radio.fn = radio_fn;
if (!radio.driver->init(&radio)) return 1;
s_radio_tx = radio_data.mesh->tx;
radio_data.mesh->tx = radio_tx;
eth_data.mdc_cr = MG_DRIVER_MDC_CR;
eth_data.mdc_holdtime = MG_DRIVER_MDC_HOLDTIME;
@@ -90,10 +81,9 @@ int main(void) {
if (!eth.driver->init(&eth)) return 1;
ENET->RCR |= ENET_RCR_PROM_MASK; // Receive frames addressed to radio nodes.
radio_data.mesh->lan = &eth;
radio_data.mesh->next_tick = 0;
mg_radio_bridge(&radio, &eth);
MG_INFO(("Ethernet/radio bridge, channel %u", MG_802154_CHANNEL));
MG_INFO(("Ethernet/radio bridge, channel %u", MG_RADIO_CHANNEL));
stats_timer = mg_millis() + 5000;
for (;;) {
uint64_t now = mg_millis();
@@ -6,6 +6,7 @@
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_RW612 1 // Ethernet
#define MG_ENABLE_DRIVER_RW612W 1 // Mesh bridge over raw 802.15.4
#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only
#define MG_ENABLE_CUSTOM_MICROS 1
-99
View File
@@ -1,99 +0,0 @@
# Pico 2 / XIAO RP2040: 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 native RP2040/RP2350 USB
controller is driven directly: no PIO, Ethernet PHY, TinyUSB, or lwIP.
Mongoose provides TCP/IP, a DHCP server, and HTTP/HTTPS servers.
The USB code is a Mongoose driver, `src/drivers/usb_rp.c`, enabled by
`MG_ENABLE_DRIVER_USB_RP` in `mongoose_config.h`. `mg_mgr_init()` starts it,
so `main.c` only sets up the LED and the HTTP listeners.
## Build and flash
Install the Pico SDK, CMake, Arm GNU toolchain, and picotool. The Makefile
uses `~/src/pico-sdk`; override `PICO_SDK_PATH` if necessary.
The default target is `PICO_BOARD=pico2` (RP2350, Arm Cortex-M33).
```sh
make # Pico 2
make PICO_BOARD=seeed_xiao_rp2040 # XIAO RP2040
```
Each board has its own build directory, `build/pico2/firmware.uf2` or
`build/seeed_xiao_rp2040/firmware.uf2`, so RP2040 and RP2350 CMake settings
never mix.
On Pico 2, hold BOOTSEL while connecting the USB cable. On XIAO, hold BOOT
while pressing and releasing RESET, then release BOOT. Flash:
```sh
make flash
```
The firmware also enters BOOTSEL when its serial port is opened at 1200 baud
and DTR drops. `picotool -f` alone cannot reboot it: the driver does not
implement the Pico SDK vendor reset interface.
## 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
```
Use the actual serial device path. The baud rate is ignored, except that
1200 baud followed by DTR dropping requests BOOTSEL. To exit screen, press
Ctrl-A, then backslash, and confirm. The serial port is an output console;
received bytes are discarded.
Linux normally provides NCM and ACM drivers. Windows 11 provides NCM and ACM;
the driver includes Microsoft OS 2.0 compatible ID descriptors for driver
binding. Linux and Windows have not been tested here. Windows 10 has no
built-in NCM driver.
## Implementation
* `main.c`: LED blink task and the HTTP/HTTPS handler.
* `../../../src/drivers/usb_rp.c`: RP2040/RP2350 USB device controller.
* `../../../src/drivers/usb.c`: controller independent NCM + ACM:
descriptors, control requests, NTB16 negotiation, framing, parser, and the
serial log buffer. Shared with the SAMD21 driver, `usb_samd21.c`.
* Network control/data interfaces 0/1; ACM control/data interfaces 2/3.
* Network endpoints: interrupt IN 0x81, bulk OUT/IN 0x02/0x82.
* Serial endpoints: interrupt IN 0x83, bulk OUT/IN 0x04/0x84.
* Full-speed USB, 64-byte packets. Transfers span multiple packets and end
with short packets or ZLPs. Ethernet FCS is not sent on USB.
* NTB16 with no CRC, 4 KiB maximum IN/OUT blocks, and up to 16 incoming
datagrams per block, including chained NDPs. The whole block is validated
before any frame is delivered. NTB32 and CRC mode are not advertised.
* One Ethernet frame per outgoing block, within the host's negotiated input
size. Outgoing frames are not aggregated.
* Host and device MAC addresses and the USB serial number come from the
board's flash ID. One outgoing block can be in flight; incoming frames go
to Mongoose's 8 KiB queue. The serial log is a nonblocking 2 KiB ring; old
logs are overwritten when the host is not reading.
* Buffer sizes can be changed with `MG_USB_NCM_NTB_SIZE`,
`MG_USB_NCM_LOG_SIZE` and `MG_USB_NCM_QUEUE_SIZE`.
* Single core, polled from `mg_mgr_poll()`. No host mode, RNDIS, suspend,
remote wake, or Ethernet bridging.
The development VID/PID is `CAFE:40E4`, not an allocation for shipped
products. Get a legitimate VID/PID before distributing hardware.
+1
View File
@@ -5,6 +5,7 @@
#define MG_ENABLE_DRIVER_USB_RP 1 // RP2040 / RP2350 USB controller
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
#define MG_USB_REBOOT() reset_usb_boot(0, 0) // 1200 baud touch: BOOTSEL
// 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
+9 -8
View File
@@ -1,16 +1,17 @@
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
MGDIR = ../../../..
SDK = silabs_sdk/platform
RAIL = $(SDK)/radio/rail_lib
CFLAGS = -W -Wall -Wextra -Werror -Wshadow # No -Wundef: RAIL headers
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
CFLAGS += -I$(SDK)/Device/SiliconLabs/EFR32MG24/Include -I$(SDK)/common/inc
CFLAGS += -I$(RAIL)/common -I$(RAIL)/protocol/ieee802154
CFLAGS += -I$(RAIL)/chip/efr32/efr32xg2x
CFLAGS += -Isilabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Include
CFLAGS += -Isilabs_sdk/platform/common/inc
CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/common
CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/protocol/ieee802154
CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/protocol/ble
CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/chip/efr32/efr32xg2x
CFLAGS += -DEFR32MG24B220F1536IM48
CFLAGS += -D__START=main # For startup_efr32mg24.c
CFLAGS += -mcpu=cortex-m33 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 -mcmse
@@ -21,8 +22,8 @@ LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc -W
SOURCES = main.c hal.c $(MGDIR)/mongoose.c
SOURCES += $(MGDIR)/tutorials/mqtt/mqtt-client/mongoose_mqtt.c
SOURCES += $(SDK)/Device/SiliconLabs/EFR32MG24/Source/startup_efr32mg24.c
SOURCES += $(SDK)/Device/SiliconLabs/EFR32MG24/Source/system_efr32mg24.c
SOURCES += silabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Source/startup_efr32mg24.c
SOURCES += silabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Source/system_efr32mg24.c
# RAIL radio library, a binary blob. Simplicity SDK keeps it in Git LFS,
# served by Silicon Labs. The oid is the file's sha256, see the LFS pointer
@@ -51,7 +52,7 @@ cmsis_core:
# Device headers, startup code and RAIL headers from Simplicity SDK
silabs_sdk:
GIT_LFS_SKIP_SMUDGE=1 git clone -q -c advice.detachedHead=false --depth 1 -b $(SDK_VERSION) --filter=blob:none --no-checkout https://github.com/SiliconLabs/simplicity_sdk $@
cd $@ && git sparse-checkout set --no-cone /platform/Device/SiliconLabs/EFR32MG24/ /platform/common/inc/ /platform/radio/rail_lib/common/ /platform/radio/rail_lib/protocol/ieee802154/ /platform/radio/rail_lib/chip/efr32/efr32xg2x/
cd $@ && git sparse-checkout set --no-cone /platform/Device/SiliconLabs/EFR32MG24/ /platform/common/inc/ /platform/radio/rail_lib/common/ /platform/radio/rail_lib/protocol/ieee802154/ /platform/radio/rail_lib/protocol/ble/ /platform/radio/rail_lib/chip/efr32/efr32xg2x/
cd $@ && GIT_LFS_SKIP_SMUDGE=1 git checkout -q
$(LIBRAIL):
@@ -0,0 +1,37 @@
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
# Nucleo-U5A5ZJ-Q: Mongoose over the USB-C port CN15, OTG_HS with its embedded
# PHY, no TinyUSB. Flash over the ST-LINK USB port
MGDIR = ../../../..
CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion
CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Icmsis_u5/Include
CFLAGS += -mcpu=cortex-m33 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard
CFLAGS += $(CFLAGS_EXTRA)
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections
SOURCES = main.c hal.c $(MGDIR)/mongoose.c
SOURCES += cmsis_u5/Source/Templates/gcc/startup_stm32u5a5xx.s
all build: firmware.bin
firmware.bin: firmware.elf
arm-none-eabi-objcopy -O binary $< $@
arm-none-eabi-size --format=berkeley $<
firmware.elf: cmsis_core cmsis_u5 $(SOURCES) $(wildcard *.h) $(MGDIR)/mongoose.h link.ld Makefile
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
flash: firmware.elf
STM32_Programmer_CLI -c port=swd -e all -w $< -hardRst
cmsis_core:
git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@
cmsis_u5:
git clone -q -c advice.detachedHead=false --depth 1 -b v1.4.2 https://github.com/STMicroelectronics/cmsis_device_u5 $@
clean:
rm -rf firmware.* cmsis_*
@@ -0,0 +1,131 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include "hal.h"
// Added to minimise the bin size: avoid pulling printf and friends
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; // or trigger the fault handler
}
bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now) {
uint64_t diff = now - *t; // Wrap-safe elapsed time since last expiry
if (period == 0) return false; // Avoid division by zero
if (diff < period) return false; // Period has not elapsed yet
*t += (diff / period) * period; // Preserve cadence, skip missed periods
return true;
}
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;
};
uint32_t SystemCoreClock = SYS_FREQUENCY;
void SystemInit(void) { // Called automatically by startup code
hal_system_init(); // Enable FPU
hal_clock_init();
SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms
}
void ExitRun0Mode(void) {
}
struct stat;
__attribute__((weak)) int _fstat(int fd, struct stat *st) {
(void) fd, (void) st;
return -1;
}
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;
}
__attribute__((weak)) int _open(const char *path) {
(void) path;
return -1;
}
__attribute__((weak)) int _close(int fd) {
(void) fd;
return -1;
}
__attribute__((weak)) int _isatty(int fd) {
(void) fd;
return 1;
}
__attribute__((weak)) int _lseek(int fd, int ptr, int dir) {
(void) fd, (void) ptr, (void) dir;
return 0;
}
__attribute__((weak)) void _exit(int status) {
(void) status;
for (;;) asm volatile("BKPT #0");
}
__attribute__((weak)) void _kill(int pid, int sig) {
(void) pid, (void) sig;
}
__attribute__((weak)) int _getpid(void) {
return -1;
}
__attribute__((weak)) int _write(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
__attribute__((weak)) int _read(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
__attribute__((weak)) int _link(const char *a, const char *b) {
(void) a, (void) b;
return -1;
}
__attribute__((weak)) int _unlink(const char *a) {
(void) a;
return -1;
}
__attribute__((weak)) int _stat(const char *path, struct stat *st) {
(void) path, (void) st;
return -1;
}
__attribute__((weak)) int mkdir(const char *path, int mode) {
(void) path, (void) mode;
return -1;
}
__attribute__((weak)) void _init(void) {
}
@@ -0,0 +1,184 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
//
// RM0456
// https://www.st.com/resource/en/reference_manual/rm0456-stm32u5-series-armbased-32bit-mcus-stmicroelectronics.pdf
// https://www.st.com/resource/en/user_manual/um2861-stm32u5-nucleo144-board-mb1549-stmicroelectronics.pdf
#pragma once
#define LED_1 PIN('C', 7) // On-board LED pin (green)
#define LED_2 PIN('B', 7) // On-board LED pin (blue)
#define LED_3 PIN('G', 2) // On-board LED pin (red)
#define LED LED_1 // Use green LED for blinking
#include <stm32u5a5xx.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
extern bool hal_timer_expired(volatile uint64_t *t, uint64_t prd, uint64_t now);
extern uint64_t hal_get_tick(void);
extern size_t hal_ram_free(void);
extern size_t hal_ram_used(void);
extern uint32_t SystemCoreClock;
#define BIT(x) (1UL << (x))
#define CLRSET(reg, clear, set) ((reg) = ((reg) & ~(clear)) | (set))
#define PIN(bank, num) ((((bank) - 'A') << 8) | (num))
#define PINNO(pin) (pin & 255)
#define PINBANK(pin) (pin >> 8)
enum {
HAL_D1PRE = 1, // actual divisor value
HAL_HPRE = 1, // actual divisor value
HAL_D2PRE = 1,
HAL_D3PRE = 1,
};
enum { PLL1_M = 1, PLL1_N = 80, PLL1_P = 2, PLL1_Q = 2, PLL1_R = 2 };
#define MSIS_FREQUENCY (4 * 1024 * 1024) // 4 Mhz
#define SYS_FREQUENCY \
(MSIS_FREQUENCY * PLL1_N / PLL1_M / PLL1_P / HAL_D1PRE) // 160MHz
#define AHB_FREQUENCY (SYS_FREQUENCY / HAL_HPRE)
#define APB2_FREQUENCY (AHB_FREQUENCY / HAL_D2PRE)
#define APB1_FREQUENCY (AHB_FREQUENCY / HAL_D1PRE)
static inline void spin(volatile uint32_t n) {
while (n--) (void) 0;
}
enum {
HAL_GPIO_MODE_INPUT,
HAL_GPIO_MODE_OUTPUT,
HAL_GPIO_MODE_AF,
HAL_GPIO_MODE_ANALOG
};
enum { HAL_GPIO_OTYPE_PUSH_PULL, HAL_GPIO_OTYPE_OPEN_DRAIN };
enum {
HAL_GPIO_SPEED_LOW,
HAL_GPIO_SPEED_MEDIUM,
HAL_GPIO_SPEED_HIGH,
HAL_GPIO_SPEED_INSANE
};
enum { HAL_GPIO_PULL_NONE, HAL_GPIO_PULL_UP, HAL_GPIO_PULL_DOWN };
#define HAL_GPIO(N) ((GPIO_TypeDef *) (GPIOA_BASE_NS + 0x400 * (N)))
static GPIO_TypeDef *hal_gpio_bank(uint16_t pin) {
return HAL_GPIO(PINBANK(pin));
}
static inline void hal_gpio_toggle(uint16_t pin) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
uint32_t mask = BIT(PINNO(pin));
gpio->BSRR = mask << (gpio->ODR & mask ? 16 : 0);
}
static inline void hal_gpio_write(uint16_t pin, bool val) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
gpio->BSRR = BIT(PINNO(pin)) << (val ? 0 : 16);
}
static inline void hal_gpio_init(uint16_t pin, uint8_t mode, uint8_t type,
uint8_t speed, uint8_t pull, uint8_t af) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
uint8_t n = (uint8_t) (PINNO(pin));
RCC->AHB2ENR1 |= BIT(PINBANK(pin)); // Enable GPIO clock
CLRSET(gpio->OTYPER, 1UL << n, ((uint32_t) type) << n);
CLRSET(gpio->OSPEEDR, 3UL << (n * 2), ((uint32_t) speed) << (n * 2));
CLRSET(gpio->PUPDR, 3UL << (n * 2), ((uint32_t) pull) << (n * 2));
CLRSET(gpio->AFR[n >> 3], 15UL << ((n & 7) * 4),
((uint32_t) af) << ((n & 7) * 4));
CLRSET(gpio->MODER, 3UL << (n * 2), ((uint32_t) mode) << (n * 2));
}
static inline void hal_gpio_output(uint16_t pin) {
hal_gpio_init(pin, HAL_GPIO_MODE_OUTPUT, HAL_GPIO_OTYPE_PUSH_PULL,
HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0);
}
static inline void hal_rng_init(void) {
RCC->CCIPR2 |= RCC_CCIPR2_RNGSEL_0; // RNG clock source pll1_q_ck
RCC->AHB2ENR1 |= RCC_AHB2ENR1_RNGEN; // Enable RNG clock
RNG->CR = RNG_CR_RNGEN; // Enable RNG
}
static inline uint32_t hal_rng_read(void) {
while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0;
return RNG->DR;
}
// OTG_HS and its embedded high-speed PHY, as ST's CubeU5 USBX examples for
// this board set them up. The PHY's reference clock is the board's 16 MHz
// HSE. PA11 and PA12 are the PHY's own pins: no GPIO setup. The Mongoose
// driver, usb_dwc2, then runs the core at full speed
static inline void hal_usb_init(void) {
RCC->CR |= RCC_CR_HSEON; // 16 MHz HSE: the PHY's reference clock
while ((RCC->CR & RCC_CR_HSERDY) == 0) spin(1);
RCC->CCIPR2 &= ~RCC_CCIPR2_USBPHYCSEL; // USB PHY clock: HSE
RCC->APB3ENR |= RCC_APB3ENR_SYSCFGEN;
CLRSET(SYSCFG->OTGHSPHYCR, SYSCFG_OTGHSPHYCR_CLKSEL,
SYSCFG_OTGHSPHYCR_CLKSEL_0 | SYSCFG_OTGHSPHYCR_CLKSEL_1); // 16 MHz
RCC->AHB2ENR1 |= RCC_AHB2ENR1_OTGEN | RCC_AHB2ENR1_USBPHYCEN;
PWR->SVMCR |= PWR_SVMCR_USV; // VDDUSB valid
PWR->VOSR |= PWR_VOSR_USBPWREN | PWR_VOSR_USBBOOSTEN; // PHY supply
SYSCFG->OTGHSPHYCR |= SYSCFG_OTGHSPHYCR_EN; // PHY on
}
static inline unsigned int hal_ahb_div2prescval(unsigned int div) {
if (div == 1) return 0;
unsigned int val = 7;
while (div >>= 1) ++val;
return val;
}
static inline unsigned int hal_apb_div2prescval(unsigned int div) {
if (div <= 1) return 0;
unsigned int val = 0;
while (div >>= 1) ++val;
return val + 2;
}
static inline void hal_clock_init(void) {
FLASH->ACR |= BIT(8); // prefetch
RCC->AHB3ENR |= RCC_AHB3ENR_PWREN;
PWR->SVMCR |= PWR_SVMCR_IO2SV; // Enable VDDIO2 supply
PWR->UCPDR |= PWR_UCPDR_UCPD_DBDIS; // Disable the internal Pull-Up in Dead
// Battery pins of UCPD peripheral
PWR->CR3 |= PWR_CR3_REGSEL; // enable SMPS
while ((PWR->SVMSR & BIT(1)) == 0) spin(1);
if ((PWR->SVMSR & PWR_SVMSR_ACTVOS) != (PWR_VOSR_VOS_0 | PWR_VOSR_VOS_1)) {
// control voltage scaling
PWR->VOSR |= PWR_VOSR_VOS_0 | PWR_VOSR_VOS_1 | PWR_VOSR_BOOSTEN;
while ((PWR->VOSR & PWR_VOSR_VOSRDY) == 0) spin(1);
while ((PWR->SVMSR & PWR_SVMSR_ACTVOSRDY) == 0) spin(1);
}
PWR->DBPR |= PWR_DBPR_DBP; // enable backup access
CLRSET(RCC->BDCR, 3 << 3, 0); // RCC_LSEDRIVE_LOW
RCC->BDCR |= RCC_BDCR_LSEON; // LSE enable
while ((RCC->BDCR & RCC_BDCR_LSERDY) == 0) spin(1);
RCC->BDCR |= RCC_BDCR_LSESYSEN; // LSESYS enable
while ((RCC->BDCR & RCC_BDCR_LSESYSRDY) == 0) spin(1);
PWR->VOSR &= ~PWR_VOSR_BOOSTEN;
RCC->CR &= ~BIT(24); // configure PLL1
while ((RCC->CR & RCC_CR_PLL1RDY) != 0) spin(1);
RCC->PLL1CFGR = BIT(0) | ((PLL1_M - 1) << 8) | BIT(16) | BIT(17) |
BIT(18); // source, PLL1_M, enable PLL1_P, PLL1_Q
RCC->PLL1DIVR = (PLL1_N - 1) | ((PLL1_P - 1) << 9) | ((PLL1_Q - 1) << 16) |
((PLL1_R - 1) << 24);
PWR->VOSR |= PWR_VOSR_BOOSTEN;
RCC->CR |= BIT(24); // PLL1ON
while ((RCC->CR & RCC_CR_PLL1RDY) == 0) spin(1);
CLRSET(FLASH->ACR, 0xf, 4); // flash latency 4
RCC->CFGR1 |= 3; // set PLL as sysclk source
CLRSET(RCC->CFGR2, 0xf, hal_ahb_div2prescval(HAL_HPRE)); // HPRE
CLRSET(RCC->CFGR2, 0x70, hal_apb_div2prescval(HAL_D1PRE) << 4); // D1PRE
CLRSET(RCC->CFGR2, 0x700, hal_apb_div2prescval(HAL_D2PRE) << 8); // D2PRE
CLRSET(RCC->CFGR3, 0x70, hal_apb_div2prescval(HAL_D3PRE) << 4); // D3PRE
}
static inline void hal_system_init(void) {
SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU
__DSB();
__ISB();
SCB->VTOR = FLASH_BASE; // Vector Table Relocation in Internal FLASH
}
@@ -0,0 +1,31 @@
ENTRY(Reset_Handler);
MEMORY {
flash(rx) : ORIGIN = 0x08000000, LENGTH = 4096k
sram(rwx) : ORIGIN = 0x20000000, LENGTH = 256k
}
_estack = ORIGIN(sram) + LENGTH(sram); /* stack points to end of SRAM */
SECTIONS {
.vectors : { KEEP(*(.isr_vector)) } > flash
.text : { *(.text* .text.*) } > flash
.rodata : { *(.rodata*) } > flash
.data : {
_sdata = .;
*(.first_data)
*(.data SORT(.data.*))
*(.iram .iram* .iram.*)
_edata = .;
} > sram AT > flash
_sidata = LOADADDR(.data);
.bss : {
_sbss = .;
*(.bss SORT(.bss.*) COMMON)
_ebss = .;
} > sram
. = ALIGN(8);
_end = .;
}
@@ -0,0 +1,90 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
//
// Nucleo-U5A5ZJ-Q: Mongoose over USB. One USB-C cable on CN15 gives the board
// a CDC-NCM Ethernet interface and a CDC-ACM serial port that carries the log
#include "hal.h"
#include "mongoose.h"
static void blink_task(void) {
static uint64_t blink_timer = 0;
if (mg_timer_expired(&blink_timer, 500, mg_millis())) hal_gpio_toggle(LED);
}
uint64_t mg_millis(void) {
return hal_get_tick();
}
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;
}
// Self-signed P-256 certificate and key for the HTTPS listener. Created by:
// openssl ecparam -genkey -name prime256v1 -noout -out key.pem
// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg
#define TLS_CERT \
"-----BEGIN CERTIFICATE-----\n" \
"MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \
"FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \
"MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \
"SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \
"uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \
"MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \
"BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \
"lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \
"BCjX++LI\n" \
"-----END CERTIFICATE-----\n"
#define TLS_KEY \
"-----BEGIN EC PRIVATE KEY-----\n" \
"MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \
"AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \
"LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \
"-----END EC PRIVATE KEY-----\n"
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener
struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT),
.key = mg_str(TLS_KEY)};
mg_tls_init(c, &opts);
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) {
mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis());
} else {
mg_http_reply(c, 200, "",
"Hi from Mongoose!\n"
"tick: %llu\n"
"ram used: %zu\n"
"ram free: %zu\n",
mg_millis(), hal_ram_used(), hal_ram_free());
}
}
}
int main(void) {
hal_rng_init();
hal_gpio_output(LED);
hal_usb_init();
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h
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_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000));
MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free()));
MG_INFO(("USB Ethernet + serial"));
for (;;) {
mg_mgr_poll(&mgr, 0);
blink_task();
}
return 0;
}
@@ -0,0 +1,32 @@
#pragma once
#include "hal.h" // Device header: UID_BASE gives the USB serial number
// See https://mongoose.ws/docs/getting-started/build-environment/
#define MG_ARCH MG_ARCH_ARMGCC
#define MG_TLS MG_TLS_BUILTIN
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_ENABLE_DRIVER_USB_DWC2 1 // STM32 OTG_HS: the USB-C port, CN15
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
#define MG_USB_DWC2_BASE USB_OTG_HS_BASE // OTG_HS
#define MG_USB_DWC2_UTMI 1 // Embedded high-speed PHY
// No VBUS sensing: tell the PHY that VBUS is valid
#define MG_USB_DWC2_GCCFG (USB_OTG_GCCFG_VBVALEXTOEN | USB_OTG_GCCFG_VBVALOVAL)
// 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)
#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0)
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2; \
mac[1] = 3; \
mac[2] = 4; \
mac[3] = 5; \
mac[4] = 6; \
mac[5] = 7; \
} while (0)
@@ -0,0 +1,43 @@
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
# Portenta H7: Mongoose over the USB-C port, no TinyUSB. Flash over USB with
# dfu-util: Arduino's bootloader stays at 0x08000000, the firmware goes to
# 0x08040000. Double-tap RESET to enter the bootloader, or `make flash` again
# once this firmware runs: it reboots into the bootloader on a 1200 baud touch
MGDIR = ../../../..
CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion
CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Icmsis_h7/Include
CFLAGS += -mcpu=cortex-m7 -mthumb -mfloat-abi=hard -mfpu=fpv5-d16 -DCORE_CM7
CFLAGS += $(CFLAGS_EXTRA)
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections
SOURCES = main.c hal.c $(MGDIR)/mongoose.c
SOURCES += cmsis_h7/Source/Templates/gcc/startup_stm32h747xx.s
all build: firmware.bin
firmware.bin: firmware.elf
arm-none-eabi-objcopy -O binary $< $@
arm-none-eabi-size --format=berkeley $<
firmware.elf: cmsis_core cmsis_h7 $(SOURCES) $(wildcard *.h) $(MGDIR)/mongoose.h link.ld Makefile
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
# Bootloader entry: open the board's serial port at 1200 baud. PORT: the
# board's USB serial port, e.g. /dev/cu.usbmodem1234. Without PORT, enter
# the bootloader by double-tapping RESET
flash: firmware.bin
$(if $(PORT),stty -f $(PORT) 1200 2>/dev/null || stty -F $(PORT) 1200;)
dfu-util -w -a 0 -s 0x8040000:leave -D $<
cmsis_core:
git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@
cmsis_h7:
git clone -q -c advice.detachedHead=false --depth 1 -b v1.10.4 https://github.com/STMicroelectronics/cmsis_device_h7 $@
clean:
rm -rf firmware.* cmsis_*
@@ -0,0 +1,131 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include "hal.h"
// Added to minimise the bin size: avoid pulling printf and friends
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; // or trigger the fault handler
}
bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now) {
uint64_t diff = now - *t; // Wrap-safe elapsed time since last expiry
if (period == 0) return false; // Avoid division by zero
if (diff < period) return false; // Period has not elapsed yet
*t += (diff / period) * period; // Preserve cadence, skip missed periods
return true;
}
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;
};
uint32_t SystemCoreClock = SYS_FREQUENCY;
void SystemInit(void) { // Called automatically by startup code
hal_system_init(); // Enable FPU
hal_clock_init();
SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms
}
void ExitRun0Mode(void) {
}
struct stat;
__attribute__((weak)) int _fstat(int fd, struct stat *st) {
(void) fd, (void) st;
return -1;
}
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;
}
__attribute__((weak)) int _open(const char *path) {
(void) path;
return -1;
}
__attribute__((weak)) int _close(int fd) {
(void) fd;
return -1;
}
__attribute__((weak)) int _isatty(int fd) {
(void) fd;
return 1;
}
__attribute__((weak)) int _lseek(int fd, int ptr, int dir) {
(void) fd, (void) ptr, (void) dir;
return 0;
}
__attribute__((weak)) void _exit(int status) {
(void) status;
for (;;) asm volatile("BKPT #0");
}
__attribute__((weak)) void _kill(int pid, int sig) {
(void) pid, (void) sig;
}
__attribute__((weak)) int _getpid(void) {
return -1;
}
__attribute__((weak)) int _write(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
__attribute__((weak)) int _read(int fd, char *ptr, int len) {
(void) fd, (void) ptr, (void) len;
return -1;
}
__attribute__((weak)) int _link(const char *a, const char *b) {
(void) a, (void) b;
return -1;
}
__attribute__((weak)) int _unlink(const char *a) {
(void) a;
return -1;
}
__attribute__((weak)) int _stat(const char *path, struct stat *st) {
(void) path, (void) st;
return -1;
}
__attribute__((weak)) int mkdir(const char *path, int mode) {
(void) path, (void) mode;
return -1;
}
__attribute__((weak)) void _init(void) {
}
@@ -0,0 +1,198 @@
// Copyright (c) 2022-2026 Cesanta Software Limited
// All rights reserved
//
// RM0399
// https://www.st.com/resource/en/reference_manual/rm0399-stm32h745755-and-stm32h747757-advanced-armbased-32bit-mcus-stmicroelectronics.pdf
// https://www.st.com/resource/en/datasheet/stm32h747xi.pdf
// https://docs.arduino.cc/hardware/portenta-h7/
#pragma once
#define LED_1 PIN('K', 5) // On-board LED pin (red)
#define LED_2 PIN('K', 6) // On-board LED pin (green)
#define LED_3 PIN('K', 7) // On-board LED pin (blue)
#define LED LED_2 // Use green LED for blinking
#include <stm32h747xx.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
extern bool hal_timer_expired(volatile uint64_t *t, uint64_t prd, uint64_t now);
extern uint64_t hal_get_tick(void);
extern size_t hal_ram_free(void);
extern size_t hal_ram_used(void);
extern uint32_t SystemCoreClock;
#define BIT(x) (1UL << (x))
#define CLRSET(reg, clear, set) ((reg) = ((reg) & ~(clear)) | (set))
#define PIN(bank, num) ((((bank) - 'A') << 8) | (num))
#define PINNO(pin) (pin & 255)
#define PINBANK(pin) (pin >> 8)
// System clock (2.1, Fig 1; 8.5, Fig 45; 8.5.5, Fig 47; 8.5.6, Fig 49)
// - This board defaults to work with an SMPS regulator, so:
// - SYS_FREQUENCY <= 400 MHz; hclk = SYS_FREQUENCY / HPRE ; hclk <= 200 MHz;
// APB clocks <= 100 MHz.
// - D1 domain bus matrix (and so flash) runs at hclk frequency. Configure flash
// latency (WS) in accordance to hclk freq (4.3.8, Table 17)
enum {
HAL_D1CPRE = 1, // actual divisor value
HAL_HPRE = 2, // actual divisor value
HAL_D1PPRE = 4, // register values, divisor value = BIT(value - 3) = / 2
HAL_D2PPRE1 = 4,
HAL_D2PPRE2 = 4,
HAL_D3PPRE = 4
};
// PLL1_P: odd division factors are not allowed (8.7.13) (according to Cube, '1'
// is also an "odd division factor").
// Make sure your chip is revision 'V', otherwise set PLL1_N = 400
enum { PLL1_HSI = 64, PLL1_M = 32, PLL1_N = 400, PLL1_P = 2, PLL1_Q = 4 };
#define SYS_FREQUENCY \
((PLL1_HSI * PLL1_N / PLL1_M / PLL1_P / HAL_D1CPRE) * 1000000)
static inline void spin(volatile uint32_t n) {
while (n--) (void) 0;
}
enum {
HAL_GPIO_MODE_INPUT,
HAL_GPIO_MODE_OUTPUT,
HAL_GPIO_MODE_AF,
HAL_GPIO_MODE_ANALOG
};
enum { HAL_GPIO_OTYPE_PUSH_PULL, HAL_GPIO_OTYPE_OPEN_DRAIN };
enum {
HAL_GPIO_SPEED_LOW,
HAL_GPIO_SPEED_MEDIUM,
HAL_GPIO_SPEED_HIGH,
HAL_GPIO_SPEED_INSANE
};
enum { HAL_GPIO_PULL_NONE, HAL_GPIO_PULL_UP, HAL_GPIO_PULL_DOWN };
#define HAL_GPIO(N) ((GPIO_TypeDef *) (0x40000000 + 0x18020000UL + 0x400 * (N)))
static inline GPIO_TypeDef *hal_gpio_bank(uint16_t pin) {
return HAL_GPIO(PINBANK(pin));
}
static inline void hal_gpio_toggle(uint16_t pin) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
uint32_t mask = BIT(PINNO(pin));
gpio->BSRR = mask << (gpio->ODR & mask ? 16 : 0);
}
static inline void hal_gpio_write(uint16_t pin, bool val) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
gpio->BSRR = BIT(PINNO(pin)) << (val ? 0 : 16);
}
static inline void hal_gpio_init(uint16_t pin, uint8_t mode, uint8_t type,
uint8_t speed, uint8_t pull, uint8_t af) {
GPIO_TypeDef *gpio = hal_gpio_bank(pin);
uint8_t n = (uint8_t) (PINNO(pin));
RCC->AHB4ENR |= BIT(PINBANK(pin)); // Enable GPIO clock
CLRSET(gpio->OTYPER, 1UL << n, ((uint32_t) type) << n);
CLRSET(gpio->OSPEEDR, 3UL << (n * 2), ((uint32_t) speed) << (n * 2));
CLRSET(gpio->PUPDR, 3UL << (n * 2), ((uint32_t) pull) << (n * 2));
CLRSET(gpio->AFR[n >> 3], 15UL << ((n & 7) * 4),
((uint32_t) af) << ((n & 7) * 4));
CLRSET(gpio->MODER, 3UL << (n * 2), ((uint32_t) mode) << (n * 2));
}
static inline void hal_gpio_output(uint16_t pin) {
hal_gpio_init(pin, HAL_GPIO_MODE_OUTPUT, HAL_GPIO_OTYPE_PUSH_PULL,
HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0);
}
static inline void hal_rng_init(void) {
RCC->D2CCIP2R |= RCC_D2CCIP2R_RNGSEL_0; // RNG clock source pll1_q_ck
RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN; // Enable RNG clock
RNG->CR = RNG_CR_RNGEN; // Enable RNG
}
static inline uint32_t hal_rng_read(void) {
while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0;
return RNG->DR;
}
// USB-C: the OTG_HS core with an external ULPI PHY, on these pins, alternate
// function 10. Pins from Arduino's mbed-os, TARGET_PORTENTA_H7
// PeripheralPins.c. Arduino's bootloader uses the same port for DFU, and
// leaves the PHY running. The OTG_HS core's kernel clock: HSI48
static inline void hal_usb_init(void) {
uint16_t pins[] = {PIN('A', 3), PIN('A', 5), PIN('B', 0), PIN('B', 1),
PIN('B', 5), PIN('B', 10), PIN('B', 11), PIN('B', 12),
PIN('B', 13), PIN('C', 0), PIN('H', 4), PIN('I', 11)};
for (size_t i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) {
hal_gpio_init(pins[i], HAL_GPIO_MODE_AF, HAL_GPIO_OTYPE_PUSH_PULL,
HAL_GPIO_SPEED_INSANE, HAL_GPIO_PULL_NONE, 10);
}
RCC->CR |= RCC_CR_HSI48ON;
while ((RCC->CR & RCC_CR_HSI48RDY) == 0) spin(1);
CLRSET(RCC->D2CCIP2R, RCC_D2CCIP2R_USBSEL, RCC_D2CCIP2R_USBSEL); // HSI48
RCC->AHB1ENR |= RCC_AHB1ENR_USB1OTGHSEN | RCC_AHB1ENR_USB1OTGHSULPIEN;
RCC->AHB1RSTR |= RCC_AHB1RSTR_USB1OTGHSRST; // A clean core: the bootloader
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_USB1OTGHSRST; // used it for DFU
}
// Restart into Arduino's bootloader, in DFU mode: what ArduinoCore-mbed's
// _ontouch1200bps_() does for the Portenta H7, RTC backup register 0 = 0xDF59
static inline void hal_reboot_to_bootloader(void) {
PWR->CR1 |= PWR_CR1_DBP; // Allow backup domain writes
RCC->APB4ENR |= RCC_APB4ENR_RTCAPBEN;
RTC->BKP0R = 0xDF59;
NVIC_SystemReset();
}
static inline unsigned int hal_div2prescval(unsigned int div) {
// 0 --> /1; 8 --> /2 ... 11 --> /16; 12 --> /64 ... 15 --> /512
if (div == 1) return 0;
if (div > 16) div /= 2;
unsigned int val = 7;
while (div >>= 1) ++val;
return val;
}
static inline unsigned int hal_pllrge(unsigned int f) {
unsigned int val = 0;
while (f >>= 1) ++val;
return val - 1;
}
// HSE: 25MHz in PH0; LSE: in PC14; both unused
static inline void hal_clock_init(void) { // Called automatically by startup
// Set flash latency. RM section 4.9.1, section 4.3.8 table 16
CLRSET(FLASH->ACR, (FLASH_ACR_WRHIGHFREQ_Msk | FLASH_ACR_LATENCY_Msk),
FLASH_ACR_LATENCY_2WS | FLASH_ACR_WRHIGHFREQ_1);
CLRSET(PWR->CR3, BIT(1), BIT(2)); // select SMPS
while ((PWR->CSR1 & BIT(13)) == 0) spin(1); // ACTVOSRDY
PWR->D3CR |= BIT(15) | BIT(14); // Select VOS1
uint32_t f = PWR->D3CR; // fake read to wait for bus clocking
while ((PWR->CSR1 & BIT(13)) == 0) spin(1); // ACTVOSRDY
(void) f;
RCC->CFGR &= ~(3 << 0); // Set clock source to HSI (bootloader...)
RCC->CR &= ~BIT(24); // Disable PLL1
CLRSET(RCC->D1CFGR, (0x0F << 8) | (7 << 4) | (0x0F << 0),
(hal_div2prescval(HAL_D1CPRE) << 8) | (HAL_D1PPRE << 4) |
(hal_div2prescval(HAL_HPRE) << 0));
RCC->D2CFGR = (HAL_D2PPRE2 << 8) | (HAL_D2PPRE1 << 4);
RCC->D3CFGR = (HAL_D3PPRE << 4);
// DIVQ1EN DIVP1EN PLL1RGE !PLL1VCOSEL !PLL1FRACEN
CLRSET(RCC->PLLCFGR, (3 << 2) | BIT(1) | BIT(0),
BIT(17) | BIT(16) | hal_pllrge(PLL1_HSI / PLL1_M) << 2);
CLRSET(RCC->PLL1DIVR, (0x7F << 16) | (0x7F << 9) | (0x1FF << 0),
((PLL1_Q - 1) << 16) | ((PLL1_P - 1) << 9) | ((PLL1_N - 1) << 0));
CLRSET(RCC->PLLCKSELR, (0x3F << 4) | (3 << 0), PLL1_M << 4); // HSI/M
RCC->CR |= BIT(24); // PLL1 on
while ((RCC->CR & BIT(25)) == 0) spin(1); // Wait until done
RCC->CFGR |= (3 << 0); // Set clock source to PLL1
while ((RCC->CFGR & (7 << 3)) != (3 << 3)) spin(1); // Wait until done
RCC->APB4ENR |= RCC_APB4ENR_SYSCFGEN; // Enable SYSCFG
}
static inline void hal_system_init(void) {
SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU
SCB_DisableDCache(); // The bootloader enables caches, disable them
SCB_DisableICache();
__DSB();
__ISB();
}
@@ -0,0 +1,33 @@
/* DTCMRAM (rwx) : ORIGIN = 0x20000400, LENGTH = 128k - 1k */ /* bootloader starts at 0x20000000 */
ENTRY(Reset_Handler);
MEMORY {
flash(rx) : ORIGIN = 0x08040000, LENGTH = 2048k - 0x40000 /* bootloader starts at 0x08000000 */
sram(rwx) : ORIGIN = 0x24000000, LENGTH = 512k
}
_estack = ORIGIN(sram) + LENGTH(sram); /* stack points to end of SRAM */
SECTIONS {
.vectors : { KEEP(*(.isr_vector)) } > flash
.text : { *(.text* .text.*) } > flash
.rodata : { *(.rodata*) } > flash
.data : {
_sdata = .;
*(.first_data)
*(.data SORT(.data.*))
*(.iram .iram* .iram.*)
_edata = .;
} > sram AT > flash
_sidata = LOADADDR(.data);
.bss : {
_sbss = .;
*(.bss SORT(.bss.*) COMMON)
_ebss = .;
} > sram
. = ALIGN(8);
_end = .;
}
@@ -0,0 +1,91 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
//
// Portenta H7: Mongoose over USB. One USB-C cable gives the board a CDC-NCM
// Ethernet interface and a CDC-ACM serial port that carries the log
#include "hal.h"
#include "mongoose.h"
static void blink_task(void) {
static uint64_t blink_timer = 0;
if (mg_timer_expired(&blink_timer, 500, mg_millis())) hal_gpio_toggle(LED);
}
uint64_t mg_millis(void) {
return hal_get_tick();
}
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;
}
// Self-signed P-256 certificate and key for the HTTPS listener. Created by:
// openssl ecparam -genkey -name prime256v1 -noout -out key.pem
// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg
#define TLS_CERT \
"-----BEGIN CERTIFICATE-----\n" \
"MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \
"FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \
"MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \
"SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \
"uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \
"MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \
"BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \
"lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \
"BCjX++LI\n" \
"-----END CERTIFICATE-----\n"
#define TLS_KEY \
"-----BEGIN EC PRIVATE KEY-----\n" \
"MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \
"AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \
"LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \
"-----END EC PRIVATE KEY-----\n"
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener
struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT),
.key = mg_str(TLS_KEY)};
mg_tls_init(c, &opts);
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) {
mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis());
} else {
mg_http_reply(c, 200, "",
"Hi from Mongoose!\n"
"tick: %llu\n"
"ram used: %zu\n"
"ram free: %zu\n",
mg_millis(), hal_ram_used(), hal_ram_free());
}
}
}
int main(void) {
hal_rng_init();
hal_gpio_output(LED);
hal_gpio_write(LED, true); // Off, the LEDs are active low
hal_usb_init();
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h
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_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000));
MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free()));
MG_INFO(("USB Ethernet + serial"));
for (;;) {
mg_mgr_poll(&mgr, 0);
blink_task();
}
return 0;
}
@@ -0,0 +1,31 @@
#pragma once
#include "hal.h" // Device header: UID_BASE gives the USB serial number
// See https://mongoose.ws/docs/getting-started/build-environment/
#define MG_ARCH MG_ARCH_ARMGCC
#define MG_TLS MG_TLS_BUILTIN
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_ENABLE_DRIVER_USB_DWC2 1 // STM32 OTG: the USB-C port
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
#define MG_USB_DWC2_BASE USB1_OTG_HS_PERIPH_BASE // OTG_HS
#define MG_USB_DWC2_ULPI 1 // External ULPI PHY
#define MG_USB_REBOOT() hal_reboot_to_bootloader() // 1200 baud touch
// 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)
#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0)
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2; \
mac[1] = 3; \
mac[2] = 4; \
mac[3] = 5; \
mac[4] = 6; \
mac[5] = 7; \
} while (0)