Skip to main content

Primeros Pasos con Seeed Studio XIAO nRF54L15(Sense)

Seeed Studio XIAO nRF54L15Seeed Studio XIAO nRF54L15 Sense

Introducción

El Seeed Studio XIAO nRF54L15 es una placa de desarrollo compacta y de alto rendimiento que cuenta con el chip Nordic nRF54L15 de vanguardia. Este SoC de próxima generación integra una radio multi-protocolo de 2.4 GHz de ultra bajo consumo con un MCU que contiene un procesador Arm® Cortex®-M33 de 128 MHz y un Arm® Cortex®-M0+ para gestión avanzada de energía. Ofrece memoria escalable de hasta 1.5 MB NVM y 256 KB RAM, y un diseño interno de ultra bajo consumo que extiende significativamente la vida útil de la batería. Su potente radio soporta Bluetooth® 6.0 (incluyendo Channel Sounding), Matter, Thread, Zigbee, y modos propietarios de 2.4 GHz de alto rendimiento hasta 4 Mbps. La placa incluye un conjunto completo de periféricos, un coprocesador RISC-V de 128 MHz integrado, y características de seguridad avanzadas como aislamiento TrustZone® y protección del motor criptográfico. Con gestión integrada de batería Li-ion, el XIAO nRF54L15 es ideal para soluciones IoT compactas, seguras y energéticamente eficientes como wearables inteligentes, sensores industriales y HMIs avanzados.

Especificaciones

ElementoXIAO nRF54L15XIAO nRF54L15 Sense
MCUArm Cortex-M33 128 MHz
Coprocesador RISC-V 128 MHz FLPR
Arm Cortex-M33 128 MHz
Coprocesador RISC-V 128 MHz FLPR
Conectividad Inalámbrica

Bluetooth LE 6.0(incluye Channel Sounding)
NFC
Thread
Zigbee
Matter
Amazon Sidewalk
Protocolos propietarios 2.4 GHz

Bluetooth LE 6.0(incluye Channel Sounding)
NFC
Thread
Zigbee
Matter
Amazon Sidewalk
Protocolos propietarios 2.4 GHz

MemoriaNVM 1.5 MB + RAM256 KBNVM 1.5 MB + RAM256 KB
Sensor IntegradoN/AIMU 6 DOF(LSM6DS3TR-C)
Micrófono (MSM261DGT006)
Potencia TX+8 dBm+8 dBm
Sensibilidad RX-96 dBm-96 dBm
Periféricos destacadosADC de 14 bits, RTC GlobalADC de 14 bits, RTC Global
Alimentación

Alimentación por interfaz USB Type-C
PMIC interno soporta alimentación por batería de litio
Soporta recolección de energía de batería de litio

Alimentación por interfaz USB Type-C
PMIC interno soporta alimentación por batería de litio
Soporta recolección de energía de batería de litio

Temperatura de operación-40 a 105°C-40 a 105°C
Rango de voltaje de alimentación3.7 a 5 V3.7 a 5 V
ESB y Protocolos Propietarios 2.4 GHzhasta 4 Mbpshasta 4 Mbps
Detectores de manipulación
Bluetooth channel sounding

Características

  • CPU Potente: Procesador Arm® Cortex®-M33 de 128 MHz con soporte para instrucciones DSP y operaciones de punto flotante FPU, arquitectura RISC de 32 bits, y coprocesador RISC-V de 128 MHz integrado.
  • Ultra Bajo Consumo: Diseñado para un consumo de energía ultra bajo superior, extiende significativamente la vida útil de la batería e incluye gestión avanzada de energía.
  • Transmisión Inalámbrica Multi-Modo: Transceptor inalámbrico multi-protocolo de 2.4 GHz integrado que soporta Bluetooth Low Energy (incluyendo Channel Sounding), 802.15.4-2020, Matter, Thread, Zigbee, y modos propietarios de 2.4 GHz (hasta 4 Mbps).
  • Seguridad Robusta: Características de seguridad avanzadas incluyendo aislamiento TrustZone®, detección de manipulación, y protección contra fugas de canal en el lado del motor de cifrado.
  • Recursos en chip abundantes: Configuraciones de memoria escalables de hasta 1.5 MB NVM y 256 KB RAM proporcionan amplio espacio de almacenamiento.
  • Interfaces Ricas: Conjunto completo de periféricos incluyendo el nuevo RTC Global (disponible en modo System OFF), ADC de 14 bits, e interfaces serie de alta velocidad. Gestión integrada de batería de litio.

Descripción General del Hardware

Diagrama de indicación frontal XIAO nRF54L15
Diagrama de indicación trasero XIAO nRF54L15
Lista de Pines XIAO nRF54L15

Uso del nRFConnect SDK

El nRF Connect SDK (NCS) es un kit de desarrollo de software extensible y unificado de Nordic Semiconductor diseñado específicamente para construir aplicaciones inalámbricas de bajo consumo para dispositivos inalámbricos basados en las series Nordic nRF52, nRF53, nRF54, nRF70 y nRF91.

NCS proporciona un ecosistema rico de aplicaciones de muestra listas para usar, pilas de protocolos, bibliotecas y controladores de hardware diseñados para simplificar el proceso de desarrollo y acelerar el tiempo de comercialización. Su naturaleza modular y configurable brinda a los desarrolladores la flexibilidad para construir software optimizado en tamaño para dispositivos con restricciones de memoria, así como funcionalidad potente para aplicaciones más avanzadas y complejas. NCS es un proyecto de código abierto alojado en GitHub y ofrece excelente soporte para entornos de desarrollo integrados como Visual Studio Code.

Usando nRF Connect SDK en VSCode

Instalar conocimientos del nRF Connect SDK por adelantado

Este documento detalla cómo instalar el entorno de desarrollo nRF Connect SDK en una computadora con Windows 11. Lo siguiente es una descripción general de las herramientas que necesitan ser instaladas

ninja --version
  • CMake
cmake --version
  • Zephyr SDK
west --version
  • nRF Connect SDK
  • Plugin nRF Connect para VSCode

Si ya lo tienes preinstalado en tu computadora, puedes verificar el número de versión de tu herramienta siguiendo el comando a continuación

1
VScode configures the board and builds the burn-in file

Open VS Code and search for nRF Connect for VS Code Extension Pack in the Plugin Center. This plugin pack will automatically install other VS Code plugins required for nRF Connect.


The nRF Connect for VS Code extension enables developers to utilize the popular Visual Studio Code Integrated Development Environment (VS Code IDE) to develop, build, debug and deploy embedded applications based on Nordic's nRF Connect SDK (Software Development Kit). The extension includes useful development tools such as a compiler interface, linker, complete build system, RTOS-enabled debugger, seamless interfacing with the nRF Connect SDK, device tree visualization editor, and an integrated serial terminal.

The nRF Connect extension package for VS Code includes the following components:

  • nRF Connect for VS Code: The main extension contains the interface between the build system and the nRF Connect SDK, as well as an interface to manage the nRF Connect SDK version and toolchain.
  • nRF DeviceTree: Provides device tree language support and a device tree visualization editor.
  • nRF Kconfig: Provides Kconfig language support.
  • nRF Terminal: Serial and RTT terminals.
  • Microsoft C/C++: Adds language support for C/C++, including features of IntelliSense.
  • CMake: CMake language support.
  • GNU Linker Mapping Files: Support for linker mapping files. We can download any preferred version of the nRF Connect SDK and its toolchain via the extension. The full nRF Connect for VS Code documentation is available at https://docs.nordicsemi.com/bundle/nrf-connect-vscode/page/index.html.
2
Installing the toolchain

The toolchain is a collection of tools that work together to build nRF Connect SDK applications, including assembler, compiler, linker, and CMake components. The first time you open nRF Connect for VS Code, you will be prompted to install the toolchain. This usually happens if the extension does not detect any installed toolchain on your computer. Click Install Toolchain and a list of toolchain versions will be listed that can be downloaded and installed on your computer. Select the version of the toolchain that matches the version of the nRF Connect SDK you plan to use. We always recommend using the latest tagged version of the nRF Connect SDK.

By default, nRF Connect for VS Code only displays the Released tab (i.e., the stable version) of the toolchain. If you are evaluating a new feature and would like to use the Preview tab or another type of tab (e.g. Customer Sampling -cs), click on "Show all toolchain versions" as shown below:

note

The ToolChain here is 3.0.1 or above

3
Installing the nRF Connect SDK

In the nRF Connect extension for VS Code, click on Manage SDK. from the Manage SDK menu, we can install or uninstall the nRF Connect SDK version. Since this is the first time we are using the extension, the interface will only show two options.

Clicking Install SDK will list all available nRF Connect SDK versions that can be downloaded and installed locally. Select the version of the nRF Connect SDK that is required for the development of your project.

If you have opened the SDK folder in VS Code, instead of the Manage SDK menu option, you will see the Manage west workspace. To resolve this issue, open another window or folder in VS Code.

note

The nRF Connect SDK here is 3.0.1 or above

tip

If you do not see either of these options, make sure you have the latest version of the nRF Connect for VS Code extension package installed. It is important to note that the nRF Connect SDK is IDE independent, which means you can choose to use any IDE or none at all. The nRF Connect SDK is available via the https://www.nordicsemi.com/Products/Development-tools/nRF-Util (nrfutil) command line The (nrfutil) command line interface (CLI) will download and install nRF Connect. However, we highly recommend using our nRF Connect for VS Code extension with VS Code, as it integrates not only a convenient graphical user interface (GUI) and an efficient command line interface (CLI), but also includes a number of features that will greatly simplify firmware development. Configuring other IDEs to work with the nRF Connect SDK requires additional manual steps beyond the scope of this course.

4
Creating User Programs

In this exercise we will write a simple application based on the blinky example to control blinking LEDs on a development board. The same applies to all supported NordicSemiconductor development boards (nRF54, nRF53, nRF52, nRF70 or nRF91 series). The goal is to make sure that all the tools needed to build and burn the example are set up correctly. The focus is on learning how to create an application, build it and burn it to a Nordic chip development board using the "Copy Example" template!

  • In VS Code, click the nRF Connect extension icon. In the Welcome view, click Create New Application.
  • Type blinky in the search bar and select the second Blinky sample (path zephyr/samples/basic/blinky), as shown below.

The Blinky example will cause the LED1 on the development board to blink continuously. Our first application will be based on the Blinky example. The Blinky example is derived from the Zephyr mold block in the nRF Connect SDK, so you will see the zephyr name in the sample path: zephyr\samples\basic\blinky.

5
Add XIAO nRF54L15 Board

Para comenzar, clona el repositorio desde el enlace de GitHub git clone https://github.com/Seeed-Studio/platform-seeedboards.git en tu carpeta local preferida. Una vez clonado, navega al directorio platform-seeedboards/zephyr/. Recuerda la ruta de esta carpeta zephyr;

Para configurar tu placa para nRF Connect en VS Code, puedes seguir estos pasos:

  • Abre VS Code y ve a Settings.

  • Escribe nRF Connect en el cuadro de búsqueda.

  • Encuentra el elemento de configuración Board Roots y haz clic en Edit in settings.json.

  • Agrega la ruta zephyr del archivo de placa XIAO nRF54L15 descargado al array boardRoots.

  • En la vista de aplicación, haz clic en Add Build Configuration debajo del nombre de la aplicación.

  • Podemos seleccionar el modelo de XIAO nRF54L15 en Board target, y seleccionar el archivo prj.config predeterminado en Base configuration files, y finalmente hacer clic en Generate and Build para construir el archivo.

6
Descargar Plugin de Grabación

Plugins Adicionales:

En Windows, usaremos el gestor de paquetes Chocolatey para instalar OpenOCD.

1.Abrir PowerShell (Ejecutar como Administrador):

  • En la barra de búsqueda de Windows, escribe "PowerShell".
  • Haz clic derecho en "Windows PowerShell" y selecciona "Run as administrator".

2.Verificar la Política de Ejecución de PowerShell:

  • Escribe Get-ExecutionPolicy y presiona Enter.
  • Escribe Get-ExecutionPolicy -List y presiona Enter.

3.Instalar Chocolatey:

  • Pega y ejecuta el siguiente comando:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

Este comando omite la política de ejecución para la sesión actual de PowerShell e instala Chocolatey. Después de la instalación, cierra y vuelve a abrir la ventana de PowerShell (aún ejecutar como administrador).

4.Instalar OpenOCD:

  • En la nueva ventana de PowerShell (como administrador), escribe:
choco install openocd

5.Verificar la Instalación de OpenOCD:

  • Escribe Get-Command openocd y presiona Enter.

  • Si la instalación es exitosa, este comando mostrará la ruta a openocd.exe.

7
Programa de grabación West Flash
  • Abre la terminal nRF

  • Simplemente ingresa el comando west flash. Para grabar tu dispositivo, simplemente ingresa el comando west flash. La ruta resaltada en rojo indica la ubicación de tu archivo .elf compilado. Puedes usar esta misma ruta para encontrar el archivo .hex correspondiente, que es adecuado para programar con un depurador J-Link.

tip

Si ocurre el error west flash, significa que hay un conflicto con el plugin CMake en VS Code, y necesitas eliminar el plugin CMake.

Cuando hayamos grabado exitosamente el programa en el Seeed Studio XIAO nRF54L15 Sense, puedes ver la placa con el indicador de usuario parpadeando continuamente en luz verde. Si tu placa también muestra el mismo efecto, ¡significa que lo has logrado exitosamente!🎊

8
Explicación del programa Blinky
/*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/

#include <stdio.h>
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>

/* 1000 msec = 1 sec */
#define SLEEP_TIME_MS 1000

/* The devicetree node identifier for the "led0" alias. */
#define LED0_NODE DT_ALIAS(led0)

/*
* A build error on this line means your board is unsupported.
* See the sample documentation for information on how to fix this.
*/
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);

int main(void)
{
int ret;
bool led_state = true;

if (!gpio_is_ready_dt(&led)) {
return 0;
}

ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
return 0;
}

while (1) {
ret = gpio_pin_toggle_dt(&led);
if (ret < 0) {
return 0;
}

led_state = !led_state;
printf("LED state: %s\n", led_state ? "ON" : "OFF");
k_msleep(SLEEP_TIME_MS);
}
return 0;
}

Definición del Dispositivo LED:

  • #define LED0_NODE DT_ALIAS(led0): Recupera el identificador del nodo del árbol de dispositivos para el alias "led0", permitiendo una referencia independiente del hardware al LED.
  • static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios): Crea una estructura de especificación GPIO (led) usando el nodo del árbol de dispositivos, conteniendo detalles del hardware (pin, puerto) para el LED. Un error de compilación aquí indica hardware no compatible.

Inicialización de la función main()

  • Configuración de Variables:

    • int ret: Almacena valores de retorno de funciones para verificar el éxito de la operación.
    • bool led_state = true: Rastrea el estado del LED (inicializado como "ENCENDIDO").
  • Verificación de Preparación GPIO:

    • if (!gpio_is_ready_dt(&led)) { return 0; }: Verifica si el hardware GPIO del LED está listo (por ejemplo, controlador cargado). Sale si no está listo.
  • Configuración GPIO:

    • ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE): Configura el pin GPIO del LED como una salida activa-alta.
    • Sale en caso de falla (ret < 0) para prevenir operaciones inválidas.

Bucle Principal: Se ejecuta en un bucle infinito while (1) para alternar el LED periódicamente:

  • Alternar Estado del LED:

    • ret = gpio_pin_toggle_dt(&led): Cambia la salida GPIO del LED (ENCENDIDO ↔ APAGADO). Sale en caso de falla.
  • Actualizar Seguimiento de Estado:

    • led_state = !led_state: Sincroniza la bandera de estado del software con el estado del hardware.
  • Registro y Retraso:

    • printf("LED state: %s\n", led_state ? "ON" : "OFF"): Imprime el estado actual del LED a través de la salida serie.
    • k_msleep(SLEEP_TIME_MS): Pausa por 1000ms (1 segundo) usando la función de retraso RTOS de Zephyr, controlando la frecuencia de parpadeo.
9
Profundización en los Aspectos Internos del nRF Connect SDK

Si quieres tener una comprensión más profunda de los principios internos del nRF Connect SDK, puedes consultar los siguientes cursos:

Restaurar configuración de fábrica

Para las placas XIAO nRF54L15, se proporciona un script de restablecimiento de fábrica para recuperar la placa de un estado defectuoso (por ejemplo, cuando no se puede cargar debido a la protección de escritura NVM interna). Este script realizará un borrado masivo de la flash y programará un firmware de fábrica.


Ubicación Los scripts están ubicados en el directorio scripts/factory_reset/. Uso El script creará y gestionará automáticamente un entorno virtual de Python local para instalar las herramientas necesarias, por lo que puede ejecutarse directamente.

Window

  • Para Windows: Navega al directorio scripts/factory_reset y ejecuta:
.\factory_reset.bat

Linux-MacOS

  • Para Linux y macOS: Navega al directorio scripts/factory_reset y ejecuta:
bash factory_reset.sh

Modo de Conmutación Inalámbrica

Este ejemplo demuestra cómo controlar el conmutador RF en el Seeed Studio XIAO nRF54L15 para alternar entre la

::: El siguiente ejemplo funciona tanto para PlatformIO como para nRF Connect SDK. Puede usarse directamente en PlatformIO, mientras que el SDK requiere agregar archivos manualmente. Consulta este enlace :::

XIAO nRF54L15 BLE Advertising Power Consumption

Antena externa

  • Antena cerámica y una antena externa.

  • Presiona el botón de usuario (SW0) para cambiar entre las antenas cerámica y externa.

  • El LED de usuario indica la selección actual de antena (LED ENCENDIDO para externa, LED APAGADO para cerámica).

  • La antena predeterminada al inicio se puede configurar a través de prj.conf.

/*
* Copyright (c) 2024 Seeed Technology Co.,Ltd
*
* SPDX-License-Identifier: Apache-2.0
*/

#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>
#include <zephyr/devicetree.h>

LOG_MODULE_REGISTER(app, CONFIG_LOG_DEFAULT_LEVEL);

/* Devicetree node identifiers */
#define RFSW_REGULATOR_NODE DT_NODELABEL(rfsw_ctl)
#define SW0_NODE DT_ALIAS(sw0)
#define LED0_NODE DT_ALIAS(led0)

/* State variables */
static uint8_t onoff_flag = 0;
#ifdef CONFIG_DEFAULT_ANTENNA_EXTERNAL
static bool is_external_antenna = true;
#else
static bool is_external_antenna = false;
#endif

/* GPIO device specs */
/* Manually build gpio_dt_spec for rfsw_ctl */
static const struct gpio_dt_spec rfsw_gpio = {
.port = DEVICE_DT_GET(DT_GPIO_CTLR(RFSW_REGULATOR_NODE, enable_gpios)),
.pin = DT_GPIO_PIN(RFSW_REGULATOR_NODE, enable_gpios),
.dt_flags = DT_GPIO_FLAGS(RFSW_REGULATOR_NODE, enable_gpios),
};
static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET(SW0_NODE, gpios);
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);

/* Button callback data */
static struct gpio_callback button_cb_data;

/* Forward declarations */
void button_pressed(const struct device *dev, struct gpio_callback *cb, uint32_t pins);
void update_antenna_switch(void);

/* Function to update antenna switch and LED */
void update_antenna_switch(void)
{
int ret;
is_external_antenna = !is_external_antenna;

if (is_external_antenna) {
/* Switch to external antenna */
LOG_INF("Switching to External Antenna");

// To get a physical high level (Inactive state), we need to set the logic to '0'
ret = gpio_pin_set_dt(&rfsw_gpio, 0);
if (ret < 0) {
LOG_ERR("Error setting rfsw-ctl to physical HIGH: %d\n", ret);
}

// Turn on the LED (set 0 for on)
ret = gpio_pin_set_dt(&led, 0);
if (ret < 0) {
LOG_ERR("Error turning on LED: %d\n", ret);
}

} else {
/* Switch back to ceramic antenna */
LOG_INF("Switching to Ceramic Antenna");

// To get a physical low level (Active state), we need to set the logic to '1'
ret = gpio_pin_set_dt(&rfsw_gpio, 1);
if (ret < 0) {
LOG_ERR("Error setting rfsw-ctl to physical LOW: %d\n", ret);
}

// Turn off the LED (set 1 for off)
ret = gpio_pin_set_dt(&led, 1);
if (ret < 0) {
LOG_ERR("Error turning off LED: %d\n", ret);
}
}
}

/* Button pressed callback function */
void button_pressed(const struct device *dev, struct gpio_callback *cb,
uint32_t pins)
{
update_antenna_switch();
}

int main(void)
{
int ret;

/* Check if GPIO devices are ready */
if (!gpio_is_ready_dt(&rfsw_gpio)) {
LOG_ERR("RF switch control GPIO not ready\n");
return -1;
}
if (!gpio_is_ready_dt(&button)) {
LOG_ERR("Button GPIO not ready\n");
return -1;
}
if (!gpio_is_ready_dt(&led)) {
LOG_ERR("LED GPIO not ready\n");
return -1;
}

/* Configure GPIO pins */
ret = gpio_pin_configure_dt(&rfsw_gpio, GPIO_OUTPUT);
if (ret < 0) {
LOG_ERR("Error configuring rfsw-ctl: %d\n", ret);
return ret;
}

/* Configure LED as output, default off */
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
LOG_ERR("Error configuring LED: %d\n", ret);
return ret;
}

/* Set initial LED state based on antenna selection */
if (is_external_antenna) {
// External antenna
LOG_INF("Initial state: External Antenna");
ret = gpio_pin_set_dt(&rfsw_gpio, 0);
if (ret < 0) {
LOG_ERR("Error setting rfsw-ctl to physical HIGH: %d\n", ret);
}
ret = gpio_pin_set_dt(&led, 0); // Turn on LED
if (ret < 0) {
LOG_ERR("Error turning on LED: %d\n", ret);
}
} else {
// Ceramic antenna
LOG_INF("Initial state: Ceramic Antenna");
ret = gpio_pin_set_dt(&rfsw_gpio, 1);
if (ret < 0) {
LOG_ERR("Error setting rfsw-ctl to physical LOW: %d\n", ret);
}
ret = gpio_pin_set_dt(&led, 1); // Turn off LED
if (ret < 0) {
LOG_ERR("Error turning off LED: %d\n", ret);
}
}

/* Configure button as input */
ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
if (ret < 0) {
LOG_ERR("Error configuring button: %d\n", ret);
return ret;
}

/* Configure button interrupt */
ret = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
if (ret < 0) {
LOG_ERR("Error configuring button interrupt: %d\n", ret);
return ret;
}

/* Initialize button callback */
gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin));
gpio_add_callback(button.port, &button_cb_data);

LOG_INF("Antenna switch example started. Press SW0 to switch.\n");
return 0;
}
tip

Si deseas cambiar entre la antena externa o interna, necesitas modificar el archivo zephyr/prj.conf., Descomenta # CONFIG_DEFAULT_ANTENNA_EXTERNAL=y para habilitar la antena externa. Si usas la antena interna, comenta la línea.

CONFIG_GPIO=y
CONFIG_SERIAL=y
CONFIG_LOG=y
CONFIG_CONSOLE=y
CONFIG_UART_CONSOLE=y
CONFIG_SHELL_BACKEND_SERIAL=y
CONFIG_SHELL_BACKEND_DUMMY=n
CONFIG_PM_DEVICE=y
CONFIG_NRFX_POWER=y
CONFIG_POWEROFF=y

CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="zephyr-ble"

# Enable this option to default to external antenna
# CONFIG_DEFAULT_ANTENNA_EXTERNAL=y

Si quieres usar JLink para programar, puedes seguir los pasos a continuación. Sin embargo, sugerimos que uses el puerto serie integrado en la placa Seeed Studio XIAO nRF54L15 para programar, lo cual será mucho más conveniente.

Hardware Requerido

tip

Necesitas descargar la versión más reciente de J-Link para tener soporte para la placa modelo nRF54L15.

Software Requerido

Es necesario descargar el software Segger desde el sitio web.

  • Paso 1. Usa Jlink para conectar los pines a continuación:

pir

  • Paso 2. Inicia J-Flash y busca nRF54L15_M33, creando un nuevo proyecto:

pir

  • Paso 3. Haz clic en "Target" y luego selecciona "Connect".

pir

  • Paso 4. Arrastra el archivo bin o hex al software. Luego presiona F4 y F5 en ese orden. La reprogramación está completa.

pir

Placa Alimentada por Batería

El XIAO nRF54L15 tiene un chip de gestión de energía integrado que permite que el XIAO nRF54L15 sea alimentado independientemente usando una batería o cargar la batería a través del puerto USB del XIAO nRF54L15.

Si quieres conectar la batería para XIAO, te recomendamos que compres una batería de litio recargable de 3.7V calificada. Al soldar la batería, ten cuidado de distinguir entre los terminales positivo y negativo.

XIAO nRF54L15 BLE Advertising Power Consumption

Esquema de Conexión de Batería

Instrucciones sobre el uso de baterías:

  1. Por favor, utilice baterías calificadas que cumplan con las especificaciones.
  2. XIAO puede conectarse a su dispositivo informático mediante cable de datos mientras usa la batería, tenga la seguridad de que XIAO tiene un chip de protección de circuito integrado, que es seguro.
  3. El XIAO nRF54L15 no tendrá ningún LED encendido cuando esté alimentado por batería (a menos que haya escrito un programa específico), por favor no juzgue si el XIAO nRF54L15 está funcionando o no por la condición del LED, por favor juzgue razonablemente por su programa.

Al mismo tiempo, diseñamos una luz indicadora roja para la carga de la batería, a través de la pantalla de la luz indicadora para informar al usuario del estado actual de la batería en la carga.

caution

Por favor, tenga cuidado de no cortocircuitar los terminales positivo y negativo y quemar la batería y el equipo al soldar.

Detección de Voltaje de Batería

El XIAO nRF54L15 integra una función de detección de voltaje de batería que se centra en gestionar eficientemente las mediciones de energía de la batería utilizando el interruptor de carga TPS22916CYFPR. Esta guía se enfocará en analizar la implementación de software de la detección de batería (especialmente el código main.c) y le guiará sobre cómo desplegar y usar fácilmente esta función en un entorno PlatformIO, evitando la complejidad del SDK Zephyr NCS.

XIAO nRF54L15 BLE Advertising Power Consumption

Esquema de Detección de Batería

Lo que hace el chip TPS22916CYFPR:

  • Es un interruptor de alimentación inteligente que controla el encendido y apagado del voltaje de la batería bajo demanda. Cuando se necesita medir el voltaje de la batería, se encenderá, conectando la batería al circuito divisor de voltaje; cuando no necesita ser medido, se apagará, desconectando la conexión.

  • ¿Qué nos ayuda a hacer esta función? A través de este mecanismo de conmutación bajo demanda, el chip reduce enormemente el consumo de corriente innecesario y extiende efectivamente la vida útil de la batería. Combinado con el circuito divisor de voltaje posterior y el ADC (convertidor analógico-digital) del nRF54L15, el XIAO nRF54L15 es capaz de monitorear con precisión la carga restante de la batería, proporcionando una optimización de rango importante para aplicaciones alimentadas por batería y de bajo consumo como dispositivos IoT.

note

El siguiente código de ejemplo está diseñado para PlatformIO, pero también es compatible con el nRF Connect SDK.

Usando XIAO nRF54L15 en PlatformIO Si desea usar XIAO nRF54L15 en PlatformIO, por favor consulte este tutorial para configurarlo: Configuración de XIAO nRF54L15 PlatformIO.


Agregar overlay y modificar el archivo conf

Si desea usar esta rutina de batería en el nRF Connect SDK, necesita agregar app.overlay y modificar el archivo prj.conf.

  • Cree un nuevo archivo llamado app.overlay bajo el directorio del proyecto. Luego pegue el siguiente código en él, y finalmente presione Ctrl + S para guardar.

    • El archivo overlay extiende la capa de descripción de hardware y personaliza las conexiones de hardware físico a través del árbol de dispositivos. No modifica la lógica del código, sino que declara los detalles reales del hardware para asegurar que el controlador pueda inicializar correctamente el dispositivo físico.

código app.overlay
/ {
/*
* @brief Device Tree Overlay for XIAO nRF54L15
*
* This file customizes the base board device tree to configure
* peripherals for a specific application, including:
* - User-defined ADC channels
* - PWM-controlled LED
* - Buttons and a relay
* - E-paper display (UC8179) via SPI
* - OLED display (SSD1306) via I2C
*
* To switch between the two displays, simply uncomment one and comment
* out the other in the "chosen" node below.
*/

/************************************************************
* Aliases for easy access to devices in application code
************************************************************/
aliases {
pwm-led = &pwm0_led0;
sw1 = &xiao_button0;
relay0 = &xiao_relay0;
};

/************************************************************
* Display selection (choose one if multiple)
************************************************************/
chosen {
zephyr,display = &uc8179_7inch5_epaper_gdew075t7;
zephyr,display = &ssd1306_128x64;
};

/************************************************************
* PWM LED, Button, and Relay configuration
************************************************************/
pwm_leds {
compatible = "pwm-leds";
pwm0_led0: my_pwm_led {
// PWM channel 0 on PWM instance 20
// PWM_MSEC(20) sets a period of 20ms
pwms = <&pwm20 0 PWM_MSEC(20) PWM_POLARITY_NORMAL>;
status = "okay";
};
};

buttons {
compatible = "gpio-keys";
xiao_button0: button_0 {
// Connect to the XIAO nRF54L15 pin D1
// GPIO_PULL_UP ensures the pin is high when the button is not pressed
// GPIO_ACTIVE_LOW means the button press drives the pin low
gpios = <&xiao_d 1 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
zephyr,code = <INPUT_KEY_0>;
};
};

relay {
compatible = "gpio-leds";
xiao_relay0: relay_0 {
// Connect to the XIAO nRF54L15 pin D0
gpios = <&xiao_d 0 GPIO_ACTIVE_HIGH>;
};
};

/************************************************************
* Local nodes that don't modify existing ones
************************************************************/
zephyr,user {
io-channels = <&adc 0>, <&adc 1>, <&adc 2>, <&adc 3>,
<&adc 4>, <&adc 5>, <&adc 6>, <&adc 7>;
};

// MIPI-DBI SPI interface for the E-paper display
mipi_dbi_xiao_epaper {
compatible = "zephyr,mipi-dbi-spi";
spi-dev = <&xiao_spi>;
// D3 pin for Data/Command control
dc-gpios = <&xiao_d 3 GPIO_ACTIVE_HIGH>;
// D0 pin for Reset
reset-gpios = <&xiao_d 0 GPIO_ACTIVE_LOW>;
write-only;
#address-cells = <1>;
#size-cells = <0>;

uc8179_7inch5_epaper_gdew075t7: uc8179@0 {
compatible = "gooddisplay,gdew075t7", "ultrachip,uc8179";
// Max SPI frequency for the display
mipi-max-frequency = <4000000>;
reg = <0>;
width = <800>;
height = <480>;
// D2 pin for Busy signal from the display
busy-gpios = <&xiao_d 2 GPIO_ACTIVE_LOW>;
softstart = [17 17 17 17];
full {
pwr = [07 07 3f 3f];
cdi = <07>;
tcon = <0x22>;
};
};
};
};

/************************************************************
* Device fragments (modifying nodes from the base board DTS)
************************************************************/
// PWM instance 20
&pwm20 {
status = "okay";
pinctrl-0 = <&pwm20_default>;
pinctrl-1 = <&pwm20_sleep>;
pinctrl-names = "default", "sleep";
};

// GPIO pin control
&pinctrl {
pwm20_default: pwm20_default {
group1 {
// Configure PWM channel 0 on P1.04 pin (Pin D0)
psels = <NRF_PSEL(PWM_OUT0, 1, 4)>;
};
};

pwm20_sleep: pwm20_sleep {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 1, 4)>;
low-power-enable;
};
};
};

// PDM instance 20 for DMIC
dmic_dev: &pdm20 {
status = "okay";
};

// Power configuration
&pdm_imu_pwr {
/delete-property/ regulator-boot-on;
};

// UART instance 20
&uart20 {
current-speed = <921600>;
};

// SPI peripheral
&xiao_spi {
status = "okay";
// D1 pin for Chip Select
cs-gpios = <&xiao_d 1 GPIO_ACTIVE_LOW>;
};

// I2C peripheral
&xiao_i2c {
status = "okay";
zephyr,concat-buf-size = <2048>;

ssd1306_128x64: ssd1306@3c {
compatible = "solomon,ssd1306fb";
reg = <0x3c>;
width = <128>;
height = <64>;
segment-offset = <0>;
page-offset = <0>;
display-offset = <0>;
multiplex-ratio = <63>;
segment-remap;
com-invdir;
prechargep = <0x22>;
};
};
  • Agregue el siguiente contenido bajo el archivo prj.conf

    • prj.conf es el archivo de configuración principal del proyecto Zephyr. Es gestionado por el sistema Kconfig para la selección de funciones de software durante la compilación. Determina qué controladores (como ADC, pantalla, Bluetooth), middleware (como LVGL) y servicios del sistema (como logging, gestión de memoria) se incluyen en el firmware, y establece sus parámetros de comportamiento (como nivel de log, tamaño del heap), finalmente presiona Ctrl + S para guardar.

código prj.conf
# =========================================================
# Basic system configuration
# =========================================================
CONFIG_GPIO=y
CONFIG_I2C=y
CONFIG_ADC=y
CONFIG_ADC_ASYNC=y
CONFIG_PWM=y
CONFIG_SENSOR=y
CONFIG_INPUT=y

# =========================================================
# Power management
# =========================================================
CONFIG_PM_DEVICE=y
CONFIG_NRFX_POWER=y
CONFIG_POWEROFF=y
CONFIG_HWINFO=y
CONFIG_CRC=y

# =========================================================
# Serial port and console configuration
# =========================================================
CONFIG_SERIAL=y
CONFIG_CONSOLE=y
CONFIG_STDOUT_CONSOLE=y
CONFIG_UART_CONSOLE=y
CONFIG_UART_ASYNC_API=y
CONFIG_UART_INTERRUPT_DRIVEN=y
CONFIG_UART_NRFX_UARTE_ENHANCED_RX=y
CONFIG_CBPRINTF_FP_SUPPORT=y

# =========================================================
# Log and Debugging
# =========================================================
CONFIG_LOG=y
CONFIG_LOG_PRINTK=y
CONFIG_LOG_MODE_IMMEDIATE=y
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_PWM_LOG_LEVEL_DBG=y
CONFIG_PRINTK=y

# =========================================================
# Memory and Stack
# =========================================================
CONFIG_MAIN_STACK_SIZE=4096
CONFIG_HEAP_MEM_POOL_SIZE=16384
CONFIG_NEWLIB_LIBC=y
CONFIG_NEWLIB_LIBC_FLOAT_PRINTF=y

# =========================================================
# Bluetooth configuration
# =========================================================
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="zephyr-ble"

# =========================================================
# Audio configuration
# =========================================================
CONFIG_AUDIO=y
CONFIG_AUDIO_DMIC=y

# =========================================================
# Display and Graphics
# =========================================================
CONFIG_DISPLAY=y
CONFIG_MIPI_DBI_SPI=y
CONFIG_SSD1306=y
CONFIG_CHARACTER_FRAMEBUFFER=y

# LVGL Graphics Library
CONFIG_LVGL=y
CONFIG_LV_Z_MEM_POOL_SIZE=49152
CONFIG_LV_Z_SHELL=y
CONFIG_LV_USE_MONKEY=y
CONFIG_LV_USE_LABEL=y
CONFIG_LV_COLOR_DEPTH_1=y
CONFIG_LV_FONT_MONTSERRAT_12=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_18=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_USE_FONT_COMPRESSED=y

# =========================================================
# Shell configuration
# =========================================================
CONFIG_SHELL=y
CONFIG_SHELL_BACKEND_DUMMY=y

Código Principal

#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/regulator.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/kernel.h>


#if !DT_NODE_EXISTS(DT_PATH(zephyr_user)) || \
!DT_NODE_HAS_PROP(DT_PATH(zephyr_user), io_channels)
#error "No suitable devicetree overlay specified"
#endif

#define DT_SPEC_AND_COMMA(node_id, prop, idx) \
ADC_DT_SPEC_GET_BY_IDX(node_id, idx),

/* Data of ADC io-channels specified in devicetree. */
static const struct adc_dt_spec adc_channels[] = {
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), io_channels,
DT_SPEC_AND_COMMA)};

static const struct device *const vbat_reg = DEVICE_DT_GET(DT_NODELABEL(vbat_pwr));

int main(void)
{
int err;
uint16_t buf;
int32_t val_mv;
struct adc_sequence sequence = {
.buffer = &buf,
/* buffer size in bytes, not number of samples */
.buffer_size = sizeof(buf),
};

regulator_enable(vbat_reg);
k_sleep(K_MSEC(100));

/* Configure channels individually prior to sampling. */
if (!adc_is_ready_dt(&adc_channels[7]))
{
printf("ADC controller device %s not ready\n", adc_channels[7].dev->name);
return 0;
}

err = adc_channel_setup_dt(&adc_channels[7]);
if (err < 0)
{
printf("Could not setup channel #7 (%d)\n", err);
return 0;
}

(void)adc_sequence_init_dt(&adc_channels[7], &sequence);

err = adc_read_dt(&adc_channels[7], &sequence);
if (err < 0)
{
printf("Could not read (%d)\n", err);
return 0;
}

/*
* If using differential mode, the 16 bit value
* in the ADC sample buffer should be a signed 2's
* complement value.
*/
if (adc_channels[7].channel_cfg.differential)
{
val_mv = (int32_t)((int16_t)buf);
}
else
{
val_mv = (int32_t)buf;
}
err = adc_raw_to_millivolts_dt(&adc_channels[7],
&val_mv);
/* conversion to mV may not be supported, skip if not */
if (err < 0)
{
printf(" value in mV not available\n");
}
else
{
printf("bat vol = %" PRId32 " mV\n", val_mv * 2);
}

regulator_disable(vbat_reg);
return 0;
}

Recursos

Seeed Studio XIAO nRF54L15

Seeed Studio XIAO nRF54L15 Sense

Soporte Técnico y Discusión del Producto

¡Gracias por elegir nuestros productos! Estamos aquí para brindarle diferentes tipos de soporte para asegurar que su experiencia con nuestros productos sea lo más fluida posible. Ofrecemos varios canales de comunicación para satisfacer diferentes preferencias y necesidades.

Loading Comments...