diff --git a/README_EN.md b/README_EN.md index d0af1709a..8ca5d689c 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,10 +1,11 @@ # SiFli-SDK -English | [中文](README.md) +English | [中文](README_EN.md) ## Getting Started - -The SiFli SDK is an official software development framework, custom-built on RT-Thread, that enables rapid development of applications running on SiFli Technology’s chip platforms. +The SiFli SDK is an official software development framework, custom-built on +RT-Thread, that enables rapid development of applications running on SiFli +Technology’s chip platforms. Relevant documentation: - https://wiki.sifli.com/ @@ -12,7 +13,8 @@ Relevant documentation: You can refer to these documents for a quick start. -**Note**: Since the SDK includes submodules, you must clone the repository with the `--recursive` flag, for example: +**Note**: Since the SDK includes submodules, you must clone the repository with +the `--recursive` flag, for example: ```bash git clone --recursive https://github.com/OpenSiFli/SiFli-SDK ``` @@ -21,69 +23,95 @@ The software framework is illustrated below: ![sdk_arch_diagram](img/sdk_arch_diagram.png) -- **HAL** is the Hardware Abstraction Layer, providing driver functionality without relying on any operating system services. -- **RT-Thread Device Drivers** are built on top of HAL and offer a higher-level abstraction; users do not need to write interrupt service routines, making them easier to use. For a detailed comparison between HAL and RT-Thread device drivers, see [Chip Peripheral Drivers](https://docs.sifli.com/projects/sdk/v2.3/sf32lb55x/app_development/drivers.html). -- **Middleware (components)** includes RT-Thread’s built-in software components (e.g., finsh, ulog), third-party components (under the `external` directory), and in-house components (under the `middleware` directory). Applications can use all service interfaces, including HAL, to build their software. +- **HAL** is the Hardware Abstraction Layer, providing driver functionality + without relying on any operating system services. +- **RT-Thread Device Drivers** are built on top of HAL and offer a higher-level + abstraction; users do not need to write interrupt service routines, making + them easier to use. For a detailed comparison between HAL and RT-Thread device + drivers, see [Chip Peripheral + Drivers](https://docs.sifli.com/projects/sdk/v2.3/sf32lb55x/app_development/drivers.html). +- **Middleware (components)** includes RT-Thread’s built-in software components + (e.g., finsh, ulog), third-party components (under the `external` directory), + and in-house components (under the `middleware` directory). Applications can + use all service interfaces, including HAL, to build their software. -### SDK Directory Structure +SDK Directory Structure ``` -+---customer // Board Support Package ++---customer // Board Support Package (BSP) | +---boards // Board configuration files +| | | +---peripherals // Board-level peripheral drivers | +| +---drivers -| +---cmsis // Chip register headers, startup files, linker scripts +| +---cmsis // Register headers, startup files, and linker scripts | | +---Include | | +---sf32lb52x +| | | | | +---sf32lb55x +| | | | | +---sf32lb56x -| | +---sf32lb58x -| +---hal // HAL implementation code -| \---Include // HAL header files +| | | +| | \---sf32lb58x +| | +| +---hal // HAL implementation +| | +| \---Include // HAL headers +| ++---example // Sample projects | -+---example // Examples +---external // Third-party components -+---middleware // In-house components +| ++---middleware // Proprietary components +| +---rtos // Operating systems | +---freertos // FreeRTOS -| +---os_adaptor // OS abstraction layer +| | +| +---os_adaptor // OS Abstraction Layer (OSAL) +| | +| | | \---rtthread // RT-Thread | \---bsp | \---sifli -| \---drivers // RT-Thread device driver adapters -\---tools // Tools +| \---drivers // RT-Thread device driver adaptation +| +| +| +\---tools // Toolsets ``` ## Versioning Policy - Version numbers follow the [Semantic Versioning](https://semver.org/) scheme. The version format is **MAJOR.MINOR.PATCH**, with the following increment rules: - -- **MAJOR** version: incompatible API changes (e.g., v1.0.0 → v2.0.0) -- **MINOR** version: backward-compatible new features or enhancements (e.g., v2.3.0 → v2.4.0) -- **PATCH** version: backward-compatible bug fixes or small functional tweaks (e.g., v2.3.1 → v2.3.2) +- **MAJOR** version: incompatible API changes (e.g., v1.0.0 → v2.0.0) +- **MINOR** version: backward-compatible new features or enhancements (e.g., + v2.3.0 → v2.4.0) +- **PATCH** version: backward-compatible bug fixes or small functional tweaks + (e.g., v2.3.1 → v2.3.2) Each release is tagged as `vX.Y.Z`. ### Release Cadence - -- **Patch releases**: as needed, typically as fast as one week -- **Minor releases**: every 4–5 months -- **Major releases**: once a year or longer +- **Patch releases**: as needed, typically as fast as one week +- **Minor releases**: every 4–5 months +- **Major releases**: once a year or longer ### Branches - The repository contains the following branches: - -- `main`: development branch where all new features and fixes land. **Not recommended** for production development. -- `release/vX.Y`: minor release branches containing all patches for that minor version. All official releases are made from these branches (tags are placed on commits in these branches). **Recommended** for project development is either the latest release tag or the tip of the corresponding `release/vX.Y` branch. -- Other branches: temporary or feature branches for internal development. **Not recommended** for general use. +- `main`: development branch where all new features and fixes land. **Not + recommended** for production development. +- `release/vX.Y`: minor release branches containing all patches for that minor + version. All official releases are made from these branches (tags are placed + on commits in these branches). **Recommended** for project development is + either the latest release tag or the tip of the corresponding `release/vX.Y` + branch. +- Other branches: temporary or feature branches for internal development. **Not + recommended** for general use. ### Support Timeline - | Version | Release Date | End-of-Support Date | Supported | -|---------|------------------|---------------------|-----------| +| ------- | ---------------- | ------------------- | --------- | | v2.3 | January 21, 2025 | | Yes | | v2.4 | June 5, 2025 | | Yes | diff --git a/docs/source/en/api/hal/adc.md b/docs/source/en/api/hal/adc.md index 85041c15c..4fdc76fbf 100644 --- a/docs/source/en/api/hal/adc.md +++ b/docs/source/en/api/hal/adc.md @@ -1,5 +1,6 @@ (hal-adc)= # bf0_hal_adc.h ```{doxygenfile} bf0_hal_adc.h + ``` diff --git a/docs/source/en/api/hal/aes.md b/docs/source/en/api/hal/aes.md index 9fe1fb80b..517e5c691 100644 --- a/docs/source/en/api/hal/aes.md +++ b/docs/source/en/api/hal/aes.md @@ -1,6 +1,7 @@ (hal-aes)= # bf0_hal_aes.h ```{doxygenfile} bf0_hal_aes.h + ``` diff --git a/docs/source/en/api/hal/aon.md b/docs/source/en/api/hal/aon.md index 08aeca454..700ac4b8c 100644 --- a/docs/source/en/api/hal/aon.md +++ b/docs/source/en/api/hal/aon.md @@ -1,5 +1,6 @@ (hal-aon)= # bf0_hal_aon.h ```{doxygenfile} bf0_hal_aon.h + ``` diff --git a/docs/source/en/api/hal/atim.md b/docs/source/en/api/hal/atim.md index 5bc18c574..9fe813f38 100644 --- a/docs/source/en/api/hal/atim.md +++ b/docs/source/en/api/hal/atim.md @@ -1,4 +1,5 @@ (hal-tim-ex)= # bf0_hal_tim_ex.h ```{doxygenfile} bf0_hal_tim_ex.h + ``` diff --git a/docs/source/en/api/hal/audcodec.md b/docs/source/en/api/hal/audcodec.md index ffa5e3e14..538d35b5b 100644 --- a/docs/source/en/api/hal/audcodec.md +++ b/docs/source/en/api/hal/audcodec.md @@ -1,4 +1,5 @@ (hal-audcodec)= # bf0_hal_audcodec.h ```{doxygenfile} bf0_hal_audcodec.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/hal/audprc.md b/docs/source/en/api/hal/audprc.md index 504068e8f..c3512fd5f 100644 --- a/docs/source/en/api/hal/audprc.md +++ b/docs/source/en/api/hal/audprc.md @@ -1,6 +1,7 @@ (hal-audprc)= # bf0_hal_audprc.h ```{doxygenfile} bf0_hal_audprc.h + ``` diff --git a/docs/source/en/api/hal/busmon.md b/docs/source/en/api/hal/busmon.md index e6f82c6de..7e48b88ed 100644 --- a/docs/source/en/api/hal/busmon.md +++ b/docs/source/en/api/hal/busmon.md @@ -1,4 +1,5 @@ # bf0_hal_busmon.h ```{doxygenfile} bf0_hal_busmon.h + ``` diff --git a/docs/source/en/api/hal/cache.md b/docs/source/en/api/hal/cache.md index 9a5eef1de..83e779338 100644 --- a/docs/source/en/api/hal/cache.md +++ b/docs/source/en/api/hal/cache.md @@ -1,4 +1,5 @@ (hal-cache)= # bf0_hal_cache.h ```{doxygenfile} bf0_hal_cache.h + ``` diff --git a/docs/source/en/api/hal/crc.md b/docs/source/en/api/hal/crc.md index 53c48fce4..48c11a076 100644 --- a/docs/source/en/api/hal/crc.md +++ b/docs/source/en/api/hal/crc.md @@ -1,3 +1,4 @@ # bf0_hal_crc.h ```{doxygenfile} bf0_hal_crc.h + ``` diff --git a/docs/source/en/api/hal/dma.md b/docs/source/en/api/hal/dma.md index 381ab1a4a..756e52fe6 100644 --- a/docs/source/en/api/hal/dma.md +++ b/docs/source/en/api/hal/dma.md @@ -1,4 +1,5 @@ # bf0_hal_dma.h ```{doxygenfile} bf0_hal_dma.h + ``` diff --git a/docs/source/en/api/hal/dsi.md b/docs/source/en/api/hal/dsi.md index 90ccdacdb..66aa99c38 100644 --- a/docs/source/en/api/hal/dsi.md +++ b/docs/source/en/api/hal/dsi.md @@ -1,4 +1,5 @@ # bf0_hal_dsi.h ```{doxygenfile} bf0_hal_dsi.h + ``` diff --git a/docs/source/en/api/hal/efuse.md b/docs/source/en/api/hal/efuse.md index 859d693a2..9d9075d5c 100644 --- a/docs/source/en/api/hal/efuse.md +++ b/docs/source/en/api/hal/efuse.md @@ -1,4 +1,5 @@ # bf0_hal_efuse.h ```{doxygenfile} bf0_hal_efuse.h + ``` diff --git a/docs/source/en/api/hal/epic.md b/docs/source/en/api/hal/epic.md index fcc51bace..dc67e4dbd 100644 --- a/docs/source/en/api/hal/epic.md +++ b/docs/source/en/api/hal/epic.md @@ -1,5 +1,6 @@ (hal-epic)= # bf0_hal_epic.h ```{doxygenfile} bf0_hal_epic.h + ``` diff --git a/docs/source/en/api/hal/ext_dma.md b/docs/source/en/api/hal/ext_dma.md index e2f175b73..757543112 100644 --- a/docs/source/en/api/hal/ext_dma.md +++ b/docs/source/en/api/hal/ext_dma.md @@ -1,5 +1,6 @@ # bf0_hal_ext_dma.h ```{doxygenfile} bf0_hal_ext_dma.h + ``` diff --git a/docs/source/en/api/hal/ezip.md b/docs/source/en/api/hal/ezip.md index 3da485d79..30048b050 100644 --- a/docs/source/en/api/hal/ezip.md +++ b/docs/source/en/api/hal/ezip.md @@ -1,5 +1,6 @@ (hal-ezip)= # bf0_hal_ezip.h ```{doxygenfile} bf0_hal_ezip.h + ``` diff --git a/docs/source/en/api/hal/facc.md b/docs/source/en/api/hal/facc.md index 19f0390e4..93e562154 100644 --- a/docs/source/en/api/hal/facc.md +++ b/docs/source/en/api/hal/facc.md @@ -1,6 +1,7 @@ (hal-facc)= # bf0_hal_facc.h ```{doxygenfile} bf0_hal_facc.h + ``` diff --git a/docs/source/en/api/hal/fft.md b/docs/source/en/api/hal/fft.md index 360bae3ee..790499325 100644 --- a/docs/source/en/api/hal/fft.md +++ b/docs/source/en/api/hal/fft.md @@ -1,5 +1,6 @@ (hal-fft)= # bf0_hal_fft.h ```{doxygenfile} bf0_hal_fft.h + ``` diff --git a/docs/source/en/api/hal/gpio.md b/docs/source/en/api/hal/gpio.md index 29ac99564..403f890e5 100644 --- a/docs/source/en/api/hal/gpio.md +++ b/docs/source/en/api/hal/gpio.md @@ -1,5 +1,6 @@ (hal-gpio)= # bf0_hal_gpio.h ```{doxygenfile} bf0_hal_gpio.h + ``` diff --git a/docs/source/en/api/hal/gpt.md b/docs/source/en/api/hal/gpt.md index 4bff89a50..b8e79de22 100644 --- a/docs/source/en/api/hal/gpt.md +++ b/docs/source/en/api/hal/gpt.md @@ -1,5 +1,6 @@ (hal-tim)= # bf0_hal_tim.h ```{doxygenfile} bf0_hal_tim.h + ``` diff --git a/docs/source/en/api/hal/i2c.md b/docs/source/en/api/hal/i2c.md index de3ac4d71..767a6efbf 100644 --- a/docs/source/en/api/hal/i2c.md +++ b/docs/source/en/api/hal/i2c.md @@ -1,5 +1,6 @@ (hal-i2c)= # bf0_hal_i2c.h ```{doxygenfile} bf0_hal_i2c.h + ``` diff --git a/docs/source/en/api/hal/i2s.md b/docs/source/en/api/hal/i2s.md index 6de7c4fb9..382396d41 100644 --- a/docs/source/en/api/hal/i2s.md +++ b/docs/source/en/api/hal/i2s.md @@ -1,5 +1,6 @@ (hal-i2s)= # bf0_hal_i2s.h ```{doxygenfile} bf0_hal_i2s.h + ``` diff --git a/docs/source/en/api/hal/index.md b/docs/source/en/api/hal/index.md index f0d8af412..1682e475c 100644 --- a/docs/source/en/api/hal/index.md +++ b/docs/source/en/api/hal/index.md @@ -5,5 +5,4 @@ :glob: * - -``` \ No newline at end of file +``` diff --git a/docs/source/en/api/hal/lcdc.md b/docs/source/en/api/hal/lcdc.md index 1f7e2848d..9fcb45dd2 100644 --- a/docs/source/en/api/hal/lcdc.md +++ b/docs/source/en/api/hal/lcdc.md @@ -1,4 +1,5 @@ # bf0_hal_lcdc.h ```{doxygenfile} bf0_hal_lcdc.h + ``` diff --git a/docs/source/en/api/hal/lptim.md b/docs/source/en/api/hal/lptim.md index d6aa4de6a..301ba7ad9 100644 --- a/docs/source/en/api/hal/lptim.md +++ b/docs/source/en/api/hal/lptim.md @@ -1,5 +1,6 @@ (hal-lptim)= # bf0_hal_lptim.h ```{doxygenfile} bf0_hal_lptim.h + ``` diff --git a/docs/source/en/api/hal/mailbox.md b/docs/source/en/api/hal/mailbox.md index 431ff3df9..6779870b2 100644 --- a/docs/source/en/api/hal/mailbox.md +++ b/docs/source/en/api/hal/mailbox.md @@ -1,6 +1,7 @@ (hal-mailbox)= # bf0_hal_mailbox.h ```{doxygenfile} bf0_hal_mailbox.h + ``` diff --git a/docs/source/en/api/hal/mpi.md b/docs/source/en/api/hal/mpi.md index f817194db..4f77f1a49 100644 --- a/docs/source/en/api/hal/mpi.md +++ b/docs/source/en/api/hal/mpi.md @@ -1,5 +1,6 @@ # bf0_hal_mpi.h ```{doxygenfile} bf0_hal_mpi.h + ``` diff --git a/docs/source/en/api/hal/nnacc.md b/docs/source/en/api/hal/nnacc.md index e8756001e..2ecefab6a 100644 --- a/docs/source/en/api/hal/nnacc.md +++ b/docs/source/en/api/hal/nnacc.md @@ -1,4 +1,5 @@ # bf0_hal_nn_acc.h ```{doxygenfile} bf0_hal_nn_acc.h + ``` diff --git a/docs/source/en/api/hal/patch.md b/docs/source/en/api/hal/patch.md index 2eca7b0cc..5fa51e3a3 100644 --- a/docs/source/en/api/hal/patch.md +++ b/docs/source/en/api/hal/patch.md @@ -1,5 +1,6 @@ # bf0_hal_patch.h ```{doxygenfile} bf0_hal_patch.h + ``` diff --git a/docs/source/en/api/hal/pcd.md b/docs/source/en/api/hal/pcd.md index e2abb5d9a..509b6a3e8 100644 --- a/docs/source/en/api/hal/pcd.md +++ b/docs/source/en/api/hal/pcd.md @@ -1,4 +1,5 @@ # bf0_hal_pcd.h ```{doxygenfile} bf0_hal_pcd.h + ``` diff --git a/docs/source/en/api/hal/pdm.md b/docs/source/en/api/hal/pdm.md index b305cd08d..b9a4b8b66 100644 --- a/docs/source/en/api/hal/pdm.md +++ b/docs/source/en/api/hal/pdm.md @@ -1,5 +1,6 @@ # bf0_hal_pdm.h ```{doxygenfile} bf0_hal_pdm.h + ``` diff --git a/docs/source/en/api/hal/pinmux.md b/docs/source/en/api/hal/pinmux.md index 134f283cc..4f9024ece 100644 --- a/docs/source/en/api/hal/pinmux.md +++ b/docs/source/en/api/hal/pinmux.md @@ -1,6 +1,7 @@ (hal-pinmux)= # bf0_hal_pinmux.h ```{doxygenfile} bf0_hal_pinmux.h + ``` diff --git a/docs/source/en/api/hal/pmu.md b/docs/source/en/api/hal/pmu.md index 9ec8b817d..8ce42c695 100644 --- a/docs/source/en/api/hal/pmu.md +++ b/docs/source/en/api/hal/pmu.md @@ -1,6 +1,7 @@ (hal-pmu)= # bf0_hal_pmu.h ```{doxygenfile} bf0_hal_pmu.h + ``` diff --git a/docs/source/en/api/hal/psram.md b/docs/source/en/api/hal/psram.md index b6a3dd6f1..2c941912d 100644 --- a/docs/source/en/api/hal/psram.md +++ b/docs/source/en/api/hal/psram.md @@ -1,5 +1,6 @@ # bf0_hal_psram.h ```{doxygenfile} bf0_hal_psram.h + ``` diff --git a/docs/source/en/api/hal/qspi.md b/docs/source/en/api/hal/qspi.md index 85f09d238..1d8dc11ff 100644 --- a/docs/source/en/api/hal/qspi.md +++ b/docs/source/en/api/hal/qspi.md @@ -1,5 +1,6 @@ (hal-qspi)= # bf0_hal_qspi.h ```{doxygenfile} bf0_hal_qspi.h + ``` diff --git a/docs/source/en/api/hal/rcc.md b/docs/source/en/api/hal/rcc.md index 45c1c61ab..d67816c38 100644 --- a/docs/source/en/api/hal/rcc.md +++ b/docs/source/en/api/hal/rcc.md @@ -1,4 +1,5 @@ # bf0_hal_rcc.h ```{doxygenfile} bf0_hal_rcc.h + ``` diff --git a/docs/source/en/api/hal/rng.md b/docs/source/en/api/hal/rng.md index 01c70a86a..588eaba93 100644 --- a/docs/source/en/api/hal/rng.md +++ b/docs/source/en/api/hal/rng.md @@ -1,5 +1,6 @@ # bf0_hal_rng.h ```{doxygenfile} bf0_hal_rng.h + ``` diff --git a/docs/source/en/api/hal/rtc.md b/docs/source/en/api/hal/rtc.md index 6d609eecf..5e3467739 100644 --- a/docs/source/en/api/hal/rtc.md +++ b/docs/source/en/api/hal/rtc.md @@ -1,6 +1,7 @@ (hal-rtc)= # bf0_hal_rtc.h ```{doxygenfile} bf0_hal_rtc.h + ``` diff --git a/docs/source/en/api/hal/spi.md b/docs/source/en/api/hal/spi.md index b05d9593f..84c1aa6e7 100644 --- a/docs/source/en/api/hal/spi.md +++ b/docs/source/en/api/hal/spi.md @@ -1,5 +1,6 @@ # bf0_hal_spi.h ```{doxygenfile} bf0_hal_spi.h + ``` diff --git a/docs/source/en/api/hal/syscfg.md b/docs/source/en/api/hal/syscfg.md index e03ba60e3..5310f8f10 100644 --- a/docs/source/en/api/hal/syscfg.md +++ b/docs/source/en/api/hal/syscfg.md @@ -1,6 +1,7 @@ (hal-syscfg)= # bf0_hal.h ```{doxygenfile} bf0_hal.h + ``` diff --git a/docs/source/en/api/hal/tsen.md b/docs/source/en/api/hal/tsen.md index ea848b37d..d95067986 100644 --- a/docs/source/en/api/hal/tsen.md +++ b/docs/source/en/api/hal/tsen.md @@ -1,5 +1,6 @@ # bf0_hal_tsen.h ```{doxygenfile} bf0_hal_tsen.h + ``` diff --git a/docs/source/en/api/hal/uart.md b/docs/source/en/api/hal/uart.md index 9eabcf161..e82bfae0f 100644 --- a/docs/source/en/api/hal/uart.md +++ b/docs/source/en/api/hal/uart.md @@ -1,6 +1,7 @@ (hal-uart)= # bf0_hal_uart.h ```{doxygenfile} bf0_hal_uart.h + ``` diff --git a/docs/source/en/api/hal/wdt.md b/docs/source/en/api/hal/wdt.md index 1f9f4a7e6..54572e145 100644 --- a/docs/source/en/api/hal/wdt.md +++ b/docs/source/en/api/hal/wdt.md @@ -1,5 +1,6 @@ # bf0_hal_wdt.h ```{doxygenfile} bf0_hal_wdt.h + ``` diff --git a/docs/source/en/api/index.md b/docs/source/en/api/index.md index 31cbf1ca4..7666d1aa3 100644 --- a/docs/source/en/api/index.md +++ b/docs/source/en/api/index.md @@ -1,6 +1,6 @@ # API Reference -Here is a list of all modules: +Table of Contents: ```{toctree} :titlesonly: @@ -11,6 +11,5 @@ Here is a list of all modules: hal/index middleware/index sifli_cmsis_device_interface/index - ``` diff --git a/docs/source/en/api/middleware/acpu_ctrl.md b/docs/source/en/api/middleware/acpu_ctrl.md index 9f7d94d08..e799ace58 100644 --- a/docs/source/en/api/middleware/acpu_ctrl.md +++ b/docs/source/en/api/middleware/acpu_ctrl.md @@ -1,4 +1,5 @@ (middleware-acpu_ctrl)= # acpu_ctrl.h ```{doxygenfile} acpu_ctrl.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/bf0_ble_gap.md b/docs/source/en/api/middleware/bf0_ble_gap.md index 0b7d2ed44..37a4778fa 100644 --- a/docs/source/en/api/middleware/bf0_ble_gap.md +++ b/docs/source/en/api/middleware/bf0_ble_gap.md @@ -1,4 +1,5 @@ (middleware-bf0_ble_gap)= # bf0_ble_gap.h ```{doxygenfile} bf0_ble_gap.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/bf0_mbox_common.md b/docs/source/en/api/middleware/bf0_mbox_common.md index 082c073d7..5e56dccbc 100644 --- a/docs/source/en/api/middleware/bf0_mbox_common.md +++ b/docs/source/en/api/middleware/bf0_mbox_common.md @@ -1,4 +1,5 @@ (middleware-bf0_mbox_common)= # bf0_mbox_common.h ```{doxygenfile} bf0_mbox_common.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/bf0_pm.md b/docs/source/en/api/middleware/bf0_pm.md index 50d58c8b8..62c529a4c 100644 --- a/docs/source/en/api/middleware/bf0_pm.md +++ b/docs/source/en/api/middleware/bf0_pm.md @@ -1,4 +1,5 @@ (middleware-bf0_pm)= # bf0_pm.h ```{doxygenfile} bf0_pm.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/bluetooth_service_interface.md b/docs/source/en/api/middleware/bluetooth_service_interface.md index 809fb3561..ff433cacc 100644 --- a/docs/source/en/api/middleware/bluetooth_service_interface.md +++ b/docs/source/en/api/middleware/bluetooth_service_interface.md @@ -4,8 +4,10 @@ ## bts2_app_interface.h ```{doxygenfile} bts2_app_interface.h + ``` ## bts2_app_interface_type.h ```{doxygenfile} bts2_app_interface_type.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/button.md b/docs/source/en/api/middleware/button.md index fef35bf7e..c7ea54519 100644 --- a/docs/source/en/api/middleware/button.md +++ b/docs/source/en/api/middleware/button.md @@ -1,4 +1,5 @@ (middleware-button)= # button.h ```{doxygenfile} button.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/common.md b/docs/source/en/api/middleware/common.md index 6ee2263a0..f269b9b9c 100644 --- a/docs/source/en/api/middleware/common.md +++ b/docs/source/en/api/middleware/common.md @@ -2,5 +2,6 @@ (middleware-sf_type)= # sf_type.h ```{doxygenfile} sf_type.h + ``` diff --git a/docs/source/en/api/middleware/context_backup.md b/docs/source/en/api/middleware/context_backup.md index 45d85ae33..449d95777 100644 --- a/docs/source/en/api/middleware/context_backup.md +++ b/docs/source/en/api/middleware/context_backup.md @@ -1,4 +1,5 @@ (middleware-context_backup)= # context_backup.h ```{doxygenfile} context_backup.h + ``` diff --git a/docs/source/en/api/middleware/cpu_usage_profiler.md b/docs/source/en/api/middleware/cpu_usage_profiler.md index 8f455596c..6e705d241 100644 --- a/docs/source/en/api/middleware/cpu_usage_profiler.md +++ b/docs/source/en/api/middleware/cpu_usage_profiler.md @@ -1,4 +1,5 @@ (middleware-cpu_usage_profiler)= # cpu_usage_profiler.h ```{doxygenfile} cpu_usage_profiler.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/data_service_interface.md b/docs/source/en/api/middleware/data_service_interface.md index 03c511c93..82a0cbc2b 100644 --- a/docs/source/en/api/middleware/data_service_interface.md +++ b/docs/source/en/api/middleware/data_service_interface.md @@ -4,15 +4,19 @@ ## data_service.h ```{doxygenfile} data_service.h + ``` ## data_service_provider.h ```{doxygenfile} data_service_provider.h + ``` ## data_service_subscriber.h ```{doxygenfile} data_service_subscriber.h + ``` ## ui_datasrv_subscriber.h ```{doxygenfile} ui_datasrv_subscriber.h + ``` diff --git a/docs/source/en/api/middleware/ezipa_dec.md b/docs/source/en/api/middleware/ezipa_dec.md index 54e37a4f6..65247d407 100644 --- a/docs/source/en/api/middleware/ezipa_dec.md +++ b/docs/source/en/api/middleware/ezipa_dec.md @@ -1,4 +1,5 @@ (middleware-ezipa_dec)= # ezipa_dec.h ```{doxygenfile} ezipa_dec.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/file_logger.md b/docs/source/en/api/middleware/file_logger.md index 9c9f395c4..16d5f91e3 100644 --- a/docs/source/en/api/middleware/file_logger.md +++ b/docs/source/en/api/middleware/file_logger.md @@ -1,4 +1,5 @@ (middleware-file_logger)= # file_logger.h ```{doxygenfile} file_logger.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/gui_app_fwk.md b/docs/source/en/api/middleware/gui_app_fwk.md index 6c4c38ccd..93c4dcd74 100644 --- a/docs/source/en/api/middleware/gui_app_fwk.md +++ b/docs/source/en/api/middleware/gui_app_fwk.md @@ -6,8 +6,10 @@ ## gui_app_fwk.h ```{doxygenfile} gui_app_fwk.h + ``` ## gui_app_fwk2.h ```{doxygenfile} gui_app_fwk2.h + ``` diff --git a/docs/source/en/api/middleware/inter-processor_queue_library.md b/docs/source/en/api/middleware/inter-processor_queue_library.md index 31e84ca3f..91a9c1acd 100644 --- a/docs/source/en/api/middleware/inter-processor_queue_library.md +++ b/docs/source/en/api/middleware/inter-processor_queue_library.md @@ -2,6 +2,7 @@ (middleware-ipc_queue)= # ipc_queue.h ```{doxygenfile} ipc_queue.h + ``` diff --git a/docs/source/en/api/middleware/ipc_queue_wrapper_device.md b/docs/source/en/api/middleware/ipc_queue_wrapper_device.md index 2e46fde8e..1b8c254f9 100644 --- a/docs/source/en/api/middleware/ipc_queue_wrapper_device.md +++ b/docs/source/en/api/middleware/ipc_queue_wrapper_device.md @@ -4,6 +4,7 @@ (middleware-ipc_queue_device)= # ipc_queue_device.h ```{doxygenfile} ipc_queue_device.h + ``` diff --git a/docs/source/en/api/middleware/memory_pool_manager.md b/docs/source/en/api/middleware/memory_pool_manager.md index 2804e2b33..317123c1a 100644 --- a/docs/source/en/api/middleware/memory_pool_manager.md +++ b/docs/source/en/api/middleware/memory_pool_manager.md @@ -4,5 +4,6 @@ (middleware-mem_pool_mng)= # mem_pool_mng.h ```{doxygenfile} mem_pool_mng.h + ``` diff --git a/docs/source/en/api/middleware/metrics_collector.md b/docs/source/en/api/middleware/metrics_collector.md index 839070580..6a31ef400 100644 --- a/docs/source/en/api/middleware/metrics_collector.md +++ b/docs/source/en/api/middleware/metrics_collector.md @@ -3,6 +3,7 @@ (middleware-metrics_collector)= # metrics_collector.h ```{doxygenfile} metrics_collector.h + ``` diff --git a/docs/source/en/api/middleware/module_installer.md b/docs/source/en/api/middleware/module_installer.md index 98c560bfe..de6064b66 100644 --- a/docs/source/en/api/middleware/module_installer.md +++ b/docs/source/en/api/middleware/module_installer.md @@ -3,4 +3,5 @@ (middleware-mod_installer)= # mod_installer.h ```{doxygenfile} mod_installer.h + ``` diff --git a/docs/source/en/api/middleware/section.md b/docs/source/en/api/middleware/section.md index 1a5fbff4d..62f149d34 100644 --- a/docs/source/en/api/middleware/section.md +++ b/docs/source/en/api/middleware/section.md @@ -1,4 +1,5 @@ (middleware-section)= # section.h ```{doxygenfile} section.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/section_iter.md b/docs/source/en/api/middleware/section_iter.md index 8d49e3a25..a79906e22 100644 --- a/docs/source/en/api/middleware/section_iter.md +++ b/docs/source/en/api/middleware/section_iter.md @@ -1,4 +1,5 @@ (middleware-section_iter)= # section_iter.h ```{doxygenfile} section_iter.h -``` \ No newline at end of file + +``` diff --git a/docs/source/en/api/middleware/shared_preference.md b/docs/source/en/api/middleware/shared_preference.md index 11789fbbd..652edf397 100644 --- a/docs/source/en/api/middleware/shared_preference.md +++ b/docs/source/en/api/middleware/shared_preference.md @@ -3,4 +3,5 @@ (middleware-share_prefs)= # share_prefs.h ```{doxygenfile} share_prefs.h + ``` diff --git a/docs/source/en/api/sifli_cmsis_device_interface/index.md b/docs/source/en/api/sifli_cmsis_device_interface/index.md index febbe7f31..675c45092 100644 --- a/docs/source/en/api/sifli_cmsis_device_interface/index.md +++ b/docs/source/en/api/sifli_cmsis_device_interface/index.md @@ -4,6 +4,4 @@ :titlesonly: peripheral_memory_map.md - - ``` diff --git a/docs/source/en/api/sifli_cmsis_device_interface/peripheral_memory_map.md b/docs/source/en/api/sifli_cmsis_device_interface/peripheral_memory_map.md index 449bb4f4b..6704fb457 100644 --- a/docs/source/en/api/sifli_cmsis_device_interface/peripheral_memory_map.md +++ b/docs/source/en/api/sifli_cmsis_device_interface/peripheral_memory_map.md @@ -3,4 +3,5 @@ (sifli_cmsis_device_interface-share_prefs)= # register.h ```{doxygenfile} register.h + ``` diff --git a/docs/source/en/app_development/build_and_configuration.md b/docs/source/en/app_development/build_and_configuration.md index c4dcf01d2..64e832913 100644 --- a/docs/source/en/app_development/build_and_configuration.md +++ b/docs/source/en/app_development/build_and_configuration.md @@ -1,21 +1,35 @@ - # Configuration and Compilation - -Through [create_application.md](create_application.md) and [create_board.md](create_board.md), you have already gained an intuitive understanding of the application and the board. This section further explains the relationship and operational mechanism between the two. - -A traditional RT-Thread project directory corresponds to an application, but it is already linked to a specific board. The `rtconfig.h` in the directory defines the complete configuration parameters for the project. To run this application on another board, you would need to create a new project directory based on the corresponding board’s BSP package and port the application code and related configurations over. This process is cumbersome and prone to errors. The SiFli-SDK follows Zephyr's approach of separating the board (hardware runtime environment) from the application. As long as the board provides the necessary hardware capabilities for the application, it becomes easy to compile the target files for any board. This type of application project that can compile for any target board is called a **generic project**. The compilation method for a specified target board is as follows: - +Through [create_application.md](create_application.md) and +[create_board.md](create_board.md), you have already gained an intuitive +understanding of the application and the board. This section further explains +the relationship and operational mechanism between the two. + +A traditional RT-Thread project directory corresponds to an application, but it +is already linked to a specific board. The `rtconfig.h` in the directory defines +the complete configuration parameters for the project. To run this application +on another board, you would need to create a new project directory based on the +corresponding board’s BSP package and port the application code and related +configurations over. This process is cumbersome and prone to errors. The +SiFli-SDK follows Zephyr's approach of separating the board (hardware runtime +environment) from the application. As long as the board provides the necessary +hardware capabilities for the application, it becomes easy to compile the target +files for any board. This type of application project that can compile for any +target board is called a **generic project**. The compilation method for a +specified target board is as follows: ```shell -scons --board= -jN +scons --board= -jN ``` - -Where `` is the name of the board. The selection method is described in [supported_boards/index.md](../supported_boards/index.md), and `-jN` is a multi-thread compilation parameter, where N represents the number of threads. For example, the following command uses 8 threads to compile the target file for the board `sf32lb52-lcd_n16r8`: - +Where `` is the name of the board. The selection method is described +in [supported_boards/index.md](../supported_boards/index.md), and `-jN` is a +multi-thread compilation parameter, where N represents the number of threads. +For example, the following command uses 8 threads to compile the target file for +the board `sf32lb52-lcd_n16r8`: ```shell scons --board=sf32lb52-lcd_n16r8 -j8 ``` - -The existing `--target=` parameter can also be combined with `--board`. For instance, to create the corresponding Keil project file for the `sf32lb52-lcd_n16r8` board, the following command can be executed: +The existing `--target=` parameter can also be combined with +`--board`. For instance, to create the corresponding Keil project file for the +`sf32lb52-lcd_n16r8` board, the following command can be executed: ```shell scons --board=sf32lb52-lcd_n16r8 --target=mdk5 -s @@ -27,19 +41,24 @@ It should be noted that the SDK uses multi-project compilation. The application ## Export Codebase Index -If you want to export all source files and header files used by the current project for external analysis tools, run the following command in the project directory: +If you want to export all source files and header files used by the current +project for external analysis tools, run the following command in the project +directory: ```shell -sdk.py export-codebase --board= +sdk.py export-codebase --board= ``` -If the target board has already been saved with `sdk.py set-target`, you can omit the `--board` parameter: +If the target board has already been saved with `sdk.py set-target`, you can +omit the `--board` parameter: ```shell sdk.py export-codebase ``` -This command internally invokes `scons --target=json` and generates `codebase_index.json` in the build directory, for example `build_sf32lb52-lcd_n16r8_hcpu/codebase_index.json`. +This command internally invokes `scons --target=json` and generates +`codebase_index.json` in the build directory, for example +`build_sf32lb52-lcd_n16r8_hcpu/codebase_index.json`. The exported JSON contains the following top-level fields: @@ -51,13 +70,23 @@ The exported JSON contains the following top-level fields: - `all_include_paths`: merged list of include paths - `all_defines`: merged list of preprocessor definitions -In addition to using the SDK’s built-in board configurations, you can use `--board_search_path` to specify a directory as a search path for third-party boards. This directory can be outside the SDK, and it can be either a relative or absolute path. When the search path is specified, the compiler will not only look for boards in the SDK’s board directory but will also check this directory for board configurations. If a board with the same name exists in both directories, the board in the `--board_search_path` specified directory will be used. For example, to compile using a relative path for the board search path in the `app1` project directory, you can run the following command: +In addition to using the SDK’s built-in board configurations, you can use +`--board_search_path` to specify a directory as a search path for third-party +boards. This directory can be outside the SDK, and it can be either a relative +or absolute path. When the search path is specified, the compiler will not only +look for boards in the SDK’s board directory but will also check this directory +for board configurations. If a board with the same name exists in both +directories, the board in the `--board_search_path` specified directory will be +used. For example, to compile using a relative path for the board search path in +the `app1` project directory, you can run the following command: ```shell scons --board=test_board --board_search_path=../../boards -j8 ``` -Of course, you can also use the `SIFLI_SDK_BOARD_SEARCH_PATH` environment variable to specify the search path, so you don't have to input the `--board_search_path` parameter every time. +Of course, you can also use the `SIFLI_SDK_BOARD_SEARCH_PATH` environment +variable to specify the search path, so you don't have to input the +`--board_search_path` parameter every time. ```shell export SIFLI_SDK_BOARD_SEARCH_PATH="../../boards" # unix @@ -65,7 +94,10 @@ $env:SIFLI_SDK_BOARD_SEARCH_PATH="../../boards" # powershell scons --board=test_board -j8 ``` -The directory structure of the code is as follows. The above command is executed in the `app1/project` directory, where the `test_board` is located in the `boards` directory. The `workspace` is an arbitrary working directory, which can be outside the SDK. +The directory structure of the code is as follows. The above command is executed +in the `app1/project` directory, where the `test_board` is located in the +`boards` directory. The `workspace` is an arbitrary working directory, which can +be outside the SDK. ``` +--workspace @@ -85,11 +117,32 @@ The directory structure of the code is as follows. The above command is executed └─test_board2 ``` -## Project Settings -The SDK uses menuconfig (a graphical interface tool within the kconfiglib package) to manage project settings. During compilation, it reads all macro switches from `rtconfig.h` to instruct SCons on which modules to compile and their parameters. The corresponding kconfig configuration is stored in `.config`. To address the previously mentioned issues, `rtconfig.h` and `.config` are no longer stored in the generic project directory. Instead, these files are dynamically generated in the build directory during compilation based on the selected board. The generated `.config` file is merged from Kconfig's default values, `board.conf`, and `proj.conf`. `board.conf` and `proj.conf` document the configurations requiring modification (those differing from default values). If identical configurations appear in both `board.conf` and `proj.conf`, the settings defined in `proj.conf` take precedence. -To modify `proj.conf`, execute `sdk.py menuconfig --board=` in the project directory. If `` lacks the `_hcpu` suffix, it defaults to HCPU configuration. To use LCPU settings, append `_lcpu` to the board name, e.g., `sf32lb52-lcd_n16r8_lcpu`. The parameter settings displayed in the menuconfig interface are identical to those used during actual compilation. After modifying settings, press {kbd}`D` to save the minimal configuration to `proj.conf`. To modify `board.conf`, switch to the board directory and execute `sdk.py menuconfig` (no any param). For example, navigate to `boards/sf32lb52-lcd_n16r8/hcpu` and run `sdk.py menuconfig`. + +## Project Settings +The SDK uses menuconfig (a graphical interface tool within the kconfiglib +package) to manage project settings. During compilation, it reads all macro +switches from `rtconfig.h` to instruct SCons on which modules to compile and +their parameters. The corresponding kconfig configuration is stored in +`.config`. To address the previously mentioned issues, `rtconfig.h` and +`.config` are no longer stored in the generic project directory. Instead, these +files are dynamically generated in the build directory during compilation based +on the selected board. The generated `.config` file is merged from Kconfig's +default values, `board.conf`, and `proj.conf`. `board.conf` and `proj.conf` +document the configurations requiring modification (those differing from default +values). If identical configurations appear in both `board.conf` and +`proj.conf`, the settings defined in `proj.conf` take precedence. + +To modify `proj.conf`, execute `sdk.py menuconfig --board=` in the +project directory. If `` lacks the `_hcpu` suffix, it defaults to +HCPU configuration. To use LCPU settings, append `_lcpu` to the board name, +e.g., `sf32lb52-lcd_n16r8_lcpu`. The parameter settings displayed in the +menuconfig interface are identical to those used during actual compilation. +After modifying settings, press {kbd}`D` to save the minimal configuration to +`proj.conf`. To modify `board.conf`, switch to the board directory and execute +`sdk.py menuconfig` (no any param). For example, navigate to +`boards/sf32lb52-lcd_n16r8/hcpu` and run `sdk.py menuconfig`. ```{note} If the configurations stored in `proj.conf` do not apply to all boards, you can create a subdirectory for the board in the project directory. Place the specific `proj.conf` for that board in this subdirectory for differentiated configuration. For more details, refer to [](../app_note/common_project.md). diff --git a/docs/source/en/app_development/create_application.md b/docs/source/en/app_development/create_application.md index 2a8d3bbf9..afd764eab 100644 --- a/docs/source/en/app_development/create_application.md +++ b/docs/source/en/app_development/create_application.md @@ -1,17 +1,18 @@ - # Creating an Application - -The fastest way to create an application is to copy an existing example. Below, we will explain how to create a new application based on the `hello_world` example.Here, the Windows platform is used as an example; the approaches for macOS and Linux are analogous. +The fastest way to create an application is to copy an existing example. Below, +we will explain how to create a new application based on the `hello_world` +example.Here, the Windows platform is used as an example; the approaches for +macOS and Linux are analogous. ## Copy the Example - -1. Copy the example: Copy the `example/get-started/hello_world/rtt` directory to any desired location, such as `c:\work\ws\hello_world`. +1. Copy the example: Copy the `example/get-started/hello_world/rtt` directory to + any desired location, such as `c:\work\ws\hello_world`. ```{image} ../../assets/app_folder.png :scale: 70% ``` - The directory structure of the application: + The directory structure of the application: ```none +---project // Project directory @@ -27,19 +28,32 @@ The fastest way to create an application is to copy an existing example. Below, SConscript ``` -2. Open the PowerShell command line window: Press the Win key or click the Windows icon on the lower left corner, type "powershell", and then open the PowerShell terminal. -3. Set environment variables: `cd c:\OpenSiFli\SiFli-SDK` to switch to the root directory of the SDK, and then enter `.\export.ps1`.The path used here is just an example. The actual path should be based on the user's local directory. -4. Change to the project directory: `cd c:\work\ws\hello_world\project` to switch to the copied example project directory. -5. Compile: `scons --board=sf32lb52-lcd_n16r8 -j8`. The selected board is `sf32lb52-lcd_n16r8`, refer to [supported_boards/index.md](../supported_boards/index.md). - - ![Alt text](../../assets/create_app_and_build.png)` + + +2. Open the PowerShell command line window: Press the Win key or click the + Windows icon on the lower left corner, type "powershell", and then open the + PowerShell terminal. +3. Set environment variables: `cd c:\OpenSiFli\SiFli-SDK` to switch to the root + directory of the SDK, and then enter `.\export.ps1`.The path used here is + just an example. The actual path should be based on the user's local + directory. +4. Change to the project directory: `cd c:\work\ws\hello_world\project` to + switch to the copied example project directory. +5. Compile: `scons --board=sf32lb52-lcd_n16r8 -j8`. The selected board is + `sf32lb52-lcd_n16r8`, refer to + [supported_boards/index.md](/supported_boards/index.md). + ```{image} ../../assets/create_app_and_build.png + + ``` 6. Flash: `build_sf32lb52-lcd_n16r8_hcpu\uart_download`. -At this point, a new `hello_world` program has been created, and the compilation and flashing methods for the new project are identical to those of the SDK’s built-in examples. +At this point, a new `hello_world` program has been created, and the compilation +and flashing methods for the new project are identical to those of the SDK’s +built-in examples. ## Modify the Code - -The application code for `hello_world` is in the `src/main.c` file, where you can see that it prints "Hello world" only once on line 5. +The application code for `hello_world` is in the `src/main.c` file, where you +can see that it prints "Hello world" only once on line 5. {lineno-start=1} ```c @@ -56,8 +70,8 @@ int main(void) return 0; } ``` - -Now, add the following two lines between lines 10 and 11 to print "Hello SiFli" every 3 seconds. +Now, add the following two lines between lines 10 and 11 to print "Hello SiFli" +every 3 seconds. {lineno-start=1 emphasize-lines="10,11"} ```c @@ -76,15 +90,20 @@ int main(void) return 0; } ``` - -After modifying the code, compile and download the program. Connect the serial port debugging tool, reset the device, and you will see the printed output as shown in the image. +After modifying the code, compile and download the program. Connect the serial +port debugging tool, reset the device, and you will see the printed output as +shown in the image. ```{image} ../../assets/print_log.png :scale: 70% ``` -In addition to adding code in `main.c`, you can also add C files in the `src` directory. Since the `SConscript` in the `src` directory already uses the `Glob` command to include all C files in the current directory for compilation, you can simply add your new C files. For more details on using Scons scripts, refer to [SCons.md](../app_note/scons.md). +In addition to adding code in `main.c`, you can also add C files in the `src` +directory. Since the `SConscript` in the `src` directory already uses the `Glob` +command to include all C files in the current directory for compilation, you can +simply add your new C files. For more details on using Scons scripts, refer to +[SCons.md](/app_note/scons.md). ```python import os from building import * @@ -97,13 +116,28 @@ Return('group') ``` ## Modify Settings +The `hello_world` example only has basic print functionality, and many +components are not enabled. Even if you include the headers for these components +in `main.c`, their corresponding functions cannot be called unless you modify +the project configuration using the `menuconfig` tool. -The `hello_world` example only has basic print functionality, and many components are not enabled. Even if you include the headers for these components in `main.c`, their corresponding functions cannot be called unless you modify the project configuration using the `menuconfig` tool. - -To modify the configuration, run `sdk.py menuconfig --board=` in the project directory. Replace `` with the name of the board you are using, such as `sdk.py menuconfig --board=sf32lb52-lcd_n16r8`. This is similar to specifying the board during `scons` compilation. By default, `hcpu` is used, meaning that `sdk.py menuconfig --board=sf32lb52-lcd_n16r8` and `sdk.py menuconfig --board=sf32lb52-lcd_n16r8_hcpu` will have the same effect, both configuring the current project for the `sf32lb52-lcd_n16r8` board's HCPU. +To modify the configuration, run `sdk.py menuconfig --board=` in the +project directory. Replace `` with the name of the board you are +using, such as `sdk.py menuconfig --board=sf32lb52-lcd_n16r8`. This is similar +to specifying the board during `scons` compilation. By default, `hcpu` is used, +meaning that `sdk.py menuconfig --board=sf32lb52-lcd_n16r8` and `sdk.py +menuconfig --board=sf32lb52-lcd_n16r8_hcpu` will have the same effect, both +configuring the current project for the `sf32lb52-lcd_n16r8` board's HCPU. -After executing `menuconfig`, a screen like the following will appear. You can use the {kbd}`⇧` and {kbd}`⇩` arrow keys to navigate between menu items, press {kbd}`Enter` to enter submenus, and press {kbd}`Space` to select menu items. Once all changes are complete, press {kbd}`D` to save the minimal configuration to the `proj.conf` file in the project directory (`project\proj.conf`). This file is a text file and can be opened to view the differences before and after modifications. For detailed usage of `menuconfig`, refer to [menuconfig.md](../app_note/menuconfig.md). +```{image} ../../assets/menuconfig.png -![Alt text](../../assets/menuconfig.png)` +``` -For more detailed information on configuration and compilation mechanisms, please read [build_and_configuration.md](build_and_configuration.md). +After executing `menuconfig`, a screen like the following will appear. You can +use the {kbd}`⇧` and {kbd}`⇩` arrow keys to navigate between menu items, press +{kbd}`Enter` to enter submenus, and press {kbd}`Space` to select menu items. +Once all changes are complete, press {kbd}`D` to save the minimal configuration +to the `proj.conf` file in the project directory (`project\proj.conf`). This +file is a text file and can be opened to view the differences before and after +modifications. For detailed usage of `menuconfig`, refer to +[menuconfig.md](build_and_configuration.md). diff --git a/docs/source/en/app_development/create_board.md b/docs/source/en/app_development/create_board.md index 9b7af368c..59df8ad80 100644 --- a/docs/source/en/app_development/create_board.md +++ b/docs/source/en/app_development/create_board.md @@ -1,55 +1,63 @@ - # Creating a Board - -The fastest way to create a new board is to modify an existing board with similar hardware configuration (refer to [](../supported_boards/index.md) to find supported boards). In this example, we will create a new board based on the `sf32lb52-lcd_n16r8` (i.e., `sf32lb52-devkit-lcd`) board. The new board uses the SF32LB525 chip and has an external NOR Flash, so starting with the `sf32lb52-lcd_n16r8` board is a good choice. +The fastest way to create a new board is to modify an existing board with +similar hardware configuration (refer to [](../supported_boards/index.md) to +find supported boards). In this example, we will create a new board based on the +`sf32lb52-lcd_n16r8` (i.e., `sf32lb52-devkit-lcd`) board. The new board uses the +SF32LB525 chip and has an external NOR Flash, so starting with the +`sf32lb52-lcd_n16r8` board is a good choice. The steps are as follows: +1. Create a folder `testboard_525` under the `boards` directory and copy the + files from `sf32lb52-lcd_n16r8` to `testboard_525`. +1. Create a folder `testboard_525_base` under the `boards` directory and copy + the files from `sf32lb52-lcd_base` to `testboard_525_base`. +1. Modify `testboard_525/SConscript`, changing the macro names in locations 1 + and 2 to the new board's name, and change the SConscript file path referenced + in location 3 to `testboard_525_base`. + ```{image} ../../assets/create_board_sconscript.png -1. Create a folder `testboard_525` under the `boards` directory and copy the files from `sf32lb52-lcd_n16r8` to `testboard_525`. - -2. Create a folder `testboard_525_base` under the `boards` directory and copy the files from `sf32lb52-lcd_base` to `testboard_525_base`. - -3. Modify `testboard_525/SConscript`, changing the macro names in locations 1 and 2 to the new board's name, and change the SConscript file path referenced in location 3 to `testboard_525_base`. - - ![Alt text](../../assets/create_board_sconscript.png)` - - The modified code looks like this: + ``` + ![Alt text]{1}` + ```{image} ../../assets/create_board_sconscript_new.png - ![Alt text](../../assets/create_board_sconscript_new.png) + ``` -4. Modify the board macros in `testboard_525/hcpu/Kconfig.board` and `testboard_525/lcpu/Kconfig.board` to match the names from the previous step. The modified code is as follows: +1. Modify the board macros in `testboard_525/hcpu/Kconfig.board` and + `testboard_525/lcpu/Kconfig.board` to match the names from the previous step. + The modified code is as follows: ```{code-block} kconfig - :caption: hcpu/Kconfig.board - + :caption: hcpu/Kconfig.board + config BSP_USING_BOARD_TESTBOARD_525 bool select SOC_SF32LB52X select BF0_HCPU default y - + rsource "../Kconfig.board" ``` ```{code-block} kconfig - :caption: lcpu/Kconfig.board - + :caption: lcpu/Kconfig.board + config BSP_USING_BOARD_TESTBOARD_525 bool select SOC_SF32LB52X select BF0_LCPU default y - + rsource "../Kconfig.board" ``` - -5. Modify `testboad_525/Kconfig.board` to reference the `Kconfig.board` from `testboard_525_base`: +1. Modify `testboad_525/Kconfig.board` to reference the `Kconfig.board` from + `testboard_525_base`: ```kconfig source "$SIFLI_SDK/customer/boards/testboard_525_base/Kconfig.board" ``` - -6. At this point, a new board has been created. You can switch to `hello_world/rtt/project` and run the following command to compile using the new board: +1. At this point, a new board has been created. You can switch to + `hello_world/rtt/project` and run the following command to compile using the + new board: ```none - > scons --board=testboard_525 -j8 + > scons --board=testboard_525 -j8 scons: Reading SConscript files ... Board: testboard_525_hcpu ======== @@ -81,7 +89,6 @@ The steps are as follows: ``` ## Board Directory Structure - The directory structure for the board is as follows: ```{code-block} none @@ -121,42 +128,58 @@ The directory structure for the board is as follows: SConscript ``` -The `testboard_525_base` directory is separated to improve code reuse. A single board might have several variants (e.g., using different chips), and by referencing `testboard_525_base`, multiple boards can be created without duplicating modifications. If there are no variants for the board, the files in `testboard_525_base` can be merged directly into `testboard_525` by adjusting the file references. +The `testboard_525_base` directory is separated to improve code reuse. A single +board might have several variants (e.g., using different chips), and by +referencing `testboard_525_base`, multiple boards can be created without +duplicating modifications. If there are no variants for the board, the files in +`testboard_525_base` can be merged directly into `testboard_525` by adjusting +the file references. ## Modify Board Configuration - The board configuration includes several aspects: - -1. Hardware connections are defined in files such as `bsp_pinmux.c`, `board.conf`, and `Kconfig.board`. - - `board.conf` stores options configurable via `menuconfig`, such as the serial port used for the console. To modify, run `menuconfig` in the directory where `board.conf` is located and press {kbd}`D` to save the minimal configuration. - - `Kconfig.board` stores options not visible in `menuconfig`, such as pin assignments for touch interrupts, PWM device numbers for backlight, etc. +1. Hardware connections are defined in files such as `bsp_pinmux.c`, + `board.conf`, and `Kconfig.board`. + - `board.conf` stores options configurable via `menuconfig`, such as the + serial port used for the console. To modify, run `menuconfig` in the + directory where `board.conf` is located and press {kbd}`D` to save the + minimal configuration. + - `Kconfig.board` stores options not visible in `menuconfig`, such as pin + assignments for touch interrupts, PWM device numbers for backlight, etc. ```kconfig config ASIC bool default y - + config TOUCH_IRQ_PIN int default 26 - + config LCD_PWM_BACKLIGHT_INTERFACE_NAME string default "pwm3" - + config LCD_PWM_BACKLIGHT_CHANEL_NUM int default 4 - + config LCD_BACKLIGHT_CONTROL_PIN int default 1 - + config RGBLED_CONTROL_PIN int - default 32 + default 32 ``` - - Files like `bsp_pinmux.c` configure pin functions and pull-up/down properties through functions such as `BSP_PIN_Init` and the `HAL_PIN_Set` interface. - -2. Memory partition table (`ptab.json`): This file describes the memory partitioning information, including NOR Flash, NAND Flash, PSRAM, internal SRAM, SD cards, etc. During compilation, `ptab.json` generates a `ptab.h` file in the build directory, which defines macros like `_START_ADDR`, `_OFFSET`, and `_SIZE` for each partition. These macros can be used in the code to access partition information. For the partition table syntax, please refer to [](/middleware/partition_table.md). - -For more details about how to use board please refer to [](build_and_configuration.md). + - Files like `bsp_pinmux.c` configure pin functions and pull-up/down + properties through functions such as `BSP_PIN_Init` and the `HAL_PIN_Set` + interface. +1. Memory partition table (`ptab.json`): This file describes the memory + partitioning information, including NOR Flash, NAND Flash, PSRAM, internal + SRAM, SD cards, etc. During compilation, `ptab.json` generates a `ptab.h` + file in the build directory, which defines macros like `_START_ADDR`, + `_OFFSET`, and `_SIZE` for each partition. These macros can be used in the + code to access partition information. For the partition table syntax, please + refer to [](/middleware/partition_table.md). + +For more details about how to use board please refer to +[](build_and_configuration.md). diff --git a/docs/source/en/app_development/drivers.md b/docs/source/en/app_development/drivers.md index 3f046346b..1c2c9af87 100644 --- a/docs/source/en/app_development/drivers.md +++ b/docs/source/en/app_development/drivers.md @@ -1,13 +1,38 @@ # Chip Peripheral Drivers +As shown in the software architecture diagram, the development framework +provides two sets of chip peripheral driver interfaces: one is the HAL +interface, and the other is the RT-Thread device driver interface. ![sdk +arch](../../assets/sdk_arch_diagram.png) -As shown in the software architecture diagram, the development framework provides two sets of chip peripheral driver interfaces: one is the HAL interface, and the other is the RT-Thread device driver interface. -![sdk arch](../../assets/sdk_arch_diagram.png) +The HAL interface does not use operating system services and provides all the +functionality supported by the chip peripherals. It requires the user to +implement interrupt service routines. The HAL interface is compatible across +different chip families. Most HAL interfaces offer both synchronous (polling) +and asynchronous versions. -The HAL interface does not use operating system services and provides all the functionality supported by the chip peripherals. It requires the user to implement interrupt service routines. The HAL interface is compatible across different chip families. Most HAL interfaces offer both synchronous (polling) and asynchronous versions. +The RT-Thread device driver interface provides a higher level of abstraction, +implemented based on the HAL interface, which makes it easier to port between +chip platforms from different manufacturers. Users do not need to implement +interrupt service routines, and the interface is relatively simpler to use than +the HAL interface. Even the synchronous interface uses a thread-suspension +mechanism, which avoids occupying CPU resources. Some peripheral drivers +integrate buffer management functions. For example, in UART devices, when DMA +mode is used, data is first stored in an internal buffer, and calling the +`rt_device_read` interface retrieves data from this buffer, relieving the user +from managing the buffer. However, due to the generic nature of the abstraction, +some hardware features are not implemented in the RT-Thread device driver layer. -The RT-Thread device driver interface provides a higher level of abstraction, implemented based on the HAL interface, which makes it easier to port between chip platforms from different manufacturers. Users do not need to implement interrupt service routines, and the interface is relatively simpler to use than the HAL interface. Even the synchronous interface uses a thread-suspension mechanism, which avoids occupying CPU resources. Some peripheral drivers integrate buffer management functions. For example, in UART devices, when DMA mode is used, data is first stored in an internal buffer, and calling the `rt_device_read` interface retrieves data from this buffer, relieving the user from managing the buffer. However, due to the generic nature of the abstraction, some hardware features are not implemented in the RT-Thread device driver layer. +The HAL interface, compared to the RT-Thread device driver interface, is closer +to the hardware layer, allowing for more flexible use of hardware and fewer +intermediary steps, resulting in higher function execution efficiency. However, +it is more complex to use. Generally, if the features provided by the RT-Thread +device driver meet the application development needs, it is recommended to use +the device driver. The HAL interface should only be chosen when the device +driver cannot fulfill the requirements or does not offer sufficient performance. +For guidance on using device drivers, refer to [device driver +guide](/drivers/index.md), and for HAL interface usage, refer to the [HAL +guide](/hal/index.md). -The HAL interface, compared to the RT-Thread device driver interface, is closer to the hardware layer, allowing for more flexible use of hardware and fewer intermediary steps, resulting in higher function execution efficiency. However, it is more complex to use. Generally, if the features provided by the RT-Thread device driver meet the application development needs, it is recommended to use the device driver. The HAL interface should only be chosen when the device driver cannot fulfill the requirements or does not offer sufficient performance. For guidance on using device drivers, refer to [device driver guide](../drivers/index.md), and for HAL interface usage, refer to the [HAL guide](../hal/index.md). ```{warning} Note that for a given peripheral, such as UART, the HAL and device driver interfaces should not be mixed. When using the HAL interface to operate UART, ensure that the `serial device drivers` in the `Device Drivers` section are not enabled. diff --git a/docs/source/en/app_development/index.md b/docs/source/en/app_development/index.md index 2a57c02f4..a40ee74fa 100644 --- a/docs/source/en/app_development/index.md +++ b/docs/source/en/app_development/index.md @@ -9,6 +9,5 @@ create_board build_and_configuration drivers.md startup_flow - ``` diff --git a/docs/source/en/app_development/startup_flow.md b/docs/source/en/app_development/startup_flow.md index f3945d849..fb878cba5 100644 --- a/docs/source/en/app_development/startup_flow.md +++ b/docs/source/en/app_development/startup_flow.md @@ -141,17 +141,17 @@ The second‑stage bootloader does not load PMU calibration parameters; it only ### ResetHandler ```{only} SF32LB52X -The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb52x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. -``` + The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb52x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. + ``` ```{only} SF32LB55X -The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb55x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. -``` + The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb55x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. + ``` ```{only} SF32LB56X -The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb56x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. -``` + The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb56x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. + ``` ```{only} SF32LB58X -The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb58x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. -``` + The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb58x\Templates\arm\startup_bf0_hcpu.S`). Its flow is shown below. The user `main` function is called by the main thread created in `rt_application_init`. See {ref}`main_thread_entry flow `. + ``` ```{image} ../../assets/ResetHandler.png :alt: reset_handler_flow :name: reset_handler_flow @@ -177,7 +177,11 @@ The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb58x\Te ``` ### rt_hw_board_init -`rt_hw_board_init` performs low‑level hardware initialization such as clock and IO configuration, PSRAM and NOR Flash initialization, heap and serial console initialization. `rt_components_board_init` is an application‑defined initialization hook and calls different functions depending on the application configuration. +`rt_hw_board_init` performs low‑level hardware initialization such as clock and +IO configuration, PSRAM and NOR Flash initialization, heap and serial console +initialization. `rt_components_board_init` is an application‑defined +initialization hook and calls different functions depending on the application +configuration. ```{image} ../../assets/rt_hw_board_init.png :alt: rt_hw_board_init @@ -187,10 +191,20 @@ The application entry function is `ResetHandler` (in `drivers\cmsis\sf32lb58x\Te #### HAL_Init -`HAL_Init` completes HAL initialization: it loads PMU calibration parameters, updates clock and IO settings, and initializes PSRAM and NOR Flash (according to the new clock configuration). In the diagram, green functions are board‑level driver functions with board‑specific implementations (`HAL_PreInit`, `BSP_IO_Init`, `BSP_PIN_Init`, `BSP_Power_Up`, etc.). Gray functions are virtual hooks implemented by the application (or not), independent of the board, so different applications on the same board can customize behavior (e.g., different IO configurations). Horizontally, the flow shows nested calls inside functions (e.g., `HAL_PreInit` calls clock‑configuration helpers; `HAL_MspInit` calls `BSP_IO_Init`). Vertically, it shows serially executed functions (e.g., after `HAL_PreInit` finishes, `HAL_PostMspInit` runs). +`HAL_Init` completes HAL initialization: it loads PMU calibration parameters, +updates clock and IO settings, and initializes PSRAM and NOR Flash (according to +the new clock configuration). In the diagram, green functions are board‑level +driver functions with board‑specific implementations (`HAL_PreInit`, +`BSP_IO_Init`, `BSP_PIN_Init`, `BSP_Power_Up`, etc.). Gray functions are virtual +hooks implemented by the application (or not), independent of the board, so +different applications on the same board can customize behavior (e.g., different +IO configurations). Horizontally, the flow shows nested calls inside functions +(e.g., `HAL_PreInit` calls clock‑configuration helpers; `HAL_MspInit` calls +`BSP_IO_Init`). Vertically, it shows serially executed functions (e.g., after +`HAL_PreInit` finishes, `HAL_PostMspInit` runs). -```{image} ../../assets/hal_init_english.png +```{image} ../../assets/hal_init.png :alt: hal_init_flow :name: hal_init_flow ``` @@ -219,7 +233,6 @@ Loaded PMU calibration registers include: * HXT\_CR1\_CBANK\_SEL (added in Xiaomi branch; previously loaded in the rt_component_board_init stage). The calibration‑loading code may run from Flash or PSRAM. The details of the PMU parameters initialized by HAL_PMU_Init can be found in the HAL_PMU_Init function in drivers/hal/bf0_hal_pmu.c. - ``` ```{only} SF32LB55X @@ -230,7 +243,6 @@ Config Clock adjusts: * If external XT32K is used, switch RTC to XT32K * Set system clock to 240 MHz (DLL1) * Set DLL2 to 96 MHz - ``` ```{only} SF32LB56X or SF32LB58X Config Clock adjusts: @@ -244,7 +256,12 @@ Config Clock adjusts: ### rt_application_init -`rt_application_init` creates the main thread with entry `main_thread_entry`. After thread scheduling is enabled (i.e., after `rt_system_scheduler_start`), the main thread is scheduled and enters `main_thread_entry`, first calling `rt_components_init` to initialize components, then calling `main` (implemented by the application). User code starts from `main`. For example, the `rt_driver` sample's main function is in `example/rt_driver/src/main.c`. +`rt_application_init` creates the main thread with entry `main_thread_entry`. +After thread scheduling is enabled (i.e., after `rt_system_scheduler_start`), +the main thread is scheduled and enters `main_thread_entry`, first calling +`rt_components_init` to initialize components, then calling `main` (implemented +by the application). User code starts from `main`. For example, the `rt_driver` +sample's main function is in `example/rt_driver/src/main.c`. ```{image} ../../assets/main_thread_entry.png @@ -265,31 +282,33 @@ Each board needs to implement the following board‑level driver functions. Refe ```{only} SF32LB58X Each board needs to implement the following board‑level driver functions. Refer to files under `customer/boards/ec-lb58x`. ``` -| **Function** | **Required** | **Description** | -| --- | --- | --- | -| HAL\_PreInit | YES | Recommend referencing a board with similar hardware form | -| BSP\_Power\_Up | NO | Called after cold boot and wake‑up | -| BSP\_IO\_Power\_Down | NO | Called before sleep | -| BSP\_LCD\_Reset | NO | | -| BSP\_LCD\_PowerUp | NO | Called when powering the display on | -| BSP\_LCD\_PowerDown | NO | Called when powering the display off | -| BSP\_TP\_Reset | NO | | -| BSP\_TP\_PowerUp | NO | Called when powering touch on | -| BSP\_TP\_PowerDown | NO | Called when powering touch off | -| HAL\_MspInit | NO | Called by `HAL_PreInit`; virtual default calls `BSP_IO_Init` | -| HAL\_PostMspInit | NO | | -| BSP\_IO\_Init | NO | Called by `HAL_MspInit` by default | -| BSP\_PIN\_Init | NO | Called by `BSP_IO_Init`; IO configuration function | -| | | | +| **Function** | **Required** | **Description** | +| -------------------- | ------------ | ------------------------------------------------------------ | +| HAL\_PreInit | YES | Recommend referencing a board with similar hardware form | +| BSP\_Power\_Up | NO | Called after cold boot and wake‑up | +| BSP\_IO\_Power\_Down | NO | Called before sleep | +| BSP\_LCD\_Reset | NO | | +| BSP\_LCD\_PowerUp | NO | Called when powering the display on | +| BSP\_LCD\_PowerDown | NO | Called when powering the display off | +| BSP\_TP\_Reset | NO | | +| BSP\_TP\_PowerUp | NO | Called when powering touch on | +| BSP_TP_PowerDown | NO | Called when powering touch off | +| HAL_MspInit | NO | Called by `HAL_PreInit`; virtual default calls `BSP_IO_Init` | +| HAL_PostMspInit | NO | | +| BSP_IO_Init | NO | Called by `HAL_MspInit` by default | +| BSP_PIN_Init | NO | Called by `BSP_IO_Init`; IO configuration function | +| | | | ## Application‑defined Driver Interfaces -If different applications on the same board need different `HAL_MspInit` behavior, you can implement `HAL_MspInit` under the application directory; otherwise, it can reside under the board directory. +If different applications on the same board need different `HAL_MspInit` +behavior, you can implement `HAL_MspInit` under the application directory; +otherwise, it can reside under the board directory. -| **Function** | **Required** | **Description** | -| --- | --- | --- | -| HAL\_MspInit | NO | | -| HAL\_PostMspInit | NO | | +| **Function** | **Required** | **Description** | +| --------------- | ------------ | --------------- | +| HAL_MspInit | NO | | +| HAL_PostMspInit | NO | | diff --git a/docs/source/en/app_note/adc.md b/docs/source/en/app_note/adc.md index 083804367..ce56601b9 100644 --- a/docs/source/en/app_note/adc.md +++ b/docs/source/en/app_note/adc.md @@ -1,30 +1,43 @@ +# ADC User Guide -# ADC Usage Guide - -## 1. ADC Introduction -Currently, the ADC has 8 available channels with a measurement range of 0 to 1.0 V. The ADC can test individual channels or perform multi-channel cyclic tests. It can stop after testing a set of data or continue to output data indefinitely. +## 1. Introduction +The ADC currently supports eight available channels with a measurement range of +0 to 1.0 V per unit. It supports both single-channel and multi-channel cyclic +scanning modes. Operation can be configured to stop after capturing a single set +of data or to provide continuous data output. ## 2. ADC Configuration -The ADC configuration includes PINMUX configuration and ADC clock-related configuration, which are defined in `adc_config.h`. Users can modify them as needed. -The PINMUX setup varies slightly for A0 and Z0. For Z0, when the PIN is used as ADC, you can select the ADC function directly during PIN configuration (e.g., `HAL_PIN_Set(PAD_PB_04, ADC_PIN, PIN_PULLUP, 0)`). -For A0, each pin that can be configured as GPADC corresponds to a different FUNCTION setting: GPADC_CH0, GPADC_CH1, and so on. When using these, set the pins according to the corresponding channels, for example, `HAL_PIN_Set(PAD_PB08, GPADC_CH0, PIN_NOPULL, 0)` for PAD_PB8 corresponding to GPADC channel 0. -Alternatively, you can directly set the PIN to analog function without worrying about the specific analog function of each PIN, such as `HAL_PIN_Set_Analog(PAD_PB08, 0)` / `HAL_PIN_Set_Analog(PAD_PB13, 0)`. - -For A0, the available PADs and their corresponding GPADC channels are as follows: -| PAD Number | Channel | Description | -|------------|---------|------------| -| PAD_PB08 | GPADC_CH0 | Connected to LCPU | -| PAD_PB10 | GPADC_CH1 | Connected to LCPU | -| PAD_PB12 | GPADC_CH2 | Connected to LCPU | -| PAD_PB13 | GPADC_CH3 | Connected to LCPU | -| PAD_PB16 | GPADC_CH4 | Connected to LCPU | -| PAD_PB17 | GPADC_CH5 | Connected to LCPU | -| PAD_PB18 | GPADC_CH6 | Connected to LCPU | -| PAD_PB19 | GPADC_CH7 | Connected to LCPU | - -## 3. ADC Usage - -In our system, the ADC is registered as a battery voltage device, which can be operated via device methods. The default device name is "bat1": +ADC configuration involves setting up the PINMUX and the ADC clock. Clock +parameters are defined in `adc_config.h` and can be modified as needed.
+PINMUX configuration differs slightly between A0 and Z0 revisions. On Z0, if a +pin is used for ADC, the ADC function can be selected directly when configuring +the pin (e.g., `HAL_PIN_Set(PAD_PB_04, ADC_PIN, PIN_PULLUP, 0)`).
On A0, +each pin configurable as a GPADC corresponds to a specific function: +`GPADC_CH0`, `GPADC_CH1`, etc.
When using A0, pins must be configured +according to their specific mapping. For example, since `PAD_PB08` corresponds +to GPADC Channel 0, it should be set as: `HAL_PIN_Set(PAD_PB08, GPADC_CH0, +PIN_NOPULL, 0)`.
Similarly, since `PAD_PB13` corresponds to GPADC Channel +3, it should be set as: `HAL_PIN_Set(PAD_PB13, GPADC_CH3, PIN_NOPULL, 0)`.
+Alternatively, a pin can be set directly to analog mode without explicitly +specifying the channel mapping, for example: `HAL_PIN_Set_Analog(PAD_PB08, 0)` +or `HAL_PIN_Set_Analog(PAD_PB13, 0)`.
The following table maps the pads +available for GPADC on the A0 revision to their respective functions:
+| Pad Number | Channel Number | Description | +| ---------- | -------------- | -------------- | +| PAD_PB08 | GPADC_CH0 | Mapped to LCPU | +| PAD_PB10 | GPADC_CH1 | Mapped to LCPU | +| PAD_PB12 | GPADC_CH2 | Mapped to LCPU | +| PAD_PB13 | GPADC_CH3 | Mapped to LCPU | +| PAD_PB16 | GPADC_CH4 | Mapped to LCPU | +| PAD_PB17 | GPADC_CH5 | Mapped to LCPU | +| PAD_PB18 | GPADC_CH6 | Mapped to LCPU | +| PAD_PB19 | GPADC_CH7 | Mapped to LCPU | + +## 3. ADC Application + +In this system, the ADC is registered by default as a battery voltage device. It +can be operated using standard device drivers (read/write). The default device +name is "bat1":
```c uint32_t chnl = 1; @@ -36,48 +49,87 @@ if (dev) { // open device rt_device_open(dev, RT_DEVICE_FLAG_RDONLY); - // enable adc + // enable adc rt_device_control(dev, RT_ADC_CMD_ENABLE, (void *)chnl); - // read adc value - rt_device_read(dev, chnl, &value, 1); + // read adc value + rt_device_read(dev, chnl, &value, 1); } ...... ``` ## 4. Voltage Calculation -The voltage value can be obtained through the ADC using the `HAL_ADC_GetValue` interface, or via the `read` interface if using `rt_device`. -Each increment of the register value corresponds to a voltage increase of approximately 1 mV (the exact value may vary per chip, requiring factory calibration). -The relationship between ADC value and voltage is linear, and to calibrate for offset and slope accuracy, you can refer to the function `sifli_adc_calibration`. -The method involves determining a line through two known points, then using this line to calculate voltage for any subsequent register value. +The ADC digital value can be obtained via the HAL_ADC_GetValue interface (or the +read interface when using rt_device).
Each increment in the register value +corresponds to a voltage increase of approximately 1 mV (this varies between +units and requires factory calibration).
There is a linear relationship +between the ADC raw value and the actual voltage. For details on how to +calibrate the precise offset and slope, refer to the sifli_adc_calibration +function.
The calibration principle utilizes a two-point linear +interpolation: a line is defined by two known coordinates, allowing any +subsequent register value (one coordinate) to be converted into its +corresponding voltage (the other coordinate).
Operation process:
Use +ATE equipment to input two precise, known voltages (e.g., 0.3V and 0.8V; avoid +0V or the maximum range). Read the corresponding ADC register values for both. +By storing these two sets of voltage and register values, the application can +determine the line parameters, including the offset (the theoretical register +value at 0V, though accuracy decreases near 0V) and the slope (voltage increment +per register LSB). These values are then saved for future voltage +measurements.
-Example conversion code for the register value to voltage: +Reference code for converting register values to voltage:
```c +// default value, they should be over write by calibrate +// it should be register value offset vs 0 v value. static uint32_t adc_vol_offset = 200; -static uint32_t adc_vol_ratio = 3930; +// mv per bit, if accuracy not enough, change to 0.1 mv or 0.01 mv later +static uint32_t adc_vol_ratio = 3930; //6; + +/** +* @brief Converts a register value to voltage. +* @param[in] value Register value. +* @retval Voltage in mV. int sifli_adc_get_mv(uint32_t value) { uint32_t offset, ratio; + // get offset offset = adc_vol_offset; + // get ratio ratio = adc_vol_ratio; + return (value - offset) * ratio / ADC_RATIO_ACCURATE; } -int sifli_adc_calibration(uint32_t value1, uint32_t value2, uint32_t vol1, uint32_t vol2, uint32_t *offset, uint32_t *ratio) +/** +* @brief Calculate voltage offset and ratio via calibration. +* @param[in] value1 Register value 1. +* @param[in] value2 Register value 2. +* @param[in] vol1 Voltage 1 in mV. +* @param[in] vol2 Voltage 2 in mV. +* @param[out] offset Register value offset relative to 0V. +* @param[out] ratio Voltage (mV) per bit; scaled by ADC_RATIO_ACCURATE (e.g., 100 for 0.01 mV resolution). +* @retval Measured offset. +*/ +int sifli_adc_calibration(uint32_t value1, uint32_t value2, + uint32_t vol1, uint32_t vol2, uint32_t *offset, uint32_t *ratio) { uint32_t gap1, gap2; + if (offset == NULL || ratio == NULL) return 0; - gap1 = value1 > value2 ? value1 - value2 : value2 - value1; - gap2 = vol1 > vol2 ? vol1 - vol2 : vol2 - vol1; + + gap1 = value1 > value2 ? value1 - value2 : value2 - value1; // register value gap + gap2 = vol1 > vol2 ? vol1 - vol2 : vol2 - vol1; // voltage gap -- mv + if (gap1 != 0) { - *ratio = gap2 * ADC_RATIO_ACCURATE / gap1; + *ratio = gap2 * ADC_RATIO_ACCURATE / gap1; // gap2 * 10 for 0.1mv, gap2 * 100 for 0.01mv adc_vol_ratio = *ratio; } *offset = value1 - vol1 * ADC_RATIO_ACCURATE / adc_vol_ratio; adc_vol_offset = *offset; + return adc_vol_offset; } ``` diff --git a/docs/source/en/app_note/common_project.md b/docs/source/en/app_note/common_project.md index 43f8ac944..864f746b3 100644 --- a/docs/source/en/app_note/common_project.md +++ b/docs/source/en/app_note/common_project.md @@ -1,121 +1,176 @@ - # Common Project Build Method ## 1. Background -In SDK versions before v2.1.5, under each example directory, different directories were created for each board to store corresponding project files. For instance, under _$SDK_ROOT/hal_example/project_, directories for eh-lb561, eh-lb563, and eh-lb523 boards were present, each corresponding to a project for the respective boards. Each directory contained similar SCons scripts and _.config_ and _rtconfig.h_ configuration files. To compile software for the eh-lb561 board, users would enter the eh-lb561 directory and execute `scons` to perform the compilation. - -The problem with this approach was that every time a new board was added, a new project directory had to be created. As the number of examples increased, many new projects were added. If a common configuration needed modification for a certain example, it had to be updated in all the projects, leading to high maintenance overhead. +In SDK versions before v2.1.5, under each example directory, different +directories were created for each board to store corresponding project files. +For instance, under _$SDK_ROOT/hal_example/project_, directories for eh-lb561, +eh-lb563, and eh-lb523 boards were present, each corresponding to a project for +the respective boards. Each directory contained similar SCons scripts and +_.config_ and _rtconfig.h_ configuration files. To compile software for the +eh-lb561 board, users would enter the eh-lb561 directory and execute `scons` to +perform the compilation. -To address this issue, starting from v2.1.5, the SDK introduced a new project build method known as the "Common Project" approach. Under this method, only one project folder is required for each example, and it no longer stores the _.config_ and _rtconfig_ files. During compilation, the software for the selected board is generated, and _.config_ and _rtconfig.h_ are generated in the build directory. Multiple boards can be compiled simultaneously, and the generated files will not overwrite each other. ## 2. Compilation Method - -In the common project directory, execute the following command to compile the image for a specified board. `board_name` is the name of the board, and it can still be followed by other scons parameters, such as `-j8` to specify the use of 8 threads for compilation. - -For dual-core chip boards, the `board_name` must specify which core is being used, for example, `eh-lb523_hcpu`, indicating the program that can run on the HCPU of the 523 HDK board. - -To reduce repetitive file maintenance work, many files are generated during compilation, such as _.config_, _rtconfig_, and linker scripts, etc. The specific generation method is described in section 3.3. - -```python - scons --board=board_name +In the common project directory, execute the following command to compile the +image for a specified board. `board_name` is the name of the board, and it can +still be followed by other scons parameters, such as `-j8` to specify the use of +8 threads for compilation. +```python +scons --board=board_name ``` -The following command compiles a program that can run on the HCPU of the eh-lb523_v2 board. +For dual-core chip boards, the `board_name` must specify which core is being +used, for example, `eh-lb523_hcpu`, indicating the program that can run on the +HCPU of the 523 HDK board. -```python - scons --board=eh-lb523_v2_hcpu -j8 +```python +scons --board=eh-lb523_v2_hcpu -j8 ``` -The generated files will be stored in the `build_eh-lb523_v2_hcpu` directory, as shown below: +To reduce repetitive file maintenance work, many files are generated during +compilation, such as _.config_, _rtconfig_, and linker scripts, etc. The +specific generation method is described in section 3.3. + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -![Build Output](../../assets/an_28_build_output.png) ## 3. How to Create a Common Project -The creation of a common project involves two parts: the board and the application. If creating a new application on an existing board, you can skip section 3.1 and directly create an application project. +The creation of a common project involves two parts: the board and the +application. If creating a new application on an existing board, you can skip +section 3.1 and directly create an application project. ### 3.1 Board -The directory structure for the board is shown below. The top-level directory stores the source files related to the board, including: - -- IO-related code, such as `bsp_pinmux.c`, `bsp_power.c` -- Initialization code, `bsp_init.c` -- `ptab.json`, memory layout -- `SConscript`, build script -- `Kconfig.board`, the board's Kconfig configuration file - -The second-level directories contain configuration files for each core, including: - -- `_board.conf_`, the minimal configuration file generated by Kconfig -- `_Kconfig.board_`, the Kconfig configuration file for the core, which can source the top-level `_Kconfig.board_` -- `_link.sct_`, optional, Keil's linker script -- `_rtconfig.py_`, which can specify JLINK_DEVICE, optimization level, and other compilation parameters (it is recommended to use the newly added Kconfig configuration for optimization) -- `_custom_mem_map.h_`, used when `CUSTOM_MEM_MAP` is enabled - -![](../../assets/an_28_board.png) - -Sometimes, different chips may be used on the same model of HDK. To avoid duplicating IO setup code in different board directories, common code can be placed in a shared directory, which is then referenced by the individual board directories. - -![](../../assets/an_28_board2.png) +The directory structure for the board is shown below. The top-level directory +stores the source files related to the board, including: +- IO-related code, such as `bsp_pinmux.c`, `bsp_power.c` +- Initialization code, `bsp_init.c` +- `ptab.json`, memory layout +- `SConscript`, build script +- `Kconfig.board`, the board's Kconfig configuration file + +The second-level directories contain configuration files for each core, +including: +- `_board.conf_`, the minimal configuration file generated by Kconfig +- `_Kconfig.board_`, the Kconfig configuration file for the core, which can + source the top-level `_Kconfig.board_` +- `_link.sct_`, optional, Keil's linker script +- `_rtconfig.py_`, which can specify JLINK_DEVICE, optimization level, and + other compilation parameters (it is recommended to use the newly added + Kconfig configuration for optimization) +- `_custom_mem_map.h_`, used when `CUSTOM_MEM_MAP` is enabled + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. + + +Sometimes, different chips may be used on the same model of HDK. To avoid +duplicating IO setup code in different board directories, common code can be +placed in a shared directory, which is then referenced by the individual board +directories. + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. #### 3.1.1 board.conf -Run `menuconfig` in the second-level directory to open the configuration window. This configuration interface loads all Kconfig files from the SDK except for the application-specific ones. After modifying the configuration, choose "[D] Save minimal config" to save the minimal differential configuration (the part that differs from the default Kconfig configuration), and name the file `board.conf`. Choosing "[S] Save" will generate `.config` and `_rtconfig.h_`, allowing the correct configuration to be displayed the next time it is opened. If `.config` is not generated, after closing `menuconfig`, the configuration will revert to the default configuration, and the settings in `board.conf` will not be loaded. It is recommended to delete the generated `_rtconfig.h_` to avoid it being mistakenly referenced. Alternatively, you can run `_gen_board_config.bat_` to generate `.config` and `config.h` based on `board.conf`. - -It is recommended to configure a basic runtime environment in `board.conf` for general application development, such as ensuring the console (selecting the appropriate serial port) and file system (selecting the appropriate file system type) work. Application-specific configurations should be set in the application's project configuration file. - -![](../../assets/an_28_board2.png) +Run `menuconfig` in the second-level directory to open the configuration window. +This configuration interface loads all Kconfig files from the SDK except for the +application-specific ones. After modifying the configuration, choose "[D] Save +minimal config" to save the minimal differential configuration (the part that +differs from the default Kconfig configuration), and name the file `board.conf`. +Choosing "[S] Save" will generate `.config` and `_rtconfig.h_`, allowing the +correct configuration to be displayed the next time it is opened. If `.config` +is not generated, after closing `menuconfig`, the configuration will revert to +the default configuration, and the settings in `board.conf` will not be loaded. +It is recommended to delete the generated `_rtconfig.h_` to avoid it being +mistakenly referenced. Alternatively, you can run `_gen_board_config.bat_` to +generate `.config` and `config.h` based on `board.conf`. + +It is recommended to configure a basic runtime environment in `board.conf` for +general application development, such as ensuring the console (selecting the +appropriate serial port) and file system (selecting the appropriate file system +type) work. Application-specific configurations should be set in the +application's project configuration file. + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. #### 3.1.2 rtconfig.py -The `rtconfig.py` file introduces two new variables: `CORE` and `CHIP`. `CORE` specifies the core type, which can be either "HCPU" or "LCPU," and `CHIP` represents the chip series, such as "SF32LB56X" or "SF32LB52X." +The `rtconfig.py` file introduces two new variables: `CORE` and `CHIP`. `CORE` +specifies the core type, which can be either "HCPU" or "LCPU," and `CHIP` +represents the chip series, such as "SF32LB56X" or "SF32LB52X." -![](../../assets/an_28_board_rtconfig.png) +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -### 3.2 Application Project -For applications that use dual-core chips, the project directory is split into `hcpu` and `lcpu` subdirectories. +### 3.2 Application Project +For applications that use dual-core chips, the project directory is split into +`hcpu` and `lcpu` subdirectories. -![](../../assets/an_28_app_folder.png) +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -For the SF32LB52X, if only the HCPU application is needed, and no LCPU is used, or a precompiled LCPU image is used, the application project only needs to create a directory for the HCPU project files, as shown in the following example project. +For the SF32LB52X, if only the HCPU application is needed, and no LCPU is used, +or a precompiled LCPU image is used, the application project only needs to +create a directory for the HCPU project files, as shown in the following example +project. -![](../../assets/an_28_52x_app.png) +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. The files in the directory include: - -- `_Kconfig.proj_`, the application’s Kconfig configuration file -- `_proj.conf_`, the application's minimal configuration file -- `_rtconfig.py_`, custom compilation options for the application, which override any matching configurations in the board directory -- `Sconscript/Sconstruct`, build scripts -- Application-specific source code +- `_Kconfig.proj_`, the application’s Kconfig configuration file +- `_proj.conf_`, the application's minimal configuration file +- `_rtconfig.py_`, custom compilation options for the application, which + override any matching configurations in the board directory +- `Sconscript/Sconstruct`, build scripts +- Application-specific source code #### 3.2.1 SConstruct -Unlike the previous project setup, the `SConstruct` script must call `PrepareEnv()` at the beginning to prepare the board’s compilation environment. +Unlike the previous project setup, the `SConstruct` script must call +`PrepareEnv()` at the beginning to prepare the board’s compilation environment. + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -![](../../assets/an_28_sconstruct.png) +Since sub-projects may run on different cores, parameters must be added in the +`SConstruct` script to specify which core the sub-project will run on. If not +specified, it defaults to the main project. For instance, the following shows +how an LCPU sub-project is added. -Since sub-projects may run on different cores, parameters must be added in the `SConstruct` script to specify which core the sub-project will run on. If not specified, it defaults to the main project. For instance, the following shows how an LCPU sub-project is added. +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -![](../../assets/an_28_app_child_proj.png) #### 3.2.2 proj.conf -Similar to generating `board.conf`, run `menuconfig` in the project directory to save the minimal configuration to `proj.conf`. If all configurations are saved, delete the generated `_rtconfig.h_`. You can also execute `_gen_proj_config.bat_` to generate `.config` and `config.h` based on `proj.conf`. The generated files are equivalent to choosing "[S] Save" in `menuconfig`. +Similar to generating `board.conf`, run `menuconfig` in the project directory to +save the minimal configuration to `proj.conf`. If all configurations are saved, +delete the generated `_rtconfig.h_`. You can also execute +`_gen_proj_config.bat_` to generate `.config` and `config.h` based on +`proj.conf`. The generated files are equivalent to choosing "[S] Save" in +`menuconfig`. -In the build directory, a Kconfig file will also be generated. Compared to the Kconfig file in the application project directory, it will additionally load the board's Kconfig file to generate a complete configuration file. -```python +```python source "$SIFLI_SDK/Kconfig.v2" source "$SIFLI_SDK/customer/boards/eh-lb56xu_v2/hcpu/Kconfig.board" source "D:/Users/xiaomingxi/code/bt7/example/multicore/data_service/common/hcpu/Kconfig.proj" ``` -Below is an example of `proj.conf`. To disable a specific option, start with a `#` and write "is not set" after the option name (with the `CONFIG_` prefix). The configuration below disables `ULOG_USING_COLOR`. +In the build directory, a Kconfig file will also be generated. Compared to the +Kconfig file in the application project directory, it will additionally load the +board's Kconfig file to generate a complete configuration file. -```python +```python CONFIG_RT_MAIN_THREAD_STACK_SIZE=4096 CONFIG_RT_MAIN_THREAD_PRIORITY=15 CONFIG_RT_USING_ULOG=y @@ -137,72 +192,129 @@ CONFIG_BSP_USING_FULL_ASSERT=y ### 3.3 File Generation Rules -To reduce repetitive file maintenance, the following files are dynamically generated during compilation based on the selected board in the build directory: - -- `_rtconfig.h` (and `.config`) -- `_ptab.json/ptab.h_` -- `_custom_mem_map.h_` -- `_link.sct/link.lds_` (linker scripts) - -The general rule for file generation is to select the highest-priority file from the relevant directories as the final used file or to override lower-priority configurations. The priority order from highest to lowest is: - -1. The board directory in the application project directory -2. The chip directory in the application project directory (specified by `rtconfig.CHIP` for the chip series, e.g., sf32lb56x) -3. The application project directory -4. The board directory -5. The chip series directory +To reduce repetitive file maintenance, the following files are dynamically +generated during compilation based on the selected board in the build directory: +- `_rtconfig.h` (and `.config`) +- `_ptab.json/ptab.h_` +- `_custom_mem_map.h_` +- `_link.sct/link.lds_` (linker scripts) + +The general rule for file generation is to select the highest-priority file from +the relevant directories as the final used file or to override lower-priority +configurations. The priority order from highest to lowest is: +1. The board directory in the application project directory +2. The chip directory in the application project directory (specified by + `rtconfig.CHIP` for the chip series, e.g., sf32lb56x) +3. The application project directory +4. The board directory +5. The chip series directory #### 3.3.1 custom_mem_map.h -For example, in the application project directory `data_service/common/hcpu`, there is a board directory `eh-lb561_v2_hcpu` that contains the `_custom_mem_map.h_`. Therefore, the `_custom_mem_map.h_` in the build directory is copied from `data_service/common/hcpu/eh-lb561_v2_hcpu/custom_mem_map.h`. If the application’s board directory doesn't have `_custom_mem_map.h_` but the application project directory does, it will be copied from there. Only if the file is not present in both the application and the board directory will it be copied from `_$SDK_ROOT/customer/boards/eh-lb561_v2/hcpu/custom_mem_map.h_`. +For example, in the application project directory `data_service/common/hcpu`, +there is a board directory `eh-lb561_v2_hcpu` that contains the +`_custom_mem_map.h_`. Therefore, the `_custom_mem_map.h_` in the build directory +is copied from `data_service/common/hcpu/eh-lb561_v2_hcpu/custom_mem_map.h`. If +the application’s board directory doesn't have `_custom_mem_map.h_` but the +application project directory does, it will be copied from there. Only if the +file is not present in both the application and the board directory will it be +copied from `_$SDK_ROOT/customer/boards/eh-lb561_v2/hcpu/custom_mem_map.h_`. #### 3.3.2 ptab.json The following order is used to select the `_ptab.json_` file for compilation: +1. The board directory in the application project directory +2. The chip directory in the application project directory +3. The application project directory +4. The board directory -1. The board directory in the application project directory -2. The chip directory in the application project directory -3. The application project directory -4. The board directory +#### 3.3.3 Link Script -The `ptab.h` is generated from `_ptab.json_` and stored in the build directory. +The following order is used to select the linker script file (Keil’s +`_link.sct_`, GCC’s `_link.lds_`) for compilation: +1. The board directory in the application project directory +2. The chip directory in the application project directory +3. The application project directory +4. The board directory -#### 3.3.3 Link Script +#### 3.3.4 rtconfig.h -The following order is used to select the linker script file (Keil’s `_link.sct_`, GCC’s `_link.lds_`) for compilation: +The `_rtconfig.h_` is generated by merging the default values from Kconfig with +`_board.conf_` and `_proj.conf_`. `_board.conf_` and `_proj.conf_` record the +modified configurations (changes compared to the default values). If the same +configuration appears in both `_board.conf_` and `_proj.conf_`, the +configuration in `_proj.conf_` takes precedence. You can also add a board +directory to the application project to place a board-specific `proj.conf`. For +instance, if most configurations are the same across boards but only a few +parameters differ, you can define the shared configurations in the root +`proj.conf` and place the specific ones in each board's directory. +1. `proj.conf` in the application’s board directory +2. `proj.conf` in the application’s chip directory +3. `proj.conf` in the application project directory +4. `_board.conf_` in the board directory +5. Default values from Kconfig -1. The board directory in the application project directory -2. The chip directory in the application project directory -3. The application project directory -4. The board directory +### 3.4 Reusing Link Scripts +During multi-project compilation, both the main project and sub-projects may use +the same board directory's linker script, but their code compilation addresses +may differ. For example, the code snippet from `_link.sct_` below shows that the +starting address is `CODE_START_ADDR`, and the size is `CODE_SIZE`, but the +values of these macros may be different for the main program and the secondary +bootloader. ![]{1}\ +To address this, the script for generating `ptab.h` adds a feature to define the +`exec` property in the `_ptab.json_` to indicate which project the region's code +belongs to. The property value for the main project is "main," and for +sub-projects, it corresponds to the name specified when adding the sub-project. +![]{2}\ +After adding the `exec` property, the main project’s generated `ptab.h` will +define `CODE_START_ADDR` as `HCPU_FLASH_CODE_START_ADDR`, and the secondary +bootloader sub-project will define `CODE_START_ADDR` as +`FLASH_BOOT_LOADER_START_ADDR`. ![]{3} -#### 3.3.4 rtconfig.h -The `_rtconfig.h_` is generated by merging the default values from Kconfig with `_board.conf_` and `_proj.conf_`. `_board.conf_` and `_proj.conf_` record the modified configurations (changes compared to the default values). If the same configuration appears in both `_board.conf_` and `_proj.conf_`, the configuration in `_proj.conf_` takes precedence. You can also add a board directory to the application project to place a board-specific `proj.conf`. For instance, if most configurations are the same across boards but only a few parameters differ, you can define the shared configurations in the root `proj.conf` and place the specific ones in each board's directory. +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -The order of parameter values in `_rtconfig.h_` and `.config` follows the priority from highest to lowest, as follows: -1. `proj.conf` in the application’s board directory -2. `proj.conf` in the application’s chip directory -3. `proj.conf` in the application project directory -4. `_board.conf_` in the board directory -5. Default values from Kconfig +To support this, the ptab.h generation script now includes a new feature: the +"exec" attribute in _ptab.json_ defines the specific project associated with a +code execution region. The attribute value corresponds to the project name, +where the primary project is designated as "main" and sub-projects use the names +specified during AddChildProj. For example, in the following _ptab.json_, the +secondary bootloader code segment is named FLASH_BOOT_LOADER, while the main +project segment is named HCPU_FLASH_CODE. + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. + + +Once the "exec" attribute is applied, the _ptab.h_ generated for the main +project defines CODE_START_ADDR as HCPU_FLASH_CODE_START_ADDR, whereas the +secondary bootloader sub-project defines CODE_START_ADDR as +FLASH_BOOT_LOADER_START_ADDR. + + +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -### 3.4 Reusing Link Scripts -During multi-project compilation, both the main project and sub-projects may use the same board directory's linker script, but their code compilation addresses may differ. For example, the code snippet from `_link.sct_` below shows that the starting address is `CODE_START_ADDR`, and the size is `CODE_SIZE`, but the values of these macros may be different for the main program and the secondary bootloader. -![](../../assets/an_28_link_script.png) -To address this, the script for generating `ptab.h` adds a feature to define the `exec` property in the `_ptab.json_` to indicate which project the region's code belongs to. The property value for the main project is "main," and for sub-projects, it corresponds to the name specified when adding the sub-project. -![](../../assets/an_28_ptab_exec_attr.png) -After adding the `exec` property, the main project’s generated `ptab.h` will define `CODE_START_ADDR` as `HCPU_FLASH_CODE_START_ADDR`, and the secondary bootloader sub-project will define `CODE_START_ADDR` as `FLASH_BOOT_LOADER_START_ADDR`. -![](../../assets/an_28_ptab_header.png) ## 4. Modifying Existing Projects -Follow these steps to convert an existing project into a common project supporting compilation for any board: +Follow these steps to convert an existing project into a common project +supporting compilation for any board: -1. Create the board folder, extract board-related configurations from the original project's `.config`, write them into `board.conf` (skip this step if the board already exists), and copy the `_ptab.json_` file from the original project to the newly created board folder. -2. Create the application project folder, extract common configurations from the original project's `.config`, write them into the root `proj.conf` of the application project, and place board-specific configurations in the corresponding board directory under the application. -3. Copy the `Sconscript` and `SConstruct` from the original project directory, and add the `PrepareEnv()` call to the `SConstruct` to support compiling for the specified board. +1. Create the board folder, extract board-related configurations from the + original project's `.config`, write them into `board.conf` (skip this step + if the board already exists), and copy the `_ptab.json_` file from the + original project to the newly created board folder. +2. Create the application project folder, extract common configurations from + the original project's `.config`, write them into the root `proj.conf` of + the application project, and place board-specific configurations in the + corresponding board directory under the application. +3. Copy the `Sconscript` and `SConstruct` from the original project directory, + and add the `PrepareEnv()` call to the `SConstruct` to support compiling for + the specified board. +The following command compiles a program that can run on the HCPU of the +eh-lb523_v2 board. -![](../../assets/an_28_sconstruct.png) \ No newline at end of file diff --git a/docs/source/en/app_note/crash_analysis.md b/docs/source/en/app_note/crash_analysis.md index 8791cf36b..ea8f24f07 100644 --- a/docs/source/en/app_note/crash_analysis.md +++ b/docs/source/en/app_note/crash_analysis.md @@ -1,13 +1,16 @@ - # Crash Analysis Guide ## 1. Introduction -The SDK integrates tools for analyzing crash issues caused by assertions or hardfaults. To facilitate memory leak analysis, enable "Enable memory trace" under `RTOS->RT-Thread Kernel->Memory Management`. +The SDK integrates tools for analyzing crash issues caused by assertions or +hardfaults. To facilitate memory leak analysis, enable "Enable memory trace" +under `RTOS->RT-Thread Kernel->Memory Management`. ![](../../assets/crash_analysis_mem_trace.png) -Below is the log information printed when an ASSERT occurs, showing the function and line number where the ASSERT happened, along with thread, message queue, and heap information. +Below is the log information printed when an ASSERT occurs, showing the function +and line number where the ASSERT happened, along with thread, message queue, and +heap information. ``` 16:21:48:257 Assertion failed at function:wait_power_on_anim_done, line number:32 ,(RT_EOK == err) 16:21:48:258 =================== @@ -112,8 +115,13 @@ Below is the log information printed when an ASSERT occurs, showing the function 16:21:48:321 fatal error on thread: app_watch ``` -When a hardfault occurs, the following information is printed, and finally the type of hardfault is printed, such as busfault, mem manage fault, etc., -The following example shows a crash due to mem manage fault. `DACCVIOL SCB->MMAR: 00000000` indicates that the MPU found an illegal access to address 0, and the instruction address of the access is recorded by the pc register, which is 0x100c6426 + +When a hardfault occurs, the following information is printed, and finally the +type of hardfault is printed, such as busfault, mem manage fault, etc., The +following example shows a crash due to mem manage fault. `DACCVIOL SCB->MMAR: +00000000` indicates that the MPU found an illegal access to address 0, and the +instruction address of the access is recorded by the pc register, which is +0x100c6426 ``` 00:48:26:197 sp: 0x200a00d8 @@ -229,78 +237,363 @@ The following example shows a crash due to mem manage fault. `DACCVIOL SCB->MMAR 00:48:26:544 app_image_psram_memh 1100000 801444 430952 00:48:26:546 FPU active! 00:48:26:550 mem manage fault: -00:48:26:553 SCB_CFSR_MFSR:0x82 DACCVIOL SCB->MMAR:00000000 +00:48:26:553 SCB_CFSR_MFSR:0x82 DACCVIOL SCB->MMAR:00000000 ``` -## 2. Preparation Work -For ASSERT type crashes, the log provides a rough idea of where the issue occurred. However, for hardfaults or more complex crashes, this information may not be enough, and additional tools are needed. One method is to use a debugger to attach to the target device to inspect global variables and memory (if it's a hardfault, after attaching, you need to modify the registers with the printed SP/LR/PC to view the function call stack. For ASSERT, the function call stack can be seen without modifying the registers). However, this approach locks the target device and isn't ideal for multi-person analysis. The SDK provides the `crash_dump_analyser` tool to save and restore the crash context, enabling developers to analyze the problem on a PC without connecting to the target device. -Required tools: +## 2. Preparation Work +For ASSERT type crashes, the log provides a rough idea of where the issue +occurred. However, for hardfaults or more complex crashes, this information may +not be enough, and additional tools are needed. One method is to use a debugger +to attach to the target device to inspect global variables and memory (if it's a +hardfault, after attaching, you need to modify the registers with the printed +SP/LR/PC to view the function call stack. For ASSERT, the function call stack +can be seen without modifying the registers). However, this approach locks the +target device and isn't ideal for multi-person analysis. The SDK provides the +`crash_dump_analyser` tool to save and restore the crash context, enabling +developers to analyze the problem on a PC without connecting to the target +device. - JLink debugger and JLink software package -- `_SDK_ROOT/tools/crash_dump_analyser/script_`: Scripts to save and restore the context -- `_SDK_ROOT/tools/crash_dump_analyser/simarm/t32marm.exe_`: Trace32 software tool to execute the recovery script +- `_SDK_ROOT/tools/crash_dump_analyser/script_`: Scripts to save and restore the + context +- `_SDK_ROOT/tools/crash_dump_analyser/simarm/t32marm.exe_`: Trace32 software + tool to execute the recovery script +- Sifli_Trace Tool: This tool includes a crash dump utility. You can download + the latest version here: (Download: + [Sifli_Trace](https://wiki.sifli.com/tools/index.html)) ## 3. Saving the Context -### 3.1 Save Context Using BAT Script - -#### 3.1.1 Accessing the chip's saved data via UART (currently only supports 52x and 56x) -- Open _SifliUsartServer.exe_ and click Connect. Use DBGUART to simulate Jlink (only a serial connection is required on the hardware side) -![](/assets/UsartServer.png) -- Opening the _save_ram_55x.bat_ window will invoke Jlink.exe and fill the SERVER address in _SifliUsartServer.exe_ into the Identifier. -![](/assets/Jlink_command.png) - -#### 3.1.2 Access the chip's saved data through Jlink -For the 55x chip, follow these steps: -- Connect the JLink emulator to the target board -- Double-click to execute the _tools/crash_dump_analyser/script/save_ram_55x.bat_ script to read data from the target board. -- You can also do this in the command line. For example, in watch_demp, call _SDK_ROOT/tools/crash_dump_analyser/script/save_ram_55x.bat_,_$SDK_ROOT/example/watch_demo/project/eh-lb555/build_ from the SDK root directory to put the generated file into _SDK_ROOT/example/watch_demo/project/eh-lb555/build_ - -**Possible reasons for the failure of preserving the scene**: -- The selected method of preserving the scene does not match the executed script. - -```Using the UART hardware connection method or the Jlink hardware connection method to save the on-site data can all be achieved by calling JLink.exe and then executing the corresponding Jlink commands. You can compare the contents of the files named save_ram_55x.bat, sf32lb55x.jlink, and sf32lb52x.jlink to view the differences. "ip" indicates using the ip simulation method of SifliUsartServer.exe to save the on-site data, while "usb" indicates using the uab connection method to save the on-site data with the JLink emulator. Before saving the on-site data, you can first confirm the Jlink file and Jlink commands called in the executed bat file to prevent failure in saving the on-site data due to mismatch between the commands and the actual saving method.``` -![](/assets/dump_command.png) - -- Has the crash program been initiated on both the primary and secondary cores - -```In most cases, the secondary core is not activated. For example, in sf32lb55x.jlink, there is the line "w4 0x4004f000 1 // Switch to LCPU". However, if the program does not start the secondary core, the saved state will be lost and the operation will fail. Therefore, we need to comment out the commands issued to the secondary core to ensure the normal operation of the script.``` -![](/assets/dump_select.png) - -After success, the following files will be generated (depending on the content of the corresponding sf32lb55x.jlink): -- _hcpu_ram.bin_: 1Mbyte of HCPU RAM data -- _psram.bin_: 32Mbyte of PSRAM data -- _ret_ram.bin_: 64Kbyte of retention RAM data -- _hcpu_itcm.bin_: 16Kbyte of retention RAM data -- _epic_reg.bin_: EPIC register -- _ezip_reg.bin_: EZIP register -- _dsi_host_reg.bin_: DSI HOST register -- _dsi_phy_reg.bin_: DSI HOST register -- _dsi_phy_reg.bin_: DSI HOST register -- _dsi_phy_reg.bin_: DSI HOST register -- _gpio1_reg.bin_: GPIO1 register -- _gpio2_reg.bin_: GPIO2 register -- _lcpu_ram.bin_: 224Kbyte of LCPU RAM data -- _lcpu_dtcm.bin_: 16Kbyte LCPU DTCM data - - -### 3.2 Save the scene using the AssertDumpUart tool -This tool directly connects to the debug UART port and then executes the corresponding JLink script to save the context, without needing to simulate JLink using _SifliUsartServer.exe_. -For example, with the 52x chip: -- Open _\$SDK_ROOT/tools/crash_dump_analyser/script/AssertDumpUart.exe_. -- Set the corresponding JLink script, chip model, serial port number, baud rate, and serial device (Note: It refers to the MCU's USART device, usually UART1 for HCPU and UART4 for LCPU). -- Click export to save the context. + +```{only} SF32LB52X +#### 3.1.1 Method 1: Using SifliUsartServer +Use _SifliUsartServer.exe_ + _save_ram_uart_52x.bat_ + J-Link Software Package. + +- _SifliUsartServer.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/Sifli_Trace.png) + +- Launch _SifliUsartServer.exe_ and click **Connect**. (Hardware requirement: A serial connection only.) + + +![](../../assets/UsartServer52.png) + +- Run _save_ram_uart_52x.bat_; this will invoke JLink.exe. + + +![](../../assets/save_ram_uart_52.png) + +![](../../assets/Jlink_command52.png) + +- Once confirmed, wait for the window to close. The exported .bin files will be available in the _script_ folder. + + +![](../../assets/downp_bin.png) + +- Underlying Logic: Executing _save_ram_uart_52x.bat_ triggers a command that calls JLink.exe with parameters `-ip 127.0.0.1:19025` (the SERVER address in _SifliUsartServer.exe_) to execute sf32lb52x_uart.jlink. The execution logs are saved to _script/log.txt_. The specific command is as follows: + + +![](../../assets/save_ram_52bat.png) + +- The `.jlink` file contains the `IP` server connection (linked to the SifliUsartServer.exe serial service) and specific commands for exporting the crash dump .bin files. These can be adjusted based on actual requirements. + + +![](../../assets/52x_jlink.png) + +#### 3.1.2 Method 2: Using AssertDumpUart +- _AssertDumpUart.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/AssertDumpUart.png) + +- The software executes export commands by invoking J-Link files via the IP service. Select the serial port as follows: UART1 for the HCPU core and UART4 for the LCPU core. Ensure the .jlink file matches the chip's PSRAM size, otherwise the psram.bin export will fail. + ![](../../assets/crash_analysis_AssertDumpUsart.png) +- You may inspect the .jlink file contents and modify the export commands as needed. + + +![](../../assets/AssertDumpUart52.png) + +- After clicking Export, a folder containing the .bin files and a command interaction log (_log.txt_) will be generated in the specified save path. + + +![](../../assets/AssertDumpUart52bin.png) +``` + +```{only} SF32LB55X + + +### 3.1 Capturing Memory via J-Link SWD +#### 3.1.1 Method 1: Using .bat Scripts to Invoke .jlink Files +Requirements: Hardware J-Link debugger + _save_ram_55x.bat_ + J-Link Software Package. +- Connect the J-Link debugger to the board's SWD pins. +- Double-click _save_ram_55x.bat_ to execute the script. + + +![](../../assets/save_ram_55x.png) + +- Wait for the command-line window to close. The exported .bin files will be located in the _script_ folder. + + +![](../../assets/sf32lb55x_jlink.png) + +![](../../assets/downp_bin.png) + +- Underlying Logic: Running _save_ram_55x.bat_ (or _save_ram_56x.bat_) invokes the _sf32lb55x.jlink_ command and outputs logs to _script/log.txt_. The specific command is shown below: + + +![](../../assets/save_ram_55bat.png) + +- The `.jlink` file contains configurations for the J-Link debugger and specific commands for exporting memory to .bin files, which can be modified for specific use cases. + + +![](../../assets/sf32lb55x.png) + + +#### 3.1.2 Method 2: Using AssertDumpUart + +- _AssertDumpUart.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/AssertDumpUart.png) + +- The utility detects connected J-Link debuggers and executes the export via a J-Link file. Select **JLINK** as the connection method and ensure the debugger ID is detected. Choose a .jlink file that matches the chip's PSRAM capacity to avoid failures during psram.bin export. + + +![](../../assets/crash_analysis_AssertDumpUsart55_jlink.png) + +- You can verify and modify the export commands by reviewing the .jlink file content. + + +![](../../assets/AssertDumpUart55.png) + +- Clicking Export will generate a folder at the destination containing the memory bins and an interaction log (_log.txt_). + + +![](../../assets/AssertDumpUart52bin.png) +``` + + + +```{only} SF32LB56X +### 3.1 Capturing Memory via UART +#### 3.1.1 Method 1: Using SifliUsartServer +- Use _SifliUsartServer.exe_ + _save_ram_uart_56x.bat_ + J-Link Software Package. + +- _SifliUsartServer.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/Sifli_Trace.png) + +- Note: The 56-series hardware exposes two serial ports. By default, UART1 corresponds to the HCPU (High-performance CPU) and UART4 corresponds to the LCPU (Low-power CPU). You can identify the LCPU port by shorting **BOOT MODE** and resetting the device to enter Boot mode (refer to the SWD diagram for pin locations: [jlink-swd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html#jlink-swd)). The port displaying logs is UART4. + +- As shown below, COM78 represents the LCPU, which implies COM79 is the HCPU. + + +![](../../assets/LCPU_COM.png) + +- Launch _SifliUsartServer.exe_ and click **Connect**. (Requires only serial wiring.) + + +![](../../assets/UsartServer56.png) + +- Running _save_ram_uart_56x.bat_ invokes JLink.exe with the parameter `-ip 127.0.0.1:19025` (the SERVER address specified in _SifliUsartServer.exe_). + + +![](../../assets/save_ram_56.png) + +![](../../assets/Jlink_command56.png) + +- Wait for the command window to close. Exported .bin files will appear in the _script_ folder. + + +![](../../assets/downp_bin.png) + +- Underlying Logic: Executing _save_ram_uart_56x.bat_ sends a command to JLink.exe to run _sf32lb56x_uart.jlink_, logging the output to _script/log.txt_. The command is as follows: + + +![](../../assets/save_ram_uart_56bat.png) + +- The `.jlink` file contains the `IP` service connection (linked to the SifliUsartServer.exe serial service) and the specific memory dump commands. Customize these as needed. + + +![](../../assets/sf32lb56x_uart.png) + +#### 3.1.2 Method 2: Using AssertDumpUart +- _AssertDumpUart.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/AssertDumpUart.png) + +- This utility invokes J-Link export commands via the IP service. Select UART1 for HCPU and UART4 for LCPU. Match the .jlink file to the chip's PSRAM size to prevent export errors. + + +![](../../assets/crash_analysis_AssertDumpUsart56.png) + +- Review or modify the export commands within the .jlink file contents. + + +![](../../assets/AssertDumpUart52.png) + +- Once exported, the destination folder will contain the collected .bin files and the communication log (_log.txt_). + + +![](../../assets/AssertDumpUart52bin.png) + + +### 3.2 Capturing Memory via J-Link SWD +#### 3.2.1 Method 1: Using .bat Scripts to Invoke .jlink Files +- Requirements: J-Link debugger + _save_ram_56x.bat_ + J-Link Software Package. +- Connect the J-Link debugger to the SWD pins: [jlink-swd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html#jlink-swd) +- Run _save_ram_56x.bat_ by double-clicking it. +- After the window closes, verify the .bin files in the _script_ folder. + + +![](../../assets/downp_bin.png) + +- Underlying Logic: _save_ram_56x.bat_ executes the _sf32lb56x.jlink_ command script and logs details to _script/log.txt_. Command detail: + + +![](../../assets/save_ram_56bat.png) + +- The `.jlink` file specifies debugger settings and memory dump commands, which can be customized. + + +![](../../assets/sf32lb56x.png) + + +#### 3.2.2 Method 2: Using AssertDumpUart + +- _AssertDumpUart.exe_ is located in the Sifli_Trace tool package folder. + + +![](../../assets/AssertDumpUart.png) + +- Connect the J-Link debugger to the SWD pins: [jlink-swd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html#jlink-swd) +- The tool detects the J-Link debugger and executes commands via the J-Link file. Ensure **JLINK** is selected, the debugger serial number is identified, and the J-Link script matches the PSRAM capacity. + + +![](../../assets/crash_analysis_AssertDumpUsart56_jlink.png) + +- Inspect and adjust the export commands in the J-Link file as needed. + +![](../../assets/AssertDumpUart56.png) + +- Clicking Export generates a folder containing the memory bins and an interaction log (_log.txt_). + +![](../../assets/AssertDumpUart52bin.png) +``` + + +```{only} SF32LB58X + + +### 3.1 Capturing Memory via J-Link SWD +#### 3.1.1 Method 1: Using .bat Scripts to Invoke .jlink Files + +Requirements: J-Link debugger + _save_ram_58x.bat_ + J-Link Software Package. + +- Connect the J-Link debugger to the SWD pins: [jlink-swd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html#jlink-swd) +- Execute _save_ram_58x.bat_. + + +![](../../assets/save_ram_58x.png) + +- Wait for completion. The .bin files will be generated in the _script_ folder. + + +![](../../assets/sf32lb58x_jlink.png) + +![](../../assets/downp_bin.png) + +Underlying Logic: _save_ram_58x.bat_ invokes _sf32lb58x.jlink_ and logs the output to _script/log.txt_. Command detail: + + +![](../../assets/save_ram_58bat.png) + +The `.jlink` file defines the debugger connection and memory dump commands, adjustable as needed. + + +![](../../assets/sf32lb58x.png) + + +#### 3.2.2 Method 2: Using AssertDumpUart + +_AssertDumpUart.exe_ is found in the Sifli_Trace folder. + + +![](../../assets/AssertDumpUart.png) + +- Connect the J-Link debugger to the SWD pins: [jlink-swd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html#jlink-swd) +- The tool detects the J-Link debugger and runs commands via a J-Link script. Choose **JLINK** mode, verify the debugger ID, and ensure the script matches the PSRAM size to avoid export errors. + + +![](../../assets/crash_analysis_AssertDumpUsart58_jlink.png) + +- Review or modify the export commands within the .jlink file. + + +![](../../assets/AssertDumpUart58.png) + +- Upon export, the .bin files and communication logs (_log.txt_) are stored in a new folder at the specified path. + + +![](../../assets/AssertDumpUart52bin.png) +``` + +**Potential reasons for memory capture failure**: +- Mismatch between selected capture method and executed script. + +```Both UART-based and J-Link-based memory capture mechanisms work by calling +JLink.exe to execute specific commands. You can verify consistency by comparing +the contents of save_ram_xxx.bat and the invoked sf32lbxxx.jlink file. The "IP" +parameter indicates memory capture via an IP service (used for serial/UART +methods), while "USB" indicates a physical J-Link debugger connection (used for +J-Link SWD methods). Before starting the capture, confirm that the J-Link script +and its commands match the actual hardware connection method to prevent +execution failures``` ![](../../assets/dump_command.png) + +- Whether both the HCPU and LCPU were active at the time of the crash. + +```In many standard routines, the LCPU (small core) is not initialized. For +example, if sf32lb55x.jlink contains the command w4 0x4004f000 1 (Switch to +LCPU) but the LCPU was never started by the application, the memory capture will +fail. In such cases, the LCPU-related commands must be commented out to ensure +the script executes correctly``` ![](../../assets/dump_select.png) + + +Upon success, the following files will be generated (subject to the contents of +the sf32lbxxx.jlink script): +- _hcpu_ram.bin_: 1 MB of HCPU RAM data. +- _psram.bin_: 32 MB of PSRAM data. +- _ret_ram.bin_: 64 KB of retention RAM data. +- _hcpu_itcm.bin_: 16 KB of ITCM RAM data. +- _epic_reg.bin_: EPIC registers. +- _ezip_reg.bin_: EZIP registers. +- _dsi_host_reg.bin_: DSI Host registers +- _dsi_phy_reg.bin_: DSI PHY registers +- _dsi_phy_reg.bin_: DSI PHY registers +- _dsi_phy_reg.bin_: DSI PHY registers +- _gpio1_reg.bin_: GPIO1 registers +- _gpio2_reg.bin_: GPIO2 registers +- _lcpu_ram.bin_: 224 KB LCPU RAM data +- _lcpu_dtcm.bin_: 16 KB LCPU DTCM data + ## 4. Restoring Context ### 4.1 Restoring HCPU Context #### Double-click to run t32marm.exe, as shown below: ![](../../assets/crash_analysis_default_view.png) + #### Click the HA button (HCPU assertion) -- Select the current chip and set the path where the exported bin files are located (ensure the path does not end with a slash), and manually place the AXF file to view the HCPU crash context. -- If some bins are missing (e.g., if some dumps don't have PSRAM), you can uncheck those. +- Select the current chip and set the path where the exported bin files are + located (ensure the path does not end with a slash), and manually place the + AXF file to view the HCPU crash context. +- If some bins are missing (e.g., if some dumps don't have PSRAM), you can + uncheck those. ![](../../assets/crash_analysis_load_hcpu_assertion_ui.png) @@ -311,100 +604,129 @@ Once loaded successfully, the following crash context information is displayed: You can switch between different windows from the Window menu. -If the window is accidentally closed, you can also enter the command below "B::" to run the wake-up process. +If the window is accidentally closed, you can also enter the command below "B::" +to run the wake-up process. -For example: From the information in the following picture, we can see the heapAllocation window, whose full name is _B::AREA.view heapAllocation_. We can input this command to open the corresponding window, or we can directly input _AREA.view heapAllocation_. +For example: From the information in the following picture, we can see the +heapAllocation window, whose full name is _B::AREA.view heapAllocation_. We can +input this command to open the corresponding window, or we can directly input +_AREA.view heapAllocation_. ![](../../assets/crash_analysis_hcpu_window_select.png) `B::v.f /l /c `The window is the function call stack of the crash site. -The heapAllocation window displays the allocation status of all heap pools in the system, including the system heap and memheap_pool: +The heapAllocation window displays the allocation status of all heap pools in +the system, including the system heap and memheap_pool: - system heap: Pool used by `rt_malloc` and `lv_mem_alloc`. -- Various memheap_pools: Pools created with `rt_memheap_init`, allocation, and release are handled by `rt_memheap_alloc` and `rt_memheap_free`. +- Various memheap_pools: Pools created with `rt_memheap_init`, allocation, and + release are handled by `rt_memheap_alloc` and `rt_memheap_free`. The fields in the allocation information list represent: -- BLOCK_ADDR: The starting address of the allocated memory block, including the management item. -- BLOCK_SIZE: The size of the allocated memory, excluding the length of the management item. +- BLOCK_ADDR: The starting address of the allocated memory block, including the + management item. +- BLOCK_SIZE: The size of the allocated memory, excluding the length of the + management item. - USED: Whether it is allocated, 1 means allocated, 0 means not allocated. - TICK: The time when the allocation occurred, in OS ticks (1 ms). - RETURN ADDR: The address of the caller. #### Handling Missing Crash Stack -After completing the previous 3 steps, sometimes the crash scene stack will not be displayed, possibly because the dump content was not saved or was saved incorrectly. You can try the following methods: -- 1. Load the scene stack from Jlink halt log information - The HR (HCPU Registers) button is used to restore CPU registers that did not reach the exception handler. - After clicking the button, select the exported _log.txt_ file, which will fill the 16 HCPU registers back into Trace32. - -![](../../assets/crash_analysis_toolsbar_HR.png) - - -- 2. From the 16 registers printed in the log, refill them into the register window of trace32 - -![](../../assets/crash_analysis_restore_registers_from_log.png) +After completing the previous 3 steps, sometimes the crash scene stack will not +be displayed, possibly because the dump content was not saved or was saved +incorrectly. You can try the following methods: +- 1. Load the scene stack from Jlink halt log information The HR (HCPU + Registers) button is used to restore CPU registers that did not reach the + exception handler. After clicking the button, select the exported _log.txt_ + file, which will fill the 16 HCPU registers back into Trace32. +- 2. From the 16 registers printed in the log, refill them into the register + window of trace32 - 3. For gcc compilation, you can try modifying PC to be the same value as r14 -![](/assets/crash_analysis_toolsbar_HR2.png) -### 4.2 Restoring LCPU Context + ![](/assets/crash_analysis_toolsbar_HR2.png) -Restoring LCPU context is similar to HCPU, but first, you need to copy the required files (lcpu.axf and rom_axf files) to the script directory. +### 4.2 Restoring LCPU Context -![](../../assets/add4.png) +Restoring LCPU context is similar to HCPU, but first, you need to copy the +required files (lcpu.axf and rom_axf files) to the script directory. -The required file paths are as shown below, choose the correct `rom_axf` file for your model. The lcpu file depends on whether it was compiled with Keil or GCC. +![]{1} #### Important Notes: -- LCPU files compiled with Keil have an `.axf` extension, while those compiled with GCC have an `.elf` extension. Make sure to distinguish between them. -- When choosing the `rom_axf` file, ensure you select the correct one based on the board model. +- LCPU files compiled with Keil have an `.axf` extension, while those compiled + with GCC have an `.elf` extension. Make sure to distinguish between them. +- When choosing the `rom_axf` file, ensure you select the correct one based on + the board model. -![](../../assets/add2.png) -![](../../assets/add3.png) +![](../../assets/add1.png) ![]{2} -Next, open Trace32 and select the LA button. In the pop-up window, configure as shown below: -![Trace32 Configuration](../../assets/add1.png) ## 5. Common Trace32 Commands -In addition to the windows that are already opened, you can use the View menu to open new windows, as shown below: +In addition to the windows that are already opened, you can use the View menu to +open new windows, as shown below: - Registers: View the CPU registers. - Dump: View data at a specific address. - List Source: View the assembly code. - Watch: View variables. -![View Menu in Trace32](../../assets/crash_analysis_cmd_view.png) +![](../../assets/crash_analysis_cmd_view.png) + + +The variable window supports wildcards. For example, input `*error*rea*` and +press Enter. It will suggest `error_reason`, which can then be selected and +added to the watch window. -The variable window supports wildcards. For example, input `*error*rea*` and press Enter. It will suggest `error_reason`, which can then be selected and added to the watch window. +![](../../assets/crash_analysis_cmd_watch.png) -![Watch Window](../../assets/crash_analysis_cmd_watch.png) +![](../../assets/crash_analysis_cmd_watch2.png) -![Watch Window 2](../../assets/crash_analysis_cmd_watch2.png) +You can also type commands in the command window below (commands are +case-insensitive) to open debugging windows. -You can also type commands in the command window below (commands are case-insensitive) to open debugging windows. +![](../../assets/crash_analysis_cmd_input.png) -![Input Command in Trace32](../../assets/crash_analysis_cmd_input.png) Examples: - `V.W`: Open the watch window. -- `D.DUMP address`: View data at a specified address, for example, `D.DUMP 20000000` will show data starting at address `0x20000000`. -- `L address/symbol`: View assembly at a specified address, for example, `L 1011D888` will open the assembly window showing code starting at `0x1011D888`. `L rt_thread_stack_restore` will show the assembly code for the `rt_thread_stack_restore` function. +- `D.DUMP address`: View data at a specified address, for example, `D.DUMP + 20000000` will show data starting at address `0x20000000`. +- `L address/symbol`: View assembly at a specified address, for example, `L + 1011D888` will open the assembly window showing code starting at `0x1011D888`. + `L rt_thread_stack_restore` will show the assembly code for the + `rt_thread_stack_restore` function. ## 6. HEAP Analysis Example -The image below shows a scenario where heap memory leak is detected. The callstack window shows the function call stack for the assertion, and the heapAllocation window's system heap list shows the memory blocks allocated by `rt_malloc`. The `RETURN ADDR` shows the function name that called `rt_malloc`, and `TICK` shows the `rt_tick_get` time at the time of allocation. +The image below shows a scenario where heap memory leak is detected. The +callstack window shows the function call stack for the assertion, and the +heapAllocation window's system heap list shows the memory blocks allocated by +`rt_malloc`. The `RETURN ADDR` shows the function name that called `rt_malloc`, +and `TICK` shows the `rt_tick_get` time at the time of allocation. + +![](../../assets/crash_analysis_heap_callstack.png) + +![](../../assets/crash_analysis_heap_detail.png) -![Heap Callstack](../../assets/crash_analysis_heap_callstack.png) -![Heap Detail](../../assets/crash_analysis_heap_detail.png) +The structure of a system heap memory management item is shown below. The first +`uint16` is a special word `0x1EA0`, which is the value for all memory +management items. If this value is not `0x1EA0`, the item has been illegally +modified. The second `uint16` is a `used` flag: 1 means allocated, and 0 means +not allocated. If values other than 0 or 1 appear, it indicates illegal +modification, which could also lead to memory allocation failures. -The structure of a system heap memory management item is shown below. The first `uint16` is a special word `0x1EA0`, which is the value for all memory management items. If this value is not `0x1EA0`, the item has been illegally modified. The second `uint16` is a `used` flag: 1 means allocated, and 0 means not allocated. If values other than 0 or 1 appear, it indicates illegal modification, which could also lead to memory allocation failures. +![](../../assets/crash_analysis_heap_struct.png) -![Heap Structure](../../assets/crash_analysis_heap_struct.png) -For example, in the HEAP window, the first row with an address of `0x200A27EC` shows a memory block allocated by the `rt_serial_open` function at the instruction address `0x1011B5FB`. The memory size allocated is 4108 bytes. According to the `struct heap_mem` structure, the system heap management item length is 28 bytes. Therefore, the memory address used by the caller is 28 bytes offset from the starting address of the memory block. +For example, in the HEAP window, the first row with an address of `0x200A27EC` +shows a memory block allocated by the `rt_serial_open` function at the +instruction address `0x1011B5FB`. The memory size allocated is 4108 bytes. +According to the `struct heap_mem` structure, the system heap management item +length is 28 bytes. Therefore, the memory address used by the caller is 28 bytes +offset from the starting address of the memory block. -In the example, the function `_lv_ll_ins_head` allocated 88 bytes of memory. The starting address of the memory block is `0x200B08E0`. In the variable view window, you can check this variable by using `(lv_obj_t*)(0x200B08E0+28)`. From the LVGL code, we can see that the size of `lv_obj_t` is 88 bytes (plus 8 bytes for the LVGL list link item after `lv_obj_t`). The function address `signal_cb` is shown in the command line window. You can enter the command `L 100DC9A1` to open the disassembly window and see the assembly code for that address, confirming the function is `lv_img_signal`, indicating that the `lv_img` control allocated the memory. +![](../../assets/crash_analysis_heap_example.png) -When memory leaks occur, you can use the allocation address and time to analyze where memory was allocated but not freed. -![Heap Analysis Example](../../assets/crash_analysis_heap_example.png) diff --git a/docs/source/en/app_note/debug_logging.md b/docs/source/en/app_note/debug_logging.md index 2cc1e02d2..55648f1d0 100644 --- a/docs/source/en/app_note/debug_logging.md +++ b/docs/source/en/app_note/debug_logging.md @@ -1,60 +1,75 @@ +# app_watc 25 ready 0x00000100 0x00002800 26% 0x00000008 000 tshell 20 suspend 0x000000f4 0x00001000 13% 0x00000008 000 ble_app 15 suspend 0x000001b4 0x00000400 54% 0x00000007 000 mbox_th 10 suspend 0x00000110 0x00001000 51% 0x00000006 000 ds_proc 12 suspend 0x0000011c 0x00000800 24% 0x00000005 000 ds_mb 11 suspend 0x00000148 0x00000400 32% 0x0000000a 000 touch_th 10 suspend 0x000000ec 0x00000200 59% 0x00000006 000 test 15 suspend 0x0000011c 0x00000400 27% 0x0000000a 000 alarmsvc 8 suspend 0x00000074 0x00000200 22% 0x00000001 000 ulog_asy 30 ready 0x000000ec 0x00000400 36% 0x0000000b 000 tidle 31 ready 0x00000064 0x00000200 19% 0x00000008 000 timer 4 suspend 0x000000e0 0x00000400 23% 0x00000003 000 main 10 suspend 0x000000ec 0x00000800 31% 0x0000000c 000 -# Debugging and Logging +## 1. Hardware Interfaces +The SF32FB55X utilizes the Serial Wire Debug (SWD) interface for debugging. +Users can switch between the HCPU and LCPU via configuration. -## 1. Hardware Interface -The SF32FB55X uses SWD as the debugging interface. Users can configure it to switch between HCPU or LCPU. +The system defaults to the HCPU upon power-up. To debug the LCPU, execute the +SDK tool _$SDK_ROOT/tools/segger/jlink_lcpu_a0.bat_ to switch the SWD connection +to the LCPU. -By default, the system powers up with HCPU. If you need to debug LCPU, you can use the SDK tool _$SDK_ROOT/tools/segger/jlink_lcpu_a0.bat_ to switch the SWD to LCPU. - -Similarly, if SWD is currently connected to LCPU, you can use the SDK tool _$SDK_ROOT/tools/segger/jlink_hcpu_a0.bat_ to switch the SWD back to HCPU. - -```{note} -1. Since SWD uses PB IO, when debugging with SWD, make sure that LPSYS is in active or light sleep mode, whether the SWD is connected to HCPU or LCPU.
-2. Sending a reset command from JLink will not change the current CPU connected via SWD.
-3. After LPSYS wakes up from standby, SWD will automatically switch back to HCPU. -``` +Conversely, if the SWD is currently connected to the LCPU, execute the SDK tool +_$SDK_ROOT/tools/segger/jlink_hcpu_a0.bat_ to switch the connection back to the +HCPU. + ```{note} + 1. Since SWD utilizes PB IOs, ensure that the LPSYS remains in either Active or Light Sleep state during debugging, regardless of whether the SWD is connected to the HCPU or LCPU.
+ 2. Issuing a reset command via J-Link does not change the CPU currently selected by the SWD interface.
+ 3. After the LPSYS wakes up from Standby mode, the SWD interface reverts to its default connection (HCPU).
+ ``` ### LCPU Log Interface -The system ROM, during initialization, uses UART3 of LCPU as the console interface with a baud rate of 1,000,000 bps for logging and command input. It is recommended to retain this interface for LCPU logs.
+During initialization, the System ROM uses UART3 (assigned to the LCPU) as the +console interface with a baud rate of 1,000,000 bps for logging and command +input. It is recommended to reserve this interface as the dedicated log port for +the LCPU.
### HCPU Log Interface -The HCPU log interface can be selected between UART1/2 or SWD. If you need to use UART3/4/5 of LCPU, ensure that the LCPU is in an active state. +The HCPU log interface can be assigned to UART1, UART2, or SWD. If LCPU-owned +peripherals (UART3/4/5) are used, ensure the LCPU remains in an awake state +during operation. -## 2. Debugging Methods -This section covers common methods for analyzing Assert or HardFault errors and solving system crashes. The JLink debugger is used for all methods. +## 2. Debugging Methodologies +This section describes common analysis methods for Assertions and HardFaults, as +well as recovery procedures for system hangs using a J-Link debugger. ### Setting Breakpoints -When JLink connects to HCPU/LCPU, the system is usually already initialized. If you need to debug initialization processes, such as cold starts or standby wake-ups, you need to halt the system as early as possible. -We suggest users modify the system initialization code: -- HCPU - _$SDK_ROOT/drivers/cmsis/sf32lb55x/Templates/arm/startup_bf0_hcpu.S_ -- LCPU - _$SDK_ROOT/drivers/cmsis/sf32lb55x/Templates/arm/startup_bf0_lcpu.S_ - -In the `Reset_Handler`, uncomment the first instruction `;` to change it to: - B . -This will halt the CPU at the first instruction. Once JLink is connected, you can adjust the PC register (+2) and set breakpoints to debug the initialization process. - -This method can also be used at other points to halt the system at a specific event and debug at the suspected location. In C files, you can add: - _asm("B ."); -This will stop the system at that instruction. Then, reconnect JLink, adjust the PC register (+2), and continue debugging. - +By the time J-Link connects to the HCPU or LCPU, the system has typically +completed initialization. To debug early-stage processes such as cold boots or +wake-up from Standby, the CPU must be halted as early as possible.
It is +recommended that users modify the system startup sequence: + - HCPU:
+ _$SDK_ROOT/drivers/cmsis/sf32lb55x/Templates/arm/startup_bf0_hcpu.S_
+ - LCPU:
+ _$SDK_ROOT/drivers/cmsis/sf32lb55x/Templates/arm/startup_bf0_lcpu.S_
In + the Reset_Handler, uncomment the first instruction by removing the ';' to + enable:
B .
This causes the CPU to loop on the first instruction + upon startup. Once the J-Link connection is established, manually increment + the Program Counter (PC) register (e.g., +2) and set the required breakpoints + to debug the initialization sequence. + +This technique can also be applied elsewhere to halt the system at specific +events. In C source files, inserting
__asm("B .");
will trap the CPU +at that instruction. After connecting J-Link, the PC can be incremented (+2) to +resume execution for further debugging. ```{note} -Do not use `while(1);` because the system will optimize it and make the statements after `while(1)` ineffective. +Do not use `while(1);` for this purpose, as the compiler may optimize out subsequent statements, making them unreachable. ``` ### Assert/HardFault Error Analysis -When an error occurs, if the development board is connected via SWD to JLink, you can use the tool _$SDK_ROOT/tools/crash_dump_analyser/script/save_ram_a0.bat_ to save RAM, EPIC registers, and PSRAM content to the current path. This is helpful for analyzing the cause of the crash. - +When an error occurs, if the board is connected to a J-Link via SWD, use the +script _$SDK_ROOT/tools/crash_dump_analyser/script/save_ram_a0.bat_ to dump the +RAM, EPIC registers, and PSRAM contents to the current directory. This data is +critical for post-mortem analysis of system crashes. ```{note} -Make sure to add the JLink path to your Windows PATH environment variable, e.g., _C:/Program Files (x86)/SEGGER/JLink_v672b_, so you can load RAM via JLink to restore the crash context. +Ensure the J-Link installation path (e.g., _C:/Program Files (x86)/SEGGER/JLink_v672b_) is added to the Windows PATH environment variable. The saved RAM dumps can subsequently be reloaded via J-Link to reconstruct the crash state. ``` - -#### Analyzing Logs -By default, the SDK will output the breakpoint line and the last CPU registers during an Assert to the log interface. Analyze the contents of the log. Note that if the log interface is asynchronous, it may not output the complete log. - +#### Log Analysis +By default, the SDK outputs the assertion line and the final CPU register states +via the log interface during an Assert. Analyze the issue based on this output. +Note that if the log interface is configured for asynchronous output, the +information may be incomplete. ``` -Assertion failed at function:app_exit, line number:704 ,(app_node->next != &running_app_list) +Assertion failed at function:app_exit, line number:704 ,(app_node->next != &running_app_list) =================== Thread Info =================== @@ -151,97 +166,122 @@ r12: 0x10069305 fatal error on thread: app_watc? ``` -#### Analyzing Crash Context with Ozone -##### Using Jlink (USB) connection for configuration -If the log analysis cannot pinpoint the crash issue, the Ozone debugging tool provided by Segger can be used. Ozone is easier to attach to the chip via JLink during a crash compared to Keil (as Keil configurations can easily reset the chip and destroy the crash context). -> Ozone can also be used in cases where the board is not crashed and can be attached for step-by-step debugging, similar to Keil, although its stack analysis seems to be less effective. -- Create a new project, select the appropriate Device driver (Cortex-M33), choose the Register Set as Cortex-M33 (with FPU), and the peripheral SVD file (select based on the chip model, the path is in _$SDK_ROOT/tools/svd_external) +#### Analyzing Crash State via Ozone +##### Configuration using J-Link (USB) connection +If the logs are insufficient for crash analysis, you can use Ozone, a debugging +tool provided by SEGGER. Compared to Keil, Ozone makes it easier to attach to a +chip via J-Link after a crash occurs (Keil's configuration often triggers a chip +reset, which destroys the crash context). -![Ozone Debug Step 1](../../assets/Ozone_debug_Step1.png) +> Ozone can also be used to attach to a running board and perform single-step +> debugging, similar to Keil’s functionality. However, its stack unwinding +> capabilities may not be as robust as those in Keil. +- Create a new project and select the appropriate device driver (Cortex-M33). + Set the Register Set to Cortex-M33 (with FPU) and select the peripheral SVD + file (depending on the chip model, located in _$SDK_ROOT/tools/svd_external). -- Select the connection method for JLink, using SWD interface. +![](../../assets/Ozone_debug_Step1.png) -![Ozone Debug Step 2](../../assets/Ozone_debug_Step2.png) +- In the next step, select the J-Link connection method and use the SWD + interface. -- Choose the ELF file for flashing and read the symbol information. +![](../../assets/Ozone_debug_Step2.png) -![Ozone Debug Step 3](../../assets/Ozone_debug_Step3.png) +- Select the ELF file of the target firmware to load symbol information. -- Once the project is set up, attach Ozone to the crashed board via JLink and halt the board. +![](../../assets/Ozone_debug_Step3.png) -![Ozone Debug Step 4](../../assets/Ozone_debug_Step4.png) +- Once the project is created, attach Ozone to the crashed board via J-Link and + halt the target. -- Now you can perform step-by-step debugging, variable inspection, stack analysis, etc., similar to Keil. +![](../../assets/Ozone_debug_Step4.png) -![Ozone Debug Step 5](../../assets/Ozone_debug_Step5.png) +- You can then use the menu functions to perform single-step debugging, inspect + variables, and analyze the call stack, similar to the workflow in Keil. -##### Configure using serial port connection method -- Create a new project, select the appropriate Device driver (Cortex-M33), choose the Register Set as Cortex-M33 (with FPU), and the peripheral SVD file (select based on the chip model, the path is $_SDK_ROOT/tools/svd_external) +![](../../assets/Ozone_debug_Step5.png) -- Open _SifliUsartServer.exe_ and click on "Connect". Pay attention to the selected core for debugging and the corresponding serial port number for that core. +##### Configuration using Serial (UART) connection +- Create a new project and select the appropriate device driver (Cortex-M33). + Set the Register Set to Cortex-M33 (with FPU) and select the peripheral SVD + file (depending on the chip model, located in _$SDK_ROOT/tools/svd_external). + +- Open _SifliUsartServer.exe_ and click Connect. Ensure you select the target + core to be debugged and its corresponding COM port. ![](../../assets/UsartServer.png) -- Next, OZone selects the connection method for UART, Host Interface is set to IP, and IP Address is filled with SERVER of UartServer. +- In OZone, select UART as the connection method. Set the Host Interface to IP + and enter the UartServer IP address. ![](../../assets/Ozone_uart_debug_Step1.png) -- Select the ELF file for the burning program and read the symbol information +- Select the ELF file of the target firmware to load symbol information. ![](../../assets/Ozone_debug_Step3.png) -## 3. Log Interface -### Logging via UART -The pinmux configuration for UART is not discussed here. Please refer to [](../hal/uart.md) for details. +## 3. Log Interfaces + +### UART Output +For details regarding UART pinmux configuration, please refer to +[](../hal/uart.md). -If using RT-Thread RTOS, after configuring the UART pinmux, you can choose different UART devices through the following menuconfig configuration: -![RTT Console Configuration](../../assets/config_rtt_console.png) +When using the RT-Thread RTOS, configure the UART pinmux and then select the +desired UART device via menuconfig as shown below: +![](../../assets/config_rtt_console.png) -Additionally, the SDK uses ULOG as the general logging output interface, detailed in [](../middleware/logger.md). +Additionally, the SDK utilizes ULOG as the standard logging interface. For more +details, see [](../middleware/logger.md). -### Logging via JLink -If there are not enough pins available, you can use JLink's RTT functionality as a console interface. The configuration steps are as follows (Segger RTT functionality is integrated into the RT-Thread RTOS provided by the SDK): +### J-Link RTT Output +If GPIO pins are limited, the J-Link RTT (Real Time Transfer) feature can be +used as the console. The configuration steps are as follows (Segger RTT is +already integrated into the SDK's RT-Thread RTOS): -1. Enable the Segger RTT functionality through menuconfig (it will automatically register an `rt-device` named `segger`). -![JLink RTT Configuration Step 1](../../assets/jlink_trace_config_step1.png) +1. Enable the Segger RTT function via menuconfig, which will automatically + register an RT-Thread device named "segger": + ![](../../assets/jlink_trace_config_step1.png) -2. Assign the default console of RT-Thread to the `segger` rt-device. -![JLink RTT Configuration Step 2](../../assets/jlink_trace_config_step2.png) +2. Set the default RT-Thread console to the "segger" device: + ![]../../assets/jlink_trace_config_step2.png) -3. Connect to the board using Ozone. If the ELF file is already specified, Ozone will automatically search for `RTT_Ctrlb`. Otherwise, you need to specify it manually. -![JLink RTT Configuration Step 3](../../assets/jlink_trace_config_step3.png) +3. Connect to the board using OZone. If an ELF file is specified, OZone will + automatically locate the RTT control block; otherwise, it must be specified + manually: ![](../../assets/jlink_trace_config_step3.png) -## 4. Using Bus Monitors +## 4. Bus Monitor -Bus monitors can track access on the bus and trigger interrupts or callbacks when specific conditions are met. This is useful for debugging memory or peripheral device accesses during development. +The Bus Monitor tracks bus access and triggers an interrupt callback when +specified conditions are met. This is useful for monitoring specific memory +regions or peripheral accesses during debugging. ### Enabling the Bus Monitor -Enable the bus controller functionality through the following menuconfig configuration: -![Bus Monitor Config](../../assets/config_busmon.png) +The Bus Monitor can be enabled via menuconfig as follows: +![](../../assets/config_busmon.png) ### Using the Bus Monitor -In the code, you can add the following code to implement specific functionality: + +The following code snippet demonstrates how to implement specific functionality: ```c void busmon_cbk() { - rt_kprintf("Busmon captured -"); // Trigger callback when a specific bus access occurs. Users can assert here and further debug. + rt_kprintf("Busmon captured\n"); // Callback triggered upon specific bus access. Users can insert assertions here for further debugging and analysis. } ... -dbg_busmon_reg_callback(busmon_cbk); // Register the callback -dbg_busmon_read(0x20080000,1); // Trigger bus monitor on first read of address 0x20080000 + dbg_busmon_reg_callback(busmon_cbk); // Register the callback + dbg_busmon_read(0x20080000, 1); // Trigger the bus monitor on the first read access to address 0x20080000 -// Reconfigure -dbg_busmon_reg_callback(busmon_cbk); // Register the callback -dbg_busmon_write(0x20080004,3); // Trigger bus monitor on third write of address 0x20080004 + // Reconfiguration + dbg_busmon_reg_callback(busmon_cbk); // Register the callback + dbg_busmon_write(0x20080004, 3); // Trigger the bus monitor on the third write access to address 0x20080004 -// Reconfigure -dbg_busmon_reg_callback(busmon_cbk); // Register the callback -dbg_busmon_write(0x20080008,2); // Trigger bus monitor on second read or write of address 0x20080008 + // Reconfiguration + dbg_busmon_reg_callback(busmon_cbk); // Register the callback + dbg_busmon_write(0x20080008, 2); // Trigger the bus monitor on the second access (either read or write) to address 0x20080008 ``` diff --git a/docs/source/en/app_note/dualcore.md b/docs/source/en/app_note/dualcore.md index 9f16a8263..60b15bbce 100644 --- a/docs/source/en/app_note/dualcore.md +++ b/docs/source/en/app_note/dualcore.md @@ -1,118 +1,217 @@ - # Dual-Core Development ## 1. Introduction to Dual-Core -The SF32LB55X features a dual-core architecture with two Cortex MStar processors: -- **Main Core HCPU** - HCPU is responsible for high-performance computation and image processing, capable of running up to 240 MHz, with 1MB of memory. - HCPU has three QSPI interfaces that can connect to NOR Flash, NAND Flash, and PSRAM. The size of Flash and PSRAM varies depending on the package. Typically, code runs from NOR Flash. - HCPU has 64KB of ROM for boot-up purposes. -- **Sub-Core LCPU** - LCPU is a low-power core designed for tasks such as simple sensor data collection, buffering, basic processing, and low-power Bluetooth tasks. It runs at a maximum frequency of 48 MHz, with 256KB of memory. - Code typically runs from RAM, loaded by HCPU. LCPU also has a QSPI interface for connecting to NOR Flash and running code. However, due to pin limitations, not all packages allow access to this interface. - LCPU has 384KB of ROM, which contains the RT-Thread OS and the Bluetooth Low Energy (BLE) protocol stack developed by Sifli. - When LCPU is awake, HCPU can access LCPU's hardware modules and receive interrupts from all hardware modules. - When HCPU is awake, LCPU can use HCPU's hardware modules but cannot receive interrupts from these modules. - -For hardware resource details for HCPU and LCPU, please refer to [](../hal/index.md). -During user design, it is essential to categorize different tasks based on the capabilities of each core and determine which core will handle which tasks and which hardware modules will be used. +The SF32LB55X features a dual-core architecture with two Cortex MStar +processors: + - **Main Core HCPU**\ + HCPU is responsible for high-performance computation and image processing, + capable of running up to 240 MHz, with 1MB of memory.\ + HCPU has three QSPI interfaces that can connect to NOR Flash, NAND Flash, and + PSRAM. The size of Flash and PSRAM varies depending on the package. + Typically, code runs from NOR Flash.\ + HCPU has 64KB of ROM for boot-up purposes. + - **Sub-Core LCPU**\ + LCPU is a low-power core designed for tasks such as simple sensor data + collection, buffering, basic processing, and low-power Bluetooth tasks. It + runs at a maximum frequency of 48 MHz, with 256KB of memory.\ + Code typically runs from RAM, loaded by HCPU. LCPU also has a QSPI interface + for connecting to NOR Flash and running code. However, due to pin + limitations, not all packages allow access to this interface.\ + LCPU has 384KB of ROM, which contains the RT-Thread OS and the Bluetooth Low + Energy (BLE) protocol stack developed by Sifli.\ + When LCPU is awake, HCPU can access LCPU's hardware modules and receive + interrupts from all hardware modules.\ + When HCPU is awake, LCPU can use HCPU's hardware modules but cannot receive + interrupts from these modules. ## 2. Dual-Core Startup ### System Boot -After power-up, the SF32LB55X system starts from the HCPU. The ROM startup code reads the Flash table from the boot Flash and loads the specified user program to run. Typically, user code starts at the third 64K address. For detailed steps, refer to [](..\bootloader.md). -After power-up, LCPU is in a powered wake-up state but not running. At this point, HCPU can use LCPU's hardware modules. +After power-up, the SF32LB55X system starts from the HCPU. The ROM startup code +reads the Flash table from the boot Flash and loads the specified user program +to run. Typically, user code starts at the third 64K address. For detailed +steps, refer to [](../bootloader.md).\ +After power-up, LCPU is in a powered wake-up state but not running. At this +point, HCPU can use LCPU's hardware modules. ### Dual-Core Program Compilation -The LCPU program file is compiled as a constant table inside the HCPU program file. Refer to the example in _$SDK_ROOT/example/multicore/ipc_queue_. -When compiling the LCPU project, in addition to generating the LCPU program file, the resulting BIN file is converted into a _lcpu_img.c_ file, which is stored in the HCPU project directory. This file uses a constant table to define the LCPU binary code and implements the _lcpu_img_install_ function to load the LCPU code into RAM. - -The LCPU compile script uses the SDK tool _$SDK_ROOT/tools/patch/gen_src.py_ to convert the generated LCPU BIN file into a C array and implement the installation function. The usage of the _gen_src.py_ script is as follows: +The LCPU program file is compiled as a constant table inside the HCPU program +file. Refer to the example in _$SDK_ROOT/example/multicore/ipc_queue_.\ +When compiling the LCPU project, in addition to generating the LCPU program +file, the resulting BIN file is converted into a _lcpu_img.c_ file, which is +stored in the HCPU project directory. This file uses a constant table to define +the LCPU binary code and implements the _lcpu_img_install_ function to load the +LCPU code into RAM. + +The LCPU compile script uses the SDK tool _$SDK_ROOT/tools/patch/gen_src.py_ to +convert the generated LCPU BIN file into a C array and implement the +installation function. The usage of the _gen_src.py_ script is as follows: ```python - python gen_src.py lcpu +python gen_src.py lcpu ``` ### LCPU Code Loading -The LCPU code is loaded by HCPU, copied into LCPU's RAM, and configured with LCPU's Stack and PC before starting the LCPU to run. +The LCPU code is loaded by HCPU, copied into LCPU's RAM, and configured with +LCPU's Stack and PC before starting the LCPU to run. + +Taking _$SDK_ROOT/example/multicore/ipc_queue_ as an example, to start LCPU, run +the `lcpu on` command from HCPU's console. This command calls the +`lcpu_power_on` function, which invokes `lcpu_img_install` to transfer the code +into LCPU's RAM, and configures the registers to start LCPU. -Taking _$SDK_ROOT/example/multicore/ipc_queue_ as an example, to start LCPU, run the `lcpu on` command from HCPU's console. This command calls the `lcpu_power_on` function, which invokes `lcpu_img_install` to transfer the code into LCPU's RAM, and configures the registers to start LCPU. ## 3. LCPU Code Development -As introduced above, compared to HCPU, LCPU operates at a lower frequency (48MHz) and has less RAM (256KB). Additionally, the BLE protocol stack runs on LCPU. Therefore, the development of LCPU code primarily focuses on the following aspects: -- Function planning -- Memory planning -- Dual-core data interaction - -### Function Planning -LCPU's main advantage over HCPU is its lower power consumption, and the core focus of function planning is on power consumption. This can be divided into Bluetooth and non-Bluetooth parts: -- **Bluetooth part**: The SF32LB55X protocol stack runs on LCPU, and on top of the protocol stack, the SF32LB55X SDK provides a simpler Bluetooth service layer. The Bluetooth service layer can be configured via menuconfig to run on either LCPU or HCPU. - Running on LCPU allows Bluetooth data exchange with the peer device without waking up HCPU. However, it requires consideration of cross-core operations and Bluetooth state synchronization between the two cores. - Running on HCPU eliminates the need to manage cross-core data operations but results in higher power consumption due to the use of HCPU for all Bluetooth operations. -- **Non-Bluetooth part**: Suitable for tasks that require frequent wake-ups with relatively simple computations, such as sensor data collection and basic data processing, which can take full advantage of LCPU's low power. - It is important to note that LCPU's RAM is limited, so careful memory planning is needed. - -### Memory Planning -LCPU has 256KB of RAM when no external flash is connected. The overall memory layout can be referenced from [](../app_note/memory_usage.md). The 256KB includes all RO (read-only) and RW (read-write) data, so careful planning is required. -LCPU's ROM includes the RT-Thread OS, BLE protocol stack, and most of the HAL interfaces. Developers can choose to call ROM functions to save RO/RW space. However, both ROM and the Bluetooth protocol stack consume some RAM, and specific memory planning is required as follows: - -| Name | Start Address | End Address | Size (bytes) | Description | -|--------------------|-----------------|-----------------|---------------|-------------| -| ROM used RAM area | 0x20124000 | 0x20130000 | 48*1024 | | -| BLE stack area | 0x20130000 | 0x20138000 | 32*1024 | | +As introduced above, compared to HCPU, LCPU operates at a lower frequency +(48MHz) and has less RAM (256KB). Additionally, the BLE protocol stack runs on +LCPU. Therefore, the development of LCPU code primarily focuses on the following +aspects: + - Function planning + - Memory planning + - Dual-core data interaction + +### Function planning +LCPU's main advantage over HCPU is its lower power consumption, and the core +focus of function planning is on power consumption. This can be divided into +Bluetooth and non-Bluetooth parts: + - **Bluetooth part**: The SF32LB55X protocol stack runs on LCPU, and on top + of the protocol stack, the SF32LB55X SDK provides a simpler Bluetooth + service layer. The Bluetooth service layer can be configured via menuconfig + to run on either LCPU or HCPU.\ + Running on LCPU allows Bluetooth data exchange with the peer device without + waking up HCPU. However, it requires consideration of cross-core operations + and Bluetooth state synchronization between the two cores.\ + Running on HCPU eliminates the need to manage cross-core data operations + but results in higher power consumption due to the use of HCPU for all + Bluetooth operations. + - **Non-Bluetooth part**: Suitable for tasks that require frequent wake-ups + with relatively simple computations, such as sensor data collection and + basic data processing, which can take full advantage of LCPU's low power.\ + It is important to note that LCPU's RAM is limited, so careful memory + planning is needed. + +### Memory planning +LCPU has 256KB of RAM when no external flash is connected. The overall memory +layout can be referenced from [](../app_note/memory_usage.md). The 256KB +includes all RO (read-only) and RW (read-write) data, so careful planning is +required.\ +LCPU's ROM includes the RT-Thread OS, BLE protocol stack, and most of the HAL +interfaces. Developers can choose to call ROM functions to save RO/RW space. +However, both ROM and the Bluetooth protocol stack consume some RAM, and +specific memory planning is required as follows: + +| Name | Start Address | End Address | Size (bytes) | Description | +| -------------------- | ------------- | ----------- | ------------ | ----------- | +| RAM area used by ROM | 0x20124000 | 0x20130000 | 48*1024 | | +| BLE stack area | 0x20130000 | 0x20138000 | 32*1024 | | #### ROM Explanation -LCPU uses a symbol definition (symdefs) file mechanism, and the LCPU RAM project can access ROM functions by importing the ROM sym file. The ROM sym file includes: +LCPU uses a symbol definition (symdefs) file mechanism, and the LCPU RAM project +can access ROM functions by importing the ROM sym file. The ROM sym file +includes: - The entire RT-Thread OS - Supported HAL modules for LCPU - Some drivers (alarm, flash, i2c, spi, timer) + - alarm + - flash + - I2C + - spi + - timer - BLE protocol stack API -The RAM project only needs to configure the relevant modules and enable the LCPU_ROM macro. When compiling, if a function name conflicts with ROM functions, it will link directly to the ROM functions. Developers can also specify whether the final linked function is from ROM or RAM by restoring deleted symbols from the sym file. - -The following steps outline how to add symdefs: -1. In the Link options, specify the ROM symdefs file to obtain the ROM symbol table. - - The ROM symdefs file is located in __$SDK_ROOT/example/rom_bin/lcpu_boot_loader/rom.sym__. It can be copied to the LCPU project directory before LCPU compilation through the prebuild step. - - Add `CUSTOM_LFLAGS = 'rom.sym'` in the project's _rtconfig.py_ file, and SCONS will automatically include the _rom.sym_ in the Link options. -2. Enable the LCPU ROM macro in the Kconfig of the LCPU project: + For RAM-based projects, simply configure the corresponding modules and enable + the LCPU_ROM macro. This ensures that the linker prioritizes functions defined + in ROM when encountering redundant definitions during compilation. Developers + can also explicitly control whether functions are linked from ROM or RAM by + managing the symbols in the .sym file.
+ + Follow these steps to add symdefs:
+ + 1. Specify the ROM symdefs file in the linker options to access the ROM symbol + table. + - The ROM symdefs file is located at + [X0X]$SDK_ROOT/example/rom_bin/lcpu_boot_loader/rom.sym[X1X]. It can be + copied to the LCPU project directory via a pre-build step before the + LCPU compilation begins. + - Add "CUSTOM_LFLAGS = 'rom.sym'" to the _rtconfig.py_ file. SCons will + automatically include _rom.sym_ from the project directory in the linker + options. + 2. Enable the LCPU_ROM macro in the LCPU project Kconfig: ```python - config LCPU_ROM +config LCPU_ROM bool default y ``` -#### Notes: -1. ROM functions are read-only and cannot be configured through menuconfig options. -2. ROM functions only use global variables defined in ROM. RAM projects can choose to use either RAM or ROM variables. Special attention should be given when modifying the sym file to avoid unexpected behavior where ROM may not work with RAM-defined global variables. - -### Dual-Core Data Interaction -1. **Communication method**: Refer to the next section on inter-core communication for details. -2. **Communication nodes**: As LCPU is started by HCPU, LCPU's startup time will always be later than HCPU's, depending on when HCPU starts LCPU. - - Both cores operate independently according to the operating system's startup sequence. - - Inter-core communication uses shared memory to exchange data. As long as data is not overwritten before the receiving module is initialized and ready to handle it, data can be exchanged. - For example, if HCPU wants to send data to LCPU through a data service, as long as the receiving side in LCPU has registered the data service before LCPU begins receiving data, HCPU can send data after triggering LCPU power-on without waiting for LCPU's state update. -3. **Other considerations**: - - Data exchange based on inter-core communication will automatically wake up the other core for data interaction. The sleep state of the other core does not need to be considered. +The RAM project only needs to configure the relevant modules and enable the +LCPU_ROM macro. When compiling, if a function name conflicts with ROM functions, +it will link directly to the ROM functions. Developers can also specify whether +the final linked function is from ROM or RAM by restoring deleted symbols from +the sym file. + 1. In the Link options, specify the ROM symdefs file to obtain the ROM symbol + table. + 2. Enable the LCPU ROM macro in the Kconfig of the LCPU project: + +### Dual-core data interaction + + 1. **Communication method**: Refer to the next section on inter-core + communication for details. + 2. **Communication nodes**: As LCPU is started by HCPU, LCPU's startup time + will always be later than HCPU's, depending on when HCPU starts LCPU. + - Both cores operate independently according to the operating system's + startup sequence. + - Inter-core communication uses shared memory to exchange data. As long as + data is not overwritten before the receiving module is initialized and + ready to handle it, data can be exchanged.\ + For example, if HCPU wants to send data to LCPU through a data service, + as long as the receiving side in LCPU has registered the data service + before LCPU begins receiving data, HCPU can send data after triggering + LCPU power-on without waiting for LCPU's state update. + 3. **Other considerations**: + - Data exchange based on inter-core communication will automatically wake + up the other core for data interaction. The sleep state of the other core + does not need to be considered. ## 4. Inter-Core Communication -There are three levels of communication between HCPU and LCPU. Users can choose different interfaces based on their needs, ranked from low to high: - -- **Mailbox** - HCPU and LCPU can access each other's memory, but the access speed is slower than local memory, and it is necessary to ensure that the other core is awake. - The same memory has different addresses in HCPU and LCPU. The SDK provides functions like HCPU_ADDR_2_LCPU_ADDR and LCPU_ADDR_2_HCPU_ADDR to convert between different address spaces. For detailed address space information, refer to [](../app_note/memory_usage.md). - The Mailbox provides interrupt trigger functionality. When one CPU needs the other CPU to perform a task, it triggers the other CPU's Mailbox interrupt, which will then handle the interrupt. Detailed API can be found in [](../hal/mailbox.md). - Both cores can agree on a shared memory address to exchange data, but data sent from HCPU to LCPU must be stored in HCPU's RAM, and vice versa. This is because LCPU may be in sleep mode before receiving the Mailbox interrupt, and HCPU cannot access LCPU's memory. - -- **IPC Queue/IPC Queue Device** - - IPC Queue is built on top of Mailbox, wrapping a circular buffer and interrupt service for easier data exchange between cores. - - IPC Queue is OS-independent but supports the RT-Thread low-power framework. The sender does not enter sleep mode before the buffer is read. - - IPC Queue Device builds on IPC Queue, implementing an RT-Thread device interface for console redirection. - - The usage of IPC Queue can be found in _$SDK_ROOT/example/multicore/ipc_queue_. - -- **Data Service** - - Data Service builds on IPC Queue and offers a client-server distributed data service architecture. The service provider (server) typically runs on LCPU, and the client (user) runs on HCPU. - - The connection between them is provided by the Data Service framework. Both the provider and the user can be developed and simulated independently, especially for LCPU code, which can be debugged on HCPU before final integration and validation on the actual core. +There are three levels of communication between HCPU and LCPU. Users can choose +different interfaces based on their needs, ranked from low to high: + + - **Mailbox**\ + HCPU and LCPU can access each other's memory, but the access speed is slower + than local memory, and it is necessary to ensure that the other core is + awake.\ + The same memory has different addresses in HCPU and LCPU. The SDK provides + functions like HCPU_ADDR_2_LCPU_ADDR and LCPU_ADDR_2_HCPU_ADDR to convert + between different address spaces. For detailed address space information, + refer to []
.\ + The Mailbox provides interrupt trigger functionality. When one CPU needs the + other CPU to perform a task, it triggers the other CPU's Mailbox interrupt, + which will then handle the interrupt. Detailed API can be found in + [](../app_note/memory_usage.md)
.\ + Both cores can agree on a shared memory address to exchange data, but data + sent from HCPU to LCPU must be stored in HCPU's RAM, and vice versa. This is + because LCPU may be in sleep mode before receiving the Mailbox interrupt, and + HCPU cannot access LCPU's memory. + + - **IPC Queue/IPC Queue Device** + - IPC Queue is built on top of Mailbox, wrapping a circular buffer and + interrupt service for easier data exchange between cores. + - IPC Queue is OS-independent but supports the RT-Thread low-power framework. + The sender does not enter sleep mode before the buffer is read. + - IPC Queue Device builds on IPC Queue, implementing an RT-Thread device + interface for console redirection. + - The usage of IPC Queue can be found in + _$SDK_ROOT/example/multicore/ipc_queue_. + - **Data Service**
+ - Data Service builds on IPC Queue and offers a client-server distributed + data service architecture. The service provider (server) typically runs on + LCPU, and the client (user) runs on HCPU. + - The connection between them is provided by the Data Service framework. Both + the provider and the user can be developed and simulated independently, + especially for LCPU code, which can be debugged on HCPU before final + integration and validation on the actual core. - Specific usage can be found in _$SDK_ROOT/example/multicore/data_service_. ## 5. Debugging and Logging Please refer to [](../app_note/debug_logging.md). + diff --git a/docs/source/en/app_note/ezip_tool_usage.md b/docs/source/en/app_note/ezip_tool_usage.md index 1280c85d0..aa7c98fe2 100644 --- a/docs/source/en/app_note/ezip_tool_usage.md +++ b/docs/source/en/app_note/ezip_tool_usage.md @@ -1,94 +1,103 @@ +# EZIP Image Conversion Tool User Guide -# EZIP Image Conversion Tool Usage - -## 1. Tool Description +## 1. Tool Overview Path: _$SDK_ROOT/tools/png2ezip/ezip.exe_ -Purpose: Converts PNG images to either EZIP format, PIXEL format binary files, or LVGL format C files. The first 4 bytes of the binary file are the file header, followed by EZIP or PIXEL formatted data. -The header format is as follows (little-endian): +Purpose: Converts PNG images into EZIP or PIXEL format binary files, or +LVGL-compatible C source files. For binary files, the first 4 bytes constitute +the file header, followed by the EZIP or PIXEL data. The file header format +(little-endian) is as follows: ### File Header Format -| [31:21] | [20:10] | [9:5] | [4:0] | -|----------|----------|------------|------------| -| Image Height | Image Width | Reserved | Format | +| [31:21] | [20:10] | [9:5] | [4:0] | +| ------------ | ----------- | -------- | ------ | +| Image Height | Image Width | Reserved | Format | + +### Format Value -### Format Values +| Format | Description | +| ------ | --------------------------- | +| 1 | EZIP (without Alpha) | +| 2 | EZIP (with Alpha) | +| 4 | Pixel formats without alpha | +| 5 | Pixel formats with alpha | -| Format | Meaning | -|--------|-----------------------------------| -| 1 | EZIP format without ALPHA | -| 2 | EZIP format with ALPHA | -| 4 | PIXEL format without ALPHA | -| 5 | PIXEL format with ALPHA | -PIXEL format without ALPHA supports RGB565 and RGB888, while PIXEL format with ALPHA supports ARGB565 and ARGB888. The detailed format is as follows (all little-endian). -The tool automatically generates the corresponding format based on whether the original PNG file includes an alpha channel. If the source image does not contain alpha, the resulting format will not contain alpha either. +Pixel formats without alpha include RGB565 and RGB888, while pixel formats with +alpha include ARGB1555 and ARGB8888. Detailed formats (all little-endian) are +shown below. During conversion, the tool automatically selects the appropriate +format based on whether the source PNG file contains an alpha channel; if the +source image lacks alpha, the generated format will also exclude alpha. ### RGB565 -| [15:11] | [10:5] | [4:0] | -|---------|---------|----------| -| Red | Green | Blue | +| [15:11] | [10:5] | [4:0] | +| ------- | ------ | ----- | +| Red | Green | Blue | ### RGB888 -| [23:16] | [15:8] | [7:0] | -|---------|---------|----------| -| Red | Green | Blue | +| [23:16] | [15:8] | [7:0] | +| ------- | ------ | ----- | +| Red | Green | Blue | ### ARGB565 -| [23:16] | [15:11] | [10:5] | [4:0] | -|---------|---------|---------|----------| -| Alpha | Red | Green | Blue | +| [23:16] | [15:11] | [10:5] | [4:0] | +| ------- | ------- | ------ | ----- | +| Alpha | Red | Green | Blue | + -### ARGB888 -| [31:24] | [23:16] | [15:8] | [7:0] | -|---------|---------|---------|----------| -| Alpha | Red | Green | Blue | +### ARGB8888 +| [31:24] | [23:16] | [15:8] | [7:0] | +| ------- | ------- | ------ | ----- | +| Alpha | Red | Green | Blue | -## 2. Usage Instructions -### Generate PIXEL Format Binary File +## 2. Usage -- Generate RGB565 or ARGB565: +### Generate PIXEL format binary files + +- Generate RGB565 or ARGB1555 ``` ezip -convert png_filename.png -rgb565 -binfile 1 ``` -- Generate RGB888 or ARGB888: +- Generate RGB888 or ARGB888 ``` ezip -convert png_filename.png -rgb888 -binfile 1 ``` -After completion, the file _png_filename.bin_ will be generated in the tool directory. +Upon completion, the file _png_filename.bin_ is generated in the tool directory. + -### Generate EZIP Format Binary File +### Generate EZIP format binary files -- Generate an EZIP file compressed with RGB565 or ARGB565: +- Generate an EZIP file compressed from RGB565 or ARGB565 ``` ezip -convert png_filename.png -rgb565 -binfile 2 ``` -- Generate an EZIP file compressed with RGB888 or ARGB888: +- Generate an EZIP file compressed from RGB888 or ARGB888 ``` ezip -convert png_filename.png -rgb888 -binfile 2 ``` -After completion, the file _png_filename.bin_ will be generated in the tool directory. +Upon completion, the file _png_filename.bin_ is generated in the tool directory. -### Generate PIXEL Format LVGL C File +### Generate LVGL C files in PIXEL format -- Generate RGB565 or ARGB565 format: +- Generate RGB565 or ARGB565 format ``` ezip -convert png_filename.png -rgb565 -cfile 1 -section ROM3_IMG ``` -- Generate RGB888 or ARGB888 format: +- Generate RGB888 or ARGB888 ``` ezip -convert png_filename.png -rgb888 -cfile 1 -section ROM3_IMG ``` -After completion, the file _png_filename.c_ will be generated in the tool directory, and the section name will be _.ROM3_IMG.png_filename_, for example: +Upon completion, the file _png_filename.c_ is generated in the tool directory +with the specified section name _.ROM3_IMG.png_filename_, for example: ``` #ifndef LV_ATTRIBUTE_MEM_ALIGN @@ -107,19 +116,20 @@ const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_IMG_eZIP_RGBARGB565A uint8_t png_filen } ``` -### Generate EZIP Format LVGL C File +### Generate LVGL C files in EZIP format -- Generate an EZIP format C file compressed with RGB565 or ARGB565: +- Generate an EZIP format C file compressed from RGB565 or ARGB565 ``` ezip -convert png_filename.png -rgb565 -cfile 2 -section ROM3_IMG ``` -- Generate an EZIP format C file compressed with RGB888 or ARGB888: +- Generate a C file in EZIP format by compressing RGB888 or ARGB888 data. ``` ezip -convert png_filename.png -rgb888 -cfile 2 -section ROM3_IMG ``` -After completion, the file _png_filename.c_ will be generated in the tool directory, and the section name will be _.ROM3_IMG.png_filename_, for example: +Upon completion, the file `png_filename.c` is generated in the tool directory, +with the specified section name `.ROM3_IMG.png_filename`. For example: ``` #ifndef LV_ATTRIBUTE_MEM_ALIGN @@ -131,19 +141,24 @@ SECTION(".ROM3_IMG.png_filename") ALIGN(4) const LV_ATTRIBUTE_MEM_ALIGN uint8_t png_filename_map[] = { ... -} ``` -### Generate GZIP BIN File for Hardware EZIP Decompression - -- For example, to compress the file _file.bin_ in the same directory, use the following command: +### Generate a GZIP BIN file for hardware EZIP decompression. +- To compress `file.bin` in the same directory, use the following command: ``` -gzip file.bin -length -noheader ``` - -After the operation, the file _file.bin.gz_ will be generated in the tool directory. -The first 4 bytes of this file represent the length of the original data. When performing hardware EZIP decompression (refer to example/hal/ezip for GZIP decompression), the length will be used to allocate the output buffer, and the decompressed data will be used directly as input for hardware EZIP. - -After running the gzip command, the decompressed data must be completely passed as input to the hardware EZIP. Therefore, if there is a large amount of data to decompress, the input and output buffers may not be enough. -It is recommended to first split the data into chunks, for example, by splitting the original file into 10KB parts, compressing each chunk separately. Then, during decompression, process each chunk sequentially. +The command generates `file.bin.gz` in the tool directory. The first 4 bytes of +this file represent the original data length. When performing hardware EZIP +decompression (refer to `example/hal/ezip` for GZIP decompression), these 4 +bytes should not be passed as input parameters; instead, use this length to +allocate the output buffer. The data following the 4-byte length header is the +GZIP-compressed payload, which serves as the input for the hardware EZIP engine. + +The compressed data from a single GZIP run must be passed in its entirety to the +hardware EZIP input parameters during decompression. Consequently, when +decompressing large datasets, the required input and output buffers may exceed +available memory. It is recommended to partition the data first—for example, by +splitting the original file into 10 KB blocks—compressing each block +independently, and decompressing them sequentially to restore the data. diff --git a/docs/source/en/app_note/flash_usage.md b/docs/source/en/app_note/flash_usage.md index 6f16a5269..3e0801d15 100644 --- a/docs/source/en/app_note/flash_usage.md +++ b/docs/source/en/app_note/flash_usage.md @@ -1,32 +1,54 @@ # Flash Usage Guide ## 1. Introduction to FLASH -The SiFLi FLASH controller supports multiple FLASH chips simultaneously (the 55X series supports 4, the 58X series supports 5, and the 56X series supports 4). These chips can be either NOR-FLASH or NAND-FLASH. -Compared to the 55X series, the 58X and 56X series controllers have added support for 8-line and 16-line PSRAM. The controller name has been changed from QSPI to MPI, meaning it is a controller dedicated to Memory. -For the 55X series, controller one by default controls the internal NOR-FLASH, while controllers two and three are determined by the specific board solution, and controller four is connected to the NOR FLASH, which can be accessed by the LCPU (HCPU can also access). -For the 58X series, controllers one and two typically control the internal NOR-FLASH or PSRAM, depending on the chip package. Controllers three and four are determined by the specific board solution, and controller five connects to internal NOR FLASH, which can be accessed by the LCPU (HCPU can also access). -For the 56X series, controllers one and two typically control the internal NOR-FLASH or PSRAM, depending on the chip package. Controller three is determined by the specific board solution, and controller five connects to internal NOR FLASH, which can be accessed by the LCPU (HCPU can also access). (There is no controller four). -The FLASH driver is divided into the HAL and DRV layers. The HAL layer provides hardware register access and simple logical interfaces, while the DRV layer provides basic operations such as FLASH read/write/erase, initialization, control, and device and file system operations. -- The controller can provide single-wire FLASH operation and 4-wire FLASH operation. +The SiFLi FLASH controller supports multiple FLASH chips simultaneously (the 55X +series supports 4, the 58X series supports 5, and the 56X series supports 4). +These chips can be either NOR-FLASH or NAND-FLASH. Compared to the 55X series, +the 58X and 56X series controllers have added support for 8-line and 16-line +PSRAM. The controller name has been changed from QSPI to MPI, meaning it is a +controller dedicated to Memory. For the 55X series, controller one by default +controls the internal NOR-FLASH, while controllers two and three are determined +by the specific board solution, and controller four is connected to the NOR +FLASH, which can be accessed by the LCPU (HCPU can also access). For the 58X +series, controllers one and two typically control the internal NOR-FLASH or +PSRAM, depending on the chip package. Controllers three and four are determined +by the specific board solution, and controller five connects to internal NOR +FLASH, which can be accessed by the LCPU (HCPU can also access). For the 56X +series, controllers one and two typically control the internal NOR-FLASH or +PSRAM, depending on the chip package. Controller three is determined by the +specific board solution, and controller five connects to internal NOR FLASH, +which can be accessed by the LCPU (HCPU can also access). (There is no +controller four). The FLASH driver is divided into the HAL and DRV layers. The +HAL layer provides hardware register access and simple logical interfaces, while +the DRV layer provides basic operations such as FLASH read/write/erase, +initialization, control, and device and file system operations.
+- The controller can provide single-wire FLASH operation and 4-wire FLASH + operation. - Internal DMA is used for acceleration. -- Supports PAGE write, supports PAGE read (NOR-FLASH can be read directly via the AHB bus in memory mode). -- Supports SECTOR/BLOCK erasure of different sizes. The basic operation unit size depends on the chip. +- Supports PAGE write, supports PAGE read (NOR-FLASH can be read directly via + the AHB bus in memory mode). +- Supports SECTOR/BLOCK erasure of different sizes. The basic operation unit + size depends on the chip. ## 2. FLASH Configuration -The properties and usage of FLASH chips corresponding to the FLASH controller can be configured via `menuconfig` (rtconfig.h), including whether to enable it, whether to use DMA, whether to connect MTD devices, and file system information, etc. -Here is an example of some functions on the 55X EVB development board: -Enter "menuconfig" in the command line to start configuration: -- Choose "RTOS --->" -- Choose "On-chip Peripheral Driver ---> " -- Choose "Enable QSPI ---> " + +The properties and usage of FLASH chips corresponding to the FLASH controller +can be configured via `menuconfig` (rtconfig.h), including whether to enable it, +whether to use DMA, whether to connect MTD devices, and file system information, +etc. Here is an example of some functions on the 55X EVB development board: +Enter "menuconfig" in the command line to start configuration:
+- Select "RTOS --->" +- Select "On-chip Peripheral Driver --->" +- Select "Enable QSPI --->" - Choose "Enable QSPI Driver" -- Choose "QSPI Controller 1 Enable --->" +- Select "QSPI Controller 1 Enable --->" - Choose "QSPI1 Mode: 0 NOR, 1 NAND, 2 PSRAM, 3 OTHERS" -- Choose "QSPI1 Use File System ---" -- Choose "QSPI1 Mem Size()MB" -- Choose "QSPI1 Manul & Device ID" +- Select "QSPI1 Use File System ---" +- Select "QSPI1 Mem Size(MB)" +- Select "QSPI1 Manual & Device ID" -Below are examples of the configuration for each FLASH controller and their corresponding macro definitions.
+Below are examples of the configuration for each FLASH controller and their +corresponding macro definitions.
### FLASH1: (FLASH1 defaults to NOR-FLASH, mode cannot be modified) ```c @@ -40,6 +62,7 @@ Below are examples of the configuration for each FLASH controller and their corr ``` ### FLASH2: + ```c #define BSP_ENABLE_QSPI2 1 /* Enable QSPI2 module */ #define BSP_QSPI2_USING_DMA 1 /* Enable FIFO DMA for QSPI2 */ @@ -60,17 +83,18 @@ Below are examples of the configuration for each FLASH controller and their corr #define BSP_QSPI3_CHIP_ID 0 /* FLASH3 DEV ID automatically obtained by the system */ ``` -Below is an example for some functions on the 58X EVB development board: -Enter "menuconfig" in the command line to start configuration: -- Choose "RTOS --->" -- Choose "On-chip Peripheral Driver ---> " -- Choose "Enable MPI ---> " -- Choose "Enable QSPI Driver " -- Choose "MPI Controller 1 Enable --->" -- Choose "MPI Mode: 0 NOR, 1 NAND, 2 PSRAM, 3 OPSRAM, 4 HPSRAM, 5 LEGACY_PSRAM " -- Choose "MPI1 Mem Size()MB" +Below is an example for some functions on the 58X EVB development board: Enter +"menuconfig" in the command line to start configuration: +- Select "RTOS --->" +- Select "On-chip Peripheral Driver --->" +- Select "Enable MPI --->" +- Choose "Enable QSPI Driver" +- Select "MPI Controller 1 Enable --->" +- Select "MPI Mode: 0 NOR, 1 NAND, 2 PSRAM, 3 OPSRAM, 4 HPSRAM, 5 LEGACY_PSRAM" +- Select "MPI1 Mem Size(MB)" -Below are examples of the configuration for each FLASH controller and their corresponding macro definitions.
+Below are examples of the configuration for each FLASH controller and their +corresponding macro definitions.
### MPI: (MPI default settings, some configurations for backward compatibility) @@ -90,6 +114,7 @@ Below are examples of the configuration for each FLASH controller and their corr ``` ### MPI2: + ```c #define BSP_ENABLE_MPI2 1 /* Enable MPI 2 module */ #define BSP_ENABLE_QSPI2 1 /* Enable MPI 2 (for backward compatibility) */ @@ -100,6 +125,7 @@ Below are examples of the configuration for each FLASH controller and their corr ``` ### MPI3: + ```c #define BSP_ENABLE_MPI3 1 /* Enable MPI 3 module */ #define BSP_ENABLE_QSPI3 1 /* Enable MPI 3 (for backward compatibility) */ @@ -111,6 +137,7 @@ Below are examples of the configuration for each FLASH controller and their corr ``` ### MPI4: + ```c #define BSP_ENABLE_MPI4 1 /* Enable MPI 4 module */ #define BSP_ENABLE_QSPI4 1 /* Enable MPI 4 (for backward compatibility) */ @@ -122,6 +149,7 @@ Below are examples of the configuration for each FLASH controller and their corr ``` ### MPI5: + ```c #define BSP_ENABLE_MPI5 1 /* Enable MPI 5 module */ #define BSP_ENABLE_QSPI5 1 /* Enable MPI 5 (for backward compatibility) */ @@ -132,22 +160,25 @@ Below are examples of the configuration for each FLASH controller and their corr #define BSP_QSPI5_MEM_SIZE 4 /* Configure MPI5 total size to 4MB */ ``` -The 56X configuration is mostly similar to the 58X series except for the absence of MPI4. Therefore, further examples will not be listed separately.
+The 56X configuration is mostly similar to the 58X series except for the absence +of MPI4. Therefore, further examples will not be listed separately.
## 3. FLASH Address Space ### 55X Series Addresses -The default FLASH size configuration on the EVB, where the size represents the usable space, is described according to how the development board is configured: - -| Name | Start Address | End Address | Max Size (bytes) | Description | -|------------------|-----------------|-----------------|-------------------|-----------------------| -| FLASH1 | 0x10000000 | 0x11FFFFFF | 32 * 1024 * 1024 | EVB capacity: 4MB | -| FLASH2 | 0x64000000 | 0x67FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | -| FLASH3 | 0x68000000 | 0x6FFFFFFF | 128 * 1024 * 1024 | EVB disabled | -| FLASH4 | 0x12000000 | 0x13FFFFFF | 32 * 1024 * 1024 | EVB disabled | - -The base addresses for the four FLASH controllers can be found in `_mem_map.h`. The actual size used is determined by the `menuconfig` based on the connected chips: - +The default FLASH size configuration on the EVB, where the size represents the +usable space, is described according to how the development board is configured: + +| Name | Start Address | End Address | Max Size (bytes) | Description | +| ------ | ------------- | ----------- | ----------------- | ------------------ | +| FLASH1 | 0x10000000 | 0x11FFFFFF | 32 * 1024 * 1024 | EVB capacity: 4MB | +| FLASH2 | 0x64000000 | 0x67FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | +| FLASH3 | 0x68000000 | 0x6FFFFFFF | 128 * 1024 * 1024 | EVB disabled | +| FLASH4 | 0x12000000 | 0x13FFFFFF | 32 * 1024 * 1024 | EVB disabled | + +The base addresses for the four FLASH controllers can be found in `_mem_map.h`. +The actual size used is determined by the `menuconfig` based on the connected +chips: ```c #define QSPI1_MEM_BASE (0x10000000) #define QSPI2_MEM_BASE (0x64000000) @@ -156,29 +187,32 @@ The base addresses for the four FLASH controllers can be found in `_mem_map.h`. ``` ### 58X Series Addresses -The default FLASH size configuration on the EVB, where the size represents the usable space, is described according to how the development board is configured: - -C-BUS Addresses: -| Name | Start Address | End Address | Max Size (bytes) | Description | -|------------------|-----------------|-----------------|-------------------|-----------------------| -| MPI1 | 0x10000000 | 0x11FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | -| MPI2 | 0x12000000 | 0x13FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | -| MPI3 | 0x14000000 | 0x17FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | -| MPI4 | 0x18000000 | 0x1BFFFFFF | 64 * 1024 * 1024 | EVB capacity: 64MB | -| MPI5 | 0x1C000000 | 0x1FFFFFFF | 64 * 1024 * 1024 | EVB capacity: 4MB | - -S-BUS Addresses: -| Name | Start Address | End Address | Max Size (bytes) | Description | -|------------------|-----------------|-----------------|-------------------|-----------------------| -| MPI1 | 0x60000000 | 0x61FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | -| MPI2 | 0x62000000 | 0x63FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | -| MPI3 | 0x64000000 | 0x67FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | -| MPI4 | 0x68000000 | 0x9FFFFFFF | 896 * 1024 * 1024 | EVB capacity: 64MB | - -To allow NAND FLASH to use more than 64MB, it is recommended to mount it on MPI4 and start from the address 0x68000000. - -The five MPI controller base addresses can be found in `_mem_map.h`. The actual size used is determined by the `menuconfig` based on the connected chips: - +The default FLASH size configuration on the EVB, where the size represents the +usable space, is described according to how the development board is configured: +
+ +C-BUS Addresses:
+| Name | Start Address | End Address | Max Size (bytes) | Description | +| ---- | ------------- | ----------- | ---------------- | ------------------ | +| MPI1 | 0x10000000 | 0x11FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | +| MPI2 | 0x12000000 | 0x13FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | +| MPI3 | 0x14000000 | 0x17FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | +| MPI4 | 0x18000000 | 0x1BFFFFFF | 64 * 1024 * 1024 | EVB capacity: 64MB | +| MPI5 | 0x1C000000 | 0x1FFFFFFF | 64 * 1024 * 1024 | EVB capacity: 4MB | + +S-BUS Addresses:
+| Name | Start Address | End Address | Max Size (bytes) | Description | +| ---- | ------------- | ----------- | ----------------- | ------------------ | +| MPI1 | 0x60000000 | 0x61FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | +| MPI2 | 0x62000000 | 0x63FFFFFF | 32 * 1024 * 1024 | EVB capacity: 16MB | +| MPI3 | 0x64000000 | 0x67FFFFFF | 64 * 1024 * 1024 | EVB capacity: 32MB | +| MPI4 | 0x68000000 | 0x9FFFFFFF | 896 * 1024 * 1024 | EVB capacity: 64MB | + +To allow NAND FLASH to use more than 64MB, it is recommended to mount it on MPI4 +and start from the address 0x68000000.
+ +The five MPI controller base addresses can be found in `_mem_map.h`. The actual +size used is determined by the `menuconfig` based on the connected chips: ```c #define QSPI1_MEM_BASE (0x10000000) #define QSPI2_MEM_BASE (0x12000000) @@ -188,25 +222,28 @@ The five MPI controller base addresses can be found in `_mem_map.h`. The actual ``` ### 56X Series Addresses -The default FLASH size configuration on the EVB, where the size represents the usable space, is described according to how the development board is configured: - -C-BUS Addresses: -| Name | Start Address | End Address | Max Size (bytes) | Description | -|------------------|-----------------|-----------------|-------------------|-----------------------| -| MPI1 | 0x10000000 | 0x107FFFFF | 8 * 1024 * 1024 | EVB capacity: 4MB | -| MPI2 | 0x10800000 | 0x13FFFFFF | 56 * 1024 * 1024 | EVB capacity: 16MB | -| MPI3 | 0x14000000 | 0x17FFFFFF | 128 * 1024 * 1024 | EVB capacity: 128MB | -| MPI5 | 0x1C000000 | 0x1FFFFFFF | 64 * 1024 * 1024 | EVB capacity: 1MB | - -S-BUS Addresses: -| Name | Start Address | End Address | Max Size (bytes) | Description | -|------------------|-----------------|-----------------|-------------------|-----------------------| -| MPI1 | 0x60000000 | 0x607FFFFF | 8 * 1024 * 1024 | | -| MPI2 | 0x60800000 | 0x63FFFFFF | 56 * 1024 * 1024 | | -| MPI3 | 0x64000000 | 0x9FFFFFFF | 960 * 1024 * 1024 | | - -The four MPI controller base addresses can be found in `_mem_map.h`. The actual size used is determined by the `menuconfig` based on the connected chips: - +The default FLASH size configuration on the EVB, where the size represents the +usable space, is described according to how the development board is configured: +
+ +C-BUS Addresses:
+| Name | Start Address | End Address | Max Size (bytes) | Description | +| ---- | ------------- | ----------- | ----------------- | ------------------- | +| MPI1 | 0x10000000 | 0x107FFFFF | 8 * 1024 * 1024 | EVB capacity: 4MB | +| MPI2 | 0x10800000 | 0x13FFFFFF | 56 * 1024 * 1024 | EVB capacity: 16MB | +| MPI3 | 0x14000000 | 0x17FFFFFF | 128 * 1024 * 1024 | EVB capacity: 128MB | +| MPI5 | 0x1C000000 | 0x1FFFFFFF | 64 * 1024 * 1024 | EVB capacity: 1MB | + +S-BUS Addresses:
+| Name | Start Address | End Address | Max Size (bytes) | Description | +| ---- | ------------- | ----------- | ----------------- | ----------- | +| MPI1 | 0x60000000 | 0x607FFFFF | 8 * 1024 * 1024 | | +| MPI2 | 0x60800000 | 0x63FFFFFF | 56 * 1024 * 1024 | | +| MPI3 | 0x64000000 | 0x9FFFFFFF | 960 * 1024 * 1024 | | + + +The four MPI controller base addresses can be found in `_mem_map.h`. The actual +size used is determined by the `menuconfig` based on the connected chips: ```c #define QSPI1_MEM_BASE (0x10000000) #define QSPI2_MEM_BASE (0x10800000) @@ -214,8 +251,10 @@ The four MPI controller base addresses can be found in `_mem_map.h`. The actual #define QSPI5_MEM_BASE (0x1C000000) ``` + ## 4. FLASH RT-Thread Driver Access -Based on RT-THREAD, the FLASH provides a set of access interfaces that can be operated by address (the absolute address determines which controller to use). +Based on RT-THREAD, the FLASH provides a set of access interfaces that can be +operated by address (the absolute address determines which controller to use). ```c /** @@ -249,14 +288,23 @@ int rt_flash_write(rt_uint32_t addr, const rt_uint8_t *buf, size_t size); * @return RT_EOK if success. */ rt_err_t rt_flash_erase(rt_uint32_t addr, size_t size); - ``` -The initialization is carried out through the interface `rt_hw_flash_init`. Before this, whether each FLASH is enabled and the corresponding configuration have been determined by _rtconfig.h_, and will not be modified through input parameters here.
-The data operation is performed through `rt_flash_read`. NOR-FLASH can be read directly from memory, while NAND-FLASH can only be read through this interface. The caller needs to maintain the management of the data buffer by himself.
-The data write operation is performed through `rt_flash_write`. For both NAND and NOR, the write operation needs to be completed through this interface, and the caller needs to maintain the data buffer.
-For NOR-FLASH, the smallest erase unit is SECTOR (usually 4KB). The address and length must be aligned to SECTOR; otherwise, incorrect erasure will occur. The caller needs to maintain the recovery of misaligned address data.
-For NAND-FLASH, the minimum erase unit is BLOCK (usually 128KB), and the address and length need to be aligned according to BLOCK. The caller needs to maintain the data backup and recovery of the unaligned part by himself.
+The initialization is carried out through the interface `rt_hw_flash_init`. +Before this, whether each FLASH is enabled and the corresponding configuration +have been determined by _rtconfig.h_, and will not be modified through input +parameters here.
The data operation is performed through `rt_flash_read`. +NOR-FLASH can be read directly from memory, while NAND-FLASH can only be read +through this interface. The caller needs to maintain the management of the data +buffer by himself.
The data write operation is performed through +`rt_flash_write`. For both NAND and NOR, the write operation needs to be +completed through this interface, and the caller needs to maintain the data +buffer.
For NOR-FLASH, the smallest erase unit is SECTOR (usually 4KB). +The address and length must be aligned to SECTOR; otherwise, incorrect erasure +will occur. The caller needs to maintain the recovery of misaligned address +data.
For NAND-FLASH, the minimum erase unit is BLOCK (usually 128KB), and +the address and length need to be aligned according to BLOCK. The caller needs +to maintain the data backup and recovery of the unaligned part by himself.
```{note} Note that FLASH does not support writing to the same Flash when XIP is not supported, so the Flash driver related code needs to be placed in SRAM for execution. The following is a link script fragment of Keil, @@ -266,7 +314,7 @@ The 64KB space starting at address 0x200E1000 is used to store the Flash driver ``` LR_IROM1 0x10020000 0x100000 { ; load region size_region ... - ER_IROM1_EX 0x200E1000 0x10000 { ; Flash code and RO need to put in SRAM + ER_IROM1_EX 0x200E1000 0x10000 { ; Flash code and RO data must be placed in SRAM drv_flash_z0.o (.text.*) drv_flash_z0.o (.rodata.*) bf0_hal_flash.o (.text.*) @@ -279,7 +327,6 @@ LR_IROM1 0x10020000 0x100000 { ; load region size_region The following is an example of writing 4KB data to FLASH1 1MB address: ```c - unsigned long address = FLASH_BASE_ADDR + 0x100000; char * buf = NULL; char * buf2 = NULL; @@ -291,7 +338,7 @@ if(res != 0) // Write flash -// malloc buf and initial data before write +// Allocate buffer and initialize data before writing buf = malloc(4096); if(buf == NULL) return ERROR; @@ -299,49 +346,59 @@ int size = rt_flash_write(address, buf, 4096); if(size != 4096) goto err; -// read flash +// Read flash buf2 = malloc(4096); if(buf2 == NULL) goto err; size = rt_flash_read(address, buf2, 4096); if(size != 4096) goto err; - -// check data -for(int i=0; i<4096; i++) + +// Verify data +for(int i=0; i<4096; i++) if(buf[i] != buf2[i]) goto err; .... - + err: if(buf) free(buf); if(buf2) - free(buf); + free(buf2); return ERROR; ... - ``` ## 5. FLASH RT-Thread MTD device is used -The MTD in RT-THREAD contains two device drivers, MTD-NOR and MTD-NAND. If the FLASH is correctly configured and enabled in the MTD of the configuration file, these devices will be automatically registered during system startup. Whether the registration is successful or not can be queried through the interface.
-For example, the query of FLASH1 can be carried out by rt_device_find("flash1"). The device names corresponding to each controller are "flash1", "flash2", and "flash3". If the query returns non-empty, it means that the registration is successful.
- -At present, MTD devices have been used in file systems and USB STORAGE. In use, the device is mainly searched and then bound. The read and write of MTD has been encapsulated in mtd_nor, so users do not need to process it.
-The following are the corresponding data types when registering. If the user registers himself, he needs to fill in the corresponding data and implement the operation interface. If the registration is completed, he only needs to find the device, and the subsequent operation will be completed by the system background.
+The MTD in RT-THREAD contains two device drivers, MTD-NOR and MTD-NAND. If the +FLASH is correctly configured and enabled in the MTD of the configuration file, +these devices will be automatically registered during system startup. Whether +the registration is successful or not can be queried through the interface. +
For example, the query of FLASH1 can be carried out by +rt_device_find("flash1"). The device names corresponding to each controller are +"flash1", "flash2", and "flash3". If the query returns non-empty, it means that +the registration is successful.
+ +At present, MTD devices have been used in file systems and USB STORAGE. In use, +the device is mainly searched and then bound. The read and write of MTD has been +encapsulated in mtd_nor, so users do not need to process it.
The following +are the corresponding data types when registering. If the user registers +himself, he needs to fill in the corresponding data and implement the operation +interface. If the registration is completed, he only needs to find the device, +and the subsequent operation will be completed by the system background.
MTD-NOR: ```c struct rt_mtd_nor_device { struct rt_device parent; - rt_uint32_t block_size; /* The Block size in the flash */ - rt_uint32_t block_start; /* The start of available block*/ - rt_uint32_t block_end; /* The end of available block */ + rt_uint32_t block_size; /* Flash block size */ + rt_uint32_t block_start; /* Start of available block range */ + rt_uint32_t block_end; /* End of available block range */ - /* operations interface */ + /* Operations interface */ const struct rt_mtd_nor_driver_ops* ops; }; @@ -364,18 +421,18 @@ struct rt_mtd_nand_device { struct rt_device parent; - rt_uint16_t page_size; /* The Page size in the flash */ - rt_uint16_t oob_size; /* Out of bank size */ - rt_uint16_t oob_free; /* the free area in oob that flash driver not use */ - rt_uint16_t plane_num; /* the number of plane in the NAND Flash */ + rt_uint16_t page_size; /* Flash page size */ + rt_uint16_t oob_size; /* Out-of-band (OOB) size */ + rt_uint16_t oob_free; /* Free OOB area available for use by the driver */ + rt_uint16_t plane_num; /* Number of planes in the NAND Flash */ - rt_uint32_t pages_per_block; /* The number of page a block */ + rt_uint32_t pages_per_block; /* Number of pages per block */ rt_uint16_t block_total; - rt_uint32_t block_start; /* The start of available block*/ - rt_uint32_t block_end; /* The end of available block */ + rt_uint32_t block_start; /* Start of available block range */ + rt_uint32_t block_end; /* End of available block range */ - /* operations interface */ + /* Operations interface */ const struct rt_mtd_nand_driver_ops* ops; }; @@ -404,7 +461,7 @@ rt_err_t rt_mtd_nand_register_device(const char* name, struct rt_mtd_nand_device Here is an example of MTD-NOR in use with a file system: ```c - // Register MTD DEVICE +// Register MTD DEVICE struct rt_mtd_nor_device *nod = malloc(sizeof(struct rt_mtd_nor_device)); nod->block_start = BSP_FLASH1_FS_START; @@ -415,7 +472,7 @@ Here is an example of MTD-NOR in use with a file system: lflash_handle[0].nod = nod; rt_mtd_nor_register_device("flash1", (struct rt_mtd_nor_device *)(lflash_handle[0].nod)); - + // Find MTD DEVICE: rt_device_t dev = rt_device_find("flash1"); if (dev) // device find, it has beed registered to mtd @@ -431,8 +488,11 @@ Here is an example of MTD-NOR in use with a file system: ## 6. Current FLASH space allocation status -From the space listed in _mem_map.h_, the first 64KB from the start of FLASH1 (0x10000000) is used for storing the flash_table, followed by another 64KB (0x10010000) for storing the boot patch, and starting from 0x10020000 for storing bin.
-FLASH2 If NOR-FLASH is the case, the watch resource file is stored from its starting position (0x64000000). +From the space listed in _mem_map.h_, the first 64KB from the start of FLASH1 +(0x10000000) is used for storing the flash_table, followed by another 64KB +(0x10010000) for storing the boot patch, and starting from 0x10020000 for +storing bin.
FLASH2 If NOR-FLASH is the case, the watch resource file is +stored from its starting position (0x64000000). ```c #define FLASH_TABLE_SIZE (20*1024) #define FLASH_CAL_TABLE_SIZE (8*1024) @@ -447,118 +507,142 @@ FLASH2 If NOR-FLASH is the case, the watch resource file is stored from its star #define FLASH_USER_CODE_START_ADDR (FLASH_BOOT_PATCH_END_ADDR + 1) /* 0x10020000 */ ``` -FLASH is also used for storing variables and logs. Currently, FLASHDB (or EasyFlash) is used. flash1/flash2 have some space temporarily used, which needs to be replanned according to system requirements. +FLASH is also used for storing variables and logs. Currently, FLASHDB (or +EasyFlash) is used. flash1/flash2 have some space temporarily used, which needs +to be replanned according to system requirements. ## 7. NOR-FLASH's Transplant -According to different development boards for different customers, different NOR-FLASH particles will be used in the design, and when using these particles, the main matching is made from hardware specifications and operation command configuration.
+According to different development boards for different customers, different +NOR-FLASH particles will be used in the design, and when using these particles, +the main matching is made from hardware specifications and operation command +configuration.
### Hardware specifications -- Voltage configuration: 3.3V or 1.8V -- SPI mode: whether to support double line and 4-line SPI in addition to single line -- Highest frequency: The highest frequency supported in single line/double line/4 line mode respectively -- Other things such as working temperature, writing speed, etc., which are not related to software porting, can be ignored first - -### operating command - -Operation commands mainly refer to read/write/erase related granular commands, which are related to vendors and specific granules, and need to be found and compared from the specification book.
-A0 has added the way to add the command table to increase the support for new FLASH particles (_flash_table.c_). The main commands involved are defined in _bf0_hal_qspi.h SPI_FLASH_CMD_E_, which includes NAND/NOR commands.
- + - Voltage configuration: 3.3V or 1.8V + - SPI mode: whether to support double line and 4-line SPI in addition to + single line + - Highest frequency: The highest frequency supported in single line/double + line/4 line mode respectively + - Other things such as working temperature, writing speed, etc., which are not + related to software porting, can be ignored first + +### operating command + +Operation commands mainly refer to read/write/erase related granular commands, +which are related to vendors and specific granules, and need to be found and +compared from the specification book.
A0 has added the way to add the +command table to increase the support for new FLASH particles (_flash_table.c_). +The main commands involved are defined in _bf0_hal_qspi.h SPI_FLASH_CMD_E_, +which includes NAND/NOR commands.
```c /** * @brief SPI_FLASH command index */ typedef enum { - SPI_FLASH_CMD_WREN = 0, /*!< write enable, nor+nand */ - SPI_FLASH_CMD_WRDI, /*!< write disable, nor+nand */ - SPI_FLASH_CMD_RDSR, /*!< read status register, nor+nand */ - SPI_FLASH_CMD_WRSR, /*!< write status register, nor+nand */ - SPI_FLASH_CMD_PREAD, /*!< page read, nand */ - SPI_FLASH_CMD_READ, /*!< single line read, nor+nand */ - SPI_FLASH_CMD_FREAD, /*!< fast read , nor + nand */ - SPI_FLASH_CMD_DREAD, /*!< fast read dual output, nor+nand */ - SPI_FLASH_CMD_QREAD, /*!< fast read quad output, nor+nand */ - SPI_FLASH_CMD_2READ, /*!< 2 line read, nor+nand */ - SPI_FLASH_CMD_4READ, /*!< 4 line read, nor+nand . ==== 10 */ - SPI_FLASH_CMD_RDID, /*!< read id, nor+nand */ - SPI_FLASH_CMD_PLD, /*!< load program data, nand */ - SPI_FLASH_CMD_QPLD, /*!< qual program load, nand */ - SPI_FLASH_CMD_PLDR, /*!< randome program load, nand */ - SPI_FLASH_CMD_QPLDR, /*!< qual random program load, nand */ - SPI_FLASH_CMD_PEXE, /*!< program execute, nand */ - SPI_FLASH_CMD_BE, /*!< block erase, nand */ - SPI_FLASH_CMD_RST, /*!< reset, nor+nand */ - SPI_FLASH_CMD_RST_EN, /*!< reset en, nor */ - SPI_FLASH_CMD_RDSR2, /*!< read status register 2, nor ==== 20 */ - SPI_FLASH_CMD_WVSR, /*!< write volatile status register, nor */ - SPI_FLASH_CMD_PP, /*!< PAGE PROGRAM, nor */ - SPI_FLASH_CMD_QPP, /*!< QUAL PAGE PROGRAM, nor */ - SPI_FLASH_CMD_RDEAR, /*!< read extended address register, nor */ - SPI_FLASH_CMD_WREAR, /*!< write extended address register, nor */ - SPI_FLASH_CMD_PE, /*!< page erase, nor */ - SPI_FLASH_CMD_SE, /*!< SECTOR erase, nor */ - SPI_FLASH_CMD_BE32, /*!< BLOCK erase 32KB, nor */ - SPI_FLASH_CMD_BE64, /*!< BLOCK erase 64KB, nor */ - SPI_FLASH_CMD_CE, /*!< CHIP ERASE, nor ===== 30 */ - SPI_FLASH_CMD_RDSR3, /*!< read status register 3, nor */ - SPI_FLASH_CMD_WRSR3, /*!< WRITE status register 3, nor */ - SPI_FLASH_CMD_EN4BM, /*!< enter 4-byte address mode, nor */ - SPI_FLASH_CMD_ET4BM, /*!< exit 4-byte address mode, nor */ - SPI_FLASH_CMD_RD4BA, /*!< read with 4-byte address, nor */ - SPI_FLASH_CMD_FR4BA, /*!< fast read with 4-byte address, nor */ - SPI_FLASH_CMD_FQR4BA, /*!< fast read quad output with 4-byte address, nor */ - SPI_FLASH_CMD_4RD4BA, /*!< 4 IO read with 4-byte address, nor */ - SPI_FLASH_CMD_PP4BA, /*!< page program with 4-byte address, nor */ - SPI_FLASH_CMD_QPP4BA, /*!< quad page program with 4-byte address, nor ==== 40 */ - SPI_FLASH_CMD_SE4BA, /*!< sector erase with 4-byte address, nor */ - SPI_FLASH_CMD_BE4BA, /*!< 64KB block erase with 4-byte address, nor */ - SPI_FLASH_CMD_WRSR2, /*!< write status register command 2, nor */ - SPI_FLASH_CMD_LEFPA, /*!< Last ECC Failue Page Address, NAND */ - SPI_FLASH_CMD_BBM, /*!< Bad Block Management, NAND */ - SPI_FLASH_CMD_RBLUT, /*!< Read BBM Look Up Table, NAND */ - SPI_FLASH_CMD_COUNT /*!< current support flash command */ + SPI_FLASH_CMD_WREN = 0, /*!< Write enable (NOR + NAND) */ + SPI_FLASH_CMD_WRDI, /*!< Write disable (NOR + NAND) */ + SPI_FLASH_CMD_RDSR, /*!< Read status register (NOR + NAND) */ + SPI_FLASH_CMD_WRSR, /*!< Write status register (NOR + NAND) */ + SPI_FLASH_CMD_PREAD, /*!< Page read (NAND) */ + SPI_FLASH_CMD_READ, /*!< Single-line read (NOR + NAND) */ + SPI_FLASH_CMD_FREAD, /*!< Fast read (NOR + NAND) */ + SPI_FLASH_CMD_DREAD, /*!< Dual-output fast read (NOR + NAND) */ + SPI_FLASH_CMD_QREAD, /*!< Quad-output fast read (NOR + NAND) */ + SPI_FLASH_CMD_2READ, /*!< Dual-line read (NOR + NAND) */ + SPI_FLASH_CMD_4READ, /*!< Quad-line read (NOR + NAND) . ==== 10 */ + SPI_FLASH_CMD_RDID, /*!< Read ID (NOR + NAND) */ + SPI_FLASH_CMD_PLD, /*!< Load program data (NAND) */ + SPI_FLASH_CMD_QPLD, /*!< Quad program load (NAND) */ + SPI_FLASH_CMD_PLDR, /*!< Random program load (NAND) */ + SPI_FLASH_CMD_QPLDR, /*!< Quad random program load (NAND) */ + SPI_FLASH_CMD_PEXE, /*!< Program execute (NAND) */ + SPI_FLASH_CMD_BE, /*!< Block erase (NAND) */ + SPI_FLASH_CMD_RST, /*!< Reset (NOR + NAND) */ + SPI_FLASH_CMD_RST_EN, /*!< Reset enable (NOR) */ + SPI_FLASH_CMD_RDSR2, /*!< Read status register 2 (NOR) ==== 20 */ + SPI_FLASH_CMD_WVSR, /*!< Write volatile status register (NOR) */ + SPI_FLASH_CMD_PP, /*!< Page program (NOR) */ + SPI_FLASH_CMD_QPP, /*!< Quad page program (NOR) */ + SPI_FLASH_CMD_RDEAR, /*!< Read extended address register (NOR) */ + SPI_FLASH_CMD_WREAR, /*!< Write extended address register (NOR) */ + SPI_FLASH_CMD_PE, /*!< Page erase (NOR) */ + SPI_FLASH_CMD_SE, /*!< Sector erase (NOR) */ + SPI_FLASH_CMD_BE32, /*!< 32KB block erase (NOR) */ + SPI_FLASH_CMD_BE64, /*!< 64KB block erase (NOR) */ + SPI_FLASH_CMD_CE, /*!< Chip erase (NOR) ===== 30 */ + SPI_FLASH_CMD_RDSR3, /*!< Read status register 3 (NOR) */ + SPI_FLASH_CMD_WRSR3, /*!< Write status register 3 (NOR) */ + SPI_FLASH_CMD_EN4BM, /*!< Enter 4-byte address mode (NOR) */ + SPI_FLASH_CMD_ET4BM, /*!< Exit 4-byte address mode (NOR) */ + SPI_FLASH_CMD_RD4BA, /*!< Read with 4-byte address (NOR) */ + SPI_FLASH_CMD_FR4BA, /*!< Fast read with 4-byte address (NOR) */ + SPI_FLASH_CMD_FQR4BA, /*!< Quad-output fast read with 4-byte address (NOR) */ + SPI_FLASH_CMD_4RD4BA, /*!< 4-IO read with 4-byte address (NOR) */ + SPI_FLASH_CMD_PP4BA, /*!< Page program with 4-byte address (NOR) */ + SPI_FLASH_CMD_QPP4BA, /*!< Quad page program with 4-byte address (NOR) ==== 40 */ + SPI_FLASH_CMD_SE4BA, /*!< Sector erase with 4-byte address (NOR) */ + SPI_FLASH_CMD_BE4BA, /*!< 64KB block erase with 4-byte address (NOR) */ + SPI_FLASH_CMD_WRSR2, /*!< Write status register command 2 (NOR) */ + SPI_FLASH_CMD_LEFPA, /*!< Last ECC Failure Page Address (NAND) */ + SPI_FLASH_CMD_BBM, /*!< Bad Block Management (NAND) */ + SPI_FLASH_CMD_RBLUT, /*!< Read BBM Look-Up Table (NAND) */ + SPI_FLASH_CMD_COUNT /*!< Supported flash command count */ } SPI_FLASH_CMD_E; - ``` -The system already contains the command table of some particles (flash_cmd_table_list). You can first check whether the function corresponding to the particle to be transplanted is consistent with this command code. If it is completely consistent, the particle can be directly used; otherwise, a new command table needs to be added.
-Command table type definition:
+The system already contains the command table of some particles +(flash_cmd_table_list). You can first check whether the function corresponding +to the particle to be transplanted is consistent with this command code. If it +is completely consistent, the particle can be directly used; otherwise, a new +command table needs to be added.
Command table type definition:
```c /** - * @brief SPI_FLASH manual command + * @brief SPI_FLASH manual command configuration */ typedef struct { uint8_t cmd; - uint8_t func_mode; /*!< manual read 0 / write 1 */ - uint8_t data_mode; /*!< 0 no data / 1 single line / 2 dual line / 3 qual line */ - uint8_t dummy_cycle; /*!< dummy cycle between command and address/data */ - uint8_t ab_size; /*!< alternate byte size, */ - uint8_t ab_mode; /*!< alternate byte mode, 0 no, 1, single line, 2, dual line, 3 fouline */ - uint8_t addr_size; /*!< address byte count - 1 */ - uint8_t addr_mode; /*!< 0 no, 1 single line / 2 dual lin / 3 four line */ - uint8_t cmd_mode; /*!< 0 no, 1 single lien / 2 dual line / 3 four line */ + uint8_t func_mode; /*!< Manual read (0) / write (1) */ + uint8_t data_mode; /*!< 0: No data, 1: Single-line, 2: Dual-line, 3: Quad-line */ + uint8_t dummy_cycle; /*!< Dummy cycles between command and address/data */ + uint8_t ab_size; /*!< Alternate byte size */ + uint8_t ab_mode; /*!< Alternate byte mode: 0: None, 1: Single-line, 2: Dual-line, 3: Quad-line */ + uint8_t addr_size; /*!< Address byte count - 1 */ + uint8_t addr_mode; /*!< 0: None, 1: Single-line, 2: Dual-line, 3: Quad-line */ + uint8_t cmd_mode; /*!< 0: None, 1: Single-line, 2: Dual-line, 3: Quad-line */ } FLASH_CMD_CFG_T; - ``` -"cmd" refers to the command ID, such as write enable command is 0x06, read status register command is 0x05, etc.
-func_mode is the function type, 0 is read operation, 1 is write operation.
-data_mode is the width of the data line. 0 means no data, 1 means single data operation, 2 means double data operation, and 3 means four data lines.
-A dummy_cycle is the number of clock pulses that may be present between a command and data.
-The ab_size and ab_mode parameters are used for setting certain commands M7~M0 after the address, such as the 4-line read command 0XEB for the PUYA. In the timing diagram, an 8-bit MBYTE setting follows ADDR (used to determine the continue mode). The table sets these parameters to 0/3, where 0 indicates a size of 1 byte (n-1), and 3 indicates a 4-line mode. -addr_size and addr_mode refer to the address parameters that the command needs to follow. addr_size is the address length (n-1 bytes), and addr_mode represents no address (0), single line (1), double line (2), and 4 lines (3). When mode = 0, there is no address requirement, and size must be 0.
-cmd_mode is a flash command, and the valid command is always 1
+"cmd" refers to the command ID, such as write enable command is 0x06, read +status register command is 0x05, etc.
func_mode is the function type, 0 is +read operation, 1 is write operation.
data_mode is the width of the data +line. 0 means no data, 1 means single data operation, 2 means double data +operation, and 3 means four data lines.
A dummy_cycle is the number of +clock pulses that may be present between a command and data.
The ab_size +and ab_mode parameters are used for setting certain commands M7~M0 after the +address, such as the 4-line read command 0XEB for the PUYA. In the timing +diagram, an 8-bit MBYTE setting follows ADDR (used to determine the continue +mode). The table sets these parameters to 0/3, where 0 indicates a size of 1 +byte (n-1), and 3 indicates a 4-line mode. addr_size and addr_mode refer to the +address parameters that the command needs to follow. addr_size is the address +length (n-1 bytes), and addr_mode represents no address (0), single line (1), +double line (2), and 4 lines (3). When mode = 0, there is no address +requirement, and size must be 0.
cmd_mode is a flash command, and the valid +command is always 1
## 8. NAND-FLASH transplant -The transplantation of NAND particles is basically the same as that of NOR, except that the commands used will be different. This depends on the timing exported according to the specific particles.
-```{note} -The acquisition ID timing of some particles is different. If the default timing cannot obtain the correct ID, the correct command table cannot be found. In this case, either the acquisition ID timing in the code needs to be modified, or the correct ID needs to be configured in the configuration to find the newly registered command table +The transplantation of NAND particles is basically the same as that of NOR, +except that the commands used will be different. This depends on the timing +exported according to the specific particles.
+```{note} 有些颗粒的获取ID的时序不同,如果用默认的时序无法获取正确的ID,则不能查找到正确的命令表,这时要么需要修改代码中的获取ID时序,要么在配置时配置上正确的ID以便查找到新注册的命令表 + ``` ## 9.PSRAM migration -At present, PSRAM has only been ported to APM PSRAM, including 4 lines, 8 lines and 16 lines. There are models that can support sizes from 4MB to 32MB.
-Among them, 55X only supports 4 line PSRAM.
-Supports 58X for 4, 8, and 16 lines,
-Support for 4-wire and 8-wire is supported on 56X.
+At present, PSRAM has only been ported to APM PSRAM, including 4 lines, 8 lines +and 16 lines. There are models that can support sizes from 4MB to 32MB.
+Among them, 55X only supports 4 line PSRAM.
Supports 58X for 4, 8, and 16 +lines,
Support for 4-wire and 8-wire is supported on 56X.
+ diff --git a/docs/source/en/app_note/index.md b/docs/source/en/app_note/index.md index 158ba030b..1930f1f61 100644 --- a/docs/source/en/app_note/index.md +++ b/docs/source/en/app_note/index.md @@ -1,9 +1,8 @@ # Application Note - + ```{toctree} :titlesonly: :glob: * - ``` diff --git a/docs/source/en/app_note/javascript.md b/docs/source/en/app_note/javascript.md index ab48e099f..b63ec80ef 100644 --- a/docs/source/en/app_note/javascript.md +++ b/docs/source/en/app_note/javascript.md @@ -1,29 +1,64 @@ # JavaScript Support -The SiFli SDK utilizes QuickJS as its JavaScript development runtime platform. QuickJS is a lightweight embeddable JavaScript engine that supports ES2020 specification features including modules, async generators, proxies, BigInt, and other functionalities. QuickJS also provides selective support for mathematical extensions such as arbitrary precision decimal floating-point numbers (BigDecimal), arbitrary precision binary floating-point numbers (BigFloat), and operator overloading. -The SDK integrates QuickJS with SiFli's application framework and watch face framework, enabling coexistence with existing C-based applications and watch faces. The watch_demo provides JavaScript examples. The JavaScript code located in _SDK_ROOT/example/watch_demo/project/jsroot_ runs on the development board and requires deployment to the development board via the jsroot.bat script in the project directory. For instance, for the ec-lb555 development board, _SDK_ROOT/example/watch_demo/project/ec-lb555/jsroot.bat packages all contents from _SDK_ROOT/example/watch_demo/project/jsroot into a filesystem image and downloads it to the development board. -The JavaScript code under _SDK_ROOT/example/watch_demo/project/simulator/disk is designed for simulator execution. While the codebase is identical to the development board version, it uses different resource formats since the simulator does not support the SiFli chip-specific EZIP compression format. +The SiFli SDK utilizes QuickJS as its JavaScript development runtime platform. +QuickJS is a lightweight embeddable JavaScript engine that supports ES2020 +specification features including modules, async generators, proxies, BigInt, and +other functionalities. QuickJS also provides selective support for mathematical +extensions such as arbitrary precision decimal floating-point numbers +(BigDecimal), arbitrary precision binary floating-point numbers (BigFloat), and +operator overloading. The SDK integrates QuickJS with SiFli's application +framework and watch face framework, enabling coexistence with existing C-based +applications and watch faces. The watch_demo provides JavaScript examples. The +JavaScript code located in _SDK_ROOT/example/watch_demo/project/jsroot_ runs on +the development board and requires deployment to the development board via the +jsroot.bat script in the project directory. For instance, for the ec-lb555 +development board, _SDK_ROOT/example/watch_demo/project/ec-lb555/jsroot.bat +packages all contents from _SDK_ROOT/example/watch_demo/project/jsroot into a +filesystem image and downloads it to the development board. The JavaScript code +under _SDK_ROOT/example/watch_demo/project/simulator/disk is designed for +simulator execution. While the codebase is identical to the development board +version, it uses different resource formats since the simulator does not support +the SiFli chip-specific EZIP compression format. + +The SDK integrates QuickJS with Silergy's application and watch face frameworks, +allowing coexistence with existing C-based applications and watch faces. +JavaScript examples are provided within `watch_demo`. The JS code located in +`_SDK_ROOT/example/watch_demo/project/jsroot_` is intended for the development +board; it must be downloaded to the board using the `_jsroot.bat_` script found +in the project directory. For instance, for the ec-lb555 development board, +`_SDK_ROOT/example/watch_demo/project/ec-lb555/jsroot.bat` packages all contents +of `_SDK_ROOT/example/watch_demo/project/jsroot` into a single file system image +for download. JavaScript code in +`_SDK_ROOT/example/watch_demo/project/simulator/disk_` is for the simulator; +while functionally identical to the development board code, it uses different +resource formats, as the simulator does not support the proprietary EZIP format +used by Silergy chips. ## 1. QuickJS initialization -Currently, the initialization of QucikJS is completed when the first JS application or dial starts. The initialization is performed by the internal SDK application\ -The dial frame JS adaptation module is called, and all JS applications are applied -The dial shares the same JS runtime context environment. In order to match the single-threaded environment of LVGL, QuickJS is also running in the single-threaded environment of LVGL. - SDK QuickJS currently requires: +Currently, the initialization of QucikJS is completed when the first JS +application or dial starts. The initialization is performed by the internal SDK +application\ +The dial frame JS adaptation module is called, and all JS applications are +applied The dial shares the same JS runtime context environment. In order to +match the single-threaded environment of LVGL, QuickJS is also running in the +single-threaded environment of LVGL. SDK QuickJS currently requires: - 4K byte stack, -- 512K running heap. The exact amount of memory used depends on the application and dial running. +- 512K running heap. The exact amount of memory used depends on the application + and dial running. - 210K base library ROM -- Other extensions, including the application framework, and LVGL support, require 10K ROM and 6K RAM. +- Other extensions, including the application framework, and LVGL support, + require 10K ROM and 6K RAM. ## 2. Application framework and dial frame support - In addition to the class support of Quick JS standard, the SDK adds application framework and dial frame support. When the system starts, it will automatically scan the root directory of the file system. If: -### -Found that the directory starts with JA_, JA_ - This is an application of Javascript. main.js in the directory is the main program of the application. You need to define a class named app_name, which inherits from the app class and is registered in the global JS variable. Thumb.bin is the APP icon. - -### -Found that the directory starts with JW_, JW_ - This is the dial of Javascript. _main.js_ in the directory is the main program of the dial. You need to define a class named watchface_name, which inherits from the app class and is registered in the global JS variable. - - ```{note} Dial and APP JS is different in constructor: - ```java +In addition to the class support of Quick JS standard, the SDK adds application +framework and dial frame support. When the system starts, it will automatically +scan the root directory of the file system. If: +### -Found that the directory starts with JA_, JA_ + This is an application of Javascript. main.js in the directory is the main program of the application. You need to define a class named app_name, which inherits from the app class and is registered in the global JS variable. Thumb.bin is the APP icon. +### -Found that the directory starts with JW_, JW_ + This is the dial of Javascript. _main.js_ in the directory is the main program of the dial. You need to define a class named watchface_name, which inherits from the app class and is registered in the global JS variable. + ```{note} 表盘和APP JS有区别在constructor: + ```java //The main.js of this dial should be in the /JW_wf8 directory class wf8 extends app{ //Define the dial constructor() { @@ -34,7 +69,8 @@ The dial shares the same JS runtime context environment. In order to match the s ``` ``` ## 3. Application framework function packaging - In the lv module, SDK also packages the gui_app_xxx function of the application framework, including:
+In the lv module, SDK also packages the gui_app_xxx function of the application +framework, including:
- \ref gui_app_cleanup
- \ref gui_app_cleanup_now
- \ref gui_app_exit
@@ -55,9 +91,11 @@ The dial shares the same JS runtime context environment. In order to match the s - \ref gui_app_set_page_userdata
## 4. LVGL Support - The SDK provides JS support for LVGL, which includes some things: - - lv.obj - lv.obj is the basic LVGL control, and each member function corresponds to lv_obj_xxx. In order to save memory, the SDK only outputs some lv_obj_xxx functions as members of lv.obj. At present, it includes the following contents: +The SDK provides JS support for LVGL, which includes some things: + - lv.obj lv.obj is the basic LVGL control, and each member function + corresponds to lv_obj_xxx. In order to save memory, the SDK only outputs + some lv_obj_xxx functions as members of lv.obj. At present, it includes the + following contents: - create
- align_to
- get_x
@@ -72,56 +110,55 @@ The dial shares the same JS runtime context environment. In order to match the s - add_flag
- move_foreground
- move_background
- - delete
- In addition, lv.obj has added: - - set_obj
- This function sets the created lv obj (c language pointer) when creating a control that inherits from lv.obj, so that the base class does not need to create it again. - - bind
- This function binds the control to a known data type and can call the callback function when the data is generated - - set_event_cb
- This function calls the callback function when the control receives lv event. + - delete
In addition, lv.obj has added: + - set_obj
This function sets the created lv obj (c language pointer) + when creating a control that inherits from lv.obj, so that the base class + does not need to create it again. + - bind
This function binds the control to a known data type and can + call the callback function when the data is generated + - set_event_cb
This function calls the callback function when the + control receives lv event. - Inheriting from the lv.obj LV control - - img
- Image control provided by LVGL - - label
- The Label control provided by LVGL - - analogclk
- The simulated dial control developed by SiFli - - idximg
- The multi-image switching control developed by SiChai has images with a common file header and a file name ending of 00-99 for cyclic switching. - - lvsfapng
- The unique compressed image animation format of Sicheng is supported by the 58x chip - - lvsfbarcode
- Barcode control developed by SiFli - - lvsfcomp
- A combination of controls with an Apple style developed by SiFli - - lvsfcorner
- Sicheng's Apple-style four-corner control - - lvsfcurve
- The curved string display control developed by SiFli - - qrcode
- The LVGL provides a QR code control - - rlottie
- Sight integrated lottie animation controls - - Image resource - In the code of Javascript, some pictures may be needed. SiChui provides a special image compression format to help users save flash controls. SiChui chip uses hardware accelerated decoding to achieve smooth user experience. - The SDK has a tool to convert PNG files to private formats. The tool is in /tools/png2ezip/ezip.exe.
- Among them, the part used for the simulator is:
+ - img
Image control provided by LVGL + - label
The Label control provided by LVGL + - analogclk
The simulated dial control developed by SiFli + - idximg
The multi-image switching control developed by SiChai has + images with a common file header and a file name ending of 00-99 for + cyclic switching. + - lvsfapng
The unique compressed image animation format of Sicheng is + supported by the 58x chip + - lvsfbarcode
Barcode control developed by SiFli + - lvsfcomp
A combination of controls with an Apple style developed by + SiFli + - lvsfcorner
Sicheng's Apple-style four-corner control + - lvsfcurve
The curved string display control developed by SiFli + - qrcode
The LVGL provides a QR code control + - rlottie
Sight integrated lottie animation controls + - Image resource In the code of Javascript, some pictures may be needed. + SiChui provides a special image compression format to help users save flash + controls. SiChui chip uses hardware accelerated decoding to achieve smooth + user experience. The SDK has a tool to convert PNG files to private + formats. The tool is in /tools/png2ezip/ezip.exe.
Among them, the part + used for the simulator is:
- Simulator:
- - ezip -convert xxx\yyy.png -rgb565 -binfile 1
- Convert a single file in RGB565 color format - - ezip -dir xxx -rgb565 -binfile 1
- Convert all PNG files in the directory to RGB565 color format + - ezip -convert xxx\yyy.png -rgb565 -binfile 1
Convert a single + file in RGB565 color format + - ezip -dir xxx -rgb565 -binfile 1
Convert all PNG files in the + directory to RGB565 color format - Development board: - - ezip -convert xxx\yyy.png -rgb565 -binfile 2
- Convert a single file in RGB565 color format - - ezip -dir xxx -rgb565 -binfile 2
- Convert all PNG files in the directory to RGB565 color format - The generated file is in the output subdirectory of the current directory. - + - ezip -convert xxx\yyy.png -rgb565 -binfile 2
Convert a single + file in RGB565 color format + - ezip -dir xxx -rgb565 -binfile 2
Convert all PNG files in the + directory to RGB565 color format The generated file is in the output + subdirectory of the current directory. + ## 5. Data service support -SDK provides the binding of LVGL controls and data services. Through lv.obj's bind function, you can process the received data in JS code. -When the underlying C code receives the data, it can send the LV_EVENT_REFRESH event to the bound lv obj and send the data as a parameter, so that the JS callback will be called for processing. -For the definition of data format, please refer to _$SDK_ROOT/external/quickjs/lvgl/gui_app_data.h_. The SDK will convert the C structure into the corresponding JS object. +SDK provides the binding of LVGL controls and data services. Through lv.obj's +bind function, you can process the received data in JS code. When the underlying +C code receives the data, it can send the LV_EVENT_REFRESH event to the bound lv +obj and send the data as a parameter, so that the JS callback will be called for +processing. For the definition of data format, please refer to +_$SDK_ROOT/external/quickjs/lvgl/gui_app_data.h_. The SDK will convert the C +structure into the corresponding JS object. diff --git a/docs/source/en/app_note/jdi_lb551.md b/docs/source/en/app_note/jdi_lb551.md index 9fbe2933d..f6783e833 100644 --- a/docs/source/en/app_note/jdi_lb551.md +++ b/docs/source/en/app_note/jdi_lb551.md @@ -1,6 +1,6 @@ # JDI screen with LB551 debugging instructions -Please refer to it[JDI屏幕+LB551调试使用说明](../extra/jdi_lb551_en.pdf) +Please refer to it[JDI屏幕+LB551调试使用说明](../extra/jdi_lb551.pdf) diff --git a/docs/source/en/app_note/low_power.md b/docs/source/en/app_note/low_power.md index 0bf765871..53bfa8953 100644 --- a/docs/source/en/app_note/low_power.md +++ b/docs/source/en/app_note/low_power.md @@ -55,7 +55,7 @@ Run `sdk.py menuconfig` in the project directory to open the configuration menu: - Toggle: Enable Low power support - Macro: `BSP_USING_PM` - Purpose: Enable low‑power features - + ```{figure} ../../assets/enable_pm.png :align: center Figure: Enable Low Power configuration menu @@ -87,20 +87,18 @@ Figure: PM debug configuration menu ``` 4) After configuration, verify `rtconfig.h` includes the following: ```{only} SF32LB52X -```c -#define RT_USING_PM 1 // Enable PM module -#define PM_DEEP_ENABLE 1 // Use DEEP sleep mode -#define BSP_USING_PM 1 // Enable PM module -#define BSP_PM_DEBUG 1 // Print PM[S], PM[W] logs (optional) + +``` +#define RT_USING_PM 1 // Enable PM module #define PM_DEEP_ENABLE 1 // Use DEEP +sleep mode #define BSP_USING_PM 1 // Enable PM module #define BSP_PM_DEBUG 1 // +Print PM[S], PM[W] logs (optional) ``` ```{only} SF32LB58X or SF32LB56X or SF32LB55X -```c -#define RT_USING_PM 1 // Enable PM module -#define PM_STANDBY_ENABLE 1 // Use STANDBY sleep mode -#define BSP_USING_PM 1 // Enable PM module -#define BSP_PM_DEBUG 1 // Print PM[S], PM[W] logs (optional) ``` - +#define RT_USING_PM 1 // Enable PM module #define PM_STANDBY_ENABLE 1 // Use +STANDBY sleep mode #define BSP_USING_PM 1 // Enable PM module #define +BSP_PM_DEBUG 1 // Print PM[S], PM[W] logs (optional) +``` ### 2.2 Disable Low‑Power Mode Run `sdk.py menuconfig` and uncheck the same options used to enable low power. @@ -114,55 +112,55 @@ Refer to `SDK\example\pm\classical` for the configuration method. Below is an HAL‑level standby wake‑up API example. You can use `HAL_LPAON_QueryWakeupPin()` and `HAL_HPAON_QueryWakeupPin()` to get the wake‑up pin index. If the IO wake‑up needs event handling, also configure the GPIO interrupt: ```{only} SF32LB55X -```c -HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 55x PA80 #WKUP_A3 -HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, AON_PIN_MODE_NEG_EDGE); // 55x PB48 #WKUP_PIN5 -// Check if configuration takes effect; compare with datasheet registers: -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // lcpu ``` - +HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 55x PA80 +#WKUP_A3 HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, +AON_PIN_MODE_NEG_EDGE); // 55x PB48 #WKUP_PIN5 // Check if configuration takes +effect; compare with datasheet registers: rt_kprintf("wsr:0x%x,wer:0x%x,\n", +hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu +rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // +lcpu +``` ```{only} SF32LB52X In 52 series DeepSleep mode, no extra wake‑up pin configuration is required. Any pin can wake up, via WSR_GPIO1. ``` ```{only} SF32LB56X -```c -HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 56x PB35 #WKUP_PIN3 -HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, AON_PIN_MODE_NEG_EDGE); // 56x PA50 #WKUP_PIN5 -// Check if configuration takes effect; compare with datasheet registers: -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // lcpu + +``` +HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 56x PB35 +#WKUP_PIN3 HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, +AON_PIN_MODE_NEG_EDGE); // 56x PA50 #WKUP_PIN5 // Check if configuration takes +effect; compare with datasheet registers: rt_kprintf("wsr:0x%x,wer:0x%x,\n", +hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu +rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // +lcpu ``` ```{only} SF32LB58X -```c -HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 58x PB57 #WKUP_PIN3 -HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, AON_PIN_MODE_NEG_EDGE); // 58x PB59 #WKUP_PIN5 -// Check if configuration takes effect; compare with datasheet registers: -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu -rt_k_printf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // lcpu ``` - +HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN3, AON_PIN_MODE_LOW); // 58x PB57 +#WKUP_PIN3 HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN5, +AON_PIN_MODE_NEG_EDGE); // 58x PB59 #WKUP_PIN5 // Check if configuration takes +effect; compare with datasheet registers: rt_kprintf("wsr:0x%x,wer:0x%x,\n", +hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu +rt_k_printf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // +lcpu +``` **Power‑off wake‑up configuration (for hibernate wake‑up)** ```{only} SF32LB55X 55 series MCU: In Hibernate, only LCPU wake‑up PIN0–PIN5 support wake‑up. See PMUC WER register in the 55 series User Manual. -```c -// 55x configuration: -HAL_PMU_EnablePinWakeup(5, AON_PIN_MODE_NEG_EDGE); // 55x PB48 #WKUP_PIN5 -rt_kprintf("CR:0x%x,WER:0x%x\n", hwp_pmuc->CR, hwp_pmuc->WER); ``` - +// 55x configuration: HAL_PMU_EnablePinWakeup(5, AON_PIN_MODE_NEG_EDGE); // 55x +PB48 #WKUP_PIN5 rt_kprintf("CR:0x%x,WER:0x%x\n", hwp_pmuc->CR, hwp_pmuc->WER); +``` ```{only} SF32LB52X or SF32LB56X or SF32LB58X Post‑55 series MCUs: Allow two wake‑up sources PIN0 and PIN1 at the same time; each source can map to any HCPU/LCPU wake pin. See PMUC CR register in the User Manual. -```c -// 58x/56x/52x configuration: -HAL_PMU_SelectWakeupPin(0, HAL_HPAON_QueryWakeupPin(hwp_gpio1, BSP_KEY1_PIN)); // select PA34 to wake_pin0 -HAL_PMU_EnablePinWakeup(0, AON_PIN_MODE_HIGH); // enable wake_pin0 +``` +// 58x/56x/52x configuration: HAL_PMU_SelectWakeupPin(0, +HAL_HPAON_QueryWakeupPin(hwp_gpio1, BSP_KEY1_PIN)); // select PA34 to wake_pin0 +HAL_PMU_EnablePinWakeup(0, AON_PIN_MODE_HIGH); // enable wake_pin0 rt_kprintf("CR:0x%x,WER:0x%x\n", hwp_pmuc->CR, hwp_pmuc->WER); ``` - - - After Hibernate power‑off, wake‑up is equivalent to a cold boot (but with the `PM_HIBERNATE_BOOT` flag), unlike Standby which resumes previous context. Wake‑up pin and level mode are controlled by PMU registers; you can print WER/CR to verify. If the same IO is used for both standby and hibernate wake‑up, both configurations must apply. ## 4 Low‑Power Debugging Methods @@ -183,16 +181,23 @@ CPU enters light sleep (WFI). High‑speed clocks are turned off. CPU‑related Wake‑up sources: LPTIM, RTC, BLE MAC (LCPU Only), Mailbox (other CPU), or specific wake‑up pins. Wake‑up latency: 30–100 µs. Execution resumes at the instruction after WFI. ``` -- `PM_SLEEP_MODE_DEEP`: -Same as LIGHT, but system power switches to RET_LDO; wake‑up latency increases to 100 µs–1 ms. -Execution resumes at the instruction after WFI. +- `PM_SLEEP_MODE_DEEP`: Same as LIGHT, but system power switches to RET_LDO; + wake‑up latency increases to 100 µs–1 ms. Execution resumes at the instruction + after WFI. -- `PM_SLEEP_MODE_STANDBY`: -CPU enters standby. High‑speed clocks are off; CPU‑related peripherals lose power; RAM power is removed except for configured retention parts; pin states are retained; system power switches to RET_LDO. -Wake‑up sources: LPTIM, RTC, BLE MAC (LCPU only), Mailbox (other CPU), or specific wake‑up pins. Wake‑up latency: 1–2 ms. -After wake‑up the system restarts; software checks AON registers to determine standby boot vs. cold boot. +- `PM_SLEEP_MODE_STANDBY`: CPU enters standby. High‑speed clocks are off; + CPU‑related peripherals lose power; RAM power is removed except for configured + retention parts; pin states are retained; system power switches to RET_LDO. + Wake‑up sources: LPTIM, RTC, BLE MAC (LCPU only), Mailbox (other CPU), or + specific wake‑up pins. Wake‑up latency: 1–2 ms. After wake‑up the system + restarts; software checks AON registers to determine standby boot vs. cold + boot. -Typical currents for each mode are shown in Table 4‑1. If PSRAM exists, HCPU backs up data that must be retained from powered‑down RAM to PSRAM and restores it after wake‑up; otherwise it backs up to 64 KB Retention RAM. Unless otherwise stated, “enter sleep” refers to entering low‑power modes other than IDLE, and “wake‑up” refers to exiting low‑power modes other than IDLE. +Typical currents for each mode are shown in Table 4‑1. If PSRAM exists, HCPU +backs up data that must be retained from powered‑down RAM to PSRAM and restores +it after wake‑up; otherwise it backs up to 64 KB Retention RAM. Unless otherwise +stated, “enter sleep” refers to entering low‑power modes other than IDLE, and +“wake‑up” refers to exiting low‑power modes other than IDLE. Table 4‑1: Low‑power modes ```{only} SF32LB52X @@ -225,29 +230,43 @@ Table 4‑1: Low‑power modes ``` ### 4.2 Power‑Off Modes -In addition to the four low‑power modes per subsystem, the chip provides two system‑level power‑off modes: -- Hibernate: All subsystems powered down; system clock switches to 32K crystal; wake‑up by PIN and RTC (RTC wake‑up time accurate). API: `HAL_PMU_EnterHibernate`. -- Shutdown: All subsystems powered down; system clock switches to RC10K; wake‑up by PIN and RTC (RTC wake‑up time not accurate). API: `HAL_PMU_EnterShutdown`. +In addition to the four low‑power modes per subsystem, the chip provides two +system‑level power‑off modes: +- Hibernate: All subsystems powered down; system clock switches to 32K crystal; + wake‑up by PIN and RTC (RTC wake‑up time accurate). API: + `HAL_PMU_EnterHibernate`. +- Shutdown: All subsystems powered down; system clock switches to RC10K; wake‑up + by PIN and RTC (RTC wake‑up time not accurate). API: `HAL_PMU_EnterShutdown`. Table 4‑2: Power‑off modes -| Mode | CPU State | Peripheral State | SRAM | IO | Wake‑up Source | Wake‑up Time | -|-----------|-----------|------------------|--------------|------|----------------|--------------| -| Hibernate | reset | reset | Not retained | Hi‑Z | RTC and PIN | >2 ms | -| Shutdown | reset | reset | Not retained | Hi‑Z | RTC and PIN | >2 ms | +| Mode | CPU State | Peripheral State | SRAM | I/O | Wake‑up Source | Wake‑up Time | +| --------- | --------- | ---------------- | ----------------- | -------------- | -------------- | ------------ | +| Hibernate | Reset | Reset | Data not retained | High impedance | RTC and PIN | >2 ms | +| Shutdown | Reset | Reset | Data not retained | High impedance | RTC and PIN | >2 ms | -Note: Current values are for reference only; actual numbers vary with enabled peripherals and IO settings. “stop” means halted but resumes without reconfiguration; “reset” means CPU resets (starts from ROM) and peripherals need reinitialization. +Note: Current values are for reference only; actual numbers vary with enabled +peripherals and IO settings. “stop” means halted but resumes without +reconfiguration; “reset” means CPU resets (starts from ROM) and peripherals need +reinitialization. -If sleep is not possible but further power reduction is needed, see WFI auto down‑clocking and scenario‑based DVFS. +If sleep is not possible but further power reduction is needed, see WFI auto +down‑clocking and scenario‑based DVFS. ### 4.3 WFI Auto Down‑Clocking -When the `IDLE` thread runs but sleep conditions are not met, reduce HCPU frequency to lower current during `WFI`. Prerequisite: all high‑speed peripherals are idle. High‑speed peripherals include: +When the `IDLE` thread runs but sleep conditions are not met, reduce HCPU +frequency to lower current during `WFI`. Prerequisite: all high‑speed +peripherals are idle. High‑speed peripherals include: - EPIC - EZIP - LCDC - USB - SD -Notes: Busy detection for EPIC/EZIP is built into the SDK’s LVGL implementation. If using a custom implementation, call `rt_pm_hw_device_start`/`rt_pm_hw_device_stop` when peripherals start/stop to avoid down‑clocking during busy periods. Busy detection for LCDC/USB/SD is integrated in RT‑Thread’s LCD Device driver. +Notes: Busy detection for EPIC/EZIP is built into the SDK’s LVGL implementation. +If using a custom implementation, call +`rt_pm_hw_device_start`/`rt_pm_hw_device_stop` when peripherals start/stop to +avoid down‑clocking during busy periods. Busy detection for LCDC/USB/SD is +integrated in RT‑Thread’s LCD Device driver. ```{only} SF32LB52X The WFI frequency after down‑clocking is configured by `HAL_RCC_HCPU_SetDeepWFIDiv`. When audio peripherals are active, it can only drop to 48 MHz; otherwise down to 4 MHz. Also set `HPSYS_RCC_DBGR_FORCE_HP` in `hwp_hpsys_rcc->DBGR` to 1. ``` @@ -255,29 +274,42 @@ The WFI frequency after down‑clocking is configured by `HAL_RCC_HCPU_SetDeepWF The WFI frequency after down‑clocking is configured by `HAL_RCC_HCPU_SetDeepWFIDiv`. When audio peripherals are active, it can only drop to 48 MHz; otherwise down to 1 MHz. ``` ### 4.4 Scenario‑Based DVFS -In low‑performance scenarios, the high‑performance core can reduce frequency/voltage to cut active power (e.g., after screen off, wrist‑raise algorithm only could run at 48 MHz). Although lower frequency increases execution time, total energy (current × time) may be lower. Measure and pick optimal modes per scenario. +In low‑performance scenarios, the high‑performance core can reduce +frequency/voltage to cut active power (e.g., after screen off, wrist‑raise +algorithm only could run at 48 MHz). Although lower frequency increases +execution time, total energy (current × time) may be lower. Measure and pick +optimal modes per scenario. -Use `rt_pm_run_enter` to set the current run mode. HCPU supports four modes (app default is `PM_RUN_MODE_HIGH_SPEED`); switching to higher speed takes effect immediately, switching to lower speed is deferred until the IDLE thread: +Use `rt_pm_run_enter` to set the current run mode. HCPU supports four modes (app +default is `PM_RUN_MODE_HIGH_SPEED`); switching to higher speed takes effect +immediately, switching to lower speed is deferred until the IDLE thread: | Mode | System Clock (MHz) | -|--------------------------|--------------------| +| ------------------------ | ------------------ | | PM_RUN_MODE_HIGH_SPEED | 240 | | PM_RUN_MODE_NORMAL_SPEED | 144 | | PM_RUN_MODE_MEDIUM_SPEED | 48 | | PM_RUN_MODE_LOW_SPEED | 24 | -SDK also provides `pm_scenario_start`/`pm_scenario_stop` for scenario toggles. Currently supports `UI` and `Audio`: +SDK also provides `pm_scenario_start`/`pm_scenario_stop` for scenario toggles. +Currently supports `UI` and `Audio`: - Either on → use HIGH_SPEED - Both off → use MEDIUM_SPEED ### 4.5 Low‑Power Flow -In this solution, HPSYS can enter sleep only after the screen turns off. With screen on, when HCPU is idle, HPSYS can only enter IDLE. LPSYS can enter sleep only after HPSYS sleeps; if HPSYS is awake, LPSYS stays in IDLE even if LCPU is idle (52 series exception: HCPU/LCPU can sleep independently). When HPSYS is asleep, LPSYS can freely enter/exit sleep without waking HPSYS. +In this solution, HPSYS can enter sleep only after the screen turns off. With +screen on, when HCPU is idle, HPSYS can only enter IDLE. LPSYS can enter sleep +only after HPSYS sleeps; if HPSYS is awake, LPSYS stays in IDLE even if LCPU is +idle (52 series exception: HCPU/LCPU can sleep independently). When HPSYS is +asleep, LPSYS can freely enter/exit sleep without waking HPSYS. #### 4.5.1 Screen‑Off -Lock‑screen timeout is configurable in settings. When no interaction exceeds the timeout, the screen turns off; the IDLE thread checks sleep conditions. If met, HPSYS sleeps, and LPSYS can then sleep as well. +Lock‑screen timeout is configurable in settings. When no interaction exceeds the +timeout, the screen turns off; the IDLE thread checks sleep conditions. If met, +HPSYS sleeps, and LPSYS can then sleep as well. -```{figure} ../../assets/low_power_english13.png +```{figure} ../../assets/low_power13.png :align: center Figure 4.1 Screen‑off flow ``` @@ -289,14 +321,17 @@ HPSYS can be woken by LPTIM, RTC, BLE MAC (LCPU only), Mailbox (other CPU), or a ```{only} SF32LB55X or SF32LB58X or SF32LB56X HPSYS wake‑up sources: LPTIM, RTC, BLE MAC (LCPU only), Mailbox (from another CPU), or specific wake‑up pins. For example, enabling wake on a button pin allows a button press to wake HPSYS. ``` -For button wake to turn the screen on, see Figure 4.2. After the screen turns on, a new screen‑off cycle begins. A wake‑up flow triggered by a smartphone app “setting” event is shown in Figure 4.3; after handling the request, the IDLE thread can immediately re‑enter sleep. +For button wake to turn the screen on, see Figure 4.2. After the screen turns +on, a new screen‑off cycle begins. A wake‑up flow triggered by a smartphone app +“setting” event is shown in Figure 4.3; after handling the request, the IDLE +thread can immediately re‑enter sleep. -```{figure} ../../assets/low_power_english14.png +```{figure} ../../assets/low_power14.png :align: center Figure 4.2 Button wake and screen‑off cycle ``` -```{figure} ../../assets/low_power_english25.png +```{figure} ../../assets/low_power25.png :align: center Figure 4.3 Wake‑up flow on phone Setting event ``` @@ -329,19 +364,22 @@ Context retention in DEEPSLEEP/STANDBY: ``` ### 4.6 Log Interpretation -HCPU and LCPU print logs via console. After enabling low‑power debug in Section 2.1, search the following keywords to analyze flows. +HCPU and LCPU print logs via console. After enabling low‑power debug in Section +2.1, search the following keywords to analyze flows. Table 4‑3: Log keywords -| Log | Meaning | -|----------------|-------------------------------------------------| -| gui_suspend | Screen off | -| gui_resume | Screen on | +| Log | Meaning | +| ----------------- | ------------------------------------------------------------------------ | +| gui_suspend | Screen off | +| gui_resume | Screen on | | [pm]S: mode,gtime | Enter sleep; mode=2 means LIGHT, 4 means STANDBY; gtime unit is 32768 Hz | -| [pm]W: gtime | Exit sleep; gtime unit is 32768 Hz | -| [pm]WSR:0xXXX | Wake‑up reason (decode by register bitfields) | +| [pm]W: gtime | Exit sleep; gtime unit is 32768 Hz | +| [pm]WSR:0xXXX | Wake‑up reason (decode by register bitfields) | -`gtime` is synchronized between HCPU and LCPU. Example: sleep at 2136602 and wake at 2142330 → `sleep_time=(2142330-2136602)/32768=175 ms`. If `WSR=0x200`, wake‑up was by LPSYS mailbox interrupt. See the datasheet for bit meanings. +`gtime` is synchronized between HCPU and LCPU. Example: sleep at 2136602 and +wake at 2142330 → `sleep_time=(2142330-2136602)/32768=175 ms`. If `WSR=0x200`, +wake‑up was by LPSYS mailbox interrupt. See the datasheet for bit meanings. ```{figure} ../../assets/low_power15.png :align: center @@ -616,8 +654,10 @@ Likely LPSYS slept if any of: Ensure the finsh shell option is enabled in LCPU Command shell. You can also check chip power pins to determine current low‑power mode: -- HPSYS active/sleep/deepsleep: `LDO1_VOUT` ≈ 1.1 V; HPSYS standby: `LDO1_VOUT` gradually drops to 0 V. -- LPSYS active/sleep/deepsleep: `LDO2_VOUT` or `BUCK2_VOUT` ≈ 0.9 V; LPSYS standby: the voltage gradually drops to 0 V. +- HPSYS active/sleep/deepsleep: `LDO1_VOUT` ≈ 1.1 V; HPSYS standby: `LDO1_VOUT` + gradually drops to 0 V. +- LPSYS active/sleep/deepsleep: `LDO2_VOUT` or `BUCK2_VOUT` ≈ 0.9 V; LPSYS + standby: the voltage gradually drops to 0 V. - Hibernate: `LDO1_VOUT/LDO2_VOUT/BUCK2_VOUT/VDD_RET` all drop to 0 V. ```{only} SF32LB55X @@ -632,7 +672,9 @@ Figure 4.5 Power pin voltages in low‑power modes **Sleep entry conditions** -For applications, sleep/work switching is transparently controlled by the lowest priority `IDLE` thread: when all higher‑priority threads are idle, `IDLE` runs and checks if all the following are met before entering sleep: +For applications, sleep/work switching is transparently controlled by the lowest +priority `IDLE` thread: when all higher‑priority threads are idle, `IDLE` runs +and checks if all the following are met before entering sleep: - Sleep not forbidden (no outstanding `rt_pm_request(PM_SLEEP_MODE_IDLE)`) - The soonest OS timer expiration > threshold (default 100 ms) @@ -641,11 +683,15 @@ For applications, sleep/work switching is transparently controlled by the lowest **Timed wake configuration before sleep** -Before sleep, configure `LPTIM` to interrupt at the soonest OS timer expiration so the timer callback fires on time during sleep. Example: if the next timer expires in 200 ms, set `LPTIM` to interrupt in 200 ms. +Before sleep, configure `LPTIM` to interrupt at the soonest OS timer expiration +so the timer callback fires on time during sleep. Example: if the next timer +expires in 200 ms, set `LPTIM` to interrupt in 200 ms. **Forbid/release sleep APIs** -Apps can explicitly suppress sleep in critical sections; the driver framework also suppresses sleep while peripherals are active to avoid sleeping during interrupt operations: +Apps can explicitly suppress sleep in critical sections; the driver framework +also suppresses sleep while peripherals are active to avoid sleeping during +interrupt operations: ```c // Forbid sleep until release @@ -656,7 +702,9 @@ rt_pm_release(PM_SLEEP_MODE_IDLE); **Timer thresholds and policy** -Refer to Power Management configuration for enabling low‑power support and selecting policies to enter different low‑power modes. The current default policy is: +Refer to Power Management configuration for enabling low‑power support and +selecting policies to enter different low‑power modes. The current default +policy is: Default policy example: @@ -675,18 +723,17 @@ Common checks (HCPU/LCPU similar): 1) Enable PM and verify macros: ```{only} SF32LB52X -```c -#define RT_USING_PM 1 -#define BSP_USING_PM 1 // Enable low‑power -#define PM_DEEP_ENABLE 1 // Use Deep low‑power -#define BSP_PM_DEBUG 1 // Enable low‑power debug logs + +``` +#define RT_USING_PM 1 #define BSP_USING_PM 1 // Enable low‑power #define +PM_DEEP_ENABLE 1 // Use Deep low‑power #define BSP_PM_DEBUG 1 // Enable +low‑power debug logs ``` ```{only} SF32LB56X or SF32LB58X or SF32LB55X -```c -#define RT_USING_PM 1 -#define BSP_USING_PM 1 // Enable low‑power -#define PM_STANDBY_ENABLE 1 // Use Standby low‑power -#define BSP_PM_DEBUG 1 // Enable low‑power debug logs +``` +#define RT_USING_PM 1 #define BSP_USING_PM 1 // Enable low‑power #define +PM_STANDBY_ENABLE 1 // Use Standby low‑power #define BSP_PM_DEBUG 1 // Enable +low‑power debug logs ``` 2) Confirm CPU is idle and in the idle thread: - Use finsh `list_thread` to check threads; except `tshell` and `tidle` ready, others should be suspend, otherwise IDLE cannot run. @@ -697,15 +744,19 @@ Figure 4.6 Output of list_thread ``` 3) Confirm sleep is not forbidden: -- In console, run `pm_dump`. If “Idle Mode Counter” > 0, some module called `rt_pm_request(PM_SLEEP_MODE_IDLE)` to forbid sleep; call `rt_pm_release(PM_SLEEP_MODE_IDLE)` to release. +- In console, run `pm_dump`. If “Idle Mode Counter” > 0, some module called + `rt_pm_request(PM_SLEEP_MODE_IDLE)` to forbid sleep; call + `rt_pm_release(PM_SLEEP_MODE_IDLE)` to release. ```{figure} ../../assets/low_power18.png :align: center Figure 4.7 Output of pm_dump ``` -4) Confirm OS timer expirations exceed the sleep threshold: -In console, run `list_timer` to show created timers. Compare the timeout of timers with flag `activated` against the sleep threshold; if smaller, that timer prevents sleep. Timeout unit is ms. +4) Confirm OS timer expirations exceed the sleep threshold: In console, run + `list_timer` to show created timers. Compare the timeout of timers with flag + `activated` against the sleep threshold; if smaller, that timer prevents + sleep. Timeout unit is ms. ```{figure} ../../assets/low_power19.png :align: center Figure 4.8 Output of list_timer @@ -759,40 +810,34 @@ rt_thread_delay(100); // 100ms - Read registers via console commands to check `WER/WSR`: ```{only} SF32LB55X 55 series WSR addresses: -```text -regop unlock 0000 -regop read 4007001c 1 # LPSYS WSR -regop read 4003001c 1 # HPSYS WSR +``` +regop unlock 0000 regop read 4007001c 1 # LPSYS WSR regop read 4003001c 1 # +HPSYS WSR ``` ```{only} SF32LB52X 52 series WSR addresses: -```text -regop unlock 0000 -regop read 40040024 1 # LPSYS WSR -regop read 500c0024 1 # HPSYS WSR +``` +regop unlock 0000 regop read 40040024 1 # LPSYS WSR regop read 500c0024 1 # +HPSYS WSR ``` ```{only} SF32LB56X 56 series WSR addresses: -```text -regop unlock 0000 -regop read 50040020 1 # LPSYS WSR -regop read 40040020 1 # HPSYS WSR +``` +regop unlock 0000 regop read 50040020 1 # LPSYS WSR regop read 40040020 1 # +HPSYS WSR ``` ```{only} SF32LB58X 58 series WSR addresses: -```text -regop unlock 0000 -regop read 50040020 1 # LPSYS WSR -regop read 40040020 1 # HPSYS WSR ``` - +regop unlock 0000 regop read 50040020 1 # LPSYS WSR regop read 40040020 1 # +HPSYS WSR +``` - You can also use Jlink/SifliUsartServer to read registers or print via logs: - -```c -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // hcpu -rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); // lcpu ``` - +rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_hpsys_aon->WSR, hwp_hpsys_aon->WER); // +hcpu rt_kprintf("wsr:0x%x,wer:0x%x,\n", hwp_lpsys_aon->WSR, hwp_lpsys_aon->WER); +// lcpu +``` Common issue: wake‑up pin level misconfigured (e.g., configured for low‑level wake‑up but the pin remains low). 6) Ensure data sent to the other core has been consumed: @@ -803,7 +848,7 @@ Common issue: wake‑up pin level misconfigured (e.g., configured for low‑leve Figure 4.9 Non‑empty ring buffer ``` -```{figure} ../../assets/low_power_english21.png +```{figure} ../../assets/low_power21.png :align: center Figure 4.10 Empty ring buffer ``` @@ -811,22 +856,22 @@ Figure 4.10 Empty ring buffer Print activation queue index: ```c -for (i = 0; i < IPC_LOGICAL_QUEUE_NUM; i++) +for (i = 0; i < IPC_LOGICAL_QUEUE_NUM; i++) { if (ipc_ctx.queues[i].active == true) { - if (ipc_ctx.queues[i].rx_ring_buffer && ipc_ctx.queues[i].tx_ring_buffer) + if (ipc_ctx.queues[i].rx_ring_buffer && ipc_ctx.queues[i].tx_ring_buffer) { LOG_I("ipc_ctx.queues[%d].tx read_idx_mirror=0x%x, write_idx_mirror=0x%x\n", i, - ipc_ctx.queues[i].tx_ring_buffer->read_idx_mirror, - ipc_ctx.queues[i].tx_ring_buffer->write_idx_mirror); + ipc_ctx.queues[i].tx_ring_buffer->read_idx_mirror, + ipc_ctx.queues[i].tx_ring_buffer->write_idx_mirror); } } } ``` -```{figure} ../../assets/low_power_english22.png +```{figure} ../../assets/low_power22.png :align: center Figure 4.11 Example: LCPU data service disabled causing missing channel ``` @@ -837,86 +882,95 @@ Figure 4.11 Example: LCPU data service disabled causing missing channel ### 5.1 Standby Leakage Analysis When both HPSYS and LPSYS are in sleep, focus on system power optimization: -- Remove detachable components (display, sensors, charging IC) and measure the minimum system current. -- Misconfigured software IO levels can cause voltage differences/floating leakage. +- Remove detachable components (display, sensors, charging IC) and measure the + minimum system current. +- Misconfigured software IO levels can cause voltage differences/floating + leakage. - On‑chip PSRAM/Flash and external NAND/Flash/eMMC may not have entered sleep. -If hardware allows measuring current per rail, identify the leaking rail (`VSYS/ VLDO2/ VLDO3/ VDD_SIP/ VDDIOA`) to narrow the scope. +If hardware allows measuring current per rail, identify the leaking rail (`VSYS/ +VLDO2/ VLDO3/ VDD_SIP/ VDDIOA`) to narrow the scope. #### 5.1.1 Peripheral Leakage Common causes: 1) Board‑level components are not powered off. -2) Board‑level components are powered off, but chip pin configuration causes back‑powering from the chip pins. +2) Board‑level components are powered off, but chip pin configuration causes + back‑powering from the chip pins. -For case 2), avoid: driving high or enabling pull‑up on pins connected to powered‑off devices. Recommended pin settings for common peripherals in active/sleep are below (no change needed if external circuits stay powered; switch to low‑power configuration if external circuits are powered off). +For case 2), avoid: driving high or enabling pull‑up on pins connected to +powered‑off devices. Recommended pin settings for common peripherals in +active/sleep are below (no change needed if external circuits stay powered; +switch to low‑power configuration if external circuits are powered off). Table 5‑1: Recommended Pin Settings -| Peripheral| Pin | Dir | Active | Sleep (external on) | Sleep (external off) | -|-----------|----------------|------|------------|-------------------------|----------------------------| -| PSRAM | PSRAM_CLK | O | Digital out| Digital out | GPIO mode output low | -| PSRAM | PSRAM_CLKB | O | Digital out| Digital out | GPIO mode output low | -| PSRAM | PSRAM_CS | O | Digital out| Digital out | GPIO mode output low | -| PSRAM | PSRAM_DM0 | O | Digital out| Digital out | GPIO mode output low | -| PSRAM | PSRAM_DM1 | O | Digital out| Digital out | GPIO mode output low | -| PSRAM | PSRAM_DQS0 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| PSRAM | PSRAM_DQS1 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| PSRAM | PSRAM_DQx | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| QSPI | QSPIx_CLK | O | Digital out| Digital out | GPIO mode output low | -| QSPI | QSPIx_CS | O | Digital out| Digital out | GPIO mode output low | -| QSPI | QSPIx_DIO0 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| QSPI | QSPIx_DIO1 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| QSPI | QSPIx_DIO2 | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| QSPI | QSPIx_DIO3 | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| QSPI | QSPIx_DIO4 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| QSPI | QSPIx_DIO5 | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| QSPI | QSPIx_DIO6 | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| QSPI | QSPIx_DIO7 | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| USART | USARTx_RXD | I | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| USART | USARTx_TXD | O | Digital out| Digital out | Digital out | -| USART | USARTx_CTS | I | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| USART | USARTx_RTS | O | Digital out| Digital out | Digital out | -| I2C | I2Cx_SCL | I/O | Digital in | Digital in | Digital in‑pd | -| I2C | I2Cx_SDA | I/O | Digital in | Digital in | Digital in‑pd | -| SPI M | SPIx_CLK | O | Digital out| Digital out | GPIO mode output low | -| SPI M | SPIx_CS | O | Digital out| Digital out | GPIO mode output low | -| SPI M | SPIx_DI | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| SPI M | SPIx_DO | O | Digital out| Digital out | GPIO mode output low | -| SPI M | SPIx_DIO | I/O | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| LCDC SPI | LCDCx_SPI_CS | O | Digital out| Digital out | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_CLK | O | Digital out| Digital out | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_DIO0 | I/O | Digital in‑pd | Digital in‑pd | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_DIO1 | O | Digital out| Digital out | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_DIO2 | O | Digital out| Digital out | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_DIO3 | O | Digital out| Digital out | GPIO mode input pull‑down | -| LCDC SPI | LCDCx_SPI_RSTB | O | Digital out| Digital out | GPIO output low | -| LCDC SPI | LCDCx_SPI_TE | I | Digital in | Digital in | GPIO mode input pull‑down | -| SDIO | SD_CLK | O | Digital out| Digital out | GPIO mode output low | -| SDIO | SD_CMD | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| SDIO | SD_DIOx | I/O | Digital in‑pu | Digital in‑pu | Digital in‑pd | -| I2S | I2S1_BCK | O | Digital out| Digital out | GPIO mode output low | -| I2S | I2S1_LRCK | O | Digital out| Digital out | GPIO mode output low | -| I2S | I2S1_SDI | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| I2S | I2S2_BCK | O | Digital out| Digital out | GPIO mode output low | -| I2S | I2S2_LRCK | O | Digital out| Digital out | GPIO mode output low | -| I2S | I2S2_SDI | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| I2S | I2S2_SDO | O | Digital out| Digital out | GPIO mode output low | -| PDM | PDM_CLK | O | Digital out| Digital out | GPIO mode output low | -| PDM | PDM_DATA | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| GPTIM Out | GPTIMx_CHx | O | Digital out| Digital out | GPIO mode output low | -| GPTIM In | GPTIMx_CHx | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| GPTIM | GPTIMx_ETR | I | Digital in‑pd | Digital in‑pd | Digital in‑pd | -| GPIO In | GPIO | I | Digital in | Digital in | GPIO output low or digital in‑pd | -| GPIO Out | GPIO | O | Digital out| Digital out | GPIO mode output low | +| Peripheral | Pin | Dir | Active | Sleep (external on) | Sleep (external off) | +| ----------- | -------------- | --- | ---------------------------- | ---------------------------- | -------------------------------- | +| PSRAM | PSRAM_CLK | O | Digital output | Digital output | GPIO mode low output | +| PSRAM | PSRAM_CLKB | O | Digital output | Digital output | GPIO mode low output | +| PSRAM | PSRAM_CS | O | Digital output | Digital output | GPIO mode low output | +| PSRAM | PSRAM_DM0 | O | Digital output | Digital output | GPIO mode low output | +| PSRAM | PSRAM_DM1 | O | Digital output | Digital output | GPIO mode low output | +| PSRAM | PSRAM_DQS0 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| PSRAM | PSRAM_DQS1 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| PSRAM | PSRAM_DQx | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| QSPI | QSPIx_CLK | O | Digital output | Digital output | GPIO mode low output | +| QSPI | QSPIx_CS | O | Digital output | Digital output | GPIO mode low output | +| QSPI | QSPIx_DIO0 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| QSPI | QSPIx_DIO1 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| QSPI | QSPIx_DIO2 | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| QSPI | QSPIx_DIO3 | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| QSPI | QSPIx_DIO4 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| QSPI | QSPIx_DIO5 | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| QSPI | QSPIx_DIO6 | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| QSPI | QSPIx_DIO7 | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| USART | USARTx_RXD | I | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| USART | USARTx_TXD | O | Digital output | Digital output | Digital output | +| USART | USARTx_CTS | I | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| USART | USARTx_RTS | O | Digital output | Digital output | Digital output | +| I2C | I2Cx_SCL | I/O | Digital input | Digital input | Digital input with pull-down | +| I2C | I2Cx_SDA | I/O | Digital input | Digital input | Digital input with pull-down | +| SPI M | SPIx_CLK | O | Digital output | Digital output | GPIO mode low output | +| SPI M | SPIx_CS | O | Digital output | Digital output | GPIO mode low output | +| SPI M | SPIx_DI | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| SPI M | SPIx_DO | O | Digital output | Digital output | GPIO mode low output | +| SPI M | SPIx_DIO | I/O | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| LCDC SPI | LCDCx_SPI_CS | O | Digital output | Digital output | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_CLK | O | Digital output | Digital output | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_DIO0 | I/O | Digital input with pull-down | Digital input with pull-down | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_DIO1 | O | Digital output | Digital output | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_DIO2 | O | Digital output | Digital output | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_DIO3 | O | Digital output | Digital output | GPIO Input with Pull-down | +| LCDC SPI | LCDCx_SPI_RSTB | O | Digital output | Digital output | GPIO output low | +| LCDC SPI | LCDCx_SPI_TE | I | Digital input | Digital input | GPIO Input with Pull-down | +| SDIO | SD_CLK | O | Digital output | Digital output | GPIO mode low output | +| SDIO | SD_CMD | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| SDIO | SD_DIOx | I/O | Digital input with pull-up | Digital input with pull-up | Digital input with pull-down | +| I2S | I2S1_BCK | O | Digital output | Digital output | GPIO mode low output | +| I2S | I2S1_LRCK | O | Digital output | Digital output | GPIO mode low output | +| I2S | I2S1_SDI | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| I2S | I2S2_BCK | O | Digital output | Digital output | GPIO mode low output | +| I2S | I2S2_LRCK | O | Digital output | Digital output | GPIO mode low output | +| I2S | I2S2_SDI | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| I2S | I2S2_SDO | O | Digital output | Digital output | GPIO mode low output | +| PDM | PDM_CLK | O | Digital output | Digital output | GPIO mode low output | +| PDM | PDM_DATA | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| GPTIM Out | GPTIMx_CHx | O | Digital output | Digital output | GPIO mode low output | +| GPTIM In | GPTIMx_CHx | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| GPTIM | GPTIMx_ETR | I | Digital input with pull-down | Digital input with pull-down | Digital input with pull-down | +| GPIO Input | GPIO | I | Digital input | Digital input | GPIO output low or digital in‑pd | +| GPIO Output | GPIO | O | Digital output | Digital output | GPIO mode low output | #### 5.1.2 On‑Chip IO Internal Leakage Common patterns (see FAQ 8.7/8.8): -1) Input pins floating (peer device powered off equals floating), causing undefined levels. +1) Input pins floating (peer device powered off equals floating), causing + undefined levels. 2) IO output levels mismatch with internal/external pull‑ups or pull‑downs. -Below shows the pin internal structure (functional blocks: DS/OE/O/IE/PE/PS, etc.). +Below shows the pin internal structure (functional blocks: DS/OE/O/IE/PE/PS, +etc.). ```{figure} ../../assets/low_power23.png :align: center @@ -1020,7 +1074,8 @@ HAL_RAM_RET_CODE_SECT(BSP_PowerUpCustom, void BSP_PowerUpCustom(bool is_deep_sle } ``` -Note: When running XIP from NOR flash, code controlling NOR sleep/wake must be placed in RAM (`HAL_RAM_RET_CODE_SECT`). +Note: When running XIP from NOR flash, code controlling NOR sleep/wake must be +placed in RAM (`HAL_RAM_RET_CODE_SECT`). ### 5.2 Code Implementation ```{only} SF32LB55X @@ -1031,13 +1086,17 @@ Pin configuration code resides in the board’s `pinmux.c` and `bsp_power.c`. Im ``` #### 5.2.1 Pin Configuration in Active State -`BSP_PIN_Init` runs once on cold boot and after STANDBY wake‑up. Set functional modes and IO directions for active state here. For example, configure `PB46` as `USART3_RX` with digital input pull‑up: +`BSP_PIN_Init` runs once on cold boot and after STANDBY wake‑up. Set functional +modes and IO directions for active state here. For example, configure `PB46` as +`USART3_RX` with digital input pull‑up: ```c HAL_PIN_Set(PAD_PB46, USART3_RXD, PIN_PULLUP, 0); ``` -For output IOs, configuring only `PIN_NOPULL` without setting a GPIO output leaves the pin in default input state, potentially causing floating leakage. Set an explicit output level, e.g.: +For output IOs, configuring only `PIN_NOPULL` without setting a GPIO output +leaves the pin in default input state, potentially causing floating leakage. Set +an explicit output level, e.g.: ```c HAL_PIN_Set(PAD_PA35, GPIO_A35, PIN_NOPULL, 1); @@ -1053,28 +1112,44 @@ In `bsp_power.c`, implement the following virtual functions to dynamically switc ``` Table 5‑2: Pin Configuration APIs for Sleep State -| Function | Description | -|--------------------|--------------------------------------------| -| BSP_IO_Power_Down | Executed before entering sleep | -| BSP_Power_Up | Executed after wake‑up (STANDBY after `BSP_PIN_Init`) | -| BSP_TP_PowerDown | Executed after screen off | -| BSP_TP_PowerUp | Executed before screen on | -| BSP_LCD_PowerDown | Executed after screen off | -| BSP_LCD_PowerUp | Executed before screen on | - -If board‑level power control should align with sleep, you can power off components and adjust pins in `BSP_IO_Power_Down`, then reverse in `BSP_Power_Up`. This is coarse‑grained: e.g., after screen‑off, HPSYS may enter sleep later, and keeping LCD powered until then wastes energy; or when HPSYS wakes to run tasks without needing the screen, powering the screen in `BSP_Power_Up` also wastes energy. To refine control, handle display/touch power‑down in `BSP_TP_PowerDown` and `BSP_LCD_PowerDown` right after screen‑off, and call them again in `BSP_Power_Up` to keep pins in power‑down state until screen‑on. If screen‑on conditions are met, the system calls `BSP_TP_PowerUp`/`BSP_LCD_PowerUp` before lighting the screen to restore power and active pin settings. +| Function | Description | +| ----------------- | ----------------------------------------------------- | +| BSP_IO_Power_Down | Executed before entering sleep | +| BSP_Power_Up | Executed after wake‑up (STANDBY after `BSP_PIN_Init`) | +| BSP_TP_PowerDown | Execute after screen-off | +| BSP_TP_PowerUp | Execute before screen-on | +| BSP_LCD_PowerDown | Execute after screen-off | +| BSP_LCD_PowerUp | Execute before screen-on | + +If board‑level power control should align with sleep, you can power off +components and adjust pins in `BSP_IO_Power_Down`, then reverse in +`BSP_Power_Up`. This is coarse‑grained: e.g., after screen‑off, HPSYS may enter +sleep later, and keeping LCD powered until then wastes energy; or when HPSYS +wakes to run tasks without needing the screen, powering the screen in +`BSP_Power_Up` also wastes energy. To refine control, handle display/touch +power‑down in `BSP_TP_PowerDown` and `BSP_LCD_PowerDown` right after screen‑off, +and call them again in `BSP_Power_Up` to keep pins in power‑down state until +screen‑on. If screen‑on conditions are met, the system calls +`BSP_TP_PowerUp`/`BSP_LCD_PowerUp` before lighting the screen to restore power +and active pin settings. Call order and coreid notes: -- `void BSP_IO_Power_Down(int coreid, bool is_deep_sleep)` is called twice before HCPU sleeps: - - First with `coreid=CORE_ID_LCPU`: before revoking LCPU wake requests, to close pins of LCPU peripherals used by HCPU. After revocation LCPU may enter low‑power and HCPU cannot access LCPU domain registers. - - Second with `coreid=CORE_ID_HCPU`: right before HCPU sleep, to close pins used by HCPU itself. -- In the LCPU project, this function is called once before LCPU sleeps to close pins used by LCPU. -- Low‑power pin configurations differ per peripheral. Generally disable pull‑ups/downs to avoid leakage loops; output levels depend on board design and external device power state. +- `void BSP_IO_Power_Down(int coreid, bool is_deep_sleep)` is called twice + before HCPU sleeps: + - First with `coreid=CORE_ID_LCPU`: before revoking LCPU wake requests, to + close pins of LCPU peripherals used by HCPU. After revocation LCPU may + enter low‑power and HCPU cannot access LCPU domain registers. + - Second with `coreid=CORE_ID_HCPU`: right before HCPU sleep, to close pins + used by HCPU itself. +- In the LCPU project, this function is called once before LCPU sleeps to close + pins used by LCPU. +- Low‑power pin configurations differ per peripheral. Generally disable + pull‑ups/downs to avoid leakage loops; output levels depend on board design + and external device power state. ### 5.3 Sleep Flow ```{only} SF32LB56X - • HCPU sleep/wake (simplified): `rt_thread_idle_entry → rt_system_power_manager → _pm_enter_sleep → pm->ops->sleep(pm, mode) → sifli_sleep →` 日志 `[pm]S:4,11620140` → 设备 `RT_DEVICE_CTRL_SUSPEND` → `sifli_standby_handler → BSP_IO_Power_Down → WFI` 进入 standby → 定时器/IO 唤醒 → `SystemInitFromStandby → HAL_Init → BSP_IO_Init → restore_context`(PC 回到 WFI 后)→ `BSP_Power_Up →` 设备 `RT_DEVICE_CTRL_RESUME` → 日志 `[pm]W:11620520`、`[pm]WSR:0x80`。 @@ -1107,7 +1182,9 @@ Enter Hibernate: call `HAL_PMU_EnterHibernate()`. Before sleep, configure PMU wa ```{only} SF32LB56X or SF32LB58X Enter Hibernate: call `HAL_PMU_EnterHibernate()`. Before sleep, configure PMU wake‑up pins and levels for Hibernate. For 56/58 series, PMU pull‑up/down is available in Hibernate; use `HAL_PIN_Set` to set wake‑up pin pulls. ``` -Hibernate wake‑up: press the wake‑up pin to wake. Use `PM_HIBERNATE_BOOT == SystemPowerOnModeGet()` to determine hibernate boot, and combine with button duration to decide whether to power on. +Hibernate wake‑up: press the wake‑up pin to wake. Use `PM_HIBERNATE_BOOT == +SystemPowerOnModeGet()` to determine hibernate boot, and combine with button +duration to decide whether to power on. #### 5.4.2 Hibernate Power‑Off Configuration @@ -1125,13 +1202,12 @@ Before entering Hibernate: – 52 series: Three internal LDOs (`PMU_PERI_LDO_1V8/PMU_PERI_LDO2_3V3/PMU_PERI_LDO3_3V3`); consider turning them off per hardware. Example: - -```c -rt_kprintf("SF32LB52X entry_hibernate\n"); -HAL_PMU_SelectWakeupPin(0, HAL_HPAON_QueryWakeupPin(hwp_gpio1, BSP_KEY1_PIN)); // select PA34 → wake_pin0 -HAL_PMU_EnablePinWakeup(0, AON_PIN_MODE_HIGH); // enable wake_pin0 -hwp_pmuc->WKUP_CNT = 0x50005; // 31-16bit: PIN1 wake CNT, 15-0bit: PIN0 wake CNT -rt_kprintf("SF32LB52X CR:0x%x,WER:0x%x\n", hwp_pmuc->CR, hwp_pmuc->WER); +``` +rt_kprintf("SF32LB52X entry_hibernate\n"); HAL_PMU_SelectWakeupPin(0, +HAL_HPAON_QueryWakeupPin(hwp_gpio1, BSP_KEY1_PIN)); // select PA34 → wake_pin0 +HAL_PMU_EnablePinWakeup(0, AON_PIN_MODE_HIGH); // enable wake_pin0 +hwp_pmuc->WKUP_CNT = 0x50005; // Bits 31-16: PIN1 wake CNT; Bits 15-0: PIN0 wake +CNT rt_kprintf("SF32LB52X CR:0x%x,WER:0x%x\n", hwp_pmuc->CR, hwp_pmuc->WER); HAL_PIN_Set(PAD_PA24, GPIO_A24, PIN_PULLDOWN, 1); // #WKUP_PIN0 HAL_PIN_Set(PAD_PA25, GPIO_A25, PIN_PULLDOWN, 1); // #WKUP_PIN1 @@ -1150,13 +1226,10 @@ HAL_PIN_Set(PAD_PA42, GPIO_A42, PIN_PULLDOWN, 1); // #WKUP_PIN18 HAL_PIN_Set(PAD_PA43, GPIO_A43, PIN_PULLDOWN, 1); // #WKUP_PIN19 HAL_PIN_Set(PAD_PA44, GPIO_A44, PIN_PULLDOWN, 1); // #WKUP_PIN20 -rt_hw_interrupt_disable(); -HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO2_3V3, false, false); -HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO3_3V3, false, false); -HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO_1V8, false, false); -HAL_PMU_EnterHibernate(); +rt_hw_interrupt_disable(); HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO2_3V3, false, +false); HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO3_3V3, false, false); +HAL_PMU_ConfigPeriLdo(PMU_PERI_LDO_1V8, false, false); HAL_PMU_EnterHibernate(); ``` - Notes: ```{only} SF32LB55X - 55 series MCU: Each wake‑up pin can be enabled individually with `HAL_PMU_EnablePinWakeup`. diff --git a/docs/source/en/app_note/memory_usage.md b/docs/source/en/app_note/memory_usage.md index 63e9f085c..3030141b0 100644 --- a/docs/source/en/app_note/memory_usage.md +++ b/docs/source/en/app_note/memory_usage.md @@ -4,128 +4,151 @@ ### HCPU Memory address space -|name |starting address| end address| size (bytes)| describe -|-----------------|----------------|----------------|------------|-------- -|HPSYS ROM | 0x00000000 | 0x0000FFFF | 64*1024 | | -|HPSYS ITCM RAM | 0x00010000 | 0x0001FFFF | 64*1024 | | -|HPSYS Retention RAM | 0x00020000 | 0x0002FFFF | 64*1024 | It can be powered off when it is in standby mode with low power consumption| -|HPSYS SRAM | 0x20000000 | 0x200FFFFF | 1024*1024 | | -|LPSYS ROM | 0x0B000000 | 0x0B05FFFF | 384*1024 | | -|LPSYS ITCM RAM | 0x0B0FC000 | 0x0B0FFFFF | 16*1024 | | -|LPSYS DTCM RAM | 0x2B0FC000 | 0x2B0FFFFF | 16*1024 | | -|LPSYS SRAM | 0x20100000 | 0x20137FFF | 224*1024 | | -|QSPI1 | 0x10000000 | 0x11FFFFFF | |The EVB has a capacity of 4MByte | -|QSPI2 | 0x64000000 | 0x67FFFFFF | |The EVB has a capacity of 32MByte| -|QSPI3 | 0x68000000 | 0x68FFFFFF | |EVB ununited| -|QSPI4 | 0x12000000 | 0x13FFFFFF | |LCPU is optional flash memory,EVB ununited| -|PSRAM-OPI | 0x60000000 | 0x61FFFFFF | |The EVB has a capacity of 4MByte | +| name | starting address | end address | size (bytes) | describe | +| ------------------- | ---------------- | ----------- | ------------ | --------------------------------------------------------------------------- | +| HPSYS ROM | 0x00000000 | 0x0000FFFF | 64*1024 | | +| HPSYS ITCM RAM | 0x00010000 | 0x0001FFFF | 64*1024 | | +| HPSYS Retention RAM | 0x00020000 | 0x0002FFFF | 64*1024 | It can be powered off when it is in standby mode with low power consumption | +| HPSYS SRAM | 0x20000000 | 0x200FFFFF | 1024*1024 | | +| LPSYS ROM | 0x0B000000 | 0x0B05FFFF | 384*1024 | | +| LPSYS ITCM RAM | 0x0B0FC000 | 0x0B0FFFFF | 16*1024 | | +| LPSYS DTCM RAM | 0x2B0FC000 | 0x2B0FFFFF | 16*1024 | | +| LPSYS SRAM | 0x20100000 | 0x20137FFF | 224*1024 | | +| QSPI1 | 0x10000000 | 0x11FFFFFF | | The EVB capacity is 4 MBytes. | +| QSPI2 | 0x64000000 | 0x67FFFFFF | | The EVB has a capacity of 32MByte | +| QSPI3 | 0x68000000 | 0x68FFFFFF | | EVB ununited | +| QSPI4 | 0x12000000 | 0x13FFFFFF | | LCPU is optional flash memory,EVB ununited | +| PSRAM-OPI | 0x60000000 | 0x61FFFFFF | | The EVB capacity is 4 MBytes. | ```{note} The first 128KB of HPSYS SRAM is DTCM, which is faster than the subsequent address space access ``` HCPU is used to access the address translation interface of LPSYS Memory -- LCPU SRAM address conversion: LCPU_ADDR_2_HCPU_ADDR, for example, call LCPU_ADDR_2_HCPU_ADDR (0x20100000) to get 0x20100000 -- LCPU ROM address conversion: LCPU_ROM_ADDR_2_HCPU_ADDR, for example, call LCPU_ROM_ADDR_2_HCPU_ADDR (0x00000000) to get 0x0B000000 -- LCPU ITCM address conversion: LCPU_ITCM_ADDR_2_HCPU_ADDR, for example, call LCPU_ITCM_ADDR_2_HCPU_ADDR (0x000FC000) to get 0x0B0FC000 -- LCPU DTCM address conversion: LCPU_DTCM_ADDR_2_HCPU_ADDR, for example, call LCPU_DTCM_ADDR_2_HCPU_ADDR (0x200FC000) to get 0x2B0FC000 +- LCPU SRAM address conversion: LCPU_ADDR_2_HCPU_ADDR, for example, call + LCPU_ADDR_2_HCPU_ADDR (0x20100000) to get 0x20100000 +- LCPU ROM address conversion: LCPU_ROM_ADDR_2_HCPU_ADDR, for example, call + LCPU_ROM_ADDR_2_HCPU_ADDR (0x00000000) to get 0x0B000000 +- LCPU ITCM address conversion: LCPU_ITCM_ADDR_2_HCPU_ADDR, for example, call + LCPU_ITCM_ADDR_2_HCPU_ADDR (0x000FC000) to get 0x0B0FC000 +- LCPU DTCM address conversion: LCPU_DTCM_ADDR_2_HCPU_ADDR, for example, call + LCPU_DTCM_ADDR_2_HCPU_ADDR (0x200FC000) to get 0x2B0FC000 -HCPU code can be executed on QSPI1/QSPI2/QSPI3 by XIP, or it can run on HPSYS ITCM/SRAM/Retention RAM +HCPU code can be executed on QSPI1/QSPI2/QSPI3 by XIP, or it can run on HPSYS +ITCM/SRAM/Retention RAM ### LCPU Memory address space -| Name | S-Bus start address | S-Bus end address | C-Bus start address | C-Bus end address | Size (bytes) | Description -|-----------------|----------------|----------------|----------------|----------------|------------|------ -|HPSYS SRAM | 0x2A000000 | 0x2A0FFFFF | | | 1024*1024 | | -|LPSYS ROM | | | 0x00000000 | 0x0005FFFF | 384*1024 | | -|LPSYS ITCM RAM | | | 0x000FC000 | 0x000FFFFF | 16*1024 | | -|LPSYS DTCM RAM | 0x200FC000 | 0x200FFFFF | | | 16*1024 | | -|LPSYS SRAM | 0x20100000 | 0x20137FFF | 0x00100000 | 0x00137FFF | 224*1024 | | -|QSPI4 | | | 0x12000000 | 0x13FFFFFF | |The LCPU is optional flash memory, and the EVB is not connected | - - -In order to improve performance, in addition to using the 0x20100000~0x20137FFF address range to access LPSYS SRAM, you can also use the 0x00100000~0x00137FFF address range to access, -The former uses S-Bus to access SRAM, and the latter uses C-Bus to access SRAM. They both access the same physical SRAM. -For example, the code can be allocated to an address starting at 0x00100000, and the remaining space in the SRAM can be allocated to the data segment using the S-Bus address space, -In this way, fetching and fetching can be parallelized to improve the execution efficiency of the code. -It is also possible to combine ITCM and SRAM. For example, if the code starts at 0x000FC000, the code that exceeds 16K bytes will be placed in the area starting at SRAM address 0x00100000, and the remaining SRAM space will still be accessed using the S-Bus address space. -See sections 4 and 5 for specific examples. +| name | S-Bus start address | S-Bus end address | C-Bus start address | C-Bus end address | size (bytes) | describe | +| -------------- | ------------------- | ----------------- | ------------------- | ----------------- | ------------ | ------------------------------------------ | +| HPSYS SRAM | 0x2A000000 | 0x2A0FFFFF | | | 1024*1024 | | +| LPSYS ROM | | | 0x00000000 | 0x0005FFFF | 384*1024 | | +| LPSYS ITCM RAM | | | 0x000FC000 | 0x000FFFFF | 16*1024 | | +| LPSYS DTCM RAM | 0x200FC000 | 0x200FFFFF | | | 16*1024 | | +| LPSYS SRAM | 0x20100000 | 0x20137FFF | 0x00100000 | 0x00137FFF | 224*1024 | | +| QSPI4 | | | 0x12000000 | 0x13FFFFFF | | LCPU is optional flash memory,EVB ununited | + + +In order to improve performance, in addition to using the 0x20100000~0x20137FFF +address range to access LPSYS SRAM, you can also use the 0x00100000~0x00137FFF +address range to access, The former uses S-Bus to access SRAM, and the latter +uses C-Bus to access SRAM. They both access the same physical SRAM. For example, +the code can be allocated to an address starting at 0x00100000, and the +remaining space in the SRAM can be allocated to the data segment using the S-Bus +address space, In this way, fetching and fetching can be parallelized to improve +the execution efficiency of the code. It is also possible to combine ITCM and +SRAM. For example, if the code starts at 0x000FC000, the code that exceeds 16K +bytes will be placed in the area starting at SRAM address 0x00100000, and the +remaining SRAM space will still be accessed using the S-Bus address space. See +sections 4 and 5 for specific examples. The LCPU is used as a conversion interface for accessing HPSYS SRAM addresses, -- HCPU_ADDR_2_LCPU_ADDR, for example, call HCPU_ADDR_2_LCPU_ADDR(0x20000000) to get 0x2A000000 +- HCPU_ADDR_2_LCPU_ADDR, for example, call HCPU_ADDR_2_LCPU_ADDR(0x20000000) to + get 0x2A000000 -The LCPU code can run on the LPSYS' ITCM/DTCM/SRAM and needs to be moved from the user program on the HCPU to the corresponding address space +The LCPU code can run on the LPSYS' ITCM/DTCM/SRAM and needs to be moved from +the user program on the HCPU to the corresponding address space ### QSPI1 address space notes -The Bootloader uses 12kbyte starting with 0x10000000 as the Flash configuration table. The default Flash configuration table specifies the Flash1 address planning as follows, and the user program starting address is 0x10020000. -If a custom Flash configuration table is used, it must be ensured that the first 12kbyte is not used and that the Flash configuration table is not rewritten. Other address Spaces can be used at will. - -| Name | Starting address | Ending address | Size (bytes) | Description -|-----------------|----------------|----------------|------------|-------- -|Flash configuration table | 0x10000000 | 0x10004FFF | 20*1024 | | -|Calibration Table | 0x10005000 | 0x10006FFF | 8*1024 | | -|Reserved | 0x10007000 | 0x1000FFFF | 36*1024 | | -|bootrom patch | 0x10010000 | 0x1001FFFF | 64*1024 | | -|User Code | 0x10020000 | | | | +The Bootloader uses 12kbyte starting with 0x10000000 as the Flash configuration +table. The default Flash configuration table specifies the Flash1 address +planning as follows, and the user program starting address is 0x10020000. If a +custom Flash configuration table is used, it must be ensured that the first +12kbyte is not used and that the Flash configuration table is not rewritten. +Other address Spaces can be used at will. + +| name | starting address | end address | size (bytes) | describe | +| ------------------------- | ---------------- | ----------- | ------------ | -------- | +| Flash configuration table | 0x10000000 | 0x10004FFF | 20*1024 | | +| Calibration Table | 0x10005000 | 0x10006FFF | 8*1024 | | +| Reserved | 0x10007000 | 0x1000FFFF | 36*1024 | | +| BootROM Patch | 0x10010000 | 0x1001FFFF | 64*1024 | | +| User Code | 0x10020000 | | | | ### HPSYS SRAM address space notes -The Bootloader uses the RAM address space shown in the following table. When the Bootloader is used to boot the user program to execute in RAM, the RAM program cannot use the address 0x20040000 to avoid being rewritten by the bootloader after moving. -This restriction does not apply if the user program is executed on Flash. +The Bootloader uses the RAM address space shown in the following table. When the +Bootloader is used to boot the user program to execute in RAM, the RAM program +cannot use the address 0x20040000 to avoid being rewritten by the bootloader +after moving. This restriction does not apply if the user program is executed on +Flash. bootloader RAM address space -| Name | Starting address | Ending address | Size (bytes) | Description -|-----------------|----------------|----------------|------------|-------------- -|DATA | 0x20040000 | 0x2004FFFF | 64*1024 | bootrom data | -|PATCH CODE | 0x20050000 | 0x2005FFFF | 64*1024 | Patch code | -|PATCH DATA | 0x20060000 | 0x2006FFFF | 64*1024 | Patch data | +| name | starting address | end address | size (bytes) | describe | +| ---------- | ---------------- | ----------- | ------------ | ------------ | +| DATA | 0x20040000 | 0x2004FFFF | 64*1024 | bootrom data | +| PATCH CODE | 0x20050000 | 0x2005FFFF | 64*1024 | Patch code | +| PATCH DATA | 0x20060000 | 0x2006FFFF | 64*1024 | Patch data | ## 2. HPSYS Memory performance comparison -| Name | Frequency (MHz) | Description -|---------------|--------------|------- -|HCLK | 240 | | -|PSRAM-OPI | 120 | DDR | -|FLASH1 | 96 | | -|FLASH2 | 80 | | - -Generally speaking, DMA has the highest efficiency in accessing SRAM, and eDMA has the highest efficiency in accessing PSRAM/FLASH. The specific throughput performance is shown in the following table. In this table, memcpy cannot use microlib, FLASH1 and FLASH2 enable CACHE, and PSRAM does not enable CACHE. - - -| Source | Purpose | memcpy(MB/s) | eDMA(MB/s) | DMA(MB/s) -|----------|------------|--------------|------------|------------- -| SRAM | SRAM | 405.54 | 430.17 | 446.35 | -| PSRAM | SRAM | 43.34 | 125.54 | 53.23 | -| FLASH1 | SRAM | 46.41 | 43.17 | 25.50 | -| FLASH2 | SRAM | 36.30 | 36.13 | 21.24 | -| SRAM | PSRAM | 48.05 | 187.01 | 47.70 | -| PSRAM | PSRAM | 20.99 | 76.72 | 12.96 | -| FLASH1 | PSRAM | 26.84 | 42.97 | 12.51 | -| FLASH2 | PSRAM | 24.94 | 36.14 | 21.25 | +| name | Frequency (MHz) | Description | +| --------- | --------------- | ----------- | +| HCLK | 240 | | +| PSRAM-OPI | 120 | DDR | +| FLASH1 | 96 | | +| FLASH2 | 80 | | + +Generally speaking, DMA has the highest efficiency in accessing SRAM, and eDMA +has the highest efficiency in accessing PSRAM/FLASH. The specific throughput +performance is shown in the following table. In this table, memcpy cannot use +microlib, FLASH1 and FLASH2 enable CACHE, and PSRAM does not enable CACHE. + + +| Source | Purpose | memcpy (MB/s) | eDMA (MB/s) | DMA (MB/s) | +| ------ | ------- | ------------- | ----------- | ---------- | +| SRAM | SRAM | 405.54 | 430.17 | 446.35 | +| PSRAM | SRAM | 43.34 | 125.54 | 53.23 | +| FLASH1 | SRAM | 46.41 | 43.17 | 25.50 | +| FLASH2 | SRAM | 36.30 | 36.13 | 21.24 | +| SRAM | PSRAM | 48.05 | 187.01 | 47.70 | +| PSRAM | PSRAM | 20.99 | 76.72 | 12.96 | +| FLASH1 | PSRAM | 26.84 | 42.97 | 12.51 | +| FLASH2 | PSRAM | 24.94 | 36.14 | 21.25 | ## 3. HCPU EPIC performance -| Name | Frequency (MHz) | Description -|---------------|--------------|------- -|HCLK | 240 | | -|PSRAM-OPI | 120 | DDR | -|FLASH1 | 96 | | -|FLASH2 | 80 | | +| name | Frequency (MHz) | Description | +| --------- | --------------- | ----------- | +| HCLK | 240 | | +| PSRAM-OPI | 120 | DDR | +| FLASH1 | 96 | | +| FLASH2 | 80 | | Unless otherwise specified, the color format is RGB565 ### Alpha mix -| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) -|----------|------------|--------------------|------------------ -| SRAM | SRAM | 1.41 | 170.16 | -| PSRAM | SRAM | 4.80 | 50.05 | -| FLASH1 | SRAM | 14.93 | 16.07 | -| FLASH2 | SRAM | 17.83 | 13.46 | -| SRAM | PSRAM | 2.54 | 94.51 | -| PSRAM | PSRAM | 7.40 | 32.46 | -| FLASH1 | PSRAM | 14.90 | 16.11 | -| FLASH2 | PSRAM | 17.83 | 13.46 | +| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) | +| ------ | ------ | -------------------------- | ---------------------- | +| SRAM | SRAM | 1.41 | 170.16 | +| PSRAM | SRAM | 4.80 | 50.05 | +| FLASH1 | SRAM | 14.93 | 16.07 | +| FLASH2 | SRAM | 17.83 | 13.46 | +| SRAM | PSRAM | 2.54 | 94.51 | +| PSRAM | PSRAM | 7.40 | 32.46 | +| FLASH1 | PSRAM | 14.90 | 16.11 | +| FLASH2 | PSRAM | 17.83 | 13.46 | ```{note} The above table shows the performance of using HAL_EPIC_BlendStart/HAL_EPIC_BlendStart_IT interface. If you use HAL_EPIC_Rotate_IT/HAL_EPIC_Rotate, @@ -133,132 +156,154 @@ SRAM will lose 50% performance in the foreground and 20% in other situations ``` ### Zoom in -| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) -|----------|------------|--------------------|--------------- -| SRAM | SRAM | 4.59 | 52.24 | -| PSRAM | SRAM | 12.82 | 18.72 | -| FLASH1 | SRAM | 41.19 | 5.82 | -| FLASH2 | SRAM | 49.43 | 4.85 | -| SRAM | PSRAM | 4.63 | 51.88 | -| PSRAM | PSRAM | 12.81 | 18.73 | -| FLASH1 | PSRAM | 41.22 | 5.82 | -| FLASH2 | PSRAM | 49.47 | 4.85 | +| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) | +| ------ | ------ | -------------------------- | ---------------------- | +| SRAM | SRAM | 4.59 | 52.24 | +| PSRAM | SRAM | 12.82 | 18.72 | +| FLASH1 | SRAM | 41.19 | 5.82 | +| FLASH2 | SRAM | 49.43 | 4.85 | +| SRAM | PSRAM | 4.63 | 51.88 | +| PSRAM | PSRAM | 12.81 | 18.73 | +| FLASH1 | PSRAM | 41.22 | 5.82 | +| FLASH2 | PSRAM | 49.47 | 4.85 | ```{note} The size of the foreground image is 88*88, and the zoom factor is 1400 ``` ### Revolve -| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) -|----------|------------|--------------------|-------------- -| SRAM | SRAM | 15.90 | 15.69 | -| PSRAM | SRAM | 136.27 | 1.76 | -| FLASH1 | SRAM | 254.80 | 0.94 | -| FLASH2 | SRAM | 313.40 | 0.76 | -| SRAM | PSRAM | 15.29 | 15.7 | -| PSRAM | PSRAM | 139.11 | 1.72 | -| FLASH1 | PSRAM | 254.80 | 0.94 | -| FLASH2 | PSRAM | 313.42 | 0.76 | +| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) | +| ------ | ------ | -------------------------- | ---------------------- | +| SRAM | SRAM | 15.90 | 15.69 | +| PSRAM | SRAM | 136.27 | 1.76 | +| FLASH1 | SRAM | 254.80 | 0.94 | +| FLASH2 | SRAM | 313.40 | 0.76 | +| SRAM | PSRAM | 15.29 | 15.7 | +| PSRAM | PSRAM | 139.11 | 1.72 | +| FLASH1 | PSRAM | 254.80 | 0.94 | +| FLASH2 | PSRAM | 313.42 | 0.76 | ```{note} The rotation Angle is 45° ``` ### Filling -| Vision | Output | Performance (cycles/pixel) | Throughput (MPixels/s) -|------------|--------------------|--------------- -| SRAM | 1.31 | 183.55 | -| PSRAM | 2.79 | 85.95 | +| Output | Performance (cycles/pixel) | Throughput (MPixels/s) | +| ------ | -------------------------- | ---------------------- | +| SRAM | 1.31 | 183.55 | +| PSRAM | 2.79 | 85.95 | ```{note} Fill the monochrome with a transparency of 255 ``` - ## 4. Application Memory Planning and Custom Interfaces -The following interfaces are defined in _$SDK_ROOT/drivers/cmsis/sf32lb55x/mem_map.h_ to plan the Memory usage of applications. -In addition to header files and C files, these macros can also be used in linker files to ensure consistency in address planning. +The following interfaces are defined in +_$SDK_ROOT/drivers/cmsis/sf32lb55x/mem_map.h_ to plan the Memory usage of +applications. In addition to header files and C files, these macros can also be +used in linker files to ensure consistency in address planning. HCPU Flash and SRAM Address Planning Table -| Macro | Description | Default Value | Description | -|-----------------------------|-------------------------------|------------|---------| -| HCPU_FLASH_CODE_START_ADDR | Starting address of the XIP code segment for the HCPU application | 0x10020000 (no DFU) or 0x10100000 (with DFU) | | -| HCPU_FLASH_CODE_SIZE | Size of the XIP code segment for the HCPU application | 896KB | | -| HCPU_FLASH2_IMG_START_ADDR | Starting address of the image resource | 0x64000000 | | -| HCPU_FLASH2_IMG_SIZE | Image resource size | 4MB | | -| HCPU_FLASH2_FONT_START_ADDR | Starting address of the font resource | 0x64400000 | | -| HCPU_FLASH2_FONT_SIZE | Font resource size | 12MB | | -| HCPU_RAM_DATA_START_ADDR | Starting address of the data segment for the HCPU application | 0x20000000 | | -| HCPU_RAM_DATA_SIZE | Size of the data segment for the HCPU application | 1007KB | | -| HCPU_RO_DATA_START_ADDR | Starting address of the U application RAM code segment | 0x200FBC00 | Used to store code that needs to be executed in SRAM | -| HCPU_RO_DATA_SIZE | Size of the RAM code segment for the U application | 16KB | | -| HCPU2LCPU_MB_CH2_BUF_START_ADDR | Starting address of the shared buffer for HCPU2LCPU | 0x200FFC00 | | -| HCPU2LCPU_MB_CH2_BUF_SIZE | Size of mailbox2 shared buffer for HCPU2LCPU | 512B | | -| HCPU2LCPU_MB_CH1_BUF_START_ADDR | Starting address of the shared buffer for mailbox1 in HCPU2LCPU | 0x200FFE00 | | -| HCPU2LCPU_MB_CH1_BUF_SIZE | Size of mailbox1 shared buffer for HCPU2LCPU | 512B | | - -The heap space size that HCPU can allocate depends on how much space static variables occupy in the HCPU application data segment. -For example, if a static variable takes up 500KB, the remaining heap space will be 1007KB - 500KB = 507KB. +| Macro | Description | Default Value | Description | +| ------------------------------- | ----------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------- | +| HCPU_FLASH_CODE_START_ADDR | Starting address of the XIP code segment for the HCPU application | 0x10020000 (no DFU) or 0x10100000 (with DFU) | | +| HCPU_FLASH_CODE_SIZE | Size of the XIP code segment for the HCPU application | 896KB | | +| HCPU_FLASH2_IMG_START_ADDR | Starting address of the image resource | 0x64000000 | | +| HCPU_FLASH2_IMG_SIZE | Image resource size | 4MB | | +| HCPU_FLASH2_FONT_START_ADDR | Starting address of the font resource | 0x64400000 | | +| HCPU_FLASH2_FONT_SIZE | Font resource size | 12MB | | +| HCPU_RAM_DATA_START_ADDR | Starting address of the data segment for the HCPU application | 0x20000000 | | +| HCPU_RAM_DATA_SIZE | Size of the data segment for the HCPU application | 1007KB | | +| HCPU_RO_DATA_START_ADDR | Starting address of the U application RAM code segment | 0x200FBC00 | Used to store code that needs to be executed in SRAM | +| HCPU_RO_DATA_SIZE | Size of the RAM code segment for the U application | 16KB | | +| HCPU2LCPU_MB_CH2_BUF_START_ADDR | Starting address of the shared buffer for HCPU2LCPU | 0x200FFC00 | | +| HCPU2LCPU_MB_CH2_BUF_SIZE | Size of mailbox2 shared buffer for HCPU2LCPU | 512B | | +| HCPU2LCPU_MB_CH1_BUF_START_ADDR | Starting address of the shared buffer for mailbox1 in HCPU2LCPU | 0x200FFE00 | | +| HCPU2LCPU_MB_CH1_BUF_SIZE | Size of mailbox1 shared buffer for HCPU2LCPU | 512B | | + +The heap space size that HCPU can allocate depends on how much space static +variables occupy in the HCPU application data segment. For example, if a static +variable takes up 500KB, the remaining heap space will be 1007KB - 500KB = +507KB. + OTA Address Planning Table -| Macro | Description | Default Value | Description | -|-----------------------------|---------------------------|------------|---------| -| DFU_FLASH_CODE_START_ADDR | Starting address of the DFU program code segment | 0x10020000 | | -| DFU_FLASH_CODE_SIZE | Size of the DFU program code segment | 256KB | | -| DFU_RES_FLASH_CODE_START_ADDR | Starting address of the application upgrade area | 0x10060000 | | -| DFU_RES_FLASH_CODE_SIZE | Size of the application upgrade area | 640KB | | -| HCPU_FLASH2_IMG_UPGRADE_START_ADDR | Starting address of the image resource upgrade area | 0x65000000 | | -| HCPU_FLASH2_IMG_UPGRADE_SIZE | Size of the image resource upgrade area | 1MB | | -| HCPU_FLASH2_FONT_UPGRADE_START_ADDR | Starting address of the font resource upgrade area | 0x65100000 | | -| HCPU_FLASH2_FONT_UPGRADE_SIZE | Size of the font resource upgrade area | 3MB | | +| Macro | Description | Default Value | Description | +| ----------------------------------- | --------------------------------------------------- | ------------- | ----------- | +| DFU_FLASH_CODE_START_ADDR | Starting address of the DFU program code segment | 0x10020000 | | +| DFU_FLASH_CODE_SIZE | Size of the DFU program code segment | 256KB | | +| DFU_RES_FLASH_CODE_START_ADDR | Starting address of the application upgrade area | 0x10060000 | | +| DFU_RES_FLASH_CODE_SIZE | Size of the application upgrade area | 640KB | | +| HCPU_FLASH2_IMG_UPGRADE_START_ADDR | Starting address of the image resource upgrade area | 0x65000000 | | +| HCPU_FLASH2_IMG_UPGRADE_SIZE | Size of the image resource upgrade area | 1MB | | +| HCPU_FLASH2_FONT_UPGRADE_START_ADDR | Starting address of the font resource upgrade area | 0x65100000 | | +| HCPU_FLASH2_FONT_UPGRADE_SIZE | Size of the font resource upgrade area | 3MB | | + + LCPU SRAM Address Planning Table -| Macro | Description | Default Value | -|-----------------------------|---------------------------|------------------| -| LCPU_RAM_CODE_START_ADDR | Starting address of the LCPU application code segment | 0x000FC000 | -| LCPU_RAM_CODE_SIZE | Size of the LCPU application code segment | 140KB | -| LPSYS_RAM_SIZE | Total size of the LCPU application code and data segment | 160KB | -| LCPU2HCPU_MB_CH1_BUF_START_ADDR | Starting address of the shared buffer for LCPU2HCPU mailbox2 | 0x20123C00 | -| LCPU2HCPU_MB_CH1_BUF_SIZE | Size of the shared buffer for LCPU2HCPU mailbox2 | 512B | -| LCPU2HCPU_MB_CH2_BUF_START_ADDR | Starting address of the shared buffer for LCPU2HCPU mailbox1 | 0x20123E00 | -| LCPU2HCPU_MB_CH2_BUF_SIZE | Size of the shared buffer for LCPU2HCPU mailbox1 | 512B | - -The heap space that LCPU can allocate depends on how much space the LCPU application code and static variables occupy. -For instance, if the code and static variables occupy 120KB, the remaining heap space will be 160KB - 120KB = 40KB. - -If you need to modify the default values, you can add the `CUSTOM_MEM_MAP` option in the project's Kconfig. -After running menuconfig and saving the settings, the `CUSTOM_MEM_MAP` switch will be added in the `rtconfig.h`, and `mem_map.h` will include `custom_mem_map.h`, where you can redefine the macros that need modification. +| Macro | Description | Default Value | +| ------------------------------- | ------------------------------------------------------------ | ------------- | +| LCPU_RAM_CODE_START_ADDR | Starting address of the LCPU application code segment | 0x000FC000 | +| LCPU_RAM_CODE_SIZE | Size of the LCPU application code segment | 140KB | +| LPSYS_RAM_SIZE | Total size of the LCPU application code and data segment | 160KB | +| LCPU2HCPU_MB_CH1_BUF_START_ADDR | Starting address of the shared buffer for LCPU2HCPU mailbox2 | 0x20123C00 | +| LCPU2HCPU_MB_CH1_BUF_SIZE | Size of the shared buffer for LCPU2HCPU mailbox2 | 512B | +| LCPU2HCPU_MB_CH2_BUF_START_ADDR | Starting address of the shared buffer for LCPU2HCPU mailbox1 | 0x20123E00 | +| LCPU2HCPU_MB_CH2_BUF_SIZE | Size of the shared buffer for LCPU2HCPU mailbox1 | 512B | + + +The heap space that LCPU can allocate depends on how much space the LCPU +application code and static variables occupy. For instance, if the code and +static variables occupy 120KB, the remaining heap space will be 160KB - 120KB = +40KB. + +If you need to modify the default values, you can add the `CUSTOM_MEM_MAP` +option in the project's Kconfig. After running menuconfig and saving the +settings, the `CUSTOM_MEM_MAP` switch will be added in the `rtconfig.h`, and +`mem_map.h` will include `custom_mem_map.h`, where you can redefine the macros +that need modification. ```c config CUSTOM_MEM_MAP bool - default y + default y ``` + + ### 4.1 Low Power Related Interfaces -To implement the low power Standby mode, the link.sct file for the HCPU project defines several interfaces used by the PM framework. For example, in _$SDK_ROOT/example/pm/ble/ec-lb555/hcpu/linker_scripts/link_flash.sct_, if the hardware platform supports PSRAM, the following regions need to be defined in the linker file. The SDK uses RW_PSRAM2 as the backup area for data during sleep, and the data in this region will not be saved during sleep. For data that needs to be saved, it can be placed in the RW_P... +To implement the low power Standby mode, the link.sct file for the HCPU project +defines several interfaces used by the PM framework. For example, in +_$SDK_ROOT/example/pm/ble/ec-lb555/hcpu/linker_scripts/link_flash.sct_, if the +hardware platform supports PSRAM, the following regions need to be defined in +the linker file. The SDK uses RW_PSRAM2 as the backup area for data during +sleep, and the data in this region will not be saved during sleep. For data that +needs to be saved, it can be placed in the RW_P... ```c - RW_PSRAM1 PSRAM_BASE UNINIT{ ; ZI data, retained +RW_PSRAM1 PSRAM_BASE UNINIT{ ; ZI data, retained *.o (.l2_ret_data_*) *.o (.l2_ret_bss_*) *.o (.l2_cache_ret_data_*) *.o (.l2_cache_ret_bss_*) } - RW_PSRAM2 +0 UNINIT{ ; ZI data, not retained and reused by SRAM retention + RW_PSRAM2 +0 UNINIT{ ; ZI data, non-retained; reused by SRAM retention *.o (.nand_cache) *.o (.l2_non_ret_data_*) *.o (.l2_non_ret_bss_*) *.o (.l2_cache_non_ret_data_*) *.o (.l2_cache_non_ret_bss_*) } - ScatterAssert((ImageLength(RW_PSRAM1)+ImageLength(RW_PSRAM2)) ### Modifying Configuration -Change the configuration values in the menu configuration interface as follows: -- Use the arrow keys to browse the menu. Vim-style key bindings are also supported. -- Use the spacebar and `Enter` key to enter menus and toggle values. A `-->` will appear next to the menu. Press `ESC` to return to the parent menu. - Boolean configuration options are enclosed in square brackets [], while numeric and string configuration values are enclosed in parentheses (). Unmodifiable values are shown as – or -*- . - You can also press Y or N to set Boolean values. -- Press `?` to display information about the currently selected symbol, including its help text. Press ESC or Q to return to the menu after viewing the help. -- Press Q in the menuconfig interface to open the "Save and Exit" dialog (if there are changes to save): - -![](../../assets/save.png) -Press Y to save the kernel configuration options with the default file name (.config). Unless using a different configuration, it will typically be saved with the default file name. -```{note} - The configuration file used during the build is always _.config_. If you want to use another saved configuration, copy it to .config. Make sure to back up the original configuration file.
-``` +Change the configuration values in the menu configuration interface as follows: +- Use the arrow keys to browse the menu. Vim-style key bindings are also + supported. +- Use the spacebar and `Enter` key to enter menus and toggle values. A `-->` + will appear next to the menu. Press `ESC` to return to the parent menu.\ + Boolean configuration options are enclosed in square brackets [], while + numeric and string configuration values are enclosed in parentheses (). + Unmodifiable values are shown as – or -*- .\ + You can also press Y or N to set Boolean values. +- Press `?` to display information about the currently selected symbol, + including its help text. Press ESC or Q to return to the menu after viewing + the help. +- Press Q in the menuconfig interface to open the "Save and Exit" dialog (if + there are changes to save): + +![](../../assets/save.png)\ +Press Y to save the kernel configuration options with the default file name +(.config). Unless using a different configuration, it will typically be saved +with the default file name. +```{note} +The configuration file used during the build is always _.config_. If you want to use another saved configuration, copy it to .config. Make sure to back up the original configuration file.
+``` -![](../../assets/search.png) -If you jump to a symbol that is currently invisible (for example, due to unsatisfied dependencies), "Show All" mode will be enabled. In "Show All" mode, all symbols, including currently invisible ones, will be displayed. To turn off "Show All" mode, press ESC in menuconfig. +![](../../assets/search.png)\ +If you jump to a symbol that is currently invisible (for example, due to +unsatisfied dependencies), "Show All" mode will be enabled. In "Show All" mode, +all symbols, including currently invisible ones, will be displayed. To turn off +"Show All" mode, press ESC in menuconfig. -- If no items are visible in the current menu, "Show All" mode cannot be turned off. - To find out why the symbol you jumped to is not visible, press to check its dependencies. If it is found to depend on another disabled symbol, you can navigate to that symbol and check if it can be enabled. -- In menuconfig, you can press 'F' to view the help for the current selection without exiting the dialog. +- If no items are visible in the current menu, "Show All" mode cannot be turned + off.\ + To find out why the symbol you jumped to is not visible, press to check its + dependencies. If it is found to depend on another disabled symbol, you can + navigate to that symbol and check if it can be enabled. +- In menuconfig, you can press 'F' to view the help for the current selection + without exiting the dialog. ## Setting Kconfig Configuration Values -The menuconfig interface can be used to configure tests during application development. This section describes how to make the settings permanent. -A generated list of all Kconfig options can be found in the Kconfig symbol reference. - -```{note} -It is recommended to review the Kconfig tips and best practices page before making changes to Kconfig files. +The menuconfig interface can be used to configure tests during application +development. This section describes how to make the settings permanent.\ +A generated list of all Kconfig options can be found in the Kconfig symbol +reference. +```{note} +It is recommended to review the Kconfig tips and best practices page before making changes to Kconfig files. ``` ### Kconfig Configuration Items -When making Kconfig changes, it is important to understand the difference between visible and invisible configuration items. Visible symbols are those defined with prompts. These visible symbols appear in the interactive configuration interface and can be set in the configuration file. +When making Kconfig changes, it is important to understand the difference +between visible and invisible configuration items. Visible symbols are those +defined with prompts. These visible symbols appear in the interactive +configuration interface and can be set in the configuration file. -Here is an example of a visible configuration: -![](../../assets/seeable.png) +Here is an example of a visible configuration:\ +![]
-This configuration item will appear in menuconfig and can be toggled: -Invisible configuration items do not have a prompt. Invisible configuration items are not displayed in the interactive configuration interface, and the user cannot directly control their value. Instead, they get their values from default values or other configuration items. -![](../../assets/unseeable.png) +This configuration item will appear in menuconfig and can be toggled:\ +Invisible configuration items do not have a prompt. Invisible configuration +items are not displayed in the interactive configuration interface, and the user +cannot directly control their value. Instead, they get their values from default +values or other configuration items.\ +![]
-In this case, the symbol `BF0_HCPU` is enabled by selecting other symbols that depend on it. +In this case, the symbol `BF0_HCPU` is enabled by selecting other symbols that +depend on it. ### Setting Configuration Items Through the Configuration File -Visible configuration items can be configured by setting them in the configuration file. The initial configuration is generated by merging the board's _.config_ file with the application settings. For more details, refer to the section on initial configuration. -The assignments in the configuration file use the following syntax: -`CONFIG=` -```{note} -No spaces allowed around the equals sign. +Visible configuration items can be configured by setting them in the +configuration file. The initial configuration is generated by merging the +board's _.config_ file with the application settings. For more details, refer to +the section on initial configuration.\ +The assignments in the configuration file use the following syntax:\ +`CONFIG=` +```{note} +No spaces allowed around the equals sign. ``` -Boolean symbols can be enabled or disabled by setting them to `y` or `n`. For example, to enable the FPU symbol: +Boolean symbols can be enabled or disabled by setting them to `y` or `n`. For +example, to enable the FPU symbol: - `CONFIG_FPU=y` +`CONFIG_FPU=y` -```{note} +```{note} 1. Boolean symbols can also be set to `n`, and their comment format is as follows: `#CONFIG_SOME_OTHER_BOOL is not set` 2. This format is seen in the merged configuration in .config. ``` -Assignments for other symbol types are as follows: +Assignments for other symbol types are as follows: - `CONFIG_SOME_STRING="cool value"` - `CONFIG_SOME_INT=123` ### Commenting with `#` - `#This is a comment` +`#This is a comment` ## SiFli SDK Configuration -The SDK includes a variety of options that users can configure, including chip, board, drivers, RTOS, peripheral circuits, middleware, third-party software, etc. Users can customize their chosen features as needed. -Users can add SDK configurations to their own project's Kconfig. -Add the following to your KConfig to include SDK configuration: +The SDK includes a variety of options that users can configure, including chip, +board, drivers, RTOS, peripheral circuits, middleware, third-party software, +etc. Users can customize their chosen features as needed.\ +Users can add SDK configurations to their own project's Kconfig.\ +Add the following to your KConfig to include SDK configuration: ```kconfig config SIFLI_SDK @@ -92,20 +128,31 @@ config SIFLI_SDK source "$SIFLI_SDK/Kconfig" ``` -This will introduce the SDK configuration, and after running menuconfig, you will see the following separator: +This will introduce the SDK configuration, and after running menuconfig, you +will see the following separator: + + ------------End of SDK configuration ----------- + +The SDK configuration mainly consists of the following sections: + +Users can also customize some Kconfig configurations and are advised not to mix +them with SDK configurations. It is recommended to use separate Kconfig files. +- Chip Selection (Select chipset)\ + Select the chip; currently, SF32LB55X should be chosen. +- Operating System Selection (RTOS)\ + RT-Thread is the primary supported operating system and is recommended. It + also includes RT-Thread driver configurations for internal IPs of the chip. +- Board-Level Peripherals (Select board peripherals)\ + This section provides configuration for external devices supported by Sifli + Technology. +- Middleware (Sifli middleware)\ + This section contains middleware configurations developed by Sifli Technology. +- Third-Party Software (Third-party package)\ + This section includes third-party software verified and optimized by Sifli + Technology. - ------------End of SDK configuration ----------- +Users may also define custom Kconfig configurations. To avoid conflicts or +confusion with the SDK configurations, it is recommended to maintain custom +settings in separate Kconfig files. -The SDK configuration mainly consists of the following sections: -- Chip Selection (Select chipset) - Select the chip; currently, SF32LB55X should be chosen. -- Operating System Selection (RTOS) - RT-Thread is the primary supported operating system and is recommended. It also includes RT-Thread driver configurations for internal IPs of the chip. -- Board-Level Peripherals (Select board peripherals) - This section provides configuration for external devices supported by Sifli Technology. -- Middleware (Sifli middleware) - This section contains middleware configurations developed by Sifli Technology. -- Third-Party Software (Third-party package) - This section includes third-party software verified and optimized by Sifli Technology. -Users can also customize some Kconfig configurations and are advised not to mix them with SDK configurations. It is recommended to use separate Kconfig files. diff --git a/docs/source/en/app_note/quick_start_52x_56x.md b/docs/source/en/app_note/quick_start_52x_56x.md index 96c53af8f..1f53a0e5c 100644 --- a/docs/source/en/app_note/quick_start_52x_56x.md +++ b/docs/source/en/app_note/quick_start_52x_56x.md @@ -5,79 +5,100 @@ ### Required Software 1. Sifli env and SiFli SDK (Download from Weiyun). 2. Keil V5.32 or above, armcc V6 or above. -3. Segger Jlink, V6.80a or above. - [Jlink Download Link](https://www.segger.com/downloads/jlink/JLink_Windows.exe) +3. Segger Jlink, V6.80a or above.\ + [Jlink Download + Link](https://www.segger.com/downloads/jlink/JLink_Windows.exe) 4. Code editing software: VSCode or Source Insight. 5. Serial log viewing tool: Use the SDK's built-in sifliTrace or sscom. ### Required Hardware -1. Windows PC x1 -2. ARM Emulator x1 -```{note} +1. One Windows PC +2. ARM Emulator x1 +```{note} 仿真器的供电和HDK板有冲突,需要关闭仿真器的供电。如果出现仿真器连接不成功,可以检查一下Jlink的供电硬件跳线。 There is a conflict between the power supply of the emulator and the HDK board, so you need to disable the emulator's power supply. If the emulator connection fails, check the power supply jumper on the Jlink. The following image shows the common Jlink power supply jumper that needs to be removed. ![](../../assets/disable_jlink_power_supply.png) ``` -3. USB Type-C Cable x2 - Used to connect the ARM emulator and the USB2UART debug board to power the HDK board and capture HDK serial log data. -4. USB2UART Debug Board x1 (SIFLI-Debug001-V1.1.0). -> Overview of the USB2UART Debug Board ![](../../assets/hdk_sifli_debug_overview.png) -5. HDK Development Board x1 set - Includes an HDK CPU board (SF56X or SF52X) and a screen sub-board (the model of the sub-board varies depending on the screen). -> HDK52x Development Board Interface Overview ![](../../assets/hdk_micro_overview.png) -> HDK56x Development Board Interface Overview ![](../../assets/hdk_lite_overview.png) -> Screen Sub-board Interface Overview ![](../../assets/hdk_screen_overview.png) +3. USB Type-C Cable x2\ + Used to connect the ARM emulator and the USB2UART debug board to power the + HDK board and capture HDK serial log data. +4. USB2UART Debug Board x1 (SIFLI-Debug001-V1.1.0).
+> Overview of the USB2UART Debug Board +> ![](../../assets/hdk_sifli_debug_overview.png) 5. HDK Development Board x1 +> set\ +> Includes an HDK CPU board (SF56X or SF52X) and a screen sub-board (the model +> of the sub-board varies depending on the screen).\ +> HDK52x Development Board Interface Overview ![]
\ +> HDK56x Development Board Interface Overview ![]
\ +> Screen Sub-board Interface Overview ![](../../assets/hdk_micro_overview.png) ## 2. Development Environment Configuration ### Configuring the ENV 1. Extract the env to your PC, for example to _D:\work\env_. -2. Enter the env directory and run _env.exe_ in this directory. If it fails to open, try using _env.bat_. +2. Enter the env directory and run _env.exe_ in this directory. If it fails to + open, try using _env.bat_. 3. Right-click on the associated folder and select the "ConEmu Here" menu. -> Add ConEmu Here to the right-click menu ![](../../assets/add_env_conemu_1.png) -> Right-click any folder to open ConEmu Here ![](../../assets/add_env_conemu_2.png) +> Add ConEmu Here to the right-click menu +> ![](../../assets/add_env_conemu_1.png)\ +> Right-click any folder to open ConEmu Here +> ![](../../assets/add_env_conemu_2.png) ### Installing Keil -Double-click the Keil installer and follow the prompts to install it. Note that Keil should be installed to the _C:\Keil_v5_ directory. After starting Keil, open _Help->>About_, -If the displayed version is not v5.32, uninstall Keil and install the latest version. -![](../../assets/keil_version_about.png) -After installing Keil, add the ARM path to the Windows environment variable PATH, for example: _C:\Keil_v5\ARM\ARMCLANG\bin_. +Double-click the Keil installer and follow the prompts to install it. Note that +Keil should be installed to the _C:\Keil_v5_ directory. After starting Keil, +open _Help->>About_,\ +If the displayed version is not v5.32, uninstall Keil and install the latest +version.\ +![]
\ +After installing Keil, add the ARM path to the Windows environment variable +PATH, for example: _C:\Keil_v5\ARM\ARMCLANG\bin_. ### Installing JLink -Jlink needs to be installed with version v6.80a or later. Double-click the installer _JLink_Windows_V680a.exe_, select the default installation path, and add the JLink path to the Windows environment variable PATH, -For example: _C:\Program Files (x86)\SEGGER\JLink_. -Copy all ELF files from the _$SDK_ROOT\tools\flash\jlink_drv\sf32lbxx_ directory to the _Devices\SiFli_ directory in the JLink installation path. The SiFli directory must be manually created. -After copying, it should look like the following. -Add Jlink drivers to Jlink installation directory ![](../../assets/JLink_drv_1.png) +Jlink needs to be installed with version v6.80a or later. Double-click the +installer _JLink_Windows_V680a.exe_, select the default installation path, and +add the JLink path to the Windows environment variable PATH,\ +For example: _C:\Program Files (x86)\SEGGER\JLink_.\ +Copy all ELF files from the _$SDK_ROOT\tools\flash\jlink_drv\sf32lbxx_ directory +to the _Devices\SiFli_ directory in the JLink installation path. The SiFli +directory must be manually created.\ +After copying, it should look like the following.\ +Add Jlink drivers to Jlink installation directory ![]
-Merge the SiFli-related content from _JLinkDevices.xml_ in the jlink_drv directory into the _JLinkDevices.xml_ in the JLink installation directory. +Merge the SiFli-related content from _JLinkDevices.xml_ in the jlink_drv +directory into the _JLinkDevices.xml_ in the JLink installation directory.\ ![](../../assets/JLink_drv_2.png) + Modify the JLinkDevice file ![](../../assets/JLink_drv_3.png) ### Configuring System Environment Variables -Add the following paths to the PATH variable in system environment variables. The actual paths need to match the local tool and code paths. +Add the following paths to the PATH variable in system environment variables. +The actual paths need to match the local tool and code paths.\ Add environment variable PATH![](../../assets/add_env_path.png) ## 3. Compiling Project Code ### SF52X Project Code Compilation -Using the `sf525` project under the `hal_example` as an example, the compilation steps are as follows: -1. Go to the SDK root directory, _$SDK_ROOT_, right-click and select "ConEmu Here". +Using the `sf525` project under the `hal_example` as an example, the compilation +steps are as follows: +1. Go to the SDK root directory, _$SDK_ROOT_, right-click and select "ConEmu + Here". 2. Execute the script `.\set_env.bat_` to configure the environment. 3. Enter the compilation directory: `cd example\hal_example\project\common` 4. Execute the compile command: `scons --board=eh-lb525_v2_hcpu -j8` -```{note} +```{note} `--board=xx` specifies the board information. You can choose a directory from _customer\\boards_ with a directory name containing "v2" and add _hcpu_ to the end, for example, `eh-lb525_v2_hcpu`. After compilation, a folder `build_eh-lb525_v2_hcpu` will be created under the common directory, storing the generated images and other files. ![sf525 Project Compilation Successful](../../assets/sf525_compile_success.png) ``` ### SF56X Project Code Compilation -Using the `sf561` project under the `hal_example` as an example, the compilation steps are as follows: +Using the `sf561` project under the `hal_example` as an example, the compilation +steps are as follows: 1. Go to the SDK root directory, right-click and select "ConEmu Here". 2. Execute the script `.\set_env.bat` to configure the environment. 3. Enter the compilation directory: `cd example\hal_example\project\common` 4. Execute the compile command: `scons --board=eh-lb561_v2_hcpu -j8` -```{note} +```{note} `--board= xx` specifies the board information. You can choose a directory from _customer\\boards_ with a directory name containing "v2" and add _hcpu_ to the end, for example, `eh-lb561_v2_hcpu`. After compilation, a folder `build_eh-lb561_v2_hcpu` will be created under the common directory, storing the generated images and other files. ![sf561 Project Compilation Successful](../../assets/sf561_compile_success.png) @@ -85,22 +106,33 @@ After compilation, a folder `build_eh-lb561_v2_hcpu` will be created under the c ## 4. Download and Flash HDK ### SF52X Project Image Download and Flash -The `sf525` uses UART interface to download the image. Connect the HDK board to the siflideubg debug board, then use the USB Type-C cable to connect the siflideubg debug board to the computer. First, confirm the COM port of the CPU's log output, for example, COM4. +The `sf525` uses UART interface to download the image. Connect the HDK board to +the siflideubg debug board, then use the USB Type-C cable to connect the +siflideubg debug board to the computer. First, confirm the COM port of the CPU's +log output, for example, COM4.
1. Close the serial log tool's COM port. -2. In the compilation directory, run the download script `.\build_eh-lb525_v2_hcpu\uart_download.bat`. -3. It will prompt you to input the COM port used for downloading. Enter 4 and press Enter to start the download. +2. In the compilation directory, run the download script + `.\build_eh-lb525_v2_hcpu\uart_download.bat`. +3. It will prompt you to input the COM port used for downloading. Enter 4 and + press Enter to start the download. > Downloading SF525 Image ![](../../assets/sf525_download_img.png) ### SF561 Project Image Download and Flash -The `sf561` uses JLink to download the image. Connect the HDK board to the siflideubg debug board, then connect the siflideubg debug board to the computer for serial log printing. Connect the ARM emulator to the siflideubg debug board using the JLink ribbon cable, and the other end of the ARM emulator should be connected to the computer via Type-C. -1. Use J-Link Commander to send the `connect` command and check if the development board can connect successfully. -```{note} +The `sf561` uses JLink to download the image. Connect the HDK board to the +siflideubg debug board, then connect the siflideubg debug board to the computer +for serial log printing. Connect the ARM emulator to the siflideubg debug board +using the JLink ribbon cable, and the other end of the ARM emulator should be +connected to the computer via Type-C. +1. Use J-Link Commander to send the `connect` command and check if the + development board can connect successfully. +```{note} The device name chosen during `connect` should match the `JLINK_DEVICE` in the `rtconfig.py` file in the project directory. For example, select `SF32LB56X` for the `sf561` project. After selecting the device, choose the interface (SWD), then configure the transmission rate with the default settings. Once connected successfully, you will see the following. > SF561 Connecting to JLink ![](../../assets/sf561_jlink_connect_1.png) -![](../../assets/sf561_jlink_connect_2.png) +![](../../assets/sf561_jlink_connect_2.png) ``` -2. In the compilation directory, run the download script `.\build_eh-lb561_v2_hcpu\download.bat` to start JLink downloading. -> Downloading SF561 Image -![](../../assets/sf561_download_img_1.png) -![](../../assets/sf561_download_img_2.png) +2. In the compilation directory, run the download script + `.\build_eh-lb561_v2_hcpu\download.bat` to start JLink downloading. +> Downloading SF561 Image\ +> ![](../../assets/sf561_download_img_1.png)\ +> ![](../../assets/sf561_download_img_2.png) diff --git a/docs/source/en/app_note/quick_start_55x.md b/docs/source/en/app_note/quick_start_55x.md index aa7afcb3f..82c484c28 100644 --- a/docs/source/en/app_note/quick_start_55x.md +++ b/docs/source/en/app_note/quick_start_55x.md @@ -1,103 +1,117 @@  -# SDK Quick Start ## 1. Development Environment Setup ### Required Software -1. Sifli env and SiFli SDK (Download from Weiyun) -2. Keil V5.32 or above, armcc V6 version or above - Add the ARM and Jlink paths to the Windows environment variable PATH, such as _C:\Keil_v5\ARM\ARMCLANG\bin_ and _C:\Program Files(x86)\SEGGER\JLink_v672b_, which is helpful for some scripts. -3. Segger Jlink, V6.72b or above. [Jlink Download Link](https://www.segger.com/downloads/jlink/JLink_Windows.exe) -4. Visual Studio 2017 or higher version +1. Sifli env and SiFli SDK (Download from WeDisk) +1. Keil V5.32 or higher, armcc V6 or higher. To enable script support, add the + ARM and J-Link paths to the Windows PATH environment variable (e.g., + _C:\Keil_v5\ARM\ARMCLANG\bin_ and _C:\Program + Files(x86)\SEGGER\JLink_v672b_). +1. SEGGER J-Link, V6.72b or higher [J-Link + Download](https://www.segger.com/downloads/jlink/JLink_Windows.exe) +1. Visual Studio 2017 or higher ### Required Hardware -1. Windows PC x1 -2. ARM Emulator x1 -```{note} - There is a conflict between the power supply of the emulator and the EVB board, so you need to disable the emulator's power supply. If the emulator connection fails, check the power supply jumper on the Jlink. - The following image shows the common Jlink power supply jumper that needs to be removed. - ![](/assets/disable_jlink_power_supply.png) -``` -3. USB Type-C Cable x1 - Used to power the EVB and connect the FTDI USB2UART chip on the EVB to capture serial log data from the EVB. -4. EVB Development Board x1 set - Includes an interface baseboard EI-LB55XXXX001, a CPU sub-board LB551, and a screen sub-board (the model of the sub-board varies depending on the screen). -> EVB Development Board Interface Overview ![](../../assets/evb_a0_overview.png) - -### Compilation Necessary Configuration -1. Extract the env to your PC, such as _c:\work\env_ -2. Enter the env directory and run _env.exe_ in this directory. If it fails to open, try using _env.bat_ -3. Right-click on the associated folder and select the "ConEmu Here" menu -![ ](../../assets/Add_Env_To_Right-click_Menu.png) - -### Adding Keil Flash Writing Driver -Copy _sf32lb55x.FLM_ from the _tools/flash/keil_drv/sf32lb55x_ directory to _C:\Keil_v5\ARM\Flash_ (this is the default Keil installation directory; if installed in another directory, place it in the appropriate folder). - -## 2. Compile Example Projects - -### Compile EVB Project (DSI Screen) -1. Open the SifliSDK directory, right-click and select "ConEmu Here" to open ConEmu, execute the batch file `set_env.bat` (this sets the necessary environment variables, and if ConEmu remains open, this only needs to be done once; reopening ConEmu will require the setup again). -```{note} -The _set_env.bat_ file includes the Keil installation directory (default is _C:/Keil_v5_). Users need to modify it according to their installation directory. +1. One Windows PC +1. ARM Emulator x1 +```{note} +Conflicts may occur between the emulator's power supply and the EVB. Ensure emulator power output is disabled. If connection fails, check the J-Link hardware power jumper. The figure below illustrates the power jumper on a common J-Link; it must be removed. + ![](../../assets/disable_jlink_power_supply.png) ``` -2. Switch to _example/watch_demo/project/ec-lb551_ +1. USB Type-C cable x1\ + Used for EVB power supply and for connecting the FTDI USB-to-UART bridge to + capture serial data. +1. EVB Development Kit x1\ + Includes an interface baseboard (EI-LB55XXXX001), a CPU daughterboard + (LB551), and a display daughterboard (models vary by display type). +> EVB Interface Overview ![](../../assets/evb_a0_overview.png) + +### Required Build Configurations +1. Extract 'env' to your PC (e.g., _c:\work\env_). +2. Navigate to the 'env' directory and run _env.exe_. If it fails to open, try + _env.bat_. +3. Associate the "ConEmu Here" context menu with folders. ![ + ](../../assets/Add_Env_To_Right-click_Menu.png) + +### Add Keil Flash Programming Driver +Copy sf32lb55x.FLM from _tools/flash/keil_drv/sf32lb55x_ to +_C:\Keil_v5\ARM\Flash_ (Note: Adjust the path if Keil is installed in a +non-default directory). + +## 2. Compiling the Sample Project + +### Compiling the EVB Project (DSI Display) +1. 1. Navigate to the SifliSDK directory, right-click and select "ConEmu Here" + to open the terminal. Execute the batch file `set_env.bat` to configure the + necessary environment variables. (Environment variables only need to be set + once per ConEmu session; if you open a new ConEmu window, you must run this + command again.) +```{note} _set_env.bat_ 里面有设置Keil的安装目录(默认是 _C:/Keil_v5_ ),用户需要根据自己的安装目录进行修改。 +2. Switch to the directory: _example/watch_demo/project/ec-lb551_ 3. Run the command `scons --target=mdk5 –s` to generate the Keil project. -4. Then open the _project.uvprojx_ in Keil to compile. -```{note} -The compilation for the `ec-lb555` project is similar. +4. Open _project.uvprojx_ in Keil and proceed to compile. ``` - -### Compile Simulator Project -1. Open the SifliSDK directory, right-click and select "ConEmu Here" to open ConEmu, execute the batch file _set_env.bat_ -2. Switch to _example\watch_demo\project\watch_simu_ -3. Run the command `scons --target=vs2017 -s` to generate the VS project, then open the _project.vcxproj_ in Visual Studio 2017 to compile and run. -```{note} -If Visual Studio prompts that it cannot find _SDL2.DLL_, add the path _env\tools\Python27_ to the PATH environment variable, then restart Visual Studio. +The compilation process for the ec-lb555 project is similar. ``` -```{note} -If a different version of Visual Studio is installed, change the Windows SDK version as prompted when opening the project. +### Compiling the Simulator Project +1. Navigate to the SifliSDK directory, right-click and select "ConEmu Here" to open the terminal, then execute _set_env.bat_. +2. Switch to the directory: _example\watch_demo\project\watch_simu_ +3. Run the command `scons --target=vs2017 -s` to generate the Visual Studio project. Open _project.vcxproj_ in Visual Studio 2017 to compile and run. +``` +If Visual Studio reports that _SDL2.DLL_ cannot be found at runtime, add the +path _env\tools\Python27_ to the PATH environment variable and restart Visual +Studio. ``` -## 3. Flashing the EVB - -The SDK provides three methods to flash the EVB. One uses the Keil environment, and the other two use Jlink tools. +``` +If using a different version of Visual Studio, you may need to update the +Windows SDK version as prompted when opening the project. +``` +## 3. Programming the EVB -```{note} -Normally, there is no need to change the jumper `boot_mode`. If there are persistent issues with flashing, or if the user program crashes, place the jumper on the VDD side, press reset to enter boot mode, and try flashing again. After flashing is complete, place the jumper on the GND side and press reset to reboot for normal operation. +The SDK provides three methods for programming the EVB: one via the Keil environment and two using J-Link tools. +``` +Under normal circumstances, the `boot_mode` jumper does not need to be adjusted. +If programming issues persist or the user application hangs, move the +`boot_mode` jumper to the VDD side and press the reset button to enter boot mode +before re-attempting flash programming. Once programming is complete, restore +the `boot_mode` jumper to the GND side and reset the device to resume normal +operation. ``` -### 3.1 Flash EVB using Keil -To flash the EVB using Keil, you first need to add the Keil Flash writing driver. Copy _sf32lb55x.FLM_ from the _tools\flash\keil_drv\sf32lb55x_ directory to _C:\Keil_v5\ARM\Flash_ (this is the default Keil installation directory; if installed in another directory, place it in the appropriate folder). +### 3.1 Programming the EVB via Keil +To program the EVB flash using Keil, you must first install the Keil Flash driver. Copy _sf32lb55x.FLM_ from the _tools\flash\keil_drv\sf32lb55x_ directory to _C:\Keil_v5\ARM\Flash_ (assuming the default Keil installation path; if installed elsewhere, use the corresponding folder). -The EVB requires at least two parts to be flashed: -- Flash Table (flash only once, used for ROM to read address from FlashTable and jump to user code after reset). The default flash table is already written when the user receives the EVB. Unless the flash is corrupted, this step can usually be ignored. -- Project Code +At a minimum, two components must be programmed to the EVB: +- **Flash Table**: This only needs to be programmed once. The ROM reads the Flash Table after reset to determine the entry point for jumping to user code. For detailed usage, refer to [Secure Bootloader](../../bootloader.md). EVBs are shipped with a default flash table; unless the flash memory is corrupted, users can typically skip this step. +- **Project Code** -#### Flashing the Flash Table -1. Open the project _example/flash_table/project.uvprojx_ -2. Follow the previous section to select the Keil Flash writing driver. -3. Select Flash1 as the compilation target, then compile and flash. +#### Programming the Flash Table +1. Open the project _example/flash_table/project.uvprojx_. +2. Select the Keil Flash driver as described in the final section. +3. Select "flash1" as the build target, then compile and program. ![ ](../../assets/keil_download_flash_table.png) -#### Flashing the Project Code -1. Open _example/hal_example/project/ec_lb551/project.uvprojx_ -2. Follow the previous section to select the Keil Flash writing driver. -3. After compiling, flash the code. +#### Programming Project Code +1. Open _example/hal_example/project/ec_lb551/project.uvprojx_. +2. Select the Keil Flash driver as described in the final section. +3. Compile and then program the flash. -#### Selecting Keil Flash Writing Driver -- Open the project options, and choose the Flash driver as shown below: +#### Selecting the Keil Flash Driver +- Open the project options and select the Flash driver as shown below: ![ ](../../assets/keil_flash_download_config_a0.png) -### 3.2 Flash EVB using Jlink -This example uses Jlink version v672b, with the installation path _D:\Software\JLink_v672b_ +### 3.2 Programming the EVB via J-Link -#### Adding Jlink Flash Writing Driver -1. Create a directory _SiFli_ in the Jlink program directory _D:\Software\JLink_v672b\Devices_ -2. Copy the elf files from _tools/flash/jlink_drv/sf32lb55x_ to the newly created SiFli directory (each elf corresponds to a flash writing driver). +This guide uses J-Link version v672b as an example, installed at _D:\Software\JLink_v672b_. +#### Adding the J-Link Flash Driver +1. Create a new directory named _SiFli_ within the J-Link device directory: _D:\Software\JLink_v672b\Devices_. +2. Copy the .elf files from _tools/flash/jlink_drv/sf32lb55x_ to the newly created "SiFli" directory (each .elf file corresponds to a specific flash driver). ![](../../assets/add_sifli_jlink_device_A0_1.png) -3. Modify the Jlink registered Device list to include the newly added file path and run parameters, as shown below: +3. Update the J-Link registered device list to include the new file paths and execution parameters, as shown here: ![](../../assets/add_sifli_jlink_device_2.png) -The added xml content is shown below: +The XML content to be added is as follows: ``` @@ -119,66 +133,76 @@ The added xml content is shown below: ``` -#### Flashing Bin/Hex Files to Flash -1. Open Jlink, connect, and select the SiFli device (make sure SF32LB55X corresponds to the EVB flash driver). -![](../../assets/download_with_jlink_a0_1.png) -2. Select the SWD interface, configure the speed, choose the corresponding bin file, and flash it to the appropriate address (you can flash ROM/RAM/FLASH). Jlink's speed depends on the hardware and is usually set to over 4MHz, with the chip supporting a maximum of 10MHz. -![](../../assets/download_with_jlink_2.png) +#### Programming Bin/Hex Files to Flash +1. Open J-Link, connect, and select the SiFli device (note that SF32LB55X + represents the EVB flash driver) + ![](../../assets/download_with_jlink_a0_1.png) -3. Flashing result. -![](../../assets/download_with_jlink_3.png) +2. Select the SWD interface and configure the clock speed. Select the + corresponding binary to flash to a specific address (ROM, RAM, or FLASH). The + maximum J-Link speed depends on the hardware; it can typically be set to 4 + MHz or higher, while the chip supports up to 10 MHz. + ![](../../assets/download_with_jlink_2.png) -4. For flashing Hex files, change `loadbin` to `loadfile` and **do not include the address**. -![](../../assets/download_with_jlink_4.png) +3. Programming results ![](../../assets/download_with_jlink_3.png) -### 3.3 Integrating into Windows, Right-Click to Flash Hex Files -After adding the Jlink drivers, for convenience in debugging, you can integrate flashing Hex files into the Windows right-click menu. Only Hex files can be flashed this way, as they have predefined addresses. Bin files do not have predefined addresses and are unsupported. +4. To program a Hex file, replace `loadbin` with `loadfile`. Note that no + target address is required for Hex files. + ![](../../assets/download_with_jlink_4.png) -1. Add to the right-click menu -![](../../assets/integrate_jlink_download_to_right_click_menu_A0_1.png) +### 3.3 Windows Shell Integration: Right-Click to Program Hex Files +After installing the J-Link driver, you can integrate Hex file programming into +the Windows context menu for convenience. Note that only .hex files are +supported as they contain embedded address information; .bin files do not +include addresses and are therefore unsupported by this method. -2. Right-click on the directory to flash, and it will convert the files in the directory to `.hex` and flash them one by one. -![](../../assets/integrate_jlink_download_to_right_click_menu_A0_2.png) +1. Add to context menu + ![](../../assets/integrate_jlink_download_to_right_click_menu_A0_1.png) -3. You can also choose to flash a single Hex file (only `.hex` files are supported). -![](../../assets/integrate_jlink_download_to_right_click_menu_3.png) +2. To program via the directory context menu: this action will rename files in + the directory to have a .hex extension and program them sequentially. + ![](../../assets/integrate_jlink_download_to_right_click_menu_A0_2.png) -```{note} -For BLE applications to run properly, input the following commands in the serial port: -1. `nvds reset_all 1` -2. `nvds update addr 6 ` - For example: `nvds update addr 6 1234567890C8`, note that the Bluetooth address format should be maintained, and it is recommended not to modify the C8 part. Other parts can be changed by the user. - Then press reset to reboot. +3. Alternatively, you can select and program a single .hex file (only files with + the .hex extension are supported). + ![](../../assets/integrate_jlink_download_to_right_click_menu_3.png) + +```{note} 为了使得BLE 应用运行正常,请在串口输入\ +1. `nvds reset_all 1` +2. `nvds update addr 6 ` + Example: `nvds update addr 6 1234567890C8`. Note that the Bluetooth address must follow a specific format. It is recommended to keep `C8` unchanged; other values may be customized by the user. +Then, press reset to reboot. ``` -```{warning} -For the 56 and 58 series projects, after compilation, the build directory will generate _download.bat_ and _download.jlink_ files. Run _download.bat_ to download the image. Do not use the right-click method to download the Hex file. If you do, it will modify the _download.jlink_ file content, causing the download to fail. Please delete the modified _download.jlink_ file and recompile to use _download.bat_ for downloading. +```{warning} +For 56 and 58 series projects, _download.bat_ and _download.jlink_ files are generated in the build directory after compilation. Run _download.bat_ to execute the flash download. Do not use the right-click context menu to download HEX files. Doing so will modify the contents of _download.jlink_, leading to download failure. If this occurs, delete the modified download.jlink file, recompile the project, and use _download.bat_ for downloading. ``` -## 4. Power-Up Boot Process -| Phase | Function | File Path | -|--------------------------|---------------------------------|-----------------------------------------------------------------| -| Interrupt Vector Table | ResetHandler | SifliSDK\drivers\cmsis\sf32lb55x\Templates\arm\startup_bf0_hcpu.S | -| MPU Setup, BOOTMODE Check | SystemInit() | SifliSDK\drivers\cmsis\sf32lb55x\Templates\system_bf0_ap.c | -| RO/RW/ZI Initialization | __main() | | -| RT_THREAD_MAIN Entry | `$Sub$$main` | SifliSDK\rtos\rtthread\src\components.c | -| ^ | rtthread_startup() | SifliSDK\rtos\rtthread\src\components.c | -| Hardware Initialization | rt_hw_board_init() | | -| | HAL_Init(); | | -| RCC Configuration | HAL_PreInit() | SifliSDK\drivers\boards\ec-lb551XXX\drv_io.c | -| | HAL_MspInit() | | -| Pin Configuration | BSP_IO_Init() | | -| | rt_system_heap_init | | -| Log Output Initialization | rt_console_set_device | | -| Driver Initialization | rt_components_board_init(); | | -| Upper-Level Initialization| rt_application_init() | SifliSDK\rtos\rtthread\src\components.c | -| | main_thread_entry | SifliSDK\rtos\rtthread\src\components.c | -| Upper-Level Middleware | rt_components_init | | -| | Main() | Project's main function | -| Start Thread Scheduling | rt_system_scheduler_start() | | - -```{note} -After plugging in the EVB development board to the PC, the PC will enumerate four serial ports. The smallest numbered port is the Boot/LCPU terminal, and the second smallest is the HCPU terminal. Currently, it is recommended for users to focus on the HCPU UART output. The other two serial ports are not assigned yet. + +## 4. Power-on Boot Sequence +| Stage | Function | File Path | +| --------------------------------- | --------------------------- | ----------------------------------------------------------------------- | +| Interrupt Vector Table | ResetHandler | SifliSDK\\drivers\\cmsis\\sf32lb55x\\Templates\\arm\\startup_bf0_hcpu.S | +| MPU configuration, BOOTMODE check | SystemInit() | SifliSDK\\drivers\\cmsis\\sf32lb55x\\Templates\\system_bf0_ap.c | +| RO/RW/ZI initialization | __main() | | +| RT-Thread main entry | `$Sub$$main` | SifliSDK\\rtos\\rtthread\\src\\components.c | +| ^ | rtthread_startup() | SifliSDK\\rtos\\rtthread\\src\\components.c | +| Hardware initialization | rt_hw_board_init() | | +| | HAL_Init(); | | +| RCC configuration | HAL_PreInit() | SifliSDK\\drivers\\boards\\ec-lb551XXX\\drv_io.c | +| | HAL_MspInit() | | +| Pin configuration | BSP_IO_Init() | | +| | rt_system_heap_init | | +| Log console initialization | rt_console_set_device | | +| Driver initialization | rt_components_board_init(); | | +| High-level initialization | rt_application_init() | SifliSDK\\rtos\\rtthread\\src\\components.c | +| | main_thread_entry | SifliSDK\\rtos\\rtthread\\src\\components.c | +| High-level middleware | rt_components_init | | +| | Main() | Project main function | +| Start thread scheduler | rt_system_scheduler_start() | | + +```{note} +When the EVB is connected to a PC, the system enumerates four serial ports. The port with the lowest index serves as the Boot/LCPU terminal, while the second port is the HCPU terminal. Users are currently advised to monitor the HCPU UART output. The remaining two serial ports are currently unassigned. ``` diff --git a/docs/source/en/app_note/rt-pkg.md b/docs/source/en/app_note/rt-pkg.md index 66d3bdaf5..d52a07341 100644 --- a/docs/source/en/app_note/rt-pkg.md +++ b/docs/source/en/app_note/rt-pkg.md @@ -2,15 +2,19 @@ ## Environment Configuration -After configuring the environment using `.\export.ps1` in the SDK path, switch to the project directory where packages need to be configured, and use the following command to enter the configuration interface: +After configuring the environment using `.\export.ps1` in the SDK path, switch +to the project directory where packages need to be configured, and use the +following command to enter the configuration interface: ```shell scons --board=sf32lb52-lcd_n16r8 --menuconfig ``` -After entering the configuration interface, select `RT-Thread online packages` to configure the relevant software packages. +After entering the configuration interface, select `RT-Thread online packages` +to configure the relevant software packages. -**Note**: When using for the first time, you need to execute `sdk.py rt-pkg-upgrade` to download and update the software package configuration. +**Note**: When using for the first time, you need to execute `sdk.py +rt-pkg-upgrade` to download and update the software package configuration. ![](../../assets/rt_pkg_option_packages.png) @@ -24,7 +28,8 @@ sdk.py --help This command can query the usage instructions for rt-pkg related commands. -**Note**: After using this command, if there are no rt-pkg related commands under Commands, please update the local SDK. +**Note**: After using this command, if there are no rt-pkg related commands +under Commands, please update the local SDK. ![](../../assets/rt_pkg_sdk.py--help.png) @@ -34,7 +39,8 @@ This command can query the usage instructions for rt-pkg related commands. sdk.py rt-pkg-list ``` -After adding new packages in `menuconfig`, use this command to output the packages that have been added. +After adding new packages in `menuconfig`, use this command to output the +packages that have been added. **Usage Example**: 1. Select `RT-Thread online packages` in `menuconfig` @@ -44,7 +50,8 @@ After adding new packages in `menuconfig`, use this command to output the packag ![](../../assets/rt_pkg_sdk.py_rt-pkg-list_1.png) -Using this command, you can see the packages that have been added along with their versions: +Using this command, you can see the packages that have been added along with +their versions: ![](../../assets/rt_pkg_sdk.py_rt-pkg-list_2.png) @@ -54,12 +61,13 @@ Using this command, you can see the packages that have been added along with the sdk.py rt-pkg-update ``` -After adding new packages in `menuconfig`, use this command to download the corresponding packages. +After adding new packages in `menuconfig`, use this command to download the +corresponding packages. -**Add Operation**: -![](../../assets/sdk.py_rt-pkg-update_add.png) +**Add Operation**: ![](../../assets/sdk.py_rt-pkg-update_add.png) -**Delete Operation**: After deselecting packages in menuconfig, use this command and enter Y to delete the corresponding packages. +**Delete Operation**: After deselecting packages in menuconfig, use this command +and enter Y to delete the corresponding packages. ![](../../assets/rt_pkg_sdk.py_rt-pkg-update_delete.png) @@ -79,7 +87,8 @@ This command can print environment variables for inspection. sdk.py rt-pkg-upgrade ``` -Use this command to upgrade already configured packages. When using rt-pkg for the first time, you need to use this command to configure the packages. +Use this command to upgrade already configured packages. When using rt-pkg for +the first time, you need to use this command to configure the packages. ![](../../assets/rt-pkg-upgrade.png) @@ -89,7 +98,7 @@ Use this command to upgrade already configured packages. When using rt-pkg for t sdk.py rt-pkg-upgrade-modules ``` -Use this command to upgrade Python module objects +Use this command to upgrade Python module objects ### Create New Package diff --git a/docs/source/en/app_note/scons.md b/docs/source/en/app_note/scons.md index 43e199e2c..070b351a1 100644 --- a/docs/source/en/app_note/scons.md +++ b/docs/source/en/app_note/scons.md @@ -1,96 +1,167 @@ - # SCons and Kconfig Quick Start -SifliSDK provides an Env configuration tool, which already includes SCons and Python. Therefore, there is no need to install SCons on the Windows platform. SifliSDK adds some script libraries on top of SCons to simplify the project configuration for users. +SifliSDK provides an Env configuration tool, which already includes SCons and +Python. Therefore, there is no need to install SCons on the Windows platform. +SifliSDK adds some script libraries on top of SCons to simplify the project +configuration for users. ## 1. Project File Structure -SCons uses SConscript and SConstruct files to organize the source code structure. Typically, a project has only one SConstruct file located in the root directory, but it may have multiple SConscript files. Generally, each subdirectory containing source code will have a corresponding SConscript file. Users can refer to _example\uart\project\ec-lbxxx_ to see the project file structure. - -SifliSDK creates a file called _rtconfig.py_ for each project. Therefore, each project directory will contain the following three files: _rtconfig.py_, _SConstruct_, and _SConscript_, which control the project compilation. A project has only one _SConstruct_ file but may have multiple _SConscript_ files. The _SConscript_ file is the main organizer of the source code. - -SifliSDK uses menuconfig to configure the project. Each project has a Kconfig file in the root directory, which serves as the starting point for configuration options. After configuration, _.config_ and _rtconfig.h_ files are generated in the project root directory, which are used by SCons scripts and C files respectively. - -Most source code folders in SifliSDK also have _SConscript_ files. These files are "found" by the _SConscript_ file in the project root directory, which adds the corresponding source code defined by the macros in _.config/rtconfig.h_ to the compiler. - -The first file executed in SCons compilation is _SConstruct_. The _SConstruct_ in the user's project can configure some project options. Together with the project configuration generated by the menuconfig tool (.config), the `SifliEnv()` function sets the default compilation options. If users need to override the compilation/linking options, they can modify the corresponding parameters in the `Environment()` function. +SCons uses SConscript and SConstruct files to organize the source code +structure. Typically, a project has only one SConstruct file located in the root +directory, but it may have multiple SConscript files. Generally, each +subdirectory containing source code will have a corresponding SConscript file. +Users can refer to _example\uart\project\ec-lbxxx_ to see the project file +structure. + +SifliSDK creates a file called _rtconfig.py_ for each project. Therefore, each +project directory will contain the following three files: _rtconfig.py_, +_SConstruct_, and _SConscript_, which control the project compilation. A project +has only one _SConstruct_ file but may have multiple _SConscript_ files. The +_SConscript_ file is the main organizer of the source code. + +SifliSDK uses menuconfig to configure the project. Each project has a Kconfig +file in the root directory, which serves as the starting point for configuration +options. After configuration, _.config_ and _rtconfig.h_ files are generated in +the project root directory, which are used by SCons scripts and C files +respectively. + +Most source code folders in SifliSDK also have _SConscript_ files. These files +are "found" by the _SConscript_ file in the project root directory, which adds +the corresponding source code defined by the macros in _.config/rtconfig.h_ to +the compiler. + +The first file executed in SCons compilation is _SConstruct_. The _SConstruct_ +in the user's project can configure some project options. Together with the +project configuration generated by the menuconfig tool (.config), the +`SifliEnv()` function sets the default compilation options. If users need to +override the compilation/linking options, they can modify the corresponding +parameters in the `Environment()` function. ## 2. Menuconfig Tool -Kconfig files are the source files for various configuration interfaces. The system configuration interface is called using the `menuconfig` command with the env tool in the project directory. This interface is generated by reading the Kconfig file in the current project directory. The Kconfig file serves as the entry point for all configurations. Kconfig files from different directories can be included in the configuration interface, and the configuration tool generates the system configuration interface for developers by reading the Kconfig files from each directory, ultimately generating the RT-Thread system configuration file _rtconfig.h_. +Kconfig files are the source files for various configuration interfaces. The +system configuration interface is called using the `menuconfig` command with the +env tool in the project directory. This interface is generated by reading the +Kconfig file in the current project directory. The Kconfig file serves as the +entry point for all configurations. Kconfig files from different directories can +be included in the configuration interface, and the configuration tool generates +the system configuration interface for developers by reading the Kconfig files +from each directory, ultimately generating the RT-Thread system configuration +file _rtconfig.h_. -Types: Each config menu item must have a type definition. There are four types of variables: bool, string, hex, and int. +Types: Each config menu item must have a type definition. There are four types +of variables: bool, string, hex, and int. -Reverse dependencies: The `select` statement indicates reverse dependencies, meaning the current configuration option depends on another option being selected. +Reverse dependencies: The `select` statement indicates reverse dependencies, +meaning the current configuration option depends on another option being +selected. -Default values: This represents the default value of the current configuration option. +Default values: This represents the default value of the current configuration +option. -After configuring with the above statements, the following macros will be generated in the _rtconfig.h_ file: +After configuring with the above statements, the following macros will be +generated in the _rtconfig.h_ file: ```c #define ASIC 1 #define BSP_USING_EMPTY_ASSERT 1 ``` -- `menu` statement The `menu` statement is used to generate a menu. A menu is defined using `menu` and `endmenu`, and it can contain many `config` statements. This is simple and won't be detailed further. +- `menu` statement The `menu` statement is used to generate a menu. A menu is + defined using `menu` and `endmenu`, and it can contain many `config` + statements. This is simple and won't be detailed further. -- `if/endif` statement This is used to define conditional statements to decide whether to display a certain configuration option based on a flag. +- `if/endif` statement This is used to define conditional statements to decide + whether to display a certain configuration option based on a flag. -- `menuconfig` statement This represents a configuration option with a menu. The `menuconfig` statement is similar to the `config` statement, but it requires all sub-options to be displayed on separate lines. The `depends on` statement indicates a dependency on another configuration option. +- `menuconfig` statement This represents a configuration option with a menu. The + `menuconfig` statement is similar to the `config` statement, but it requires + all sub-options to be displayed on separate lines. The `depends on` statement + indicates a dependency on another configuration option. -- `choice/endchoice` statement This groups multiple similar configuration options together for the user to choose from. The `prompt` statement gives a hint to be displayed as the title of a popup. Multiple options can be provided, but only one can be selected, similar to a radio button. +- `choice/endchoice` statement This groups multiple similar configuration + options together for the user to choose from. The `prompt` statement gives a + hint to be displayed as the title of a popup. Multiple options can be + provided, but only one can be selected, similar to a radio button. -- `comment` statement The `comment` statement appears at the top of the interface and is used to define informational messages. +- `comment` statement The `comment` statement appears at the top of the + interface and is used to define informational messages. -- `source` statement This is used to read Kconfig files from another file. +- `source` statement This is used to read Kconfig files from another file. For more detailed configuration, refer to [](../app_note/menuconfig.md). ## 3. Basic Functions of SCons -You can compile the project directly by entering the `scons` command in the Env tool. By default, it uses the ARM CLANG compiler. The SifliSDK root directory contains a _set_env.bat_ file, which sets the compiler directory. +You can compile the project directly by entering the `scons` command in the Env +tool. By default, it uses the ARM CLANG compiler. The SifliSDK root directory +contains a _set_env.bat_ file, which sets the compiler directory. -If you want to specify your own compiler, you can modify the commands in _set_env.bat_: +If you want to specify your own compiler, you can modify the commands in +_set_env.bat_: -```batch -set RTT_CC = keil -set RTT_EXEC = C:/Keilv5 -``` + set RTT_CC = keil + set RTT_EXEC = C:/Keilv5 -Scons command -This command not only compiles the project but also generates MDK/IAR/VS projects. Adding different parameters will result in different effects. +Scons command This command not only compiles the project but also generates +MDK/IAR/VS projects. Adding different parameters will result in different +effects. - The `-s` parameter will suppress printing of internal commands. -- The `-c` parameter will clean the build targets, temporary files, and object files. -- The `--target=XXX` parameter is used when using MDK/IAR for project development. If you modify _rtconfig.h_ to enable or disable certain components, you need to use this parameter to regenerate the corresponding customized project and then compile it in MDK/IAR. +- The `-c` parameter will clean the build targets, temporary files, and object + files. +- The `--target=XXX` parameter is used when using MDK/IAR for project + development. If you modify _rtconfig.h_ to enable or disable certain + components, you need to use this parameter to regenerate the corresponding + customized project and then compile it in MDK/IAR. ```{warning} Note: To generate MDK or IAR project files, the prerequisite is that the project directory contains a project template file. Only then will `scons` generate the relevant source code, header file search paths, compiler parameters, and linker parameters based on the template. The template file typically specifies which chip the project is for. Therefore, in most cases, the template file is an empty project file, used to assist _SCons_ in generating _project.uvprojx_ or _project.eww_. To make it easier for customers, if no _project.uvprojx_ is found, SiFliSDK will use a default template to generate _project.uvprojx_. If you don't want to use the default template (for example, if you want to add your own compilation options), you can copy the _template.uvprojx_ file from _SifliSDK\tools\build\template_ into your project directory as your own template and make the necessary changes. ``` -- The `-jN` parameter enables multi-threaded compilation. On a multi-core machine, you can use this command to speed up the compilation. Generally, one CPU core can support two threads. On a dual-core machine, use `scons -j4`. -- The `--verbose` parameter is used to display the compilation parameters. By default, the output of the `scons` command does not show compilation parameters, but with this parameter, the compilation parameters will be displayed. +- The `-jN` parameter enables multi-threaded compilation. On a multi-core + machine, you can use this command to speed up the compilation. Generally, one + CPU core can support two threads. On a dual-core machine, use `scons -j4`. +- The `--verbose` parameter is used to display the compilation parameters. By + default, the output of the `scons` command does not show compilation + parameters, but with this parameter, the compilation parameters will be + displayed. ## 4. Built-in Functions of SCons +If you want to add some source code to the _SCons_ compilation environment, you +can generally create or modify an existing _SConscript_ file. -If you want to add some source code to the _SCons_ compilation environment, you can generally create or modify an existing _SConscript_ file. +The SConscript file controls the inclusion of source code files and allows you +to specify the file's group (similar to the concept of groups in MDK/IAR IDEs). -The SConscript file controls the inclusion of source code files and allows you to specify the file's group (similar to the concept of groups in MDK/IAR IDEs). - -SCons provides many built-in functions to help us quickly add source code. By using these functions in combination with simple Python statements, we can freely add or remove source code from the project. Below are some commonly used functions. In fact, each _SConscript_ file is a Python file. +SCons provides many built-in functions to help us quickly add source code. By +using these functions in combination with simple Python statements, we can +freely add or remove source code from the project. Below are some commonly used +functions. In fact, each _SConscript_ file is a Python file. - `GetCurrentDir()` function: Gets the current directory. -- `Glob('*.c')` function: Gets all C files in the current directory. You can modify the suffix in the parameter to match files of a specific type. -- `GetDepend(macro)` function: Defined in the script file in the tools directory, this function reads configuration information from the _rtconfig.h_ file. Its parameter is the macro name from _rtconfig.h_. If a macro is enabled in _rtconfig.h_, this function will return true; otherwise, it returns false. +- `Glob('*.c')` function: Gets all C files in the current directory. You can + modify the suffix in the parameter to match files of a specific type. +- `GetDepend(macro)` function: Defined in the script file in the tools + directory, this function reads configuration information from the _rtconfig.h_ + file. Its parameter is the macro name from _rtconfig.h_. If a macro is enabled + in _rtconfig.h_, this function will return true; otherwise, it returns false. - `Split(str)` function: Splits the string `str` into a list. -- `DefineGroup(name, src, depend, **parameters)` function: This is a method (function) extended from _SCons_. `DefineGroup` is used to define a component. A component can be a directory (including files or subdirectories) and also a group or folder in subsequent IDE project files. The parameters can include: - - - `LIBS=`: Links a specific library into the project. - - `LIBPATH=`: Adds a library path for searching. - - `LIBRARY=`: Compiles and links all source code in the group to generate a .lib file. - - `INSTALL_PATH=`: Installs the generated .lib file to a specific directory. - - `CCFLAGS=`: Adds compiler options. - - `CPPPATH=`: Adds a C header file search directory. - - `CPPDEFINES=`: Adds C macro definitions. - - `LINKFLAGS=`: Adds linker options. - - `ASFLAGS=`: Adds assembly options. +- `DefineGroup(name, src, depend, **parameters)` function: This is a method + (function) extended from _SCons_. `DefineGroup` is used to define a component. + A component can be a directory (including files or subdirectories) and also a + group or folder in subsequent IDE project files. The parameters can include: + + - `LIBS=`: Links a specific library into the project.
+ - `LIBPATH=`: Adds a library path for searching.
+ - `LIBRARY=`: Compiles and links all source code in the group to + generate a .lib file.
+ - `INSTALL_PATH=`: Installs the generated .lib file to a specific + directory.
+ - `CCFLAGS=`: Adds compiler options.
+ - `CPPPATH=`: Adds a C header file search directory.
+ - `CPPDEFINES=`: Adds C macro definitions.
+ - `LINKFLAGS=`: Adds linker options.
+ - `ASFLAGS=`: Adds assembly options.
+ diff --git a/docs/source/en/app_note/sensor.md b/docs/source/en/app_note/sensor.md index da2621dc7..457549012 100644 --- a/docs/source/en/app_note/sensor.md +++ b/docs/source/en/app_note/sensor.md @@ -1,17 +1,34 @@ - # Sensor Adding Guide ## 1. Preparation -When a new sensor device needs to be added to the SiFli Technology SDK, the first step is to determine the sensor's functionality type and interface type.
-From a functionality perspective, supported sensors include 6-axis (acceleration, angular velocity), temperature, pressure, geomagnetic, light sensing, GPS, motor, etc. From an interface perspective, the currently supported types include I2C, SPI, and UART.
-Once the device's datasheet is obtained, first determine the interface used, ensuring with hardware that the necessary interfaces are enabled and routed through the pins. Additionally, verify that the voltage and frequency ranges match. Then, based on the functional descriptions in the datasheet, confirm with the user the interfaces and other information required.
+When a new sensor device needs to be added to the SiFli Technology SDK, the +first step is to determine the sensor's functionality type and interface type. +
From a functionality perspective, supported sensors include 6-axis +(acceleration, angular velocity), temperature, pressure, geomagnetic, light +sensing, GPS, motor, etc. From an interface perspective, the currently supported +types include I2C, SPI, and UART.
Once the device's datasheet is obtained, +first determine the interface used, ensuring with hardware that the necessary +interfaces are enabled and routed through the pins. Additionally, verify that +the voltage and frequency ranges match. Then, based on the functional +descriptions in the datasheet, confirm with the user the interfaces and other +information required.
+ ## 2. Code Preparation -Currently, peripheral code is placed under _rtos/rthread/bsp/sifli/peripherals_. After confirming the interface and implementation plan, a new directory is added under this path. -Additionally, the _rtos/rthread/bsp/sifli/peripherals/Kconfig_ file needs to be modified to include menuconfig items, such as sensor control macros, I2C/SPI interface configuration, pin settings for switches, power, and interrupts.
-Once the Kconfig modifications are complete, implement the code in the newly added directory. The interface names, pin numbers, interrupt numbers, etc., used in the code can be obtained from the configuration in Kconfig. Finally, link the Kconfig switch macros in the SConscript file for the directory.
-After completing the code and configuration, go to the project directory's menuconfig configuration page. Choose "Select board peripherals" to enter the peripheral configuration. Find the newly added module, enable it, and proceed with further configuration.
+Currently, peripheral code is placed under _rtos/rthread/bsp/sifli/peripherals_. +After confirming the interface and implementation plan, a new directory is added +under this path. Additionally, the _rtos/rthread/bsp/sifli/peripherals/Kconfig_ +file needs to be modified to include menuconfig items, such as sensor control +macros, I2C/SPI interface configuration, pin settings for switches, power, and +interrupts.
Once the Kconfig modifications are complete, implement the +code in the newly added directory. The interface names, pin numbers, interrupt +numbers, etc., used in the code can be obtained from the configuration in +Kconfig. Finally, link the Kconfig switch macros in the SConscript file for the +directory.
After completing the code and configuration, go to the project +directory's menuconfig configuration page. Choose "Select board peripherals" to +enter the peripheral configuration. Find the newly added module, enable it, and +proceed with further configuration.
## 3. Interface Configuration @@ -52,15 +69,27 @@ menuconfig SENSOR_USING_6D endif endif ``` -The macro `SENSOR_USING_6D` is the main switch for enabling the 6D sensor in the system. Below, the supported sensor models will be listed, such as LSM6DSL, SC7A20, etc. It's recommended to enable only one sensor at a time to avoid interface conflicts.
-For LSM6DSL, `ACC_USING_LSM6DSL` is the switch for this specific sensor.
-`LSM6DSL_USING_I2C` defines the interface type. Since this sensor supports both I2C and SPI, the configuration must specify which interface is used. If the sensor only supports one interface, this configuration is unnecessary.
-`LSM6DSL_BUS_NAME` is used to define the interface name, which RT-Thread's sensor uses to find the interface device. For more details, refer to the code implementation.
-`LSM6DSL_INT_GPIO_BIT/LSM6DSL_INT2_GPIO_BIT` define the interrupt pins (if allocated in hardware).
-`LSM_USING_AWT/LSM_USING_PEDO/LSM6DSL_USE_FIFO` correspond to specific functionalities of the sensor and are not explained here.
- -Example of using interface devices:
-Through the `rt_i2c_bus_device_find` or `rt_device_find` functions, you can find the bus device, then call the corresponding read/write functions of the bus according to the interface mode to read and write to the device. The specific control commands for the device need to be implemented based on the device's address and register definitions from the datasheet.
+The macro `SENSOR_USING_6D` is the main switch for enabling the 6D sensor in the +system. Below, the supported sensor models will be listed, such as LSM6DSL, +SC7A20, etc. It's recommended to enable only one sensor at a time to avoid +interface conflicts.
For LSM6DSL, `ACC_USING_LSM6DSL` is the switch for +this specific sensor.
`LSM6DSL_USING_I2C` defines the interface type. +Since this sensor supports both I2C and SPI, the configuration must specify +which interface is used. If the sensor only supports one interface, this +configuration is unnecessary.
`LSM6DSL_BUS_NAME` is used to define the +interface name, which RT-Thread's sensor uses to find the interface device. For +more details, refer to the code implementation.
+`LSM6DSL_INT_GPIO_BIT/LSM6DSL_INT2_GPIO_BIT` define the interrupt pins (if +allocated in hardware).
`LSM_USING_AWT/LSM_USING_PEDO/LSM6DSL_USE_FIFO` +correspond to specific functionalities of the sensor and are not explained +here.
+ +Example of using interface devices:
Through the `rt_i2c_bus_device_find` +or `rt_device_find` functions, you can find the bus device, then call the +corresponding read/write functions of the bus according to the interface mode to +read and write to the device. The specific control commands for the device need +to be implemented based on the device's address and register definitions from +the datasheet.
```c int LSM6DSL_I2C_Init() { @@ -117,13 +146,16 @@ int32_t LSM_I2C_Read(void *ctx, uint8_t reg, uint8_t *data, uint16_t len) return -3; } - ``` -Example of using interrupt PINs:
-Set the interrupt PIN to input mode using `rt_pin_mode`; -Set the interrupt handler and conditions for triggering the interrupt using `rt_pin_attach_irq`, where interrupts can be triggered on rising edge `PIN_IRQ_MODE_RISING`, falling edge `PIN_IRQ_MODE_FALLING`, both edges `PIN_IRQ_MODE_RISING_FALLING`, or high/low level `PIN_IRQ_MODE_HIGH_LEVEL` / `PIN_IRQ_MODE_LOW_LEVEL`;
-Enable or disable interrupts using `rt_pin_irq_enable`. The interrupt handler implementation depends on the specific sensor.
+Example of using interrupt PINs:
Set the interrupt PIN to input mode using +`rt_pin_mode`; Set the interrupt handler and conditions for triggering the +interrupt using `rt_pin_attach_irq`, where interrupts can be triggered on rising +edge `PIN_IRQ_MODE_RISING`, falling edge `PIN_IRQ_MODE_FALLING`, both edges +`PIN_IRQ_MODE_RISING_FALLING`, or high/low level `PIN_IRQ_MODE_HIGH_LEVEL` / +`PIN_IRQ_MODE_LOW_LEVEL`;
Enable or disable interrupts using +`rt_pin_irq_enable`. The interrupt handler implementation depends on the +specific sensor.
```c int lsm6dsl_gpio_int_enable(void) { @@ -156,13 +188,17 @@ int lsm6dsl_gpio_int_enable(void) ## 4. Register SENSOR Device -In the added device directory, create a file `sensor_xxx.c` to register the new sensor device to the RT-Thread sensor device list, so that upper-level code can directly control the corresponding sensor device through the sensor device.
-This part mainly consists of two parts: device registration and control callback implementation.
-The code example is for the BMP280 barometric and temperature sensor:
-Fill in the device information, interface type, data range, etc., then register it to the sensor device list using the `rt_hw_sensor_register` function. The `sensor_ops` defines the operation callbacks.
-The callback handles mainly include data reading, mode control, sleep/wake-up, etc.
+In the added device directory, create a file `sensor_xxx.c` to register the new +sensor device to the RT-Thread sensor device list, so that upper-level code can +directly control the corresponding sensor device through the sensor device. +
This part mainly consists of two parts: device registration and control +callback implementation.
The code example is for the BMP280 barometric and +temperature sensor:
Fill in the device information, interface type, data +range, etc., then register it to the sensor device list using the +`rt_hw_sensor_register` function. The `sensor_ops` defines the operation +callbacks.
The callback handles mainly include data reading, mode control, +sleep/wake-up, etc.
```c - int rt_hw_bmp280_init(const char *name, struct rt_sensor_config *cfg) { rt_int8_t result; @@ -175,23 +211,23 @@ int rt_hw_bmp280_init(const char *name, struct rt_sensor_config *cfg) goto __exit; } - /* temperature sensor register */ + /* Register temperature sensor */ { sensor_temp = rt_calloc(1, sizeof(struct rt_sensor_device)); if (sensor_temp == RT_NULL) return -1; - sensor_temp->info.type = RT_SENSOR_CLASS_TEMP; - sensor_temp->info.vendor = RT_SENSOR_VENDOR_BOSCH; - sensor_temp->info.model = "bmp280_temp"; - sensor_temp->info.unit = RT_SENSOR_UNIT_DCELSIUS; - sensor_temp->info.intf_type = RT_SENSOR_INTF_I2C; - sensor_temp->info.range_max = 85; - sensor_temp->info.range_min = -40; - sensor_temp->info.period_min = 5; + sensor_temp->info.type = RT_SENSOR_CLASS_TEMP; + sensor_temp->info.vendor = RT_SENSOR_VENDOR_BOSCH; + sensor_temp->info.model = "bmp280_temp"; + sensor_temp->info.unit = RT_SENSOR_UNIT_DCELSIUS; + sensor_temp->info.intf_type = RT_SENSOR_INTF_I2C; + sensor_temp->info.range_max = 85; + sensor_temp->info.range_min = -40; + sensor_temp->info.period_min = 5; - rt_memcpy(&sensor_temp->config, cfg, sizeof(struct rt_sensor_config)); - sensor_temp->ops = &sensor_ops; + rt_memcpy(&sensor_temp->config, cfg, sizeof(struct rt_sensor_config)); + sensor_temp->ops = &sensor_ops; result = rt_hw_sensor_register(sensor_temp, name, RT_DEVICE_FLAG_RDWR, RT_NULL); if (result != RT_EOK) @@ -201,23 +237,23 @@ int rt_hw_bmp280_init(const char *name, struct rt_sensor_config *cfg) } } - /* barometer sensor register */ + /* Register barometer sensor */ { sensor_baro = rt_calloc(1, sizeof(struct rt_sensor_device)); if (sensor_baro == RT_NULL) goto __exit; - sensor_baro->info.type = RT_SENSOR_CLASS_BARO; - sensor_baro->info.vendor = RT_SENSOR_VENDOR_BOSCH; - sensor_baro->info.model = "bmp280_bora"; - sensor_baro->info.unit = RT_SENSOR_UNIT_PA; - sensor_baro->info.intf_type = RT_SENSOR_INTF_I2C; - sensor_baro->info.range_max = 110000; - sensor_baro->info.range_min = 30000; - sensor_baro->info.period_min = 5; + sensor_baro->info.type = RT_SENSOR_CLASS_BARO; + sensor_baro->info.vendor = RT_SENSOR_VENDOR_BOSCH; + sensor_baro->info.model = "bmp280_bora"; + sensor_baro->info.unit = RT_SENSOR_UNIT_PA; + sensor_baro->info.intf_type = RT_SENSOR_INTF_I2C; + sensor_baro->info.range_max = 110000; + sensor_baro->info.range_min = 30000; + sensor_baro->info.period_min = 5; - rt_memcpy(&sensor_baro->config, cfg, sizeof(struct rt_sensor_config)); - sensor_baro->ops = &sensor_ops; + rt_memcpy(&sensor_baro->config, cfg, sizeof(struct rt_sensor_config)); + sensor_baro->ops = &sensor_ops; result = rt_hw_sensor_register(sensor_baro, name, RT_DEVICE_FLAG_RDWR, RT_NULL); if (result != RT_EOK) @@ -239,19 +275,24 @@ __exit: rt_free(bmp_dev); return -RT_ERROR; } - ``` ## 5. Debug Method -After adding the code, you can perform basic functionality verification of the sensor device by adding a command-line function.
- -Create a command function `int cmd_xxx(int argc, char *argv[])`, and use `FINSH_FUNCTION_EXPORT_ALIAS` to register the function as a Finsh command.
-The command function should include the following methods:
-Sensor initialization— including interface initialization and device address checking;
-Register read/write—use I2C/SPI interfaces to perform read and write operations to the SENSOR's internal registers.
-Sensor functionality verification—this depends on the specific sensor type. For example, a pressure sensor should be able to get the correct pressure, a temperature sensor should get the temperature, and an accelerometer should retrieve velocity information.
-The following is part of the command-line implementation for the BMP280 pressure sensor:
+After adding the code, you can perform basic functionality verification of the +sensor device by adding a command-line function.
+ +Create a command function `int cmd_xxx(int argc, char *argv[])`, and use +`FINSH_FUNCTION_EXPORT_ALIAS` to register the function as a Finsh command.
+The command function should include the following methods:
Sensor +initialization— including interface initialization and device address checking; +
Register read/write—use I2C/SPI interfaces to perform read and write +operations to the SENSOR's internal registers.
Sensor functionality +verification—this depends on the specific sensor type. For example, a pressure +sensor should be able to get the correct pressure, a temperature sensor should +get the temperature, and an accelerometer should retrieve velocity information. +
The following is part of the command-line implementation for the BMP280 +pressure sensor:
```c #define DRV_BMP280_TEST @@ -317,7 +358,8 @@ int cmd_bmpt(int argc, char *argv[]) FINSH_FUNCTION_EXPORT_ALIAS(cmd_bmpt, __cmd_bmpt, Test driver bmp280); #endif //DRV_BMP280_TEST - ``` + + diff --git a/docs/source/en/app_note/watchdog.md b/docs/source/en/app_note/watchdog.md index f720f9419..dd7069c1b 100644 --- a/docs/source/en/app_note/watchdog.md +++ b/docs/source/en/app_note/watchdog.md @@ -1,26 +1,41 @@ - # Watchdog Usage Guide ## Using the Watchdog -The SiFli SF32LB55X chip provides a corresponding watchdog for both HCPU and LCPU. In the SDK, you can enable the watchdog by enabling the following switch in the project via menuconfig.
+The SiFli SF32LB55X chip provides a corresponding watchdog for both HCPU and +LCPU. In the SDK, you can enable the watchdog by enabling the following switch +in the project via menuconfig.
![](../../assets/watchdog.png) -This switch enables the chip's hardware watchdog and also activates the RT-Thread watchdog software driver. The default watchdog timeout is 30 seconds. +This switch enables the chip's hardware watchdog and also activates the +RT-Thread watchdog software driver. The default watchdog timeout is 30 seconds. -If you need to modify the watchdog's timeout, you can make the following configuration in menuconfig: +If you need to modify the watchdog's timeout, you can make the following +configuration in menuconfig: ![](../../assets/watchdog2.png) ## Notes -- The system will automatically feed the watchdog in the IDLE thread. If other threads do not run continuously beyond the watchdog's timeout, no additional code is needed. +- The system will automatically feed the watchdog in the IDLE thread. If other + threads do not run continuously beyond the watchdog's timeout, no additional + code is needed. + +- If the user has a high-priority thread that needs to run continuously beyond + the watchdog timeout (this use case is rare), the user needs to call + `rt_hw_watchdog_pet()` in the corresponding thread to ensure the watchdog is + fed before the timeout occurs. -- If the user has a high-priority thread that needs to run continuously beyond the watchdog timeout (this use case is rare), the user needs to call `rt_hw_watchdog_pet()` in the corresponding thread to ensure the watchdog is fed before the timeout occurs. +- When the system enters Standby/hibernate sleep modes, the watchdog will be + disabled. It will be re-enabled when the system wakes up. In other sleep + modes, the watchdog will continue running. The system must be woken up and fed + the watchdog before the timeout. -- When the system enters Standby/hibernate sleep modes, the watchdog will be disabled. It will be re-enabled when the system wakes up. In other sleep modes, the watchdog will continue running. The system must be woken up and fed the watchdog before the timeout. +- The HCPU uses the system watchdog. When triggered, it will reset the entire + chip. -- The HCPU uses the system watchdog. When triggered, it will reset the entire chip. +- The LCPU uses the LCPU subsystem's watchdog. When triggered, it generates an + interrupt. The interrupt handler will trigger a software restart of the entire + chip. -- The LCPU uses the LCPU subsystem's watchdog. When triggered, it generates an interrupt. The interrupt handler will trigger a software restart of the entire chip. diff --git a/docs/source/en/audio/audio_dump.md b/docs/source/en/audio/audio_dump.md index a5f3e92ad..80107dffc 100644 --- a/docs/source/en/audio/audio_dump.md +++ b/docs/source/en/audio/audio_dump.md @@ -1,41 +1,70 @@ # Audio PCM Raw Data Dump - Sometimes it is necessary to examine the raw audio data, such as gain levels and noise, by saving the data at nodes where the audio data passes through for offline analysis. Currently, two methods are supported: using the `siflitrace` tool to dump audio data in real-time via serial port or saving audio PCM data to a file for later export and analysis. Only scenarios involving both microphone and speaker operation are currently supported for data dumping. For file-based methods, it is preferable to store files on the NAND flash file system rather than the NOR flash (as speed may be insufficient). When dumping audio data, ensure the BT HCI log is disabled. You can use `nvds update hci_log 0` to disable it, then restart the device. +Sometimes it is necessary to examine the raw audio data, such as gain levels and +noise, by saving the data at nodes where the audio data passes through for +offline analysis. Currently, two methods are supported: using the `siflitrace` +tool to dump audio data in real-time via serial port or saving audio PCM data to +a file for later export and analysis. Only scenarios involving both microphone +and speaker operation are currently supported for data dumping. For file-based +methods, it is preferable to store files on the NAND flash file system rather +than the NOR flash (as speed may be insufficient). When dumping audio data, +ensure the BT HCI log is disabled. You can use `nvds update hci_log 0` to +disable it, then restart the device. ## 1 Dump via serial port ### 1.1 Serial port configuration -To use serial port dump, DMA should be used to enable the tx DMA configuration for the corresponding serial port. For example, if serial port 1 is used, BSP_UART1-TX-USING-DMA should be enabled +To use serial port dump, DMA should be used to enable the tx DMA configuration +for the corresponding serial port. For example, if serial port 1 is used, +BSP_UART1-TX-USING-DMA should be enabled -Calculate how many data streams need to be dumped at the same time, and whether it is necessary to increase the baud rate of the serial port RT_SRIAL_DFAUULTRATE +Calculate how many data streams need to be dumped at the same time, and whether +it is necessary to increase the baud rate of the serial port +RT_SRIAL_DFAUULTRATE -For example, if three 16k sampling rates of call data are dumped simultaneously, and 16k * 3 * 2=80k or more, the default 1M baud rate is not very rich, and it is best to change it to 1500000 baud rate. -The higher the baud rate, the better. Some USB serial port adapters may not meet the set baud rate, which can cause data loss. Using the default 1M baud rate, it is possible to dump two data streams at once. +For example, if three 16k sampling rates of call data are dumped simultaneously, +and 16k * 3 * 2=80k or more, the default 1M baud rate is not very rich, and it +is best to change it to 1500000 baud rate. The higher the baud rate, the better. +Some USB serial port adapters may not meet the set baud rate, which can cause +data loss. Using the default 1M baud rate, it is possible to dump two data +streams at once. ### 1.2 software configuration -- Check these two in audio_Server. c, the default values are as follows (only supports serial port dump) +- Check these two in audio_Server. c, the default values are as follows (only + supports serial port dump) ```c #define AUDIO_DATA_CAPTURE_UART //#define AUDIO_DATA_CAPTURE_FILE ``` -- If you want to support saving to a file, change it to this way: file dump mode takes priority, and serial port dump becomes invalid +- If you want to support saving to a file, change it to this way: file dump mode + takes priority, and serial port dump becomes invalid ```c #define AUDIO_DATA_CAPTURE_UART #define AUDIO_DATA_CAPTURE_FILE ``` -- enable RT_USING_FINSH in RT-thread -To dump data through serial port, you need to input the command 'audio_data' through the serial port, which corresponds to the command function 'audio_data_cmd()' in audio_Server. c. Enter 'help' through the serial port, and you should be able to see the command 'audio_data'. +- enable RT_USING_FINSH in RT-thread To dump data through serial port, you need + to input the command 'audio_data' through the serial port, which corresponds + to the command function 'audio_data_cmd()' in audio_Server. c. Enter 'help' + through the serial port, and you should be able to see the command + 'audio_data'. ### 1.3 dump Tool -Download and install the new SifliTrace tool(https://wiki.sifli.com/tools/index.html) -After opening the tool, select the serial port for logging the large core, select the audio, and then click connect. You should be able to see the large core log, and then you can enter the audio_data command to dump data (the system cannot sleep, otherwise the command cannot be entered) +Download and install the new SifliTrace +tool(https://wiki.sifli.com/tools/index.html) After opening the tool, select the +serial port for logging the large core, select the audio, and then click +connect. You should be able to see the large core log, and then you can enter +the audio_data command to dump data (the system cannot sleep, otherwise the +command cannot be entered) -The parameters after the audio_data command indicate which data channels can be dumped (if the serial port baudrate is not high, it cannot carry too much) +The parameters after the audio_data command indicate which data channels can be +dumped (if the serial port baudrate is not high, it cannot carry too much) -The meaning of different algorithm parameters varies, depending on the code in the manual. The default webRTC parameter meanings are as follows (different versions may have differences, depending on the code in the manual) +The meaning of different algorithm parameters varies, depending on the code in +the manual. The default webRTC parameter meanings are as follows (different +versions may have differences, depending on the code in the manual) ``` -audprc data from mic -downlink BT downlink data @@ -43,13 +72,19 @@ The meaning of different algorithm parameters varies, depending on the code in t -aecm_out Data after echo cancellation algorithm -ramp_out_out Data sending to BT ``` -The system log cannot be seen during the dump data process. Entering audio_data - stop after the dump stops the dump data and restores the system log printing. Some versions will crash during this process. It may be that LOG_HEX was called during the middle note, but LOG_HEX is still using the serial port. The newer version has solved the problem. After dumping the data, click "Save" on the tool. The dump result will be found in the xxx_audio directory of the tool's log directory, and the latest date will be the current dump date - - - -The correspondence between types and parameters in commands can be found in the audio_data_cmd() function in audio_derver. c +The system log cannot be seen during the dump data process. Entering audio_data +- stop after the dump stops the dump data and restores the system log printing. +Some versions will crash during this process. It may be that LOG_HEX was called +during the middle note, but LOG_HEX is still using the serial port. The newer +version has solved the problem. After dumping the data, click "Save" on the +tool. The dump result will be found in the xxx_audio directory of the tool's log +directory, and the latest date will be the current dump date + + +The correspondence between types and parameters in commands can be found in the +audio_data_cmd() function in audio_derver. c ``` - ADUMP_DOWNLINK -downlink +ADUMP_DOWNLINK -downlink ADUMP_DOWNLINK_AGC -downlink_agc ADUMP_AUDPRC -audprc ADUMP_DC_OUT -dc_out @@ -62,8 +97,11 @@ The correspondence between types and parameters in commands can be found in the ADUMP_RAMP_OUT_OUT -ramp_out_out ADUMP_PDM_RX -pdm ``` -A typical dump is to add a dump before and after the algorithm in audio_3a *. c, usually only dumping the algorithm input and output. Depending on which type of dump is used for each data channel in the corresponding version, the corresponding parameters are used. -If Ankai algorithm is used, corresponding to audio_3a_anyka. c, it supports these parameters +A typical dump is to add a dump before and after the algorithm in audio_3a *. c, +usually only dumping the algorithm input and output. Depending on which type of +dump is used for each data channel in the corresponding version, the +corresponding parameters are used. If Ankai algorithm is used, corresponding to +audio_3a_anyka. c, it supports these parameters ``` -audprc data from mic -downlink BT downlink data @@ -74,8 +112,9 @@ If Ankai algorithm is used, corresponding to audio_3a_anyka. c, it supports thes ``` ## 2. Modify dump type -If you want to modify it yourself, search for where to call audio_rump_data(). The first parameter represents the type and cannot be added by yourself. The tool will not recognize it after adding it -There are currently so many types: +If you want to modify it yourself, search for where to call audio_rump_data(). +The first parameter represents the type and cannot be added by yourself. The +tool will not recognize it after adding it There are currently so many types: ```c typedef enum { @@ -94,18 +133,23 @@ typedef enum ADUMP_NUM, } audio_dump_type_t; ``` -Adding data of the same type can only be used by one channel of data, and two channels of data cannot use the same type to cause data confusion +Adding data of the same type can only be used by one channel of data, and two +channels of data cannot use the same type to cause data confusion ## BLE Audio Dump -If you want to support saving to a file, change it to this way: file dump mode takes priority, and serial port dump becomes invalid +If you want to support saving to a file, change it to this way: file dump mode +takes priority, and serial port dump becomes invalid ```c #define AUDIO_DATA_CAPTURE_UART #define AUDIO_DATA_CAPTURE_FILE ``` ### FAQ1 How to use SiFliBleApp to dump audio data -- Purpose: Use SIFLI BLE APP to dump audio data and export the data to mobile devices. -- After downloading and installing SifliBleApp, click the search button and then click SORT to refresh the device. Connect to BLE based on the MAC address and click on the device to view its information. +- Purpose: Use SIFLI BLE APP to dump audio data and export the data to mobile + devices. +- After downloading and installing SifliBleApp, click the search button and then + click SORT to refresh the device. Connect to BLE based on the MAC address and + click on the device to view its information. @@ -113,11 +157,14 @@ If you want to support saving to a file, change it to this way: file dump mode t -- Click CONNECT, note: The connection process needs to wait for a while, when the state is CONNECT. +- Click CONNECT, note: The connection process needs to wait for a while, when + the state is CONNECT. -- After connecting to BLE, click READER, then click SELECT DUMP TYPE to select the data type that needs to be dumped. For example, choose DOWLINK, select Finish, and click ON to start dumping data +- After connecting to BLE, click READER, then click SELECT DUMP TYPE to select + the data type that needs to be dumped. For example, choose DOWLINK, select + Finish, and click ON to start dumping data @@ -125,28 +172,39 @@ If you want to support saving to a file, change it to this way: file dump mode t ### FAQ2 software code for Ble_Audio_dump -- The dump data needs to be saved into the file system, with a defined save path and file name. All dump files are saved in the root directory. +- The dump data needs to be saved into the file system, with a defined save path + and file name. All dump files are saved in the root directory. -- When using ble dump audio data, there may be an error stating that the DOWNLINK_STANCK_SIZE is not enough. You can try increasing the DOWNLINK_STANCK_SIZE slightly. +- When using ble dump audio data, there may be an error stating that the + DOWNLINK_STANCK_SIZE is not enough. You can try increasing the + DOWNLINK_STANCK_SIZE slightly. -- Note: Using BLE to dump audio data may conflict with UART to dump audio data. So you can define another AUDIO_daTA_CPTUREFHIR LE macro, and once it is defined, it will not execute audio_dataw_rite_art(). +- Note: Using BLE to dump audio data may conflict with UART to dump audio data. + So you can define another AUDIO_daTA_CPTUREFHIR LE macro, and once it is + defined, it will not execute audio_dataw_rite_art(). -- If we need to adjust the dump data entered by d_record_time, we can use a custom command to set the input time by using the "time=" command. For example, in the SIFLI BLE APP, we can input "time=15" into the SEND and set the duration of dump data entry to 15. +- If we need to adjust the dump data entered by d_record_time, we can use a + custom command to set the input time by using the "time=" command. For + example, in the SIFLI BLE APP, we can input "time=15" into the SEND and set + the duration of dump data entry to 15. ### FAQ3 How to export dump files using SiFliBleApp -- After the dump is completed, you can export the file to your mobile device using GET DUMP +- After the dump is completed, you can export the file to your mobile device + using GET DUMP -- This file will be stored in the Android/data/com. sifli. siflible/files/DeviceAudioDump directory on the mobile device. +- This file will be stored in the Android/data/com. sifli. + siflible/files/DeviceAudioDump directory on the mobile device. + diff --git a/docs/source/en/audio/audio_tuning.md b/docs/source/en/audio/audio_tuning.md index be83736a7..1cefbab0d 100644 --- a/docs/source/en/audio/audio_tuning.md +++ b/docs/source/en/audio/audio_tuning.md @@ -1,3 +1,3 @@ # Audio Tuning Guide -please download[Audio Tuning Guide](/extra/audio_tuning_guide.pdf) \ No newline at end of file +please download[Audio Tuning Guide](/extra/audio_tuning_guide.pdf) diff --git a/docs/source/en/audio/index.md b/docs/source/en/audio/index.md index f83bb0a55..eaffb97c2 100644 --- a/docs/source/en/audio/index.md +++ b/docs/source/en/audio/index.md @@ -1,9 +1,8 @@ # audio tuning - + ```{toctree} :titlesonly: :glob: * - ``` diff --git a/docs/source/en/audio/mic.md b/docs/source/en/audio/mic.md index c25aea60c..96aef854c 100644 --- a/docs/source/en/audio/mic.md +++ b/docs/source/en/audio/mic.md @@ -1,21 +1,31 @@ # Mic Gain Debug -## EQ Tool -[Sifli_EQ](https://wiki.sifli.com/tools/index.html) -The EQ tool can adjust the digital microphone gain by modifying the variable `g_adc_volume` in the file `drv_audprc.c`. The default value of this variable is 0, and reducing it decreases the microphone gain. Most echo cancellation algorithms require microphone sampling values to remain between 3k and 5k. -The microphone sampling values can be captured using the audio dump tool. Currently, the platform software for the microphone is set to 16-bit, with a saturation range of -32768 to +32767. Sometimes, when the microphone gain is lowered, it may saturate at lower values, affecting echo cancellation performance. -At this point, the g_adc_volume can be set to 0 to adjust the rough volumeThe code is located in bf0_hal_audcodec.c (56x/58x platform) or bf0_hal_audcodec_m.c (52x/57x platform)Here, the rough vol is set to 0xc. To address this, reduce the value corresponding to ADC_CH0_CFG_ROUGH_VOL by changing it from 0xc to 0xa. -By appropriately lowering the rough vol, this digital gain value can be reduced to improve the issue of excessively low saturation. -The step size for the value of ROUGH_VOL is 6 dB, with the corresponding settings as follows: -```c -0 ----- -60db -1 ----- -54db +## EQ Tool +[Sifli_EQ](https://wiki.sifli.com/tools/index.html) The EQ tool can adjust the +digital microphone gain by modifying the variable `g_adc_volume` in the file +`drv_audprc.c`. The default value of this variable is 0, and reducing it +decreases the microphone gain. Most echo cancellation algorithms require +microphone sampling values to remain between 3k and 5k. The microphone sampling +values can be captured using the audio dump tool. Currently, the platform +software for the microphone is set to 16-bit, with a saturation range of -32768 +to +32767. Sometimes, when the microphone gain is lowered, it may saturate at +lower values, affecting echo cancellation performance. At this point, the +g_adc_volume can be set to 0 to adjust the rough volumeThe code is located in +bf0_hal_audcodec.c (56x/58x platform) or bf0_hal_audcodec_m.c (52x/57x +platform)Here, the rough vol is set to 0xc. To address this, reduce the value +corresponding to ADC_CH0_CFG_ROUGH_VOL by changing it from 0xc to 0xa. By +appropriately lowering the rough vol, this digital gain value can be reduced to +improve the issue of excessively low saturation. The step size for the value of +ROUGH_VOL is 6 dB, with the corresponding settings as follows: +``` +0 ----- -60dB +1 ----- -54dB ... ... -0xa ----- 0db -0xb ----- 6db +0xa ----- 0dB +0xb ----- 6dB ... -0xf ----- 30db +0xf ----- 30dB ``` FINE_VOL value is 0 ~ 0xc,corresponding 0~6db, step is 0.5db @@ -33,12 +43,19 @@ hacodec->Instance_lp->ADC_CH0_CFG = (1 << AUDCODEC_LP_ADC_CH0_CFG_ENABLE_Pos) ```c //52x/57x - hacodec->Instance->ADC_CH0_CFG = (1 << AUDCODEC_ADC_CH0_CFG_ENABLE_Pos) | - (0 << AUDCODEC_ADC_CH0_CFG_HPF_BYPASS_Pos) | - (0x7 << AUDCODEC_ADC_CH0_CFG_HPF_COEF_Pos) | - (0 << AUDCODEC_ADC_CH0_CFG_STB_INV_Pos) | - (0 << AUDCODEC_ADC_CH0_CFG_DMA_EN_Pos) | - (0xc << AUDCODEC_ADC_CH0_CFG_ROUGH_VOL_Pos) | - (0 << AUDCODEC_ADC_CH0_CFG_FINE_VOL_Pos) | - (1 << AUDCODEC_ADC_CH0_CFG_DATA_FORMAT_Pos); + hacodec->Instance->ADC_CH0_CFG = (1 << AUDCODEC_ADC_CH0_CFG_ENABLE_Pos) | + (0 << AUDCODEC_ADC_CH0_CFG_HPF_BYPASS_Pos) | + (0x7 << AUDCODEC_ADC_CH0_CFG_HPF_COEF_Pos) | + (0 << AUDCODEC_ADC_CH0_CFG_STB_INV_Pos) | + (0 << AUDCODEC_ADC_CH0_CFG_DMA_EN_Pos) | + (0xc << AUDCODEC_ADC_CH0_CFG_ROUGH_VOL_Pos) | + (0 << AUDCODEC_ADC_CH0_CFG_FINE_VOL_Pos) | + (1 << AUDCODEC_ADC_CH0_CFG_DATA_FORMAT_Pos); +``` + +If saturation persists, decrease the value corresponding to the analog register +ADC1_CFG1_GC. Note that adjusting analog gain is generally not recommended. To +proceed, search for ADC1_CFG1 in the code and slightly decrease its value. +```c +ADC1_CFG1 |= (0x1E << AUDCODEC_LP_ADC1_CFG1_GC_Pos); ``` diff --git a/docs/source/en/bootloader.md b/docs/source/en/bootloader.md index 34cb892eb..043da56b6 100644 --- a/docs/source/en/bootloader.md +++ b/docs/source/en/bootloader.md @@ -1,85 +1,117 @@ # Secure Bootloader -The butterfli on-chip ROM contains a secure bootloader with the following features: +The butterfli on-chip ROM contains a secure bootloader with the following +features: - UART download -- AES encryption for image file transmission, Flash can store encrypted images with hardware real-time decryption for execution, also supports plaintext images -- Encrypted storage of image keys, preventing execution on different butterfli chips even if encrypted images are copied -- RSA digital signature verification for image file integrity, preventing download of illegal image files +- AES encryption for image file transmission, Flash can store encrypted images + with hardware real-time decryption for execution, also supports plaintext + images +- Encrypted storage of image keys, preventing execution on different butterfli + chips even if encrypted images are copied +- RSA digital signature verification for image file integrity, preventing + download of illegal image files - PingPong download - Install patches to modify Flash drivers ## Keys The bootloader uses the following keys: - rootkey: Stored in the non-readable area of efuse, used to encrypt image keys -- image key: Key used for image encryption/decryption, stored in Flash after encryption with rootkey -- Digital signature RSA public key: Used to decrypt and verify image identity and integrity -- UID: Chip ID, stored in the readable area of efuse, used as nonce parameter to encrypt image keys +- image key: Key used for image encryption/decryption, stored in Flash after + encryption with rootkey +- Digital signature RSA public key: Used to decrypt and verify image identity + and integrity +- UID: Chip ID, stored in the readable area of efuse, used as nonce parameter to + encrypt image keys Image encryption download process: -1. Write rootkey, digital signature public key hash, and UID to efuse (only once) -2. Download Flash configuration table and digital signature public key to Flash (only once) -3. Encrypt image using image key, calculate hash of encrypted data using SHA256, encrypt hash using digital signature private key to obtain digital signature, -package image header (encrypted with rootkey, containing image key and other information), encrypted image, and digital signature to generate final encrypted image -4. Transmit encrypted image, bootloader extracts image key from image header to decrypt image, after receiving, compare digital signature to confirm source and verify integrity, if valid, download is successful +1. Write rootkey, digital signature public key hash, and UID to efuse (only + once) +2. Download Flash configuration table and digital signature public key to Flash + (only once) +3. Encrypt image using image key, calculate hash of encrypted data using SHA256, + encrypt hash using digital signature private key to obtain digital signature, + package image header (encrypted with rootkey, containing image key and other + information), encrypted image, and digital signature to generate final + encrypted image +4. Transmit encrypted image, bootloader extracts image key from image header to + decrypt image, after receiving, compare digital signature to confirm source + and verify integrity, if valid, download is successful ## Boot Modes -The bootloader boot mode can be set through bootmode jumpers. If jumper is connected to 0, it's normal boot mode where bootloader reads flash to determine if user program can be booted. If jumper is connected to 1, it enters download mode waiting for PC to send download commands. -In normal boot mode, if no valid user image is found on flash, it automatically enters download mode. +The bootloader boot mode can be set through bootmode jumpers. If jumper is +connected to 0, it's normal boot mode where bootloader reads flash to determine +if user program can be booted. If jumper is connected to 1, it enters download +mode waiting for PC to send download commands. In normal boot mode, if no valid +user image is found on flash, it automatically enters download mode. + ## Memory Planning **Default Flash Address Space Planning** -|Name | Start Address | End Address | Size(bytes)| Description -|-----------------|----------------|----------------|------------|-------- -|Flash Config Table| 0x10000000 | 0x10004FFF | 20*1024 | | -|Calibration Table| 0x10005000 | 0x10006FFF | 8*1024 | | -|Reserved | 0x10007000 | 0x1000FFFF | 36*1024 | | -|bootrom patch | 0x10010000 | 0x1001FFFF | 64*1024 | | -|User Code | 0x10020000 | | | | +| Name | Start Address | End Address | Size(bytes) | Description | +| ------------------ | ------------- | ----------- | ----------- | ----------- | +| Flash Config Table | 0x10000000 | 0x10004FFF | 20*1024 | | +| Calibration Table | 0x10005000 | 0x10006FFF | 8*1024 | | +| Reserved | 0x10007000 | 0x1000FFFF | 36*1024 | | +| BootROM Patch | 0x10010000 | 0x1001FFFF | 64*1024 | | +| User Code | 0x10020000 | | | | + +The location and format of the Flash configuration table cannot be modified. The +addresses and sizes of other table entries are specified by the Flash +configuration table. -The location and format of the Flash configuration table cannot be modified. The addresses and sizes of other table entries are specified by the Flash configuration table. **Flash Configuration Table Format** -Name | Start Offset | End Offset | Size(bytes)| Description -------------------|----------------|----------------|------------|------------ -MAGIC | 0x00000000 | 0x00000003 | 4 | 0x53454346 -Flash Partition Table| 0x00000004 | 0x00000103 | 16*16 | 16 partitions -Digital Signature Public Key| 0x00000104| 0x00000229| 294 | RSA public key in DER format -Reserved | 0x0000022A | 0x00000FFF | 3542 | | -Image Descriptor Table| 0x00001000 | 0x00002BFF | 14*512 | 14 image descriptor entries -Image Index Table | 0x00002C00 | 0x00002C0F | 4*4 | Points to active (currently running) image descriptor table entry +| Name | Start Offset | End Offset | Size(bytes) | Description | +| ---------------------------- | ------------ | ---------- | ----------- | ----------------------------------------------------------------- | +| MAGIC | 0x00000000 | 0x00000003 | 4 | 0x53454346 | +| Flash Partition Table | 0x00000004 | 0x00000103 | 16*16 | 16 partitions | +| Digital Signature Public Key | 0x00000104 | 0x00000229 | 294 | RSA public key in DER format | +| Reserved | 0x0000022A | 0x00000FFF | 3542 | | +| Image Descriptor Table | 0x00001000 | 0x00002BFF | 14*512 | 14 image descriptor entries | +| Image Index Table | 0x00002C00 | 0x00002C0F | 4*4 | Points to active (currently running) image descriptor table entry | + + -The Flash partition table consists of 16 partition information entries, each specifying the start address and size of the partition. + +The Flash partition table consists of 16 partition information entries, each +specifying the start address and size of the partition. **Partition Table** -|Index | Name | Description -|------------|---------------------|------------ -|0 | Flash Partition Table| | -|1 | Calibration Table | | -|2 | LCPU image Ping area| | -|3 | BCPU image Ping area| | -|4 | HCPU image Ping area| | -|5 | Flash Boot patch area| | -|6 | LCPU image Pong area| | -|7 | BCPU image Pong area| | -|8 | HCPU image Pong area| | -|9 | RAM Boot patch area | | -|10 | HCPU image extension area 1| | -|11 | HCPU image extension area 2| | -|12 | LCPU image extension area 1| | -|13 | LCPU image extension area 2| | -|14 | Reserved | | -|15 | Reserved | | +| Index | Name | Description | +| ----- | --------------------------- | ----------- | +| 0 | Flash Partition Table | | +| 1 | Calibration Table | | +| 2 | LCPU image Ping area | | +| 3 | BCPU image Ping area | | +| 4 | HCPU image Ping area | | +| 5 | Flash Boot patch area | | +| 6 | LCPU image Pong area | | +| 7 | BCPU image Pong area | | +| 8 | HCPU image Pong area | | +| 9 | RAM Boot patch area | | +| 10 | HCPU image extension area 1 | | +| 11 | HCPU image extension area 2 | | +| 12 | LCPU image extension area 1 | | +| 13 | LCPU image extension area 2 | | +| 14 | Reserved | | +| 15 | Reserved | | + + **Partition Information Format** -Name | Size(bytes)| Description -------------------|------------|------------ -Partition Start Address| 4 | Start address of partition -Partition Size | 4 | Partition size -Partition Execute Address| 4 | For image partitions, specifies the execution address of this partition -Flags | 4 | Unused - -The following table shows the default Flash configuration table. `struct sec_configuration` is the data structure name for the Flash configuration table. +| Name | Size(bytes) | Description | +| ------------------------- | ----------- | ----------------------------------------------------------------------- | +| Partition Start Address | 4 | Start address of partition | +| Partition Size | 4 | Partition Size | +| Partition Execute Address | 4 | For image partitions, specifies the execution address of this partition | +| Flags | 4 | Unused | + + + + +The following table shows the default Flash configuration table. `struct +sec_configuration` is the data structure name for the Flash configuration table. ```c const struct sec_configuration sec_config = { @@ -106,50 +138,62 @@ const struct sec_configuration sec_config = .imgs[13] = {.length = 0xFFFFFFFF}, .running_imgs[0] = (struct image_header_enc *)0xFFFFFFFF, .running_imgs[1] = (struct image_header_enc *)0xFFFFFFFF, - .running_imgs[2] = (struct image_header_enc *) &sec_config.imgs[2], + .running_imgs[2] = (struct image_header_enc *) &sec_config.imgs[2], .running_imgs[3] = (struct image_header_enc *)0xFFFFFFFF, }; ``` -The bootrom uses the RAM address space shown in the following table. When using bootrom to boot user programs to execute in RAM, address space conflicts must be avoided. +The bootrom uses the RAM address space shown in the following table. When using +bootrom to boot user programs to execute in RAM, address space conflicts must be +avoided. **Bootloader RAM Address Space** -Name | Start Address | End Address | Size(bytes)| Description ------------------|----------------|----------------|------------|-------- -DATA | 0x20040000 | 0x2004FFFF | 64*1024 | Bootrom data -PATCH CODE | 0x20050000 | 0x2005FFFF | 64*1024 | Patch code -PATCH DATA | 0x20060000 | 0x2006FFFF | 64*1024 | Patch data +| Name | Start Address | End Address | Size(bytes) | Description | +| ---------- | ------------- | ----------- | ----------- | ------------ | +| DATA | 0x20040000 | 0x2004FFFF | 64*1024 | Bootrom data | +| PATCH CODE | 0x20050000 | 0x2005FFFF | 64*1024 | Patch code | +| PATCH DATA | 0x20060000 | 0x2006FFFF | 64*1024 | Patch data | + ## Encrypted Image Generation and Download ### Download without bootloader -Use JTAG to download the default Flash configuration table provided by SDK to address `0x10000000`, then download unencrypted user image to address `0x10020000`. After reset, the bootloader can boot the user image to run. The user image is compiled using address `0x10020000`. +Use JTAG to download the default Flash configuration table provided by SDK to +address `0x10000000`, then download unencrypted user image to address +`0x10020000`. After reset, the bootloader can boot the user image to run. The +user image is compiled using address `0x10020000`. ### Download with bootloader -Related tools are located in `$sdk_root/tools/secureboot`. The bootloader uses the chip's UART4 as the download serial port. +Related tools are located in `$sdk_root/tools/secureboot`. The bootloader uses +the chip's UART4 as the download serial port. #### Generate Keys -Execute script `genkeys.bat` to generate UID, rootkey, digital signature keys and public key hash. +Execute script `genkeys.bat` to generate UID, rootkey, digital signature keys +and public key hash. ```bat genkeys.bat sifli01 ``` -`sifli01` is the path for generating keys. After running, the following files will be generated: +`sifli01` is the path for generating keys. After running, the following files +will be generated: + +| Name | Description | +| ------------ | ------------------------------------------ | +| s01.bin | rootkey | +| uid.bin | rootkey | +| sig_hash.bin | Digital signature public key hash | +| sig_pri.pem | Digital signature private key | +| sig_pub.pem | Digital Signature Public Key | +| sig_pub.der | Digital signature public key in DER format | -Name | Description --------------|------------ -s01.bin | rootkey -uid.bin | rootkey -sig_hash.bin | Digital signature public key hash -sig_pri.pem | Digital signature private key -sig_pub.pem | Digital signature public key -sig_pub.der | Digital signature public key in DER format #### Program Keys -Programming keys to efuse can only be executed once. After programming, the keys in efuse cannot be modified. +Programming keys to efuse can only be executed once. After programming, the keys +in efuse cannot be modified. 1. Set butterfli bootmode jumper to download mode 2. Enter bootloader download mode after reset -3. Run script `program_efuse.bat` to program keys. The first parameter is the path where keys are located, the second parameter is the serial port number +3. Run script `program_efuse.bat` to program keys. The first parameter is the + path where keys are located, the second parameter is the serial port number ```bat program_efuse.bat sifli01/ COM3 ``` @@ -157,36 +201,48 @@ program_efuse.bat sifli01/ COM3 #### Download Flash Configuration Table 1. Enter bootloader download mode -2. Run script `factory_flash_default.bat` to download flash configuration table (`ftab\ftab_flash_default.json`) and digital signature public key. The first parameter is the path where keys are located, the second parameter is the serial port number +2. Run script `factory_flash_default.bat` to download flash configuration table + (`ftab\ftab_flash_default.json`) and digital signature public key. The first + parameter is the path where keys are located, the second parameter is the + serial port number ```bat factory_flash_default.bat sifli01/ COM3 ``` -If the Flash configuration table has not changed, there is no need to download it again when updating the image. +If the Flash configuration table has not changed, there is no need to download +it again when updating the image. #### Generate Image ##### Encrypted Image -Run `gen_sec_img.bat`. The first parameter is the path where keys are located, the second parameter is the image path to be encrypted. The generated encrypted image is named `image_sec.bin` +Run `gen_sec_img.bat`. The first parameter is the path where keys are located, +the second parameter is the image path to be encrypted. The generated encrypted +image is named `image_sec.bin` ```bat gen_sec_img.bat sifli01/ example.bin ``` ##### Plaintext Image -Run `gen_plain_img.bat`. The first parameter is the path where keys are located, the second parameter is the image path to be encrypted. The generated encrypted image is named `image_plain.bin` +Run `gen_plain_img.bat`. The first parameter is the path where keys are located, +the second parameter is the image path to be encrypted. The generated encrypted +image is named `image_plain.bin` ```bat gen_plain_img.bat sifli01/ example.bin ``` + #### Download Image ##### Encrypted Image -Run `download_sec_image.bat`. The specified port is the serial port used by the bootloader +Run `download_sec_image.bat`. The specified port is the serial port used by the +bootloader ```bat download_sec_image.bat --port=COM3 ``` + #### Plaintext Image -Run `download_plain_image.bat`. The specified port is the serial port used by the bootloader +Run `download_plain_image.bat`. The specified port is the serial port used by +the bootloader ```bat download_plain_image.bat --port=COM3 -``` \ No newline at end of file +``` diff --git a/docs/source/en/contribute/coding_style.md b/docs/source/en/contribute/coding_style.md index 012874292..07f0e663b 100644 --- a/docs/source/en/contribute/coding_style.md +++ b/docs/source/en/contribute/coding_style.md @@ -1,40 +1,55 @@ - # Coding Style (Non-HAL Modules) -This is a development guideline for SiFli-SDK developers. Since SiFli-SDK is based on RT-Thread, the coding style for modules other than HAL is consistent with that of RT-Thread. +This is a development guideline for SiFli-SDK developers. Since SiFli-SDK is +based on RT-Thread, the coding style for modules other than HAL is consistent +with that of RT-Thread. ## 1. Directory Names -Directory names should be in all lowercase unless there is a special requirement. The directory name should reflect the content, such as chip-specific directories named after the chip or chip category, and components directories should reflect the purpose of the component. +Directory names should be in all lowercase unless there is a special +requirement. The directory name should reflect the content, such as +chip-specific directories named after the chip or chip category, and components +directories should reflect the purpose of the component. ## 2. File Names -File names should be in all lowercase unless there is a special requirement (if referencing files from elsewhere, the original name may be kept). To avoid name conflicts, avoid using common or frequently used names. +File names should be in all lowercase unless there is a special requirement (if +referencing files from elsewhere, the original name may be kept). To avoid name +conflicts, avoid using common or frequently used names. -Device driver source files: Naming convention follows `drv_class.c`, for example: +Device driver source files: Naming convention follows `drv_class.c`, for +example: - drv_spi.c - drv_gpio.c ## 3. Header File Definitions -To avoid multiple inclusions of C language header files, a symbol must be defined. The format for defining this symbol should follow this style: +To avoid multiple inclusions of C language header files, a symbol must be +defined. The format for defining this symbol should follow this style: ```c - #ifndef __FILE_H__ +#ifndef __FILE_H__ #define __FILE_H__ /* header file content */ #endif ``` -Symbols should be wrapped with "__" to avoid conflicts. If the file name contains multiple words, they can be connected with underscores. +Symbols should be wrapped with "__" to avoid conflicts. If the file name +contains multiple words, they can be connected with underscores. ## 4. Variables -Variable names should use lowercase letters and "_" to connect them. To avoid name conflicts, global variables should start with the module name, for example, `pm_reg_ctx` is a global variable for the `pm` module. Static variables can omit the module name and should preferably begin with `s_`, for example, `static bool s_freq_scaling_enabled = true;` +Variable names should use lowercase letters and "_" to connect them. To avoid +name conflicts, global variables should start with the module name, for example, +`pm_reg_ctx` is a global variable for the `pm` module. Static variables can omit +the module name and should preferably begin with `s_`, for example, `static bool +s_freq_scaling_enabled = true;` + ## 5. Enum Definitions -Enum values should use uppercase, and enum types should be in lowercase with "_" connecting the words. +Enum values should use uppercase, and enum types should be in lowercase with "_" +connecting the words. -```c +``` enum rt_object_class_type { RT_Object_Class_Null = 0, /**< The object is not used. */ @@ -56,41 +71,49 @@ enum rt_object_class_type ## 6. Structure Definitions -Structure names should be in lowercase letters, with words connected by "_". For example: +Structure names should be in lowercase letters, with words connected by "_". For +example: ```c - struct rt_list_node +struct rt_list_node { struct rt_list_node *next; struct rt_list_node *prev; }; ``` -Where **"{" and "}"** should be placed on separate lines, and subsequent member definitions should be indented. +Where **"{" and "}"** should be placed on separate lines, and subsequent member +definitions should be indented. -Type definitions should use the structure or enum name followed by "_t", such as: +Type definitions should use the structure or enum name followed by "_t", such +as: ```c - typedef struct rt_list_node rt_list_t; +typedef struct rt_list_node rt_list_t; ``` ## 7. Macro Definitions -Macro definitions should use uppercase letters with words connected by "_". For example: +Macro definitions should use uppercase letters with words connected by "_". For +example: ```c - #define RT_TRUE 1 +#define RT_TRUE 1 ``` ## 8. Function Names and Declarations -Function names should be in lowercase letters, with words connected by "_". APIs provided for upper-level applications must be declared in the corresponding header file. If the function's entry parameter is empty, `void` should be used as the entry parameter. +Function names should be in lowercase letters, with words connected by "_". APIs +provided for upper-level applications must be declared in the corresponding +header file. If the function's entry parameter is empty, `void` should be used +as the entry parameter. ```c rt_thread_t rt_thread_self(void); ``` -Internal static functions should be named with an underscore prefix, such as `_class_method`, without the `_rt_` prefix, for example: +Internal static functions should be named with an underscore prefix, such as +`_class_method`, without the `_rt_` prefix, for example: ```c /* IPC object init */ @@ -98,20 +121,23 @@ static rt_err_t _ipc_object_init() /* UART driver ops */ static rt_err_t _uart_configure() -static rt_err_t _uart_control() +static rt_err_t _uart_control() ``` -Functions calling the device registration interface should follow the naming pattern `rt_hw_class_init()`, for example: +Functions calling the device registration interface should follow the naming +pattern `rt_hw_class_init()`, for example: ```c int rt_hw_uart_init(void) int rt_hw_spi_init(void) ``` -Function names should follow the module name + verb pattern. For example, in the `rt_timer` module, function names are composed of the module name `rt_timer` + verb phrase: +Function names should follow the module name + verb pattern. For example, in the +`rt_timer` module, function names are composed of the module name `rt_timer` + +verb phrase: ```c - struct rt_timer +struct rt_timer { struct rt_object parent; /* other fields */ @@ -119,6 +145,7 @@ Function names should follow the module name + verb pattern. For example, in the typedef struct rt_timer* rt_timer_t; ``` + ```c rt_timer_t rt_timer_create(const char* name, void (*timeout)(void* parameter), @@ -131,11 +158,17 @@ rt_err_t rt_timer_stop(rt_timer_t timer); ## 9. Commenting -Please use **English** for comments. Writing comments in Chinese would require constant switching between input languages, disrupting coding flow. Using English comments also facilitates better communication with developers outside China. +Please use **English** for comments. Writing comments in Chinese would require +constant switching between input languages, disrupting coding flow. Using +English comments also facilitates better communication with developers outside +China. **Statement Comments**: -Comments in the source code should not be excessive. Most comments should explain what the code does, and only complex algorithms should have explanatory comments on how they work. Comments should only appear **above or to the right** of the statement, any other positions are invalid. +Comments in the source code should not be excessive. Most comments should +explain what the code does, and only complex algorithms should have explanatory +comments on how they work. Comments should only appear **above or to the right** +of the statement, any other positions are invalid. ```c /* Your English comment */ @@ -143,7 +176,28 @@ Comments in the source code should not be excessive. Most comments should explai **Function Comments**: -Use the [doxygen style](https://www.doxygen.nl/manual/commands.html), starting with `/**` and ending with `*/`, with the function comment in between. The structure should align the description elements, and each element should be separated by a blank line. Example: +Use the [doxygen style](https://www.doxygen.nl/manual/commands.html), starting +with `/**` and ending with `*/`, with the function comment in between. The +structure should align the description elements, and each element should be +separated by a blank line. Example: + +- @brief + Brief function description. Emphasize the primary purpose of the + function. Capitalize the first letter of each sentence and end with a period. +- @note + Detailed function remarks. Provide technical details or clarifications + not covered in the brief description. Capitalize the first letter of each + sentence and end with a period. +- @see + Related API references. List APIs that are closely related to the + current function. +- @param + [Parameter name] + [be verb] + description. State the meaning, + purpose, or source of the parameter. +- @return + [Enumerated return value] + description. If the return value is a + data type, describe its function or meaning. +- @warning + Critical usage notes. Describe precautions such as operating + environment requirements or usage constraints. Capitalize the first letter of + each sentence and end with a period. + +For comment templates, refer to the rt-thread/src/ipc.c source file. Utilize +Grammarly or Google Translate for English phrasing assistance. ```C /** @@ -180,9 +234,10 @@ rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) ``` ### Structure Members and Enum Value Comments -For alignment purposes, structure member and enum value comments should be placed on the right side of the code, also following the [doxygen style](https://www.doxygen.nl/manual/commands.html), for example: - -```c +For alignment purposes, structure member and enum value comments should be +placed on the right side of the code, also following the [doxygen +style](https://www.doxygen.nl/manual/commands.html), for example: +``` enum rt_object_class_type { RT_Object_Class_Null = 0, /**< The object is not used. */ @@ -202,44 +257,51 @@ enum rt_object_class_type }; ``` + ## 10. Indentation and Line Breaks -Indentation should use 4 spaces. If there is no special meaning, please break the line after "{" and indent subsequent lines, for example: +Indentation should use 4 spaces. If there is no special meaning, please break +the line after "{" and indent subsequent lines, for example: ```c - if (condition) +if (condition) { /* others */ } ``` -The only exception is the `switch` statement, where `switch-case` statements should align with the `switch`, for example: +The only exception is the `switch` statement, where `switch-case` statements +should align with the `switch`, for example: ```c - switch (value) +switch (value) { case value1: break; } ``` -Do not use more than one blank line consecutively in the code unless there is a special need. +Do not use more than one blank line consecutively in the code unless there is a +special need. ## 11. Braces and Spaces -From a readability perspective, each brace should occupy its own line, not be placed at the end of a statement: +From a readability perspective, each brace should occupy its own line, not be +placed at the end of a statement: ```c - if (condition) +if (condition) { /* others */ } ``` -Matching braces should be on separate lines to provide structure and avoid confusion. A space should be added before parentheses in non-function calls to distinguish them, for example: +Matching braces should be on separate lines to provide structure and avoid +confusion. A space should be added before parentheses in non-function calls to +distinguish them, for example: ```c - if (x <= y) +if (x <= y) { /* others */ } @@ -253,32 +315,46 @@ Matching braces should be on separate lines to provide structure and avoid confu No spaces should appear inside parentheses of expressions, for example: ```c - if (x <= y) +if (x <= y) { /* other */ } ``` -It is recommended to use the `.clang-format` configuration file from the SDK root directory for code formatting, ensuring consistency in coding style. +It is recommended to use the `.clang-format` configuration file from the SDK +root directory for code formatting, ensuring consistency in coding style. + +It is recommended to use the `.clang-format` file located in the SDK root +directory as the configuration file for `clang-format`. This ensures consistency +in code styling across the project. ## 12. Logging Information Use `ulog` for logging output, for example: -```c +``` #define DBG_TAG "Driver" #define DBG_LVL DBG_INFO #include -LOG_D("this is a debug log."); +LOG_D("this is a debug log."); ``` -- In RT-Thread, commonly used log levels are `LOG_D`, `LOG_I`, `LOG_W`, `LOG_E`, and they can be differentiated by `DBG_TAG` and controlled by `DBG_LVL`. +- In RT-Thread, commonly used log levels are `LOG_D`, `LOG_I`, `LOG_W`, `LOG_E`, + and they can be differentiated by `DBG_TAG` and controlled by `DBG_LVL`. - Logs should be output in a way that is easy to understand and diagnose. -- Do not redefine `DBG_TAG` in header files to prevent uncontrollable issues when other modules include it. +- Do not redefine `DBG_TAG` in header files to prevent uncontrollable issues + when other modules include it. - Avoid excessive logging in timers or interrupts, and keep logs lightweight. -- Avoid using `rt_kprintf` for logging, as it is generally used for terminal command-line interactions. +- Avoid using `rt_kprintf` for logging, as it is generally used for terminal + command-line interactions. ## 13. Functions -Functions should be as concise as possible, performing only relatively independent, simple tasks. The implementation of a function should not be too long. If a function becomes too lengthy, consider refactoring or splitting it into smaller, more understandable parts. +Functions should be as concise as possible, performing only relatively +independent, simple tasks. The implementation of a function should not be too +long. If a function becomes too lengthy, consider refactoring or splitting it +into smaller, more understandable parts. + + + diff --git a/docs/source/en/contribute/creating-examples.md b/docs/source/en/contribute/creating-examples.md index a6ad2c461..75abb14ab 100644 --- a/docs/source/en/contribute/creating-examples.md +++ b/docs/source/en/contribute/creating-examples.md @@ -1,26 +1,55 @@ - # Creating Example Projects -Each SiFli-SDK example is a complete project that others can copy to their local machine and modify according to their needs. Please note that example projects are primarily meant to showcase the functionality of SiFli-SDK. +Each SiFli-SDK example is a complete project that others can copy to their local +machine and modify according to their needs. Please note that example projects +are primarily meant to showcase the functionality of SiFli-SDK. ## Example Project Structure -- The `src` directory must contain a source file named `main.c`, which includes the main functionality of the example project. -- If the example project has multiple sub-tasks, split them into multiple C or C++ source files under the `main` directory and place the corresponding header files in the same directory. -- The example project must include a `README.md` file. It is recommended to use the [Example Project README Template (English)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README.md) or the [Example Project README Template (Chinese)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README_CN.md) and modify it according to the project's actual situation. +- The `src` directory must contain a source file named `main.c`, which includes + the main functionality of the example project. +- If the example project has multiple sub-tasks, split them into multiple C or + C++ source files under the `main` directory and place the corresponding header + files in the same directory. +- The example project must include a `README.md` file. It is recommended to use + the [Example Project README Template + (English)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README.md) + or the [Example Project README Template + (Chinese)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README_CN.md) + and modify it according to the project's actual situation. ## General Guidelines -The example code must adhere to the requirements in the [SiFli-SDK Coding Guidelines](coding_style.md). The code in the example project must be clear, readable, and maintainable. +The example code must adhere to the requirements in the [SiFli-SDK Coding +Guidelines](coding_style.md). The code in the example project must be clear, +readable, and maintainable. ## Checklist Before submitting a new example project, ensure the following: -- Each example project should focus on one main feature. If an example project has multiple main features, it should be split into two or more projects. -- Each example project must include a `README.md` file. It is recommended to use the [Example Project README Template (English)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README.md) or the [Example Project README Template (Chinese)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README_CN.md). -- Functions and variable names in the example project should follow the rules outlined in the [SiFli-SDK Coding Guidelines](coding_style.md). Non-static variables/functions that are used only within the example project's source file should be prefixed with `example` or another similar prefix. -- All code in the example project should be well-structured, with key sections clearly commented. -- Any unnecessary code in the example project (such as old debug logs, commented-out code, etc.) should be removed. -- Options used in the example project (such as network names, addresses, etc.) must not be hard-coded. Configuration options, or defined macros/constants, should be used wherever possible. -- All source code must specify licensing information at the beginning of the file (indicating that the code is `in the public domain CC0`) and include a disclaimer. Alternatively, the source code can apply the `Apache License 2.0`. Please refer to the licensing information and disclaimers of existing example projects and modify them as necessary. -- Any third-party code (whether used directly or with modifications) must retain the original licensing information, and the licensing must be compatible with the `Apache License 2.0` agreement. +- Each example project should focus on one main feature. If an example project + has multiple main features, it should be split into two or more projects. +- Each example project must include a `README.md` file. It is recommended to use + the [Example Project README Template + (English)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README.md) + or the [Example Project README Template + (Chinese)](https://github.com/OpenSiFli/SiFli-SDK/blob/main/docs/TEMPLATE_EXAMPLE_README_CN.md). +- Functions and variable names in the example project should follow the rules + outlined in the [SiFli-SDK Coding Guidelines](coding_style.md). Non-static + variables/functions that are used only within the example project's source + file should be prefixed with `example` or another similar prefix. +- All code in the example project should be well-structured, with key sections + clearly commented. +- Any unnecessary code in the example project (such as old debug logs, + commented-out code, etc.) should be removed. +- Options used in the example project (such as network names, addresses, etc.) + must not be hard-coded. Configuration options, or defined macros/constants, + should be used wherever possible. +- All source code must specify licensing information at the beginning of the + file (indicating that the code is `in the public domain CC0`) and include a + disclaimer. Alternatively, the source code can apply the `Apache License 2.0`. + Please refer to the licensing information and disclaimers of existing example + projects and modify them as necessary. +- Any third-party code (whether used directly or with modifications) must retain + the original licensing information, and the licensing must be compatible with + the `Apache License 2.0` agreement. diff --git a/docs/source/en/contribute/index.md b/docs/source/en/contribute/index.md index b015f91a0..8341c61e0 100644 --- a/docs/source/en/contribute/index.md +++ b/docs/source/en/contribute/index.md @@ -1,37 +1,52 @@ - # Contribution Guidelines + Welcome to contribute to the SiFli-SDK project! ## How to Contribute -We welcome contributions to the SiFli-SDK project, such as bug fixes, new features, documentation additions, etc. You can submit your contributions via [Github Pull Requests](https://github.com/OpenSiFli/SiFli-SDK/pulls). +We welcome contributions to the SiFli-SDK project, such as bug fixes, new +features, documentation additions, etc. You can submit your contributions via +[Github Pull Requests](https://github.com/OpenSiFli/SiFli-SDK/pulls). ## Preparation Before submitting a Pull Request, please check the following points: -- Is the contribution entirely your own work, or has it been obtained with an open-source license compatible with Apache License 2.0? If not, we cannot accept the contribution. - -- Is the code sufficiently commented, making it easier for readers to understand its structure? -- Has the code been formatted using clang-format? Please use the format defined in the `.clang-format` file. For coding style guidelines, refer to [Coding Style](coding_style.md). +- Is the contribution entirely your own work, or has it been obtained with an + open-source license compatible with Apache License 2.0? If not, we cannot + accept the contribution. + +- Is the code sufficiently commented, making it easier for readers to understand + its structure? +- Has the code been formatted using clang-format? Please use the format defined + in the `.clang-format` file. For coding style guidelines, refer to [Coding + Style](coding_style.md). - Does the contribution include documentation or examples? -- Are the comments and documentation written in clear English with no spelling or grammatical errors? +- Are the comments and documentation written in clear English with no spelling + or grammatical errors? - New code examples are welcome contributions. -- If submitting multiple changes, have you grouped all changes by type (each pull request corresponds to one main change)? -- If unsure about any of the above points, feel free to submit a Pull Request and seek feedback from us. +- If submitting multiple changes, have you grouped all changes by type (each + pull request corresponds to one main change)? +- If unsure about any of the above points, feel free to submit a Pull Request + and seek feedback from us. ## Pull Request Submission Process -After creating the Pull Request, there may be discussions about the request in the PR comments section. +After creating the Pull Request, there may be discussions about the request in +the PR comments section. -Once the Pull Request is ready for merging, it will first be merged into our internal Git system for automated testing. +Once the Pull Request is ready for merging, it will first be merged into our +internal Git system for automated testing. -After passing the testing process, your contribution will be merged into the public GitHub repository. +After passing the testing process, your contribution will be merged into the +public GitHub repository. ## Legal Compliance -Before submitting contributions, you need to sign the Contributor License Agreement (CLA). The agreement will be automatically prompted during the Pull Request process. +Before submitting contributions, you need to sign the Contributor License +Agreement (CLA). The agreement will be automatically prompted during the Pull +Request process. ## Related Documents @@ -40,5 +55,4 @@ Before submitting contributions, you need to sign the Contributor License Agreem coding_style creating-examples - ``` diff --git a/docs/source/en/copyright/copyright.md b/docs/source/en/copyright/copyright.md index 2aab6aeee..c347c6bce 100644 --- a/docs/source/en/copyright/copyright.md +++ b/docs/source/en/copyright/copyright.md @@ -1,77 +1,122 @@ # Copyright and License -2019 - 2026 SiFli Technology (Nanjing) Co., Ltd. owns the copyright of all original source code in this codebase. The source code is licensed under the Apache License 2.0 as described in the LICENSE file. +2019 - 2026 SiFli Technology (Nanjing) Co., Ltd. owns the copyright of all +original source code in this codebase. The source code is licensed under the +Apache License 2.0 as described in the LICENSE file. The following licenses also include some third-party copyrighted code. -If the copyright and license information is specified in the source code header file, that information takes precedence over the summary here. +If the copyright and license information is specified in the source code header +file, that information takes precedence over the summary here. -Some examples use external components not licensed under Apache. Please refer to the copyright description in each example's source code. +Some examples use external components not licensed under Apache. Please refer to +the copyright description in each example's source code. ## Third-Party Components -The following third-party libraries may be included in applications (firmware) generated by SiFli-SDK. If you use them, please comply with the relevant license agreements. +The following third-party libraries may be included in applications (firmware) +generated by SiFli-SDK. If you use them, please comply with the relevant license +agreements. -1. [cherryusb](https://github.com/cherry-embedded/CherryUSB): Copyright 2021-2026 CherryUSB Open Source Community, licensed under the Apache License 2.0. +1. [cherryusb](https://github.com/cherry-embedded/CherryUSB): Copyright + 2021-2026 CherryUSB Open Source Community, licensed under the Apache License + 2.0. -2. [cJSON](https://github.com/RT-Thread-packages/cJSON): Copyright 2017 The packages repositories of RT-Thread, licensed under the MIT License. +2. [cJSON](https://github.com/RT-Thread-packages/cJSON): Copyright 2017 The + packages repositories of RT-Thread, licensed under the MIT License. -3. [CmBacktrace](https://github.com/armink/CmBacktrace): Copyright 2016-2019 Armink and 2016-2018 zylx, licensed under the MIT License. +3. [CmBacktrace](https://github.com/armink/CmBacktrace): Copyright 2016-2019 + Armink and 2016-2018 zylx, licensed under the MIT License. -4. [CMSIS](https://github.com/ARM-software/CMSIS): Copyright 2013-2018 Arm Limited, licensed under the Apache License 2.0. +4. [CMSIS](https://github.com/ARM-software/CMSIS): Copyright 2013-2018 Arm + Limited, licensed under the Apache License 2.0. -5. [coremark](https://www.github.com/eembc/coremark-pro): Copyright 2009 EEMBC, licensed under the Apache License 2.0. +5. [coremark](https://www.github.com/eembc/coremark-pro): Copyright 2009 EEMBC, + licensed under the Apache License 2.0. -6. easytlv: Copyright 2020 John Boyd , licensed under the MIT License. +6. easytlv: Copyright 2020 John Boyd , licensed under the + MIT License. -7. [FlashDB](https://gitee.com/armink/FlashDB): Copyright 2020 Armink and 2020 enkiller, licensed under the Apache License 2.0. +7. [FlashDB](https://gitee.com/armink/FlashDB): Copyright 2020 Armink and 2020 + enkiller, licensed under the Apache License 2.0. -8. [libhelix-mp3](http://www.helixcommunity.org): Copyright 1995-2004 RealNetworks, Inc.; the official original version is licensed under RealNetworks Proprietary Dual License (RPSL/RCSL, see RPSL.txt and RCSL.txt files in the component for details). +8. [libhelix-mp3](http://www.helixcommunity.org): Copyright 1995-2004 + RealNetworks, Inc.; the official original version is licensed under + RealNetworks Proprietary Dual License (RPSL/RCSL, see RPSL.txt and RCSL.txt + files in the component for details). -9. [lvgl-v8](https://lvgl.io): Copyright 2021 LVGL Kft, licensed under the MIT License. +9. [lvgl-v8](https://lvgl.io): Copyright 2021 LVGL Kft, licensed under the MIT + License. -10. [lvgl-v9](https://lvgl.io): Copyright 2021 LVGL Kft, licensed under the MIT License. +10. [lvgl-v9](https://lvgl.io): Copyright 2021 LVGL Kft, licensed under the MIT + License. -11. [lz4](https://github.com/lz4/lz4): Copyright 2011-2016 Yann Collet, licensed under a BSD-style license. +11. [lz4](https://github.com/lz4/lz4): Copyright 2011-2016 Yann Collet, licensed + under a BSD-style license. -12. [mbedtls](https://github.com/Mbed-TLS/mbedtls): Copyright 2006-2015 ARM Limited, licensed under the Apache License 2.0. +12. [mbedtls](https://github.com/Mbed-TLS/mbedtls): Copyright 2006-2015 ARM + Limited, licensed under the Apache License 2.0. -13. [mbedtls_228](https://github.com/ARMmbed/mbedtls): Copyright 2006-2015 ARM Limited, licensed under the Apache License 2.0. +13. [mbedtls_228](https://github.com/ARMmbed/mbedtls): Copyright 2006-2015 ARM + Limited, licensed under the Apache License 2.0. -14. [micropython](https://www.rt-thread.org/document/site/submodules/micropython): Copyright 2013, 2014 Damien P. George, licensed under the MIT License. +14. [micropython](https://www.rt-thread.org/document/site/submodules/micropython): + Copyright 2013, 2014 Damien P. George, licensed under the MIT License. -15. [opus](https://github.com/xiph/opus): Copyright 2001-2011 Xiph.Org and other contributors, licensed under a BSD-style license. +15. [opus](https://github.com/xiph/opus): Copyright 2001-2011 Xiph.Org and other + contributors, licensed under a BSD-style license. -16. [quickjs](https://bellard.org/quickjs/): Copyright 2017-2021 Fabrice Bellard, Charlie Gordon, licensed under the MIT License. +16. [quickjs](https://bellard.org/quickjs/): Copyright 2017-2021 Fabrice + Bellard, Charlie Gordon, licensed under the MIT License. -17. [rlottie](https://github.com/Samsung/rlottie): Copyright 2020 Samsung Electronics Co., licensed under the MIT License. +17. [rlottie](https://github.com/Samsung/rlottie): Copyright 2020 Samsung + Electronics Co., licensed under the MIT License. -18. [rpmsg-lite](https://github.com/nxp-mcuxpresso/rpmsg-lite): Copyright 2014-2023 NXP, Freescale, and other contributors, licensed under the MIT License. +18. [rpmsg-lite](https://github.com/nxp-mcuxpresso/rpmsg-lite): Copyright + 2014-2023 NXP, Freescale, and other contributors, licensed under the MIT + License. -19. [state_machine-latest](https://github.com/misje/stateMachine): Copyright 2013 Andreas Misje, licensed under the MIT License. +19. [state_machine-latest](https://github.com/misje/stateMachine): Copyright + 2013 Andreas Misje, licensed under the MIT License. -20. vglite: Copyright 2012-2023 Vivante Corporation, licensed under the MIT License. +20. vglite: Copyright 2012-2023 Vivante Corporation, licensed under the MIT + License. -21. [webclient](https://github.com/RT-Thread-packages/webclient): Copyright RT-Thread Development Team, licensed under the Apache License 2.0. +21. [webclient](https://github.com/RT-Thread-packages/webclient): Copyright + RT-Thread Development Team, licensed under the Apache License 2.0. -22. [WebRTC_audio_processing](https://webrtc.org): Copyright The WebRTC project authors, licensed under a BSD-style license. +22. [WebRTC_audio_processing](https://webrtc.org): Copyright The WebRTC project + authors, licensed under a BSD-style license. -23. wpa_supplicant-rtos: Copyright 2003-2022 Jouni Malinen and all contributors, licensed under a BSD-style license. +23. wpa_supplicant-rtos: Copyright 2003-2022 Jouni Malinen and all + contributors, licensed under a BSD-style license. -24. [FreeType](https://www.freetype.org): Copyright 1996-2021 David Turner, Robert Wilhelm, and Werner Lemberg, licensed under FTL license (see FTL.TXT file in the component for details). +24. [FreeType](https://www.freetype.org): Copyright 1996-2021 David Turner, + Robert Wilhelm, and Werner Lemberg, licensed under FTL license (see FTL.TXT + file in the component for details). -25. nanopb: Copyright 2014 Petteri Aimonen , licensed under the MIT License. +25. nanopb: Copyright 2014 Petteri Aimonen , licensed under the + MIT License. -26. [SDL2](https://www.libsdl.org): Copyright 1997-2017 Sam Lantinga , licensed under the SDL relaxed open-source license. +26. [SDL2](https://www.libsdl.org): Copyright 1997-2017 Sam Lantinga + , licensed under the SDL relaxed open-source license. -27. [SEGGER SystemView](https://www.segger.com/footer/support/): Copyright 2015-2017 SEGGER Microcontroller GmbH & Co. KG, licensed under SEGGER proprietary BSD-style redistribution license. +27. [SEGGER SystemView](https://www.segger.com/footer/support/): Copyright + 2015-2017 SEGGER Microcontroller GmbH & Co. KG, licensed under SEGGER + proprietary BSD-style redistribution license. -28. sensor-lib: Copyright 2015 Steven Chen , see source code headers or accompanying license files for license type. +28. sensor-lib: Copyright 2015 Steven Chen , see + source code headers or accompanying license files for license type. -29. [tinymp3](https://github.com/mackron/dr_libs): Copyright David Reid , licensed under dual-option license (Public Domain/MIT-0 License, see license declaration at the end of the file). +29. [tinymp3](https://github.com/mackron/dr_libs): Copyright David Reid + , licensed under dual-option license (Public Domain/MIT-0 + License, see license declaration at the end of the file). ```{warning} - 1. [ffmpeg](https://ffmpeg.org): Copyright FFmpeg project contributors and related rights holders, primarily licensed under the GNU Lesser General Public License (LGPL) v2.1+ (some optional components are subject to the GNU General Public License (GPL) v2+). Specific copyright and license information in the source code headers takes precedence over this summary. 2. [FAAD2](http://www.nero.com): Copyright 2003-2005 M. Bakker, Nero AG, licensed under the GPL. +``` + +The license files or source code headers of the aforementioned third-party +libraries shall take precedence over this summary. diff --git a/docs/source/en/copyright/index.md b/docs/source/en/copyright/index.md index 751ec639f..5814add0c 100644 --- a/docs/source/en/copyright/index.md +++ b/docs/source/en/copyright/index.md @@ -1,4 +1,4 @@ -# 版权 +# Copyright ```{toctree} :titlesonly: diff --git a/docs/source/en/drivers/adc.md b/docs/source/en/drivers/adc.md index 09fb6687a..539d9ff70 100644 --- a/docs/source/en/drivers/adc.md +++ b/docs/source/en/drivers/adc.md @@ -2,7 +2,8 @@ ## Driver Configuration -Select the ADC device to be used and configure relevant parameters in the menu {menuselection}`On-Chip Peripheral RTOS Drivers --> Enable ADC`. +Select the ADC device to be used and configure relevant parameters in the menu +{menuselection}`On-Chip Peripheral RTOS Drivers --> Enable ADC`. The following macro definitions indicate that the ADC1 device is enabled: ```c @@ -11,20 +12,25 @@ The following macro definitions indicate that the ADC1 device is enabled: ``` ## Device Naming -- `bat`, -where x is the device index, such as `bat1`, `bat2`, corresponding to the peripheral device number. +- `bat`, where x is the device index, such as `bat1`, `bat2`, corresponding + to the peripheral device number. ## PinMux and Slot Definitions -Each ADC slot corresponds to a pin, and this pin can be multiplexed for different functionalities. Before using it as an ADC input, its pinmux function must be set. Below is an example of configuring the pin for ADC SLOT 0. For more details, refer to the hardware pinmux table: +Each ADC slot corresponds to a pin, and this pin can be multiplexed for +different functionalities. Before using it as an ADC input, its pinmux function +must be set. Below is an example of configuring the pin for ADC SLOT 0. For more +details, refer to the hardware pinmux table: ```c HAL_PIN_Set(PAD_PB_04, ADC_PIN, PIN_INPUT, 0); ``` ## ADC to Voltage Conversion -Two different voltage levels are required to obtain their register values, which allows for accurate calculation of offset and ratio (millivolts per bit). +Two different voltage levels are required to obtain their register values, which +allows for accurate calculation of offset and ratio (millivolts per bit). ## Example Code + ```c // Find and open ADC device dev = rt_device_find("bat1"); @@ -45,7 +51,8 @@ res = (value - TC_ADC_OFFSET) * ratio; rt_device_close(dev); ``` -[adc]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc +[adc]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc ## RT-Thread Reference Documentation - [ADC Device][adc] diff --git a/docs/source/en/drivers/audprc_audcodec.md b/docs/source/en/drivers/audprc_audcodec.md index 7a79ba7d0..268e00011 100644 --- a/docs/source/en/drivers/audprc_audcodec.md +++ b/docs/source/en/drivers/audprc_audcodec.md @@ -1,15 +1,15 @@ - # Audprc/Audcodec Audio Device -The chip contains Audprc and Audcodec. Audprc is used for digital processing, while Audcodec is for digital-to-analog conversion. -The common audio data flow is Audprc --> Audcodec --> Speaker. -Another possible configuration is Audprc --> I2S --> External Codec chip. -Main functionalities include: +The chip contains Audprc and Audcodec. Audprc is used for digital processing, +while Audcodec is for digital-to-analog conversion. The common audio data flow +is Audprc --> Audcodec --> Speaker. Another possible configuration is Audprc --> +I2S --> External Codec chip. Main functionalities include:
- Input and output sample rate settings - Input and output channel count settings - Bit depth setting for each sample - Volume control settings -The playback code explanation, with specific examples, can be found in the `drv_audprc.c` file and the `example/rt_device/audprc` directory. +The playback code explanation, with specific examples, can be found in the +`drv_audprc.c` file and the `example/rt_device/audprc` directory. ```c static rt_event_t g_tx_ev; @@ -40,14 +40,14 @@ void test_demo() // 2. Set the callback for transmission completion rt_device_set_tx_complete(audprc_dev, speaker_tx_done); - + // 3. Set the size of one DMA buffer, the underlying driver uses two such buffers for ping-pong buffering rt_device_control(audprc_dev, AUDIO_CTL_SET_TX_DMA_SIZE, (void *)DMA_BUF_SIZE); // 4. Output audio to the codec, if using I2S, set AUDPRC_TX_TO_I2S rt_device_control(audcodec_dev, AUDIO_CTL_SETOUTPUT, (void *)AUDPRC_TX_TO_CODEC); rt_device_control(audprc_dev, AUDIO_CTL_SETOUTPUT, (void *)AUDPRC_TX_TO_CODEC); - + // 5. Configure codec parameters struct rt_audio_caps caps; @@ -60,7 +60,7 @@ void test_demo() caps.udata.config.samplerate = 16000; // Sample rate, options: 8000/11025/12000/16000/22050/24000/32000/44100/48000 caps.udata.config.samplefmt = 16; // Bit depth: 8, 16, 24, or 32 rt_device_control(audcodec_dev, AUDIO_CTL_CONFIGURE, &caps); - + struct rt_audio_sr_convert cfg; cfg.channel = 2; // Source data channels, if 2, data will be in interleave format: LRLRLR... cfg.source_sr = 16000; // Source data sample rate @@ -114,7 +114,6 @@ void test_demo() rt_event_delete(g_tx_ev); } ``` - Receiving Code Explanation: ```c @@ -140,7 +139,7 @@ void test_demo() RT_ASSERT(RT_EOK == err); err = rt_device_open(audcodec_dev, RT_DEVICE_FLAG_WRONLY); RT_ASSERT(RT_EOK == err); - + // Set the callback for reception of one frame rt_device_set_rx_indicate(audprc_dev, mic_rx_ind); @@ -171,7 +170,7 @@ void test_demo() stream = AUDIO_STREAM_RECORD | ((1 << HAL_AUDPRC_RX_CH0) << 8); rt_device_control(audprc_dev, AUDIO_CTL_START, &stream); rt_uint32_t evt; - + uint8_t g_pipe_data[CFG_AUDIO_RECORD_PIPE_SIZE]; while (1) { @@ -183,14 +182,12 @@ void test_demo() rt_event_delete(g_rx_ev); } ``` - ## Driver Configuration Enable in {menuselection}: -- `On-Chip Peripheral RTOS Drivers --> Enable Audio codec Driver` -- `On-Chip Peripheral RTOS Drivers --> Enable Audio Process driver --> Enable AUDPRC TX Channel 0 DMA` -- `On-Chip Peripheral RTOS Drivers --> Enable Audio Process driver --> Enable AUDPRC RX Channel 0 DMA` - +[audio]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/audio/audio ## RT-Thread Documentation -- [AUDIO Device Documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/audio/audio) +- [AUDIO Device Documentation][audio] + diff --git a/docs/source/en/drivers/epic.md b/docs/source/en/drivers/epic.md index 49130b78d..126f42dbf 100644 --- a/docs/source/en/drivers/epic.md +++ b/docs/source/en/drivers/epic.md @@ -1,33 +1,45 @@ # Graphics Rendering Driver Layer - -The graphics rendering driver layer provides a more user-friendly image rendering interface for upper-level applications. There are two different types of implementation interfaces here (which cannot be used simultaneously): -1. Single-step rendering mode -- simple functionality, low requirements for the graphics library -2. Render list mode -- more features, higher requirements for graphics library memory management +The graphics rendering driver layer provides a more user-friendly image +rendering interface for upper-level applications. There are two different types +of implementation interfaces here (which cannot be used simultaneously): +1. Single-step rendering mode -- simple functionality, low requirements for the + graphics library +2. Render list mode -- more features, higher requirements for graphics library + memory management Differences between the two rendering modes: -| | Single-step Rendering Mode | Render List Mode | -|---------------------------------|:-----:|:------:| -| Supports fill, blending, rotation, scaling | Y | Y | -| Supports drawing lines, circles, polygons, arcs | N | Y | -| Supports 55x series | Y | N | -| Input buffer for rendering can be a local variable | Y | N | +| | Single-step Rendering Mode | Render List Mode | +| -------------------------------------------------- | :------------------------: | :--------------: | +| Supports fill, blending, rotation, scaling | Y | Y | +| Supports drawing lines, circles, polygons, arcs | N | Y | +| Supports 55x series | Y | N | +| Input buffer for rendering can be a local variable | Y | N | ## How to Choose the Rendering Mode -Select the mode through the following menuconfig switch (enabled means render list mode, disabled means single-step rendering mode): -![Render List Mode menuconfig](../../assets/driver_epic_render_list_menuconfig.png) +Select the mode through the following menuconfig switch (enabled means render +list mode, disabled means single-step rendering mode): ![Render List Mode +menuconfig](../../assets/driver_epic_render_list_menuconfig.png) ## Single-step Rendering Mode -Interfaces with the `cbk` parameter in single-step rendering mode are asynchronous; you need to wait for the callback to complete before rendering is finished. +Interfaces with the `cbk` parameter in single-step rendering mode are +asynchronous; you need to wait for the callback to complete before rendering is +finished. + -Explanation of common parameters `input_layers` and `input_layer_cnt` in the interface: +Explanation of common parameters `input_layers` and `input_layer_cnt` in the +interface: - `input_layer_cnt` is the number of `input_layers` -- `input_layers` are the input layers for blending. The blending order is `input_layers[0]` at the bottom, `input_layers[1]` above `input_layers[0]`, and so on. Note that for mask layers, the mask object is the layer below the mask layer. +- `input_layers` are the input layers for blending. The blending order is + `input_layers[0]` at the bottom, `input_layers[1]` above `input_layers[0]`, + and so on. Note that for mask layers, the mask object is the layer below the + mask layer. -*** The mask layer format is A2/A4/A8, and the input layer with ax_mode = ALPHA_BLEND_MASK *** +*** The mask layer format is A2/A4/A8, and the input layer with ax_mode = +ALPHA_BLEND_MASK *** ### 1. Fill Functions - Supports solid color fill, gradient fill, and solid color fill with mask +Supports solid color fill, gradient fill, and solid color fill with mask ``` rt_err_t drv_epic_fill_ext(EPIC_LayerConfigTypeDef *input_layers, uint8_t input_layer_cnt, @@ -48,7 +60,8 @@ rt_err_t drv_epic_fill_grad(EPIC_GradCfgTypeDef *param, ### 2. Area Copy Interface -Copies a certain area from the src buffer to the corresponding area of the dst buffer. The src and dst can be of different formats. +Copies a certain area from the src buffer to the corresponding area of the dst +buffer. The src and dst can be of different formats. ``` rt_err_t drv_epic_copy(const uint8_t *src, uint8_t *dst, @@ -62,14 +75,19 @@ rt_err_t drv_epic_copy(const uint8_t *src, uint8_t *dst, ### 3. Image Blending Interface (including planar rotation and scaling) Supports image blending, rotation, and scaling with mask. -For example, if you need to blend an image with a mask onto a framebuffer, the input is: +For example, if you need to blend an image with a mask onto a framebuffer, the +input is: - `input_layer_cnt` is 3, - `input_layers[0]` is the background layer - `input_layers[1]` is the image - `input_layers[2]` is the mask, which only masks `input_layers[1]` -- `output_canvas` is the output buffer. In this example, it is the same buffer as `input_layers[0]`, but since the blending area is only the area of the image, the height and width of the `output_canvas` layer may be smaller than `input_layers[0]`. +- `output_canvas` is the output buffer. In this example, it is the same buffer + as `input_layers[0]`, but since the blending area is only the area of the + image, the height and width of the `output_canvas` layer may be smaller than + `input_layers[0]`. -See the explanation in the HAL_EPIC layer about output area clipping for blending. +See the explanation in the HAL_EPIC layer about output area clipping for +blending. ``` rt_err_t drv_epic_blend(EPIC_LayerConfigTypeDef *input_layers, @@ -78,6 +96,7 @@ rt_err_t drv_epic_blend(EPIC_LayerConfigTypeDef *input_layers, drv_epic_cplt_cbk cbk); ``` + ### 4. 3D Flip Interface Around X/Y Axis ``` @@ -96,20 +115,26 @@ rt_err_t drv_epic_cont_blend(EPIC_LayerConfigTypeDef *input_layers, void drv_epic_cont_blend_reset(void); ``` + ## Render List Mode -Render list mode collects a series of rendering operations and then renders them together, so all related memory references cannot be changed before these rendering operations are completed. +Render list mode collects a series of rendering operations and then renders them +together, so all related memory references cannot be changed before these +rendering operations are completed. ### Render List API Usage Process There are two scenarios when executing a render list: -1. Render + display - In this scenario, the rendering area is rendered in blocks according to the configured render buffer size. After each block is completed, the specified callback is executed, and the screen is refreshed (or other operations) in the callback. -2. Render to a specified buffer - In this scenario, the rendering result is written directly to the specified buffer, and the callback is called after the entire process is completed. +1. Render + display In this scenario, the rendering area is rendered in blocks + according to the configured render buffer size. After each block is + completed, the specified callback is executed, and the screen is refreshed + (or other operations) in the callback. +1. Render to a specified buffer In this scenario, the rendering result is + written directly to the specified buffer, and the callback is called after + the entire process is completed. #### Render + Display -For this scenario, you can refer to the example in `SiFli-SDK_1\example\rt_device\gpu\render_list_mode`. +For this scenario, you can refer to the example in +`SiFli-SDK_1\example\rt_device\gpu\render_list_mode`. ```c - static void partial_done_cb(drv_epic_render_list_t rl, EPIC_LayerConfigTypeDef *p_dst, void *usr_data, uint32_t last) { rt_device_t p_lcd_device = usr_data; @@ -174,10 +199,11 @@ void main(void) ``` #### Render to a Specified Buffer -Render the contents of a render list to a specified buffer, supporting scaling to the size of the specified buffer after rendering is complete. +Render the contents of a render list to a specified buffer, supporting scaling +to the size of the specified buffer after rendering is complete. ```c - drv_gpu_open(); // Open the driver +drv_gpu_open(); // Open the driver drv_epic_setup_render_buffer(&buf1, &buf2, buf_size); // Set up render buffers (need two buffers of the same size) /* @@ -231,19 +257,22 @@ Render the contents of a render list to a specified buffer, supporting scaling t ``` ### Explanation of Specific Rendering Operation Parameters -This section mainly explains the parameters of the structure `drv_epic_operation`. +This section mainly explains the parameters of the structure +`drv_epic_operation`. Explanation of common parameters for each rendering operation: ```c - drv_epic_op_type_t op; // Rendering operation type +drv_epic_op_type_t op; // Rendering operation type EPIC_AreaTypeDef clip_area; // Clipping area for rendering EPIC_LayerConfigTypeDef mask; // Bitmap mask for the rendering operation (optional) ``` -Parameter explanations for different rendering operation data structures `drv_epic_operation.desc`: + +Parameter explanations for different rendering operation data structures +`drv_epic_operation.desc`: 1. Rectangle (DRV_EPIC_DRAW_RECT) ```c - struct +struct { EPIC_AreaTypeDef area; // Rectangle coordinates @@ -256,7 +285,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 2. Image (DRV_EPIC_DRAW_IMAGE) ```c - struct +struct { EPIC_LayerConfigTypeDef layer; // Image description layer, including rotation, scaling, etc. uint8_t use_dest_as_bg; // Options for blending with the background: fixed color, blend with background, or direct output @@ -267,7 +296,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 3. Arc (DRV_EPIC_DRAW_ARC) ```c - struct +struct { int16_t center_x; // Center coordinates int16_t center_y; @@ -285,7 +314,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 4. Line (DRV_EPIC_DRAW_LINE) ```c - struct +struct { EPIC_PointTypeDef p1; // Start point coordinates EPIC_PointTypeDef p2; // End point coordinates @@ -301,7 +330,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 5. Border (DRV_EPIC_DRAW_BORDER) ```c - struct +struct { EPIC_AreaTypeDef area; // Border area @@ -319,7 +348,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 6. Polygon (DRV_EPIC_DRAW_POLYGON) ```c - struct +struct { EPIC_PointTypeDef points[DRV_EPIC_POLYGON_POINT_MAX]; // Polygon vertex coordinates uint16_t point_cnt; // Number of vertices used @@ -328,7 +357,7 @@ Parameter explanations for different rendering operation data structures `drv_ep ``` 7. Bitmap Text (DRV_EPIC_DRAW_LETTERS) ```c - struct +struct { uint32_t color_mode; // Bitmap format uint8_t r; // Text color @@ -356,7 +385,9 @@ rt_err_t drv_gpu_check_done(rt_int32_t ms); 3. Non-cache memory segment function -**This function is implemented by the upper layer** and is used to specify which memory blocks do not require Dcache cleaning (i.e., buffers operated purely by hardware, not read or written by the CPU), which can save Dcache cleaning time. +**This function is implemented by the upper layer** and is used to specify which +memory blocks do not require Dcache cleaning (i.e., buffers operated purely by +hardware, not read or written by the CPU), which can save Dcache cleaning time. ``` /** @@ -369,4 +400,6 @@ uint8_t drv_gpu_is_cached_ram(uint32_t start, uint32_t len); ``` 4. Immediately return whether the rendering driver is busy -``` \ No newline at end of file +``` +bool drv_epic_is_busy(void); +``` diff --git a/docs/source/en/drivers/gpio.md b/docs/source/en/drivers/gpio.md index 34a903d50..eb86eb27f 100644 --- a/docs/source/en/drivers/gpio.md +++ b/docs/source/en/drivers/gpio.md @@ -1,64 +1,69 @@ +# PIN Devices -# PIN Device - -The PIN device allows configuring GPIO input, output, and interrupt triggers, but does not support pull-up or pull-down functionalities. +The PIN device enables configuration of GPIO inputs, outputs, and interrupt +triggers; however, it does not support internal pull-up or pull-down resistors. ## Driver Configuration -To add the PIN device, select `{menuselection}` `On-Chip Peripheral RTOS Drivers --> Enable GPIO` menu. You do not need to fill in the `GPIO BASE number` option. +To add a PIN device, select the {menuselection}`On-Chip Peripheral RTOS Drivers +--> Enable GPIO` menu option. The `GPIO BASE number` field should be left +blank. -Corresponding macro switches are as follows: +The corresponding macro switches are as follows: ```c #define RT_USING_PIN #define BSP_USING_GPIO ``` -## Getting Pin Numbers (Pin ID) -Unlike the HAL layer, where GPIOs need to specify the GPIO group and group number, the driver layer uses a numeric ID to represent a specific pin (including GPIOA, GPIOB, and PBR on supported series). The numbering method is as follows: - -Pin | Pin ID | Notes -------------|--------|------ -GPIOA_00 | 0 | `GET_PIN(1, 0)` -GPIOA_01 | 1 | `GET_PIN(1, 1)` -GPIOA_02 | 2 | `GET_PIN(1, 2)` -... | ... | -GPIOB_00 | 96 | `GET_PIN(2, 0)` -GPIOB_01 | 97 | `GET_PIN(2, 1)` -GPIOB_02 | 98 | `GET_PIN(2, 2)` -... | ... | -PBR0 | 160 | `GET_PIN(0, 0)` -PBR1 | 161 | `GET_PIN(0, 1)` -... | ... | Range depends on series, see note below - -Example: - - GPIOB03 pin, Pin ID is 99 - - GPIOA03 pin, Pin ID is 3 - +## Obtaining the Pin ID +Unlike the HAL layer, which requires specifying both a GPIO group and its +offset, the driver layer typically represents a GPIO pin (including GPIOA, +GPIOB, and PBR supported by certain series) using a single numerical ID. The +following method is used to assign IDs to GPIOs and PBRs at the driver layer: + +| Pin | Pin ID | Description | +| -------- | ------ | ------------------------------------------------------------------ | +| GPIOA_00 | 0 | `GET_PIN(1, 0)` | +| GPIOA_01 | 1 | `GET_PIN(1, 1)` | +| GPIOA_02 | 2 | `GET_PIN(1, 2)` | +| ... | ... | | +| GPIOB_00 | 96 | `GET_PIN(2, 0)` | +| GPIOB_01 | 97 | `GET_PIN(2, 1)` | +| GPIOB_02 | 98 | `GET_PIN(2, 2)` | +| ... | ... | | +| PBR0 | 160 | `GET_PIN(0, 0)` | +| PBR1 | 161 | `GET_PIN(0, 1)` | +| ... | ... | The range varies by series; see the description below for details. | + +Examples: + - GPIOB03: Pin ID is 99 + - GPIOA03: Pin ID is 3 ```{note} -You can also use macros to obtain pin numbers. +Pin numbers can also be retrieved via macro definitions. ``` ```c GET_PIN(port, pin) #define LED0_PIN GET_PIN(1, 3) //GPIOA_03 -#define LED1_PIN GET_PIN(2, 9) //GPIOB_09 +#define LED1_PIN GET_PIN(2, 9) //GPIOB_09 ``` ```{note} -For PBR pins in the pin device layer, use `GET_PIN(0, pbr_index)`. +`PBR` uses `port=0` in the pin device, denoted as `GET_PIN(0, pbr_index)`. -Chip Difference Description: -- SF32LB52 / SF32LB56: support `PBR0~PBR3` (pin id `160~163`) -- SF32LB58: support `PBR0~PBR5` (pin id `160~165`) -- SF32LB55: PBR is not supported +Chip Variations: +- SF32LB52/SF32LB56: Supports `PBR0~PBR3` (pin IDs `160~163`) +- SF32LB58: Supports `PBR0~PBR5` (pin IDs `160~165`) +- SF32LB55: PBR is not supported. ``` -## Example 1 – Interrupt Mode -Set PA00 as rising edge interrupt trigger mode and disable the interrupt trigger mode after 3 seconds. +## Example 1: Interrupt Mode +Set PA00 to rising-edge interrupt mode, wait for 3 seconds, and then disable the +interrupt. ```c static void pin_irq_callback(void *args) { @@ -74,9 +79,9 @@ void pin_irq() rt_pin_attach_irq(pin_id, PIN_IRQ_MODE_RISING, gpio_int_callback, RT_NULL); //Enable interrupt rt_pin_irq_enable(pin_id, 1); - + rt_thread_mdelay(3000); - + //Disable interrupt rt_pin_irq_enable(pin_id, 0); //Detach irq handler @@ -84,8 +89,9 @@ void pin_irq() } ``` -## Example 2 – Input or Output Mode -Set PB02 to input mode, then read the level, followed by outputting a high level. +## Example 2: Input or Output Mode +Configure PB02 as an input to read the logic level, then switch it to output +mode and drive the signal high. ```c void pin_read_and_write(void) { @@ -95,7 +101,7 @@ void pin_read_and_write(void) rt_pin_mode(pin_id, PIN_MODE_INPUT_PULLUP); v = rt_pin_read(pin_id); LOG_I("pin_read value=%d",v); - + //Set pin output mode rt_pin_mode(pin_id, PIN_MODE_OUTPUT); //Set pin output high @@ -103,7 +109,8 @@ void pin_read_and_write(void) } ``` -[pin]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/pin/pin +[pin]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/pin/pin ## RT-Thread Reference Documentation diff --git a/docs/source/en/drivers/i2c.md b/docs/source/en/drivers/i2c.md index 95c5dadb7..e8c2e2b1c 100644 --- a/docs/source/en/drivers/i2c.md +++ b/docs/source/en/drivers/i2c.md @@ -1,10 +1,13 @@ - # I2C Device -The I2C driver consists of two layers: the Hardware Access Layer (HAL) and the RT-Thread adapter layer. -The hardware access layer provides basic APIs for accessing I2C peripheral registers. For more details, please refer to the I2C HAL API documentation. -The adapter layer provides support for the RT-Thread driver framework. Users can use the RT-Thread POSIX driver interface for I2C programming. Please refer to the RT-Thread driver API documentation. -Main features include: +The I2C driver consists of two layers: the Hardware Access Layer (HAL) and the +RT-Thread adapter layer.\ +The hardware access layer provides basic APIs for accessing I2C peripheral +registers. For more details, please refer to the I2C HAL API documentation.\ +The adapter layer provides support for the RT-Thread driver framework. Users can +use the RT-Thread POSIX driver interface for I2C programming. Please refer to +the RT-Thread driver API documentation.\ +Main features include:
- Multi-instance support - I2C operates in master mode - Supports I2C operation at speeds of 100Kbps/400Kbps/1Mbps @@ -14,7 +17,9 @@ Main features include: ## Driver Configuration -In the `{menuselection}` `On-Chip Peripheral RTOS Drivers --> Enable I2C BUS` menu, select the I2C bus device to be used and configure whether DMA support is required. +In the `{menuselection}` `On-Chip Peripheral RTOS Drivers --> Enable I2C BUS` +menu, select the I2C bus device to be used and configure whether DMA support is +required. The following macro switches enable I2C1/I2C2/I2C3 devices, and all support DMA: ```c @@ -32,12 +37,12 @@ Selecting DMA in menuconfig only configures the driver to support DMA, but wheth ``` ## Device Names -- `i2c`, -Where `x` is the device number, such as `i2c1`, `i2c2`, corresponding to the peripheral number being operated on. - +- `i2c`, Where `x` is the device number, such as `i2c1`, `i2c2`, + corresponding to the peripheral number being operated on. ## Example Code + ```c // Find and open device struct rt_i2c_bus_device *rt_i2c_bus_device_find(const char *bus_name); @@ -75,78 +80,64 @@ rt_size_t rt_i2c_transfer(struct rt_i2c_bus_device *bus, // Interrupt callback, try not to issue read in interrupt context. __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); __weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +``` +```{note} +i2c_bus = rt_i2c_bus_device_find("i2c1"); +if (RT_NULL == i2c_bus) +{ + return; +} -``` -// example -void i2c_trans_test() +ret = rt_device_open(&(i2c_bus->parent), RT_DEVICE_FLAG_RDWR); +if (RT_EOK != ret) { - struct rt_i2c_bus_device *i2c_bus = RT_NULL; - struct rt_i2c_msg msgs; - struct rt_i2c_configuration cfg = {0}; - rt_uint8_t *rd_buff; - rt_err_t ret; - - - i2c_bus = rt_i2c_bus_device_find("i2c1"); - if (RT_NULL == i2c_bus) - { - return; - } - - ret = rt_device_open(&(i2c_bus->parent), RT_DEVICE_FLAG_RDWR); - if (RT_EOK != ret) - { - return; - } - - cfg.timeout = 5000; - cfg.max_hz = 400000; - //cfg.mode |= RT_I2C_ADDR_10BIT; - //cfg.addr = 0xe; - - if (rt_i2c_configure(i2c_bus, &cfg) != HAL_OK) - { - rt_device_close(&(i2c_bus->parent)); - return; - } - - rd_buff = rt_malloc(100); - if (RT_NULL == rd_buff) - { - rt_device_close(&(i2c_bus->parent)); - return; - } - - for (int m = 0; m < rw_len; m++) - { - rd_buff[m] = m; - } - - msgs.addr = 0xe; - msgs.flags = RT_I2C_WR; - msgs.buf = rd_buff; - msgs.len = 100; - - rt_i2c_transfer(i2c_bus, &msgs, 1); - - //msgs.addr = 0xe; - msgs.flags = RT_I2C_RD; - //msgs.buf = rd_buff; - //msgs.len = 100; - - rt_i2c_transfer(i2c_bus, &msgs, 1); + return; +} +cfg.timeout = 5000; +cfg.max_hz = 400000; +//cfg.mode |= RT_I2C_ADDR_10BIT; +//cfg.addr = 0xe; + +if (rt_i2c_configure(i2c_bus, &cfg) != HAL_OK) +{ + rt_device_close(&(i2c_bus->parent)); + return; +} + +rd_buff = rt_malloc(100); +if (RT_NULL == rd_buff) +{ rt_device_close(&(i2c_bus->parent)); + return; } -``` -```{note} -DMA support is configured via the menuconfig tool. To use DMA, developers need to set the corresponding flag when opening the device. +for (int m = 0; m < rw_len; m++) +{ + rd_buff[m] = m; +} + +msgs.addr = 0xe; +msgs.flags = RT_I2C_WR; +msgs.buf = rd_buff; +msgs.len = 100; + +rt_i2c_transfer(i2c_bus, &msgs, 1); + +//msgs.addr = 0xe; +msgs.flags = RT_I2C_RD; +//msgs.buf = rd_buff; +//msgs.len = 100; + +rt_i2c_transfer(i2c_bus, &msgs, 1); + +rt_device_close(&(i2c_bus->parent)); ``` -[i2c]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/i2c/i2c +[I2C]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/i2c/i2c ## RT-Thread Reference Documentation -- [I2C Device][i2c] +- [I2C Device][I2C] diff --git a/docs/source/en/drivers/i2s.md b/docs/source/en/drivers/i2s.md index 2962da8c0..2ce4e5e9a 100644 --- a/docs/source/en/drivers/i2s.md +++ b/docs/source/en/drivers/i2s.md @@ -1,18 +1,30 @@ # I2S Audio Device -The audio driver includes two layers: a hardware access layer (HAL) for I2S and an adapter layer for RT-Thread. -The hardware access layer provides basic APIs for accessing I2S peripheral registers. Detailed information is available in the I2S API documentation. -The adapter layer supports the RT-Thread driver framework, enabling audio programming via RT-Thread POSIX driver interfaces. Refer to the RT-Thread driver API documentation for details. -Main functionalities include: - i2s samplerate -- i2s channel +- i2s channel - i2s sample bitwidth - i2s slave/master select +The audio driver includes two layers: a hardware access layer (HAL) for I2S and +an adapter layer for RT-Thread. The hardware access layer provides basic APIs +for accessing I2S peripheral registers. Detailed information is available in the +I2S API documentation. The adapter layer supports the RT-Thread driver +framework, enabling audio programming via RT-Thread POSIX driver interfaces. +Refer to the RT-Thread driver API documentation for details. Main +functionalities include:
+- Microphone and speaker device support +- DMA for audio capture and playback +- The audio capture dump tool is supported and saves data to the PC. +- Some chips feature multiple I2S hardware instances. On the 58x series, I2S1 is + dedicated exclusively to input; please refer to the specific chip datasheet + for details. + ## Driver Configuration -Select the desired I2S device in the {menuselection} `On-Chip Peripheral RTOS Drivers --> Enable I2S Audio Driver` menu. +Select the desired I2S device in the {menuselection} `On-Chip Peripheral RTOS +Drivers --> Enable I2S Audio Driver` menu. +The following macro switches enable the I2S_MIC and I2S_CODEC devices: ```c #define BSP_USING_DMA 1 #define RT_USING_AUDIO 1 @@ -22,12 +34,18 @@ Select the desired I2S device in the {menuselection} `On-Chip Peripheral RTOS Dr ``` ## Device Names -- `i2s`, where x is the device number, such as `i2s1`, `i2s2`, corresponding to the peripheral number. -Refer to the definitions in audio_config.h. You can see that the device name is i2s2, but it actually corresponds to the hardware i2s1 (hwp_i2s1). For chips with only one I2S, or if I2s1 is actually used, note that hwp_i2s2 should be changed to hwp_i2s1. If configuring BF0_MIC_CONFIG, the I2S used as a mic will use drv_i2s_mic.c. If using BSP_ENABLE_I2S_CODEC, drv_i2s_audio.c is generally used for playback data. Note that rt_device_find("i2s1") or rt_device_find("i2s2") should match the .name below. You need to specifically check which one is used in the configuration below. - -struct i2s_audio_cfg_t bf0_i2s_audio_obj[] = { - ... -} +- `i2s`, where x is the device number, such as `i2s1`, `i2s2`, corresponding + to the peripheral number. Refer to the definitions in audio_config.h. You can + see that the device name is i2s2, but it actually corresponds to the hardware + i2s1 (hwp_i2s1). For chips with only one I2S, or if I2s1 is actually used, + note that hwp_i2s2 should be changed to hwp_i2s1. If configuring + BF0_MIC_CONFIG, the I2S used as a mic will use drv_i2s_mic.c. If using + BSP_ENABLE_I2S_CODEC, drv_i2s_audio.c is generally used for playback data. + Note that rt_device_find("i2s1") or rt_device_find("i2s2") should match the + .name below. You need to specifically check which one is used in the + configuration below. + +struct i2s_audio_cfg_t bf0_i2s_audio_obj[] = { ... } ```c #ifdef BSP_USING_I2S @@ -60,12 +78,11 @@ struct i2s_audio_cfg_t bf0_i2s_audio_obj[] = { } #endif /* BF0_I2S2_CONFIG */ #endif /* BSP_ENABLE_I2S_CODEC */ - ``` ## Usage Process ### 1. Open the I2S Device ```c - /* Choose i2s2 or i2s1 based on the configuration in audio_config.h */ +/* Choose i2s2 or i2s1 based on the configuration in audio_config.h */ rt_device_t i2s = rt_device_find("i2s2"); if (i2s) { @@ -73,7 +90,7 @@ struct i2s_audio_cfg_t bf0_i2s_audio_obj[] = { ``` ### 2. Configure Parameters ```c - struct rt_audio_caps caps; +struct rt_audio_caps caps; caps.main_type = AUDIO_TYPE_INPUT; caps.sub_type = AUDIO_DSP_PARAM; /* 1 for mono, 2 for stereo */ @@ -89,10 +106,11 @@ struct i2s_audio_cfg_t bf0_i2s_audio_obj[] = { caps.udata.value = 0; rt_device_control(i2s, AUDIO_CTL_CONFIGURE, &caps); ``` -By default, I2S outputs directly to peripherals. There is also an advanced usage where I2S inputs from audprc module. This is not commonly used. If needed, configure it as follows: -**if you don't know what is audprc->i2s, skip this** +By default, I2S outputs directly to peripherals. There is also an advanced usage +where I2S inputs from audprc module. This is not commonly used. If needed, +configure it as follows: **if you don't know what is audprc->i2s, skip this** ```c - /* i2s input from audprc*/ +/* i2s input from audprc*/ rt_uint32_t inter = 1; rt_device_control(i2s, AUDIO_CTL_SETINPUT, (void *)inter); ``` @@ -117,17 +135,17 @@ rt_err_t audio_tx_done(rt_device_t dev, void *buffer) ``` ### 4. I2S Start ```c - int stream = 0; +int stream = 0; //select one for stream #if playback_only stream = AUDIO_STREAM_REPLAY; /*playback only*/ #else if capture_only stream = AUDIO_STREAM_RECORD; /*record only*/ #else if capture_and_playback - stream = AUDIO_STREAM_RXandTX; /*record & playback*/ + stream = AUDIO_STREAM_RXandTX; /*record & playback*/ #endif - rt_device_control(i2s, AUDIO_CTL_START, &stream); - + rt_device_control(i2s, AUDIO_CTL_START, &stream); + rt_thread_mdelay(xxxx); rt_device_close(i2s); @@ -139,13 +157,16 @@ rt_err_t audio_tx_done(rt_device_t dev, void *buffer) ALIGN(4) static uint8_t audio_data[AUDIO_DATA_SIZE]; ALIGN(4) static uint8_t audio_tx_data[AUDIO_DATA_SIZE]; ``` +AUDIO_DATA_SIZE is size of DMA ping-pong buffer,one DMA frame size is +(AUDIO_DATA_SIZE / 2), when read or write,data size should be (AUDIO_DATA_SIZE / +2). -AUDIO_DATA_SIZE is size of DMA ping-pong buffer,one DMA frame size is (AUDIO_DATA_SIZE / 2), -when read or write,data size should be (AUDIO_DATA_SIZE / 2). ## Using the Audio Driver -The adapter layer registers hardware support functions for RT-Thread and implements these functions using the I2S HAL. The I2S HAL API is detailed in the [I2S documentation](#hal-i2s). +The adapter layer registers hardware support functions for RT-Thread and +implements these functions using the I2S HAL. The I2S HAL API is detailed in the +[I2S documentation](#hal-i2s). ## Example Code for Audio Capture Using RT-Thread Microphone Device: @@ -194,11 +215,16 @@ rt_device_control(g_i2s, AUDIO_CTL_START, &stream); ``` ## other exmaple for i2s - $(sdk_root)\example\rt_device\i2s +$(sdk_root)\example\rt_device\i2s ## shell cmd example - There are command lines at the end of the drv_i2s_audio.c and drv_i2s_mic.c files, which can also be used as a reference. - +There are command lines at the end of the drv_i2s_audio.c and drv_i2s_mic.c +files, which can also be used as a reference. + + +[audio]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/audio/audio ## RT-Thread Documentation -- [AUDIO Device Documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/audio/audio) +- [AUDIO Device Documentation][audio] + diff --git a/docs/source/en/drivers/index.md b/docs/source/en/drivers/index.md index 037c0a647..16b6d8851 100644 --- a/docs/source/en/drivers/index.md +++ b/docs/source/en/drivers/index.md @@ -1,34 +1,37 @@ - # RT-Thread Device Drivers -[device]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/device +[device]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/device -[watchdog]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/watchdog/watchdog +[watchdog]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/watchdog/watchdog -[touch]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/touch/touch +[touch]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/touch/touch -Introduction to RT-Thread device model: [I/O Device Model][device] +For an introduction to the RT-Thread device model, see [I/O Device +Model][device]. -## Chip Peripherals +## On-chip Peripherals -Device Driver | Corresponding HAL | --------------------------|-----------------------------| -[UART Device](uart.md) | [UART](../hal/uart.md) | -[PIN Device](gpio.md) | [GPIO](../hal/gpio.md) | -[ADC Device](adc.md) | [ADC](../hal/adc.md) | -[HWTIMER Device](timer.md)| [GPT](../hal/gpt.md) | -[I2C Device](i2c.md) | [I2C](../hal/i2c.md) | -[PWM Device](pwm.md) | [GPT](../hal/gpt.md) | -[RTC Device](rtc.md) | [RTC](../hal/rtc.md) | -[SPI Device](spi.md) | [SPI](../hal/spi.md) | -[Watchdog Device][watchdog] | [WDT](../hal/wdt.md) | -[audprc_audcodec](i2s.md) | [audprc](../hal/audprc.md) and [audcodec](../hal/audcodec.md) | -[I2S Audio Device](i2s.md) | [I2S](../hal/i2s.md) | -[USBD Device](usbd.md) | [USBC](../hal/pcd.md) | -[SDIO Device](sdio.md) | | -[EPIC Driver](epic.md) | [EPIC](/hal/epic.md) | +| Device Drivers | Corresponding HAL | +| ------------------------------------------ | --------------------------------------------------------- | +| [UART Device](uart.md) | [UART](/hal/uart.md) | +| [PIN Device](gpio.md) | [GPIO](/hal/gpio.md) | +| [ADC Device](adc.md) | [ADC](/hal/adc.md) | +| [HWTIMER Device](timer.md) | [GPT](/hal/gpt.md) | +| [I2C Device](i2c.md) | [I2C](/hal/i2c.md) | +| [PWM Device](pwm.md) | [GPT](/hal/gpt.md) | +| [RTC Device](rtc.md) | [RTC](/hal/rtc.md) | +| [SPI Device](spi.md) | [SPI](/hal/spi.md) | +| [Watchdog Device][watchdog] | [WDT](/hal/wdt.md) | +| [audprc_audcodec](audprc_audcodec.md) | [audprc](/hal/audprc.md) and [audcodec](/hal/audcodec.md) | +| [I2S Audio Device](i2s.md) | [I2S](/hal/i2s.md) | +| [USBD Device](usbd.md) | [USBC](/hal/pcd.md) | +| [SDIO Device](sdio.md) | | +| [Graphics Rendering Driver Layer](epic.md) | [EPIC](/hal/epic.md) | ```{toctree} :hidden: @@ -41,7 +44,8 @@ i2c.md pwm.md rtc.md spi.md -audio.md +audprc_audcodec.md +i2s.md usbd.md sdio.md spi_flash.md @@ -51,23 +55,28 @@ epic.md ### Configuration -Run `menuconfig`, then enter the `On-chip Peripheral RTOS Drivers` menu to configure the peripherals to be used. After selecting a device in menuconfig, it means that the corresponding device will be registered during system initialization, and the application can use the `rt_device_find` interface to obtain the device pointer by device name. For unregistered devices, `rt_device_find` will return a NULL pointer. For example, after selecting the UART1 device, the application can use `rt_device_find("uart1")` to obtain the device pointer. +Run `menuconfig` and navigate to the `On-chip Peripheral RTOS Drivers` menu to +configure the required peripherals. Selecting a device in menuconfig ensures it +is registered during system initialization. Once registered, applications can +retrieve the device pointer by name using the `rt_device_find` interface. If a +device is not registered, `rt_device_find` returns a null pointer. For example, +after enabling the UART1 device, the application can obtain its pointer using +`rt_device_find("uart1")`. ```{note} -If running `menuconfig` in the project directory, you need to add `--board=` to specify the board being used. Refer to the instructions in [](/app_development/create_application.md). The modified configuration is saved in `proj.conf`. +When running `menuconfig` from the project directory, use the `--board=` option to specify the target board, as described in [](/app_development/create_application.md). The modified configuration is saved to `proj.conf`. ``` -## Board-Level Peripherals -- [Display Device](lcd.md) -- [Touch Device](touch.md) +## Board-Level Peripherals +- [Display Devices](lcd.md) +- [Touch Devices](touch.md) ```{toctree} :hidden: lcd.md touch.md - ``` diff --git a/docs/source/en/drivers/lcd.md b/docs/source/en/drivers/lcd.md index 9373b4db4..8101cf44e 100644 --- a/docs/source/en/drivers/lcd.md +++ b/docs/source/en/drivers/lcd.md @@ -1,20 +1,27 @@ # LCD Device ## Introduction -LCD device is an rt_device with a simple LCD framework inside for registering different screen drivers. This chapter mainly introduces the usage and framework of LCD device, and how to register a new screen to this framework. +LCD device is an rt_device with a simple LCD framework inside for registering +different screen drivers. This chapter mainly introduces the usage and framework +of LCD device, and how to register a new screen to this framework. ## Internal Structure The LCD driver has 3 layers: - rt_device_graphic layer - Provides unified calling interface to upper layer - - Supports multiple driver search functionality internally, convenient for compatibility with multiple screens (determined by comparing registered ID and ReadID function return value) - - Contains 3 framebuffer mechanisms internally, allowing rendering and screen refresh to proceed simultaneously, supporting compression. + - Supports multiple driver search functionality internally, convenient for + compatibility with multiple screens (determined by comparing registered ID + and ReadID function return value) + - Contains 3 framebuffer mechanisms internally, allowing rendering and + screen refresh to proceed simultaneously, supporting compression. - Specific driver logic layer - - Specific interface, frequency, TE and other configurations for each screen driver, as well as initialization code, screen refresh commands, sleep, and power on/off instructions + - Specific interface, frequency, TE and other configurations for each screen + driver, as well as initialization code, screen refresh commands, sleep, + and power on/off instructions - Physical interface abstraction layer for screens - - Provides unified operation functions for most interfaces. See [](../hal/lcdc.md) for details + - Provides unified operation functions for most interfaces. See + [](../hal/lcdc.md) for details - -![Figure 1: lcd device SW arch](../../assets/lcd_device_arch.png) +![Figure 1: LCD device software architecture](../../assets/lcd_device_arch.png) @@ -29,10 +36,10 @@ The SDK implements 2 rt_device_graphic instances with rt_device names: ## Example of Upper Layer Using LCD Device -Draw a 100*100 RGB565 format red area in the center of the screen. Each refresh deepens the red color slightly, cycling after 32 times. +Draw a 100*100 RGB565 format red area in the center of the screen. Each refresh +deepens the red color slightly, cycling after 32 times. ```c - #define RGB565_FB_WIDTH 100 #define RGB565_FB_HEIGHT 100 static uint16_t rgb565_frambuffer[RGB565_FB_WIDTH * RGB565_FB_HEIGHT]; @@ -99,7 +106,7 @@ void lcd_flush_task(void *parameter) /* Draw a buffer to the LCD device, asynchronous function, calls lcd_flush_done when complete - + About the {x0,y0,x1,y1} area: 1. This area represents the region the entire buffer occupies on the screen, not for clipping the buffer 2. If only updating part of the buffer, use in conjunction with set_window function @@ -114,12 +121,18 @@ void lcd_flush_task(void *parameter) ## Process for Adding a New Screen ## 1. Select the corresponding board project under example\\rt_driver -- This project contains a simple example of drawing rectangular areas (see previous "_rt_device_graphic_ layer interface usage example") -- If choosing to use the _watch_demo_ project, you need to ***disable the tp thread before tuning the screen*** to prevent TP failure from blocking the UI screen refresh thread (disable method: in `drv_touch.c` `touch_open` function, remove _rt_thread_startup(touch_thread);_ ) +- This project contains a simple example of drawing rectangular areas (see + previous "_rt_device_graphic_ layer interface usage example") +- If choosing to use the _watch_demo_ project, you need to ***disable the tp + thread before tuning the screen*** to prevent TP failure from blocking the UI + screen refresh thread (disable method: in `drv_touch.c` `touch_open` function, + remove _rt_thread_startup(touch_thread);_ ) ## 2. Add new driver to compilation project - Add new screen code to directory _customer\\peripherals_ - - You can copy code from other existing drivers, then change the name, ID, and corresponding commands (most are the same and don't need changes) to your own + - You can copy code from other existing drivers, then change the name, ID, + and corresponding commands (most are the same and don't need changes) to + your own - Note to modify the depend macro in the internal Kconfig file - Screen driver registration macro explanation: ```c @@ -133,17 +146,21 @@ void lcd_flush_task(void *parameter) 2 //Pixel alignment during refresh (write 1 if not needed) ); ``` - + ```{note} Glass resolution is fixed in the `LCD_DRIVER_EXPORT` macro definition, see macros `LCD_HOR_RES_MAX` and `LCD_VER_RES_MAX` ``` -- In _customer\\peripherals\\Kconfig_, add a hidden option for the newly added driver, for example: +- In _customer\\peripherals\\Kconfig_, add a hidden option for the newly added + driver, for example: ```c config LCD_USING_RM69090 bool default n ``` -- Add screen module switch in board-level configuration. The module switch should select the previously added hidden switch and the interface switch used (interface switch is used to modify pinmux), for example, in _customer\\boards\\ec-lb551XXX\\Kconfig_, add module switch: +- Add screen module switch in board-level configuration. The module switch + should select the previously added hidden switch and the interface switch used + (interface switch is used to modify pinmux), for example, in + _customer\\boards\\ec-lb551XXX\\Kconfig_, add module switch: ```c config LCD_USING_ED_LB55SPI17801_QADSPI_LB551 bool "1.78 rect QAD-SPI LCD(ED-LB55SPI17801)" @@ -157,9 +174,11 @@ Glass resolution is fixed in the `LCD_DRIVER_EXPORT` macro definition, see macro endif ``` ```{note} - Touch controller addition process is similar to screen, and should be selected together in this module switch +Touch controller addition process is similar to screen, and should be selected together in this module switch ``` -- Still in the above file, define resolution and DPI values for the newly added screen (***Note: this is the module glass resolution, not the maximum resolution the screen IC can support***) +- Still in the above file, define resolution and DPI values for the newly added + screen (***Note: this is the module glass resolution, not the maximum + resolution the screen IC can support***) ```c config LCD_HOR_RES_MAX int @@ -182,45 +201,73 @@ Glass resolution is fixed in the `LCD_DRIVER_EXPORT` macro definition, see macro default 315 if LCD_USING_ED_LB55_387A_JDI_LB551 default 315 if LCD_USING_ED_LB55SPI17801_QADSPI_LB551 <-------- Newly added line ``` -- If using scons compilation, enter the project menuconfig selection menu, then select the newly added screen module, finally generating _.config_ and _rtconfig.h_ -- If using Keil compilation, you can also directly add source code (but still recommend the same method as scons compilation, so it will be automatically included when regenerating Keil project next time) +- If using scons compilation, enter the project menuconfig selection menu, then + select the newly added screen module, finally generating _.config_ and + _rtconfig.h_ +- If using Keil compilation, you can also directly add source code (but still + recommend the same method as scons compilation, so it will be automatically + included when regenerating Keil project next time) ## 3. Check pinmux for pins used by new LCD and reset pin -- As mentioned earlier, when configuring modules, an interface macro will be selected. The SDK internally handles pin mux processing for different LCDC interface macros -- Since reset pin is controlled by independent GPIO, need to confirm if the pin controlled by `BPS_LCD_Reset` function is correct +- As mentioned earlier, when configuring modules, an interface macro will be + selected. The SDK internally handles pin mux processing for different LCDC + interface macros +- Since reset pin is controlled by independent GPIO, need to confirm if the pin + controlled by `BPS_LCD_Reset` function is correct ## 4. Modify interface, frequency, and output color format of new screen -- See example below, modify the `init_cfg` structure in `LCD_DRIVER_EXPORT` macro (output frequency may differ from configured value, please use actual output as reference, because HAL layer implementation output frequency = HCLK/divider, HCLK can be viewed by entering "sysinfo" in console, divider is an integer from 2~255) -- It's recommended to disable TE during initial debugging to prevent LCDC from not sending data due to waiting for TE signal (our TE signal is handled automatically by LCDC, no software involvement needed) +- See example below, modify the `init_cfg` structure in `LCD_DRIVER_EXPORT` + macro (output frequency may differ from configured value, please use actual + output as reference, because HAL layer implementation output frequency = + HCLK/divider, HCLK can be viewed by entering "sysinfo" in console, divider is + an integer from 2~255) +- It's recommended to disable TE during initial debugging to prevent LCDC from + not sending data due to waiting for TE signal (our TE signal is handled + automatically by LCDC, no software involvement needed) ```{note} Our TE signal is handled automatically by LCDC, no software involvement needed, so there's no TE software interrupt. As long as TE pin mux and polarity are configured correctly, after starting LCDC data transmission (_HAL_LCDC_SendLayerData2Reg_IT_), LCDC will start sending data when it receives TE pulse ``` ## 5. Using Any GPIO as TE Signal (Optional) -In most cases, as long as the corresponding pin is defined as TE function, LCDC can automatically handle TE signal. However, in some special cases where TE signal cannot come from the expected path, it needs to be changed to ordinary GPIO implementation. At this time, software GPIO interrupt method can be used: +In most cases, as long as the corresponding pin is defined as TE function, LCDC +can automatically handle TE signal. However, in some special cases where TE +signal cannot come from the expected path, it needs to be changed to ordinary +GPIO implementation. At this time, software GPIO interrupt method can be used: - Enable TE and set TE delay according to normal configuration -- Define macro "`LCD_USE_GPIO_TE`" as an ordinary GPIO, which will actively create a TE signal (flip TE polarity) on interrupt rising edge to trigger LCDC data transmission +- Define macro "`LCD_USE_GPIO_TE`" as an ordinary GPIO, which will actively + create a TE signal (flip TE polarity) on interrupt rising edge to trigger LCDC + data transmission ```{note} Since normal TE path is not working, the first step setting cannot work, only the second step artificial signal creation can trigger data transmission to achieve normal TE processing ``` ## 6. Modify initialization code of new screen driver -- Generally, first initialize LCDC, configure interface, frequency, etc. Call API - HAL_LCDC_Init. -- Then reset LCD through `BPS_LCD_Reset` function implemented in drv_io.c to control GPIO reset screen. +- Generally, first initialize LCDC, configure interface, frequency, etc. Call + API - HAL_LCDC_Init. +- Then reset LCD through `BPS_LCD_Reset` function implemented in drv_io.c to + control GPIO reset screen. - Then the initialization code provided by screen manufacturer ## 7. Modify read id function -- `drv_lcd.c` will use this function's return value to compare with ID registered in `LCD_DRIVER_EXPORT`. ***Only when they match will the driver be considered usable and called.*** +- `drv_lcd.c` will use this function's return value to compare with ID + registered in `LCD_DRIVER_EXPORT`. ***Only when they match will the driver be + considered usable and called.*** ## 8. QAD-SPI LCD Extended Command Modification -- QAD-SPI LCD generally extends standard 8bit commands to 32bit, need to modify extension method. Can refer to rm69330.c, generally these functions need modification: _RM69330_WriteMultiplePixels_, _RM69330_WriteReg_, _RM69330_ReadData_. +- QAD-SPI LCD generally extends standard 8bit commands to 32bit, need to modify + extension method. Can refer to rm69330.c, generally these functions need + modification: _RM69330_WriteMultiplePixels_, _RM69330_WriteReg_, + _RM69330_ReadData_.


## Customer New Screen Driver Code Example (Partial) -The following example code shows how RM69330 registers to `drv_lcd.c` (rt_device_graphic layer) and interface configuration, function callbacks, etc. Please refer to SDK code for specific implementation of each function, not detailed here. +The following example code shows how RM69330 registers to `drv_lcd.c` +(rt_device_graphic layer) and interface configuration, function callbacks, etc. +Please refer to SDK code for specific implementation of each function, not +detailed here. ```c @@ -275,9 +322,6 @@ LCD_DRIVER_EXPORT(rm69330, RM69330_ID, &lcdc_int_cfg_qspi, &RM69330_drv, RM69330_LCD_PIXEL_WIDTH, RM69330_LCD_PIXEL_HEIGHT,2); - - - ``` ```{note} As mentioned earlier, `drv_lcd.c` during initialization will compare ***RM69330_ID registered in LCD_DRIVER_EXPORT*** and ***ID returned by RM69330_ReadID***, only when they match will it be called. @@ -286,10 +330,14 @@ As mentioned earlier, `drv_lcd.c` during initialization will compare ***RM69330_ ## Supporting Multiple Screen Modules Simultaneously Assuming compatibility with 2 modules: -- Module 1: LB55SPI17801 (screen IC is RM69090, touch IC is FT3168), +- Module 1: LB55SPI17801 (screen IC is RM69090, touch IC is FT3168), - Module 2: LB55BILI8688E (screen IC is ILI8688E, touch IC is CST918), - -Same as adding screens before, just add an item to the project's corresponding Kconfig file that simultaneously selects both modules' screen drivers and touch drivers (note: screen driver's ReadID function must be able to distinguish between the 2 ICs, similarly touch probe function must also be able to distinguish different ICs). + +Same as adding screens before, just add an item to the project's corresponding +Kconfig file that simultaneously selects both modules' screen drivers and touch +drivers (note: screen driver's ReadID function must be able to distinguish +between the 2 ICs, similarly touch probe function must also be able to +distinguish different ICs). Kconfig file example: ```c @@ -319,16 +367,24 @@ Other screen resolution configurations and DPI configurations can share the `LCD ## DSI Screen Debugging -It's recommended to debug low-speed mode first because low-speed can bypass hardware-caused issues and is easy to analyze with oscilloscope. After low-speed mode is working, read ID - reading ID can check if screen power-on is normal. -After low-speed mode read ID and screen refresh are normal, then switch to high-speed mode for screen refresh. +It's recommended to debug low-speed mode first because low-speed can bypass +hardware-caused issues and is easy to analyze with oscilloscope. After low-speed +mode is working, read ID - reading ID can check if screen power-on is normal. +After low-speed mode read ID and screen refresh are normal, then switch to +high-speed mode for screen refresh. ## DSI Low-Speed Mode Operation Flow - Reduce LCDC data transmission speed - - Need to reduce system clock to 48M, in `drv_io.c`, change _HAL_RCC_HCPU_ClockSelect(RCC_CLK_MOD_SYS, XXX)_; XXX is the system clock frequency, change to _RCC_SYSCLK_HXT48_ (crystal clock 48MHz) - - Change all commands to LP mode (low-speed mode) transmission, and enable LCD acknowledge for easy waveform analysis with logic analyzer or oscilloscope (configure in the `LCDC_InitTypeDef` structure mentioned earlier, as follows:) + - Need to reduce system clock to 48M, in `drv_io.c`, change + _HAL_RCC_HCPU_ClockSelect(RCC_CLK_MOD_SYS, XXX)_; XXX is the system clock + frequency, change to _RCC_SYSCLK_HXT48_ (crystal clock 48MHz) + - Change all commands to LP mode (low-speed mode) transmission, and enable + LCD acknowledge for easy waveform analysis with logic analyzer or + oscilloscope (configure in the `LCDC_InitTypeDef` structure mentioned + earlier, as follows:) ```c - .LPCmd = { + .LPCmd = { .LPGenShortWriteNoP = DSI_LP_GSW0P_ENABLE, .LPGenShortWriteOneP = DSI_LP_GSW1P_ENABLE, .LPGenShortWriteTwoP = DSI_LP_GSW2P_ENABLE, @@ -345,11 +401,13 @@ After low-speed mode read ID and screen refresh are normal, then switch to high- }, ``` ```{note} - After setting _init->cfg.dsi.LPCmd.LPDcsLongWrite_ to `DSI_LP_DLW_ENABLE`, _HAL_LCDC_Init_ will automatically reduce DBI transmission frequency to minimum (48 * 16 / 126 = ~6Mbps, where 48 is system clock, 16 is DBI bandwidth, 126 is maximum division factor) + After setting _init->cfg.dsi.LPCmd.LPDcsLongWrite_ to `DSI_LP_DLW_ENABLE`, _HAL_LCDC_Init_ will automatically reduce DBI transmission frequency to minimum (48 * 16 / 126 = ~6Mbps, where 48 is system clock, 16 is DBI bandwidth, 126 is maximum division factor) ``` - -- Adjust DSI LP mode frequency to screen-supported range (generally 6~20Mbps), with following configuration LP frequency = 480 / 8 / 4 = 15Mbps (where 480 is freq, 8 is fixed value, 4 is TXEscapeCkdiv) + +- Adjust DSI LP mode frequency to screen-supported range (generally 6~20Mbps), + with following configuration LP frequency = 480 / 8 / 4 = 15Mbps (where 480 is + freq, 8 is fixed value, 4 is TXEscapeCkdiv) ```c static LCDC_InitTypeDef lcdc_int_cfg_dsi = { @@ -375,23 +433,30 @@ After low-speed mode read ID and screen refresh are normal, then switch to high- } ``` -- Extend screen refresh timeout in drv_lcd layer, otherwise default 500ms easily times out at low speed. Adjust macro `MAX_LCD_DRAW_TIME` value. +- Extend screen refresh timeout in drv_lcd layer, otherwise default 500ms easily + times out at low speed. Adjust macro `MAX_LCD_DRAW_TIME` value. -- Enable log in `bf0_hal_dsi.c` (need to override _HAL_DBG_printf_), can check communication process errors through log +- Enable log in `bf0_hal_dsi.c` (need to override _HAL_DBG_printf_), can check + communication process errors through log ```c #define DSI_LOG_D(...) HAL_DBG_printf(__VA_ARGS__) #define DSI_LOG_E(...) HAL_DBG_printf(__VA_ARGS__) ``` -- If conditions permit, use logic analyzer or oscilloscope to capture waveforms on P,N pins of DATALANE0, parse whether commands, color formats, etc. are expected data +- If conditions permit, use logic analyzer or oscilloscope to capture waveforms + on P,N pins of DATALANE0, parse whether commands, color formats, etc. are + expected data ```{note} When reading ID, check if screen has ack after bus turnaround. If not, power-on or reset may be abnormal ``` ## DSI High-Speed Mode Configuration -- After low-speed mode can read ID and refresh expected colors, can switch to high-speed mode, generally it will work. - - High-speed mode needs to change AcknowledgeRequest to disable, otherwise it easily causes data transmission fifo overflow - - Also note that some screens have different maximum frequencies for different color formats. +- After low-speed mode can read ID and refresh expected colors, can switch to + high-speed mode, generally it will work. + - High-speed mode needs to change AcknowledgeRequest to disable, otherwise + it easily causes data transmission fifo overflow + - Also note that some screens have different maximum frequencies for + different color formats. ``` Configure in the LCDC_InitTypeDef structure mentioned earlier: @@ -401,17 +466,15 @@ When reading ID, check if screen has ack after bus turnaround. If not, power-on ... .AcknowledgeRequest = DSI_ACKNOWLEDGE_DISABLE, //Need to disable Ack packets in high-speed mode } - ``` - - + ``` ## DSI Color and TE Function Configuration - DSI color format reference [](../hal/dsi.md) -- DSI TE function - DSI TE has 2 optional paths: through DSI link or through LCDC_TE function pin - If using LCDC_TE pin, need to simultaneously specify physical pin pinmux as LCDC_TE function (can be LCDCx_SPI_TE/LCDCx_8080_TE) +- DSI TE function DSI TE has 2 optional paths: through DSI link or through + LCDC_TE function pin If using LCDC_TE pin, need to simultaneously specify + physical pin pinmux as LCDC_TE function (can be LCDCx_SPI_TE/LCDCx_8080_TE) ``` - static LCDC_InitTypeDef lcdc_int_cfg_dsi = + static LCDC_InitTypeDef lcdc_int_cfg_dsi = { .lcd_itf = LCDC_INTF_DSI, .freq = DSI_FREQ_480MHZ, @@ -423,8 +486,8 @@ When reading ID, check if screen has ack after bus turnaround. If not, power-on .CmdCfg = { ... .TearingEffectSource = DSI_TE_EXTERNAL, <<<---- DSI_TE_EXTERNAL means using LCDC_TE pin, DSI_TE_DSILINK means using DSI link - ``` ```{note} On 55x series chips, DSI using LCDC_TE function pin is not supported. Please refer to the "Using Any GPIO as TE Signal" section above. - ``` \ No newline at end of file + ``` + diff --git a/docs/source/en/drivers/psram.md b/docs/source/en/drivers/psram.md index 83a6f5d63..28214f4c2 100644 --- a/docs/source/en/drivers/psram.md +++ b/docs/source/en/drivers/psram.md @@ -1,24 +1,33 @@ # PSRAM -PSRam driver includes two layers: hardware access layer (HAL) and RT-Thread adaptation layer.
-HAL provides basic APIs for accessing psram peripheral registers. For details, please refer to the API documentation of psram HAL.
-The adaptation layer provides hardware initial interface. After initialization, it is used as sram memory. +PSRam driver includes two layers: hardware access layer (HAL) and RT-Thread +adaptation layer.
HAL provides basic APIs for accessing psram peripheral +registers. For details, please refer to the API documentation of psram HAL.
+The adaptation layer provides hardware initial interface. After initialization, +it is used as sram memory. ## Driver Configuration -The hardware driver uses only one instance with a base address of 0x60000000, which cannot be changed. It can be enabled for each project using the menuconfig tool, usually saved in C header files. By default, the configuration is saved as _rtconfig.h_. +The hardware driver uses only one instance with a base address of 0x60000000, +which cannot be changed. It can be enabled for each project using the menuconfig +tool, usually saved in C header files. By default, the configuration is saved as +_rtconfig.h_. -The following example shows the flags defined in a project header file, where the project enables the PSRAM controller and sets its memory size (in MB). Configuration selection steps: +The following example shows the flags defined in a project header file, where +the project enables the PSRAM controller and sets its memory size (in MB). +Configuration selection steps: - Enter "menuconfig" in the command under the project - Select "RTOS --->" -- Select "On-chip Peripheral Driver--->" -- Select "Enable PSRAM --->" Use psram driver, define macro BSP_USING_PSRAM -- Enter "PSram full chip size(MB)" Set psram memory size in MB, define macro PSRAM_FULL_SIZE +- Select "On-chip Peripheral Driver--->" +- Select "Enable PSRAM --->" Use psram driver, define macro BSP_USING_PSRAM +- Enter "PSram full chip size(MB)" Set psram memory size in MB, define macro + PSRAM_FULL_SIZE ```c #define BSP_USING_PSRAM #define PSRAM_FULL_SIZE 4 ``` -After configuration, users need to include header files in all source code that needs to access the driver. +After configuration, users need to include header files in all source code that +needs to access the driver. ## Memory Address and Initial Interface When using psram memory, its base address is defined in the memory map: @@ -29,36 +38,36 @@ When using psram memory, its base address is defined in the memory map: Initial interface, called once before using psram. ```c /** - * @brief psram hardware initial. - * @param[none] . - * @return 0 if initial success. + * @brief Initializes the PSRAM hardware. + * @param None. + * @return 0 on successful initialization. */ int rt_psram_init(void); ``` ## Using PSRAM -After initialization, PSRAM memory can be accessed by CPU and DMA like normal sram memory, as shown below: +After initialization, PSRAM memory can be accessed by CPU and DMA like normal +sram memory, as shown below: ```c - -// Initial PSRAM hardware before using it +// Initialize PSRAM hardware before use rt_psram_init(); -// Define PSRAM base address for memory access, it can not be changed +// Define the PSRAM base address for memory access (constant) #define PSRAM_BASE_ADDR PSRAM_BASE int *buf = (int *)PSRAM_BASE_ADDR; int i; -// Write psram memory -for(i=0; i<1000; i++) +// Write to PSRAM memory +for(i=0; i<1000; i++) buf[i] = i*6543; -// Read psram +// Read from PSRAM int value = *buf; -// Read and Write +// Read and Write operations int *src = (int *)PSRAM_BASE_ADDR; int *dst = (int *)(PSRAM_BASE_ADDR + 0x100000); memcpy(dst, src, 1000); @@ -66,7 +75,7 @@ memcpy(dst, src, 1000); ... -// Close device, keep it open for more user. +// Close the device; keep it open if required by other users. +``` -``` \ No newline at end of file diff --git a/docs/source/en/drivers/pwm.md b/docs/source/en/drivers/pwm.md index d926a5d4e..5d5ae3d2c 100644 --- a/docs/source/en/drivers/pwm.md +++ b/docs/source/en/drivers/pwm.md @@ -1,19 +1,35 @@ # PWM Device -GPTim (General Purpose Timer), LPTim (Low Power Timer), and ATIM (Advanced Timer) can work in PWM mode for hardware timers: -- General Purpose Timer (GPTim): GPTim implements a 16-bit counter for system PCLK, providing 1-65536 prescaler. It has 4 input/output channels. GPTim can be used for PWM to generate waveform signals or measure input signals. -- Low Power Timer (LPTim): LPTim implements a 16-bit counter for system PCLK or low power clock, providing 1-128 prescaler. LPTim can be used for PWM to generate waveform signals. -- Advanced Timer (ATIM): ATIM implements a 32-bit counter for system PCLK, providing 1-65536 prescaler. It has 6 channels, channels 1-3 can be configured as input or output mode respectively, where each channel can output two complementary PWM signals with dead-time protection, channel 4 can be configured as input or output mode and can output single PWM, channels 5-6 can be configured as output compare mode. - -Hardware PWM driver includes two layers: hardware access layer (HAL) and RT-Thread adaptation layer.
-HAL provides basic APIs for accessing hardware timer peripheral registers. For details, please refer to the API documentation of hardware timer HAL.
-The adaptation layer provides support for RT-Thread driver framework. Users can use RT-Thread POSIX driver interface for PWM programming. Device names like pwm3, pwm4, pwmlp1, and pwmlp3 are configured in menuconfig. +GPTim (General Purpose Timer), LPTim (Low Power Timer), and ATIM (Advanced +Timer) can work in PWM mode for hardware timers: +- General Purpose Timer (GPTim): GPTim implements a 16-bit counter for system + PCLK, providing 1-65536 prescaler. It has 4 input/output channels. GPTim can + be used for PWM to generate waveform signals or measure input signals. +- Low Power Timer (LPTim): LPTim implements a 16-bit counter for system PCLK or + low power clock, providing 1-128 prescaler. LPTim can be used for PWM to + generate waveform signals. +- Advanced Timer (ATIM): ATIM implements a 32-bit counter for system PCLK, + providing 1-65536 prescaler. It has 6 channels, channels 1-3 can be configured + as input or output mode respectively, where each channel can output two + complementary PWM signals with dead-time protection, channel 4 can be + configured as input or output mode and can output single PWM, channels 5-6 can + be configured as output compare mode. + +Hardware PWM driver includes two layers: hardware access layer (HAL) and +RT-Thread adaptation layer.
HAL provides basic APIs for accessing hardware +timer peripheral registers. For details, please refer to the API documentation +of hardware timer HAL.
The adaptation layer provides support for RT-Thread +driver framework. Users can use RT-Thread POSIX driver interface for PWM +programming. Device names like pwm3, pwm4, pwmlp1, and pwmlp3 are configured in +menuconfig. ## Driver Configuration -Select the PWM devices to use in the {menuselection}`On-Chip Peripheral RTOS Drivers --> Enable pwm` menu. +Select the PWM devices to use in the {menuselection}`On-Chip Peripheral RTOS +Drivers --> Enable pwm` menu. -The following macro switches indicate that PWM3, PWM4, LPTIM3, PWMA1 and other devices are enabled: +The following macro switches indicate that PWM3, PWM4, LPTIM3, PWMA1 and other +devices are enabled: ```c #define RT_USING_PWM #define BSP_USING_PWM 1 @@ -24,48 +40,52 @@ The following macro switches indicate that PWM3, PWM4, LPTIM3, PWMA1 and other d ``` ## Device Names -- `pwm`: x is the device number, such as `pwm2`, `pwm3`. Note that device numbering starts from 2, device `pwm2` corresponds to peripheral `GPTIM1`, `pwm3` corresponds to peripheral `GPTIM2`, and so on -- `pwmlp`: x is the device number, such as `pwmlp1`, `pwmlp2`, corresponding to peripherals `LPTIM1` and `LPTIM2` -- `pwma`: x is the device number, such as `pwma1`, corresponding to peripheral `ATIM1` +- `pwm`: x is the device number, such as `pwm2`, `pwm3`. Note that device + numbering starts from 2, device `pwm2` corresponds to peripheral `GPTIM1`, + `pwm3` corresponds to peripheral `GPTIM2`, and so on +- `pwmlp`: x is the device number, such as `pwmlp1`, `pwmlp2`, corresponding + to peripherals `LPTIM1` and `LPTIM2` +- `pwma`: x is the device number, such as `pwma1`, corresponding to + peripheral `ATIM1` ## Example Code ```c -// Find and open device +// Locate and open the device rt_device_t rt_device_find(const char *name); - name: pwmlp1 / pwmlp3 / pwm3 / pwm4 /pwma1 ... + name: pwmlp1 / pwmlp3 / pwm3 / pwm4 / pwma1 ... -// Set +// Configure PWM parameters rt_err_t rt_pwm_set(struct rt_device_pwm *device, int channel, rt_uint32_t period, rt_uint32_t pulse); - channel: 1-4 for GPTim, ignored for LPTim - period: unit:ns 1ns~4.29s:1Ghz~0.23hz - pulse: unit:ns (pulse<=period) + channel: 1-4 for GPTIM; ignored for LPTIM + period: unit: ns (range: 1 ns to 4.29 s; frequency: 1 GHz to 0.23 Hz) + pulse: unit: ns (pulse <= period) -// Start & Stop +// Enable and disable PWM rt_err_t rt_pwm_enable(struct rt_device_pwm *device, int channel); rt_err_t rt_pwm_disable(struct rt_device_pwm *device, int channel); -//atimer deadtime break set +// Configure ATIMER dead-time and break functionality rt_err_t rt_pwm_set_brk_dead(struct rt_device_pwm *device, rt_uint32_t *bkd, rt_uint32_t dt_ns); -bkd: struct rt_pwm_break_dead config value -dt_ns: dead time ,unit ns. if dt_ns is 0, dead time use bkd->dtg (0~1023). +bkd: Pointer to the struct rt_pwm_break_dead configuration structure +dt_ns: Dead-time duration (ns). If set to 0, the dead-time defaults to the bkd->dtg value (0–1023). -// example +// Usage Example { struct rt_device_pwm *device = RT_NULL; - - device = (struct rt_device_pwm *)rt_device_find("pwm3"); + + device = (struct rt_device_pwm *)rt_device_find("pwm3"); if (!device) { return; } rt_pwm_set(device, 1, 500000000, 250000000); - if (is_comp) //is pwm complementary + if (is_comp) // Check if PWM is in complementary mode { - struct rt_pwm_break_dead bkd = {0}; // TODO: set the BKD. - rt_pwm_set_brk_dead(device, (rt_uint32_t *)&bkd, 100); + struct rt_pwm_break_dead bkd = {0}; // TODO: Initialize BKD structure parameters. + rt_pwm_set_brk_dead(device, (rt_uint32_t *)&bkd, 100); rt_pwm_enable2(device, channel, 1); } else @@ -75,11 +95,11 @@ dt_ns: dead time ,unit ns. if dt_ns is 0, dead time use bkd->dtg (0~1023). ...... rt_pwm_disable(device, 1); } - ``` -[pwm]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/pwm/pwm +[PWM]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/pwm/pwm ## RT-Thread Reference Documentation -- [PWM Device][pwm] +- [PWM Device][PWM] diff --git a/docs/source/en/drivers/rtc.md b/docs/source/en/drivers/rtc.md index 28cf1a9fc..bfe862e9e 100644 --- a/docs/source/en/drivers/rtc.md +++ b/docs/source/en/drivers/rtc.md @@ -1,12 +1,22 @@ # RTC Device -The Real-Time Clock (RTC) of SIFLI chipset is an independent binary coded decimal (BCD) timer/counter. -The RTC core consists of counter, prescaler, clock divider, alarm data registers, etc. -Like any standard RTC chip, the embedded RTC can be used to provide full-featured software-based calendar as well as alarm functionality. -However, more work needs to be done on the software side rather than hardware side. When using RTC chips, you only need to read or write separate date-time registers. In SIFLI chipset, we need to do more than this because there are no separate date-time registers. -Resetting or waking up the MCU from sleep/standby mode does not reinitialize the time once set. -The effect is better if there is a backup battery on the backup battery (VBAT) pin. All VDD of SIFLI chipset can be turned off, in other words, the entire MCU core can be completely shut down, but the backup battery keeps the RTC and backup domain running. Therefore, time does not change or get lost during power-off and sleep modes. The main features of SIFLI embedded RTC are as follows: +The Real-Time Clock (RTC) of SIFLI chipset is an independent binary coded +decimal (BCD) timer/counter. The RTC core consists of counter, prescaler, clock +divider, alarm data registers, etc. Like any standard RTC chip, the embedded RTC +can be used to provide full-featured software-based calendar as well as alarm +functionality. However, more work needs to be done on the software side rather +than hardware side. When using RTC chips, you only need to read or write +separate date-time registers. In SIFLI chipset, we need to do more than this +because there are no separate date-time registers. + +Resetting or waking up the MCU from sleep/standby mode does not reinitialize the +time once set. The effect is better if there is a backup battery on the backup +battery (VBAT) pin. All VDD of SIFLI chipset can be turned off, in other words, +the entire MCU core can be completely shut down, but the backup battery keeps +the RTC and backup domain running. Therefore, time does not change or get lost +during power-off and sleep modes. The main features of SIFLI embedded RTC are as +follows: Programmable prescaler: division factor up to - 18-bit programmable counter for long-term wakeup. @@ -17,7 +27,8 @@ For detailed API of RTC driver, please refer to [RTC](#hal-rtc). ## Driver Configuration -Select to enable RTC device in the {menuselection}`On-Chip Peripheral RTOS Drivers --> Enable RTC` menu. +Select to enable RTC device in the {menuselection}`On-Chip Peripheral RTOS +Drivers --> Enable RTC` menu. The following macro switch indicates that RTC device is enabled: ```c @@ -29,7 +40,8 @@ The following macro switch indicates that RTC device is enabled: ## Example Code -The following code will initialize RTC registers and use them as timestamps later. +The following code will initialize RTC registers and use them as timestamps +later. ```c { // Set time to January 7, 2020, 16:02:15 @@ -50,25 +62,26 @@ The following code will use RTC for alarm service. rt_device_t device; struct rt_rtc_wkalarm alm; -// Set alarm at 18:30:00 +// Set alarm for 18:30:00 alm.enable = 1 alm.tm_hour = 18; alm.tm_min = 30; alm.tm_sec = 00; device = rt_device_find("rtc"); -rt_device_control(device, RT_DEVICE_CTRL_RTC_SET_ALARM, &alm); +rt_device_control(device, RT_DEVICE_CTRL_RTC_SET_ALARM, &alm); ... - + void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) { LOG_I("Alarm triggered"); } - ``` -[rtc]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc +[rtc]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc ## RT-Thread Reference Documentation - [RTC Device][rtc] + diff --git a/docs/source/en/drivers/sdio.md b/docs/source/en/drivers/sdio.md index c8db3253f..42942b71b 100644 --- a/docs/source/en/drivers/sdio.md +++ b/docs/source/en/drivers/sdio.md @@ -1,18 +1,24 @@ # SDIO -SDIO driver includes two layers: hardware access layer (HAL) and RT-Thread adaptation layer.
-HAL provides basic APIs for accessing SDIO peripheral registers. For details, please refer to the API documentation of SDIO HAL.
-The adaptation layer provides SDCARD access functionality. After initialization, it registers an SDCARD device that can be accessed by the file system. +SDIO driver includes two layers: hardware access layer (HAL) and RT-Thread +adaptation layer.
HAL provides basic APIs for accessing SDIO peripheral +registers. For details, please refer to the API documentation of SDIO HAL.
+The adaptation layer provides SDCARD access functionality. After initialization, +it registers an SDCARD device that can be accessed by the file system. ## Driver Configuration -The hardware driver is initialized by default as a block device for SDMMC cards. It can be enabled for each project using the menuconfig tool, usually saved in C header files. By default, the configuration is saved as _rtconfig.h_. +The hardware driver is initialized by default as a block device for SDMMC cards. +It can be enabled for each project using the menuconfig tool, usually saved in C +header files. By default, the configuration is saved as _rtconfig.h_. -The following example shows the flags defined in a project header file that enables SDIO in BSP. For RT-Thread, its SDMMC device also needs to be enabled. Steps to select configuration for BSP: +The following example shows the flags defined in a project header file that +enables SDIO in BSP. For RT-Thread, its SDMMC device also needs to be enabled. +Steps to select configuration for BSP: - Enter "menuconfig" in the command under the project - Select "RTOS --->" -- Select "On-chip Peripheral Driver--->" -- Select "Enable SDIO" Enable SDIO driver, define macro `BSP_USING_SDIO` +- Select "On-chip Peripheral Driver--->" +- Select "Enable SDIO" Enable SDIO driver, define macro `BSP_USING_SDIO` ```c #define BSP_USING_SDIO ``` @@ -21,7 +27,9 @@ Here shows the RT-Thread SDIO driver configuration: - Select "RT-Thread Components --->" - Select "Device Driver--->" - Select "Using SD/MMC device drivers" -- Select "The stack size for mmcsd thread" Enter 2048, change macro `RT_MMCSD_STACK_SIZE`, 1024 is too small. Other configurations remain unchanged if not needed. +- Select "The stack size for mmcsd thread" Enter 2048, change macro + `RT_MMCSD_STACK_SIZE`, 1024 is too small. Other configurations remain + unchanged if not needed. ```c #define RT_USING_SDIO @@ -31,27 +39,33 @@ Here shows the RT-Thread SDIO driver configuration: #define RT_MMCSD_THREAD_PREORITY 22 #define RT_MMCSD_MAX_PARTITION 16 ``` -After configuration, users need to include header files in all source code that needs to access the driver. +After configuration, users need to include header files in all source code that +needs to access the driver. ## Using SDMMC -The adapter layer registers hardware support functions requested by RT-Thread and implements these functions using HAL. For users using RT-Thread, the following code can be used as an example: +The adapter layer registers hardware support functions requested by RT-Thread +and implements these functions using HAL. For users using RT-Thread, the +following code can be used as an example: ```c -// Find and open sdcard as block device -rt_device_t dev = rt_device_find("sd0"); // get block device +// Locate and open the SD card as a block device +rt_device_t dev = rt_device_find("sd0"); // Retrieve handle for the block device rt_err_t err = rt_device_open(dev, RT_DEVICE_FLAG_RDWR); -// read sdmmc, it's a block device, read size should be block based(default as 512) +// Read from the SD/MMC block device. +// Note: Read operations must be block-aligned (the default block size is 512 bytes). char * buf = malloc(4096); -blk = len >> 9; +blk = len >> 9; int size = rt_device_read(dev, addr, (void *)buf, blk); -// Write sdmmc +// Write to the SD/MMC block device size = rt_device_write(dev, addr, buf, blk); ... -// Close block device -rt_device_close(dev); \ No newline at end of file +// Close the block device +rt_device_close(dev); +``` + diff --git a/docs/source/en/drivers/spi.md b/docs/source/en/drivers/spi.md index 8af83fa22..bff762734 100644 --- a/docs/source/en/drivers/spi.md +++ b/docs/source/en/drivers/spi.md @@ -1,9 +1,12 @@ # SPI Device -SPI driver includes two layers: hardware access layer (HAL) and RT-Thread adaptation layer.
-The hardware access layer provides basic APIs for accessing SPI peripheral registers. For details, please refer to the API documentation of SPI HAL.
-The adaptation layer provides support for RT-Thread driver framework. Users can use RT-Thread POSIX driver interface for SPI programming. Please refer to the API documentation of RT-Thread driver.
-Main features include:
+SPI driver includes two layers: hardware access layer (HAL) and RT-Thread +adaptation layer.
The hardware access layer provides basic APIs for +accessing SPI peripheral registers. For details, please refer to the API +documentation of SPI HAL.
The adaptation layer provides support for +RT-Thread driver framework. Users can use RT-Thread POSIX driver interface for +SPI programming. Please refer to the API documentation of RT-Thread driver.
+Main features include:
- Multi-instance support - Support SPI working in master or slave mode - Support SPI speed up to 24Mbps @@ -13,9 +16,11 @@ Main features include:
## Driver Configuration -Select the SPI bus devices to use in the {menuselection}`On-Chip Peripheral RTOS Drivers -> Enable SPI BUS` menu, and configure whether to support DMA. +Select the SPI bus devices to use in the {menuselection}`On-Chip Peripheral RTOS +Drivers -> Enable SPI BUS` menu, and configure whether to support DMA. -The following macro switches indicate that SPI1 and SPI2 devices are enabled, and both support DMA for transmit and receive: +The following macro switches indicate that SPI1 and SPI2 devices are enabled, +and both support DMA for transmit and receive: ```c #define RT_USING_SPI #define BSP_USING_SPI @@ -25,7 +30,6 @@ The following macro switches indicate that SPI1 and SPI2 devices are enabled, an #define BSP_SPI1_RX_USING_DMA #define BSP_SPI2_TX_USING_DMA #define BSP_SPI2_RX_USING_DMA - ``` ```{note} @@ -33,25 +37,25 @@ Selecting DMA in menuconfig only means configuring the driver to support DMA, bu ``` ## Device Names -- `spi`, -where x is the device number, such as `spi1`, `spi2`, corresponding to the peripheral numbers being operated +- `spi`, where x is the device number, such as `spi1`, `spi2`, corresponding + to the peripheral numbers being operated ## Example Code ```c -// Find and open device +// Locate and open device rt_device_t rt_device_find(const char *name); name: spi1 / spi2 rt_err_t rt_hw_spi_device_attach(const char *bus_name, const char *device_name); bus_name: spi1 / spi2 rt_err_t rt_device_open(rt_device_t dev, rt_uint16_t oflag); - oflag: dma mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_DMA_RX|RT_DEVICE_FLAG_DMA_TX - int mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_INT_RX|RT_DEVICE_FLAG_INT_TX - normal mode: RT_DEVICE_FLAG_RDWR - + oflag: DMA mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_DMA_RX|RT_DEVICE_FLAG_DMA_TX + Interrupt mode: RT_DEVICE_FLAG_RDWR|RT_DEVICE_FLAG_INT_RX|RT_DEVICE_FLAG_INT_TX + Normal mode: RT_DEVICE_FLAG_RDWR + // Configure SPI rt_err_t rt_spi_configure(struct rt_spi_device *device, struct rt_spi_configuration *cfg) - cfg: use struct rt_spi_configuration as following: + cfg: use struct rt_spi_configuration as follows: struct rt_spi_configuration { rt_uint8_t mode; @@ -60,19 +64,19 @@ rt_err_t rt_spi_configure(struct rt_spi_device *device, struct rt_spi_configurat rt_uint32_t max_hz; }; -// RX/TX +// Transmit/Receive rt_size_t rt_spi_transfer(struct rt_spi_device *device, const void *send_buf, void *recv_buf, rt_size_t length); -// Interrupt callback, try not issue read in interrupt context. +// Interrupt callbacks (avoid issuing reads within an interrupt context) __weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) __weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) __weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) __weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) -// example +// Example void spi_trans_test() { rt_device_t spi_bus = RT_NULL; @@ -81,7 +85,7 @@ void spi_trans_test() rt_err_t err_code; rt_uint8_t *rx_buff = RT_NULL; rt_uint8_t *tx_buff = RT_NULL; - + spi_bus = rt_device_find("spi1"); if (RT_NULL == spi_bus) { @@ -98,26 +102,26 @@ void spi_trans_test() } spi_dev = (struct rt_spi_device *) rt_device_find("spi1_dev"); } - + if (RT_NULL == spi_dev) { return; } - - err_code = rt_device_open(&(spi_dev->parent), RT_DEVICE_FLAG_RDWR); + + err_code = rt_device_open(&(spi_dev->parent), RT_DEVICE_FLAG_RDWR); if (RT_EOK != err_code) { return; } - + cfg.data_width = 8; cfg.max_hz = 4000000; - //frame_mode, //b0:SPO b1:SPH b2:moto(spi) b3:ti(ssi) b4:microwire - //cfg.mode = RT_SPI_MODE_1 | RT_SPI_MSB; + // frame_mode: b0:SPO, b1:SPH, b2:Motorola (SPI), b3:TI (SSI), b4:Microwire + // cfg.mode = RT_SPI_MODE_1 | RT_SPI_MSB; cfg.mode = RT_SPI_MSB | RT_SPI_MASTER | RT_SPI_MODE_1; cfg.frameMode = RT_SPI_MOTO; - err_code = rt_spi_configure(spi_dev, &cfg); + err_code = rt_spi_configure(spi_dev, &cfg); uassert_int_equal(RT_EOK, err_code); err_code = rt_spi_take_bus(spi_dev); @@ -128,11 +132,11 @@ void spi_trans_test() rx_buff = rt_malloc(rw_len + 2); tx_buff = rt_malloc(rw_len + 2); - uassert_true((RT_NULL != tx_buff) && (RT_NULL != rx_buff)); + uassert_true((RT_NULL != tx_buff) && (RT_NULL != rx_buff)); - if ((RT_NULL != tx_buff) && (RT_NULL != rx_buff)) + if ((RT_NULL != tx_buff) && (RT_NULL != rx_buff)) { - for (int m = 0; m < rw_len; m++) + for (int m = 0; m < rw_len; m++) { tx_buff[m] = m; } @@ -157,20 +161,21 @@ void spi_trans_test() err_code = rt_spi_release_bus(spi_dev); uassert_int_equal(RT_EOK, err_code); - err_code = rt_device_close(&(spi_dev->parent)); + err_code = rt_device_close(&(spi_dev->parent)); uassert_true_ret(RT_EOK == err_code); - -} - +} ``` ```{note} DMA support is configured through the menuconfig tool. To use DMA, developers need to set the corresponding flags when opening the device. ``` -[spi]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/spi/spi + +[spi]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/spi/spi ## RT-Thread Reference Documentation - [SPI Device][spi] + diff --git a/docs/source/en/drivers/spi_flash.md b/docs/source/en/drivers/spi_flash.md index 4abe17e8b..ca49204d1 100644 --- a/docs/source/en/drivers/spi_flash.md +++ b/docs/source/en/drivers/spi_flash.md @@ -1,8 +1,13 @@ # Flash -SPI Flash driver includes two layers: hardware access layer (HAL/QSPI) and RT-Thread adaptation layer.
-HAL provides basic QSPI APIs to access QSPI peripheral registers. For details, please refer to the API documentation of QSPI HAL.
-The adaptation layer provides common SPI-Flash access functionality. Users can use it directly without operating system. It also registers to MTD for RT-Thread, which can be accessed by file system. Flash controller also supports FIFO DMA mode and QSPI mode by default, which can be disabled through configuration header file. Main features include:
+SPI Flash driver includes two layers: hardware access layer (HAL/QSPI) and +RT-Thread adaptation layer.
HAL provides basic QSPI APIs to access QSPI +peripheral registers. For details, please refer to the API documentation of QSPI +HAL.
The adaptation layer provides common SPI-Flash access functionality. +Users can use it directly without operating system. It also registers to MTD for +RT-Thread, which can be accessed by file system. Flash controller also supports +FIFO DMA mode and QSPI mode by default, which can be disabled through +configuration header file. Main features include:
- Multi-instance support up to 4 - FIFO DMA support for read/write - DMA support for flash read @@ -12,21 +17,34 @@ The adaptation layer provides common SPI-Flash access functionality. Users can u ## Driver Configuration -Hardware driver can use multiple instances (hardware limited to maximum 4 instances). It can be selected for each project using menuconfig tool and usually saved in C header files. By default, configuration is saved as _rtconfig.h_. +Hardware driver can use multiple instances (hardware limited to maximum 4 +instances). It can be selected for each project using menuconfig tool and +usually saved in C header files. By default, configuration is saved as +_rtconfig.h_. -The following example shows flags defined in a project header file where the project enables FLASH controller, SPI-FLASH mode is enabled, using QSPI controller 1 in NOR mode and QSPI2 in NAND mode, and FLASH1 with size 2MB, FLASH2 with 128MB. Steps to select configuration: +The following example shows flags defined in a project header file where the +project enables FLASH controller, SPI-FLASH mode is enabled, using QSPI +controller 1 in NOR mode and QSPI2 in NAND mode, and FLASH1 with size 2MB, +FLASH2 with 128MB. Steps to select configuration: - Enter "menuconfig" in the command under project - Select "RTOS --->" -- Select "On-chip Peripheral Driver--->" -- Select "Enable QSPI --->" Use QSPI driver, define macro `BSP_USING_QSPI` -- Select "Enable QSPI Driver" Use spi flash controller, define macro `BSP_USING_SPI_FLASH` -- Select "QSPI Controller 1 Enable --->" Use QSPI1 controller, define macro `BSP_ENABLE_QSPI1` -- Enter "QSPI1 Mode" Select QSPI1 as Nor/Nand flash, define macro `BSP_QSPI1_MODE` -- Enter "QSPI1 Mem Size (MB)" Set flash1 memory size in MB, define macro `BSP_QSPI1_MEM_SIZE` -- Back to QSPI controller enable: -- Select "QSPI Controller 2 Enable --->" Use QSPI2 controller, define macro `BSP_ENABLE_QSPI2` -- Enter "QSPI2 Mode:" Select QSPI2 as Nor/Nand flash, define macro `BSP_QSPI1_MODE` -- Enter "QSPI2 Mem Size (MB)" Set flash2 memory size in MB, define macro `BSP_QSPI2_MEM_SIZE` +- Select "On-chip Peripheral Driver--->" +- Select "Enable QSPI --->" Use QSPI driver, define macro `BSP_USING_QSPI` +- Select "Enable QSPI Driver" Use spi flash controller, define macro + `BSP_USING_SPI_FLASH` +- Select "QSPI Controller 1 Enable --->" Use QSPI1 controller, define macro + `BSP_ENABLE_QSPI1` +- Enter "QSPI1 Mode" Select QSPI1 as Nor/Nand flash, define macro + `BSP_QSPI1_MODE` +- Enter "QSPI1 Mem Size (MB)" Set flash1 memory size in MB, define macro + `BSP_QSPI1_MEM_SIZE` +- Back to QSPI controller enable: +- Select "QSPI Controller 2 Enable --->" Use QSPI2 controller, define macro + `BSP_ENABLE_QSPI2` +- Enter "QSPI2 Mode:" Select QSPI2 as Nor/Nand flash, define macro + `BSP_QSPI1_MODE` +- Enter "QSPI2 Mem Size (MB)" Set flash2 memory size in MB, define macro + `BSP_QSPI2_MEM_SIZE` ```c #define BSP_USING_QSPI @@ -41,20 +59,26 @@ The following example shows flags defined in a project header file where the pro #define BSP_QSPI2_MEM_SIZE 128 ``` -If you want to use flash for file system or use it as rt-device, you should enable MTD, which also uses menuconfig tool and is included in header file. Steps to enable RT-DEVICE flash interface (in menuconfig main menu): +If you want to use flash for file system or use it as rt-device, you should +enable MTD, which also uses menuconfig tool and is included in header file. +Steps to enable RT-DEVICE flash interface (in menuconfig main menu): - Select "RTOS"—> - Select "RT-Thread Components--->" - Select "Device Driver--->" -- Enable "Using MTD Nor Flash device drivers" Register Nor Flash to MTD device, define macro RT_USING_MTD_NOR -- Select "Enable Nor Flash file system" Use file system on Flash, define macro RT_USING_NOR_FS -- Enter "Base sector for file system" Starting address for file system on Flash (by sector) +- Enable "Using MTD Nor Flash device drivers" Register Nor Flash to MTD device, + define macro RT_USING_MTD_NOR +- Select "Enable Nor Flash file system" Use file system on Flash, define macro + RT_USING_NOR_FS +- Enter "Base sector for file system" Starting address for file system on Flash + (by sector) ```c #define RT_USING_MTD_NOR #define RT_USING_NOR_FS #define RT_NOR_FS_BASE_SEC 4096 ``` -After configuration, users need to include header files in all source code that needs to access the driver. +After configuration, users need to include header files in all source code that +needs to access the driver. ## Memory Address and Device Names When using flash as memory, its base address is defined in memory map: @@ -89,59 +113,62 @@ When using flash as memory, its base address is defined in memory map: #else #define FLASH4_SIZE (0) #endif - ``` -FLASH device names registered to RT-DEVICE are fixed. For FLASH1, its device name is "flash1". For FLASH2, its device name is "flash2". + +FLASH device names registered to RT-DEVICE are fixed. For FLASH1, its device +name is "flash1". For FLASH2, its device name is "flash2". ## Non-OS Flash API ```c /** - * @brief Read nor-flash memory - * @param[in] addr: start address for flash memory. - * @param[out] buf: output data buffer, should not be null. - * @param[in] size: read memory size, in bytes. - * @return read size, 0 if fail. + * @brief Read data from NOR Flash memory. + * @param[in] addr: Start address in Flash memory. + * @param[out] buf: Pointer to the output data buffer (must not be NULL). + * @param[in] size: Number of bytes to read. + * @return Number of bytes read; 0 if the operation fails. */ int rt_flash_read(rt_uint32_t addr, rt_uint8_t *buf, size_t size); /** - * @brief Write nor-flash memory - * @param[in] addr: start address for flash memory. - * @param[in] buf: input data buffer, should not be null. - * @param[in] size: write memory size, in bytes. - * @return write size, 0 if fail. + * @brief Write data to NOR Flash memory. + * @param[in] addr: Start address in Flash memory. + * @param[in] buf: Pointer to the input data buffer (must not be NULL). + * @param[in] size: Number of bytes to write. + * @return Number of bytes written; 0 if the operation fails. */ int rt_flash_write(rt_uint32_t addr, const rt_uint8_t *buf, size_t size); /** - * @brief erase flash. - * @param[in] addr: start address for flash memory. - * @param[in] size: erase memory size, in bytes. - * @return RT_EOK if success. + * @brief Erase Flash memory sectors. + * @param[in] addr: Start address in Flash memory. + * @param[in] size: Size of the memory region to erase, in bytes. + * @return RT_EOK on success; error code otherwise. */ rt_err_t rt_flash_erase(rt_uint32_t addr, size_t size); - ``` ## Using SPI or Flash -The adapter layer registers hardware support functions requested by RT-Thread and implements these functions using HAL. For users using RT-Thread, the following code can be used as an example (for block device process, its address and size are sector-based): +The adapter layer registers hardware support functions requested by RT-Thread +and implements these functions using HAL. For users using RT-Thread, the +following code can be used as an example (for block device process, its address +and size are sector-based): ```c -// Find and open flash device +// Locate and open the Flash device rt_device_t fdev = rt_device_find("flash1"); rt_err_t err = rt_device_open(fdev, RT_DEVICE_FLAG_RDWR); -// read flash -char * buf = malloc(4096); +// Read from Flash +char *buf = malloc(4096); int size = rt_device_read(fdev, 0, buf, 1); -// Write flash -// initial buffer, +// Write to Flash +// Initialize buffer before writing size = rt_device_write(fdev, 0, buf, 1); -// Erase flash +// Erase Flash sector unsigned long param[2]; param[0] = 0; param[1] = 1; @@ -149,26 +176,24 @@ rt_device_control(fdev, RT_DEVICE_CTRL_BLK_ERASE, param); ... -// Close device, keep it open for more user. - - +// Close the device, or keep it open for subsequent operations. ``` -Users can also use flash access with driver interface without system (address and size are byte-based, address should be absolute address), as shown below: +Users can also use flash access with driver interface without system (address +and size are byte-based, address should be absolute address), as shown below: ```c -// read flash -char * buf = malloc(4096); +// Read from Flash +char *buf = malloc(4096); unsigned long address = FLASH_BASE_ADDR; int size = rt_flash_read(address, buf, 4096); -// Write flash -// initial buffer and address, +// Write to Flash +// Initialize buffer and address before writing size = rt_flash_write(address, buf, 4096); -// Erase flash +// Erase Flash sector rt_flash_erase(address, 4096); ... - -``` \ No newline at end of file +``` diff --git a/docs/source/en/drivers/spi_flash_52x.md b/docs/source/en/drivers/spi_flash_52x.md index 5c66cdd5b..1682d1bc2 100644 --- a/docs/source/en/drivers/spi_flash_52x.md +++ b/docs/source/en/drivers/spi_flash_52x.md @@ -1,8 +1,13 @@ # Flash -SPI Flash driver includes two layers: hardware access layer (HAL/QSPI) and RT-Thread adaptation layer.
-HAL provides basic QSPI APIs to access QSPI peripheral registers. For details, please refer to the API documentation of QSPI HAL.
-The adaptation layer provides common SPI-Flash access functionality. Users can use it directly without operating system. It also registers to MTD for RT-Thread, which can be accessed by file system. Flash controller also supports FIFO DMA mode and QSPI mode by default, which can be disabled through configuration header file. Main features include:
+SPI Flash driver includes two layers: hardware access layer (HAL/QSPI) and +RT-Thread adaptation layer.
HAL provides basic QSPI APIs to access QSPI +peripheral registers. For details, please refer to the API documentation of QSPI +HAL.
The adaptation layer provides common SPI-Flash access functionality. +Users can use it directly without operating system. It also registers to MTD for +RT-Thread, which can be accessed by file system. Flash controller also supports +FIFO DMA mode and QSPI mode by default, which can be disabled through +configuration header file. Main features include:
- Multi-instance support up to 4 - FIFO DMA support for read/write - DMA support for flash read @@ -12,21 +17,34 @@ The adaptation layer provides common SPI-Flash access functionality. Users can u ## Driver Configuration -Hardware driver can use multiple instances (hardware limited to maximum 4 instances). It can be selected for each project using menuconfig tool and usually saved in C header files. By default, configuration is saved as _rtconfig.h_. +Hardware driver can use multiple instances (hardware limited to maximum 4 +instances). It can be selected for each project using menuconfig tool and +usually saved in C header files. By default, configuration is saved as +_rtconfig.h_. -The following example shows flags defined in a project header file where the project enables FLASH controller, SPI-FLASH mode is enabled, using QSPI controller 1 in NOR mode and QSPI2 in NAND mode, and FLASH1 with size 2MB, FLASH2 with 128MB. Steps to select configuration: +The following example shows flags defined in a project header file where the +project enables FLASH controller, SPI-FLASH mode is enabled, using QSPI +controller 1 in NOR mode and QSPI2 in NAND mode, and FLASH1 with size 2MB, +FLASH2 with 128MB. Steps to select configuration: - Enter "menuconfig" in the command under project - Select "RTOS --->" -- Select "On-chip Peripheral Driver--->" -- Select "Enable QSPI --->" Use QSPI driver, define macro `BSP_USING_QSPI` -- Select "Enable QSPI Driver" Use spi flash controller, define macro `BSP_USING_SPI_FLASH` -- Select "QSPI Controller 1 Enable --->" Use QSPI1 controller, define macro `BSP_ENABLE_QSPI1` -- Enter "QSPI1 Mode" Select QSPI1 as Nor/Nand flash, define macro `BSP_QSPI1_MODE` -- Enter "QSPI1 Mem Size (MB)" Set flash1 memory size in MB, define macro `BSP_QSPI1_MEM_SIZE` -- Back to QSPI controller enable: -- Select "QSPI Controller 2 Enable --->" Use QSPI2 controller, define macro `BSP_ENABLE_QSPI2` -- Enter "QSPI2 Mode:" Select QSPI2 as Nor/Nand flash, define macro `BSP_QSPI1_MODE` -- Enter "QSPI2 Mem Size (MB)" Set flash2 memory size in MB, define macro `BSP_QSPI2_MEM_SIZE` +- Select "On-chip Peripheral Driver--->" +- Select "Enable QSPI --->" Use QSPI driver, define macro `BSP_USING_QSPI` +- Select "Enable QSPI Driver" Use spi flash controller, define macro + `BSP_USING_SPI_FLASH` +- Select "QSPI Controller 1 Enable --->" Use QSPI1 controller, define macro + `BSP_ENABLE_QSPI1` +- Enter "QSPI1 Mode" Select QSPI1 as Nor/Nand flash, define macro + `BSP_QSPI1_MODE` +- Enter "QSPI1 Mem Size (MB)" Set flash1 memory size in MB, define macro + `BSP_QSPI1_MEM_SIZE` +- Back to QSPI controller enable: +- Select "QSPI Controller 2 Enable --->" Use QSPI2 controller, define macro + `BSP_ENABLE_QSPI2` +- Enter "QSPI2 Mode:" Select QSPI2 as Nor/Nand flash, define macro + `BSP_QSPI1_MODE` +- Enter "QSPI2 Mem Size (MB)" Set flash2 memory size in MB, define macro + `BSP_QSPI2_MEM_SIZE` ```c #define BSP_USING_QSPI @@ -41,35 +59,40 @@ The following example shows flags defined in a project header file where the pro #define BSP_QSPI2_MEM_SIZE 128 ``` -If you want to use flash for file system or use it as rt-device, you should enable MTD, which also uses menuconfig tool and is included in header file. Steps to enable RT-DEVICE flash interface (in menuconfig main menu): +If you want to use flash for file system or use it as rt-device, you should +enable MTD, which also uses menuconfig tool and is included in header file. +Steps to enable RT-DEVICE flash interface (in menuconfig main menu): - Select "RTOS"—> - Select "RT-Thread Components--->" - Select "Device Driver--->" -- Enable "Using MTD Nor Flash device drivers" Register Nor Flash to MTD device, define macro RT_USING_MTD_NOR -- Select "Enable Nor Flash file system" Use file system on Flash, define macro RT_USING_NOR_FS -- Enter "Base sector for file system" Starting address for file system on Flash (by sector) +- Enable "Using MTD Nor Flash device drivers" Register Nor Flash to MTD device, + define macro RT_USING_MTD_NOR +- Select "Enable Nor Flash file system" Use file system on Flash, define macro + RT_USING_NOR_FS +- Enter "Base sector for file system" Starting address for file system on Flash + (by sector) ```c #define RT_USING_MTD_NOR #define RT_USING_NOR_FS #define RT_NOR_FS_BASE_SEC 4096 ``` -After configuration, users need to include header files in all source code that needs to access the driver. +After configuration, users need to include header files in all source code that +needs to access the driver. ### Dual-Flash Configuration - -In the SF32LB52 series, the `MPI2` controller supports connecting two external NOR Flash devices, allowing for expanded Flash capacity. This feature can be enabled in **menuconfig** by selecting `BSP_QSPI2_DUAL_MODE` -(Path: `On-chip Peripheral RTOS Drivers` → `Enable MPI` → `MPI Controller 2 Enable` → `MPI2 Connected With Two NOR Flash Memory`). - -The chip-select (CS) pins for the two Flash devices are defined by `FLASH_1ST_CS_PIN` and `FLASH_2ND_CS_PIN`. These options are configurable through **menuconfig** and are located in the same menu as the `BSP_QSPI2_DUAL_MODE` option. The pin number corresponds to the pin device index. For example: - -* Setting `FLASH_1ST_CS_PIN` to `12` assigns `PA12` as the CS pin for the first Flash device. -* Setting `FLASH_2ND_CS_PIN` to `26` assigns `PA26` as the CS pin for the second Flash device. +In the SF32LB52 series, the `MPI2` controller supports connecting two external +NOR Flash devices, allowing for expanded Flash capacity. This feature can be +enabled in **menuconfig** by selecting `BSP_QSPI2_DUAL_MODE` (Path: `On-chip +Peripheral RTOS Drivers` → `Enable MPI` → `MPI Controller 2 Enable` → `MPI2 +Connected With Two NOR Flash Memory`). ```{note} The `MPI2 Mem Size` parameter must be configured as the total capacity of both Flash devices combined. ``` + + ## Memory Address and Device Names When using flash as memory, its base address is defined in memory map: ```c @@ -85,59 +108,62 @@ When using flash as memory, its base address is defined in memory map: #else #define FLASH2_SIZE (0) #endif - ``` -FLASH device names registered to RT-DEVICE are fixed. For FLASH1, its device name is "flash1". For FLASH2, its device name is "flash2". + +FLASH device names registered to RT-DEVICE are fixed. For FLASH1, its device +name is "flash1". For FLASH2, its device name is "flash2". ## Non-OS Flash API ```c /** - * @brief Read nor-flash memory - * @param[in] addr: start address for flash memory. - * @param[out] buf: output data buffer, should not be null. - * @param[in] size: read memory size, in bytes. - * @return read size, 0 if fail. + * @brief Read data from NOR Flash memory. + * @param[in] addr: Start address in Flash memory. + * @param[out] buf: Pointer to the output data buffer (must not be NULL). + * @param[in] size: Number of bytes to read. + * @return Number of bytes read; 0 if the operation fails. */ int rt_flash_read(rt_uint32_t addr, rt_uint8_t *buf, size_t size); /** - * @brief Write nor-flash memory - * @param[in] addr: start address for flash memory. - * @param[in] buf: input data buffer, should not be null. - * @param[in] size: write memory size, in bytes. - * @return write size, 0 if fail. + * @brief Write data to NOR Flash memory. + * @param[in] addr: Start address in Flash memory. + * @param[in] buf: Pointer to the input data buffer (must not be NULL). + * @param[in] size: Number of bytes to write. + * @return Number of bytes written; 0 if the operation fails. */ int rt_flash_write(rt_uint32_t addr, const rt_uint8_t *buf, size_t size); /** - * @brief erase flash. - * @param[in] addr: start address for flash memory. - * @param[in] size: erase memory size, in bytes. - * @return RT_EOK if success. + * @brief Erase Flash memory sectors. + * @param[in] addr: Start address in Flash memory. + * @param[in] size: Size of the memory region to erase, in bytes. + * @return RT_EOK on success; error code otherwise. */ rt_err_t rt_flash_erase(rt_uint32_t addr, size_t size); - ``` ## Using SPI or Flash -The adapter layer registers hardware support functions requested by RT-Thread and implements these functions using HAL. For users using RT-Thread, the following code can be used as an example (for block device process, its address and size are sector-based): +The adapter layer registers hardware support functions requested by RT-Thread +and implements these functions using HAL. For users using RT-Thread, the +following code can be used as an example (for block device process, its address +and size are sector-based): ```c -// Find and open flash device +// Locate and open the Flash device rt_device_t fdev = rt_device_find("flash1"); rt_err_t err = rt_device_open(fdev, RT_DEVICE_FLAG_RDWR); -// read flash -char * buf = malloc(4096); +// Read from Flash +char *buf = malloc(4096); int size = rt_device_read(fdev, 0, buf, 1); -// Write flash -// initial buffer, +// Write to Flash +// Initialize buffer before writing size = rt_device_write(fdev, 0, buf, 1); -// Erase flash +// Erase Flash sector unsigned long param[2]; param[0] = 0; param[1] = 1; @@ -145,26 +171,24 @@ rt_device_control(fdev, RT_DEVICE_CTRL_BLK_ERASE, param); ... -// Close device, keep it open for more user. - - +// Close the device, or keep it open for subsequent operations. ``` -Users can also use flash access with driver interface without system (address and size are byte-based, address should be absolute address), as shown below: +Users can also use flash access with driver interface without system (address +and size are byte-based, address should be absolute address), as shown below: ```c -// read flash -char * buf = malloc(4096); +// Read from Flash +char *buf = malloc(4096); unsigned long address = FLASH_BASE_ADDR; int size = rt_flash_read(address, buf, 4096); -// Write flash -// initial buffer and address, +// Write to Flash +// Initialize buffer and address before writing size = rt_flash_write(address, buf, 4096); -// Erase flash +// Erase Flash sector rt_flash_erase(address, 4096); ... - -``` \ No newline at end of file +``` diff --git a/docs/source/en/drivers/timer.md b/docs/source/en/drivers/timer.md index 93a3c9b97..375f000de 100644 --- a/docs/source/en/drivers/timer.md +++ b/docs/source/en/drivers/timer.md @@ -1,15 +1,25 @@ # HWTIMER Device There are 3 different types of hardware timers: -- General Purpose Timer (GPTim): BTim implements a 16-bit counter for system PCLK, providing 1-65536 prescaler. It has 4 input/output channels that can be independently configured as input/output mode. GPTim can be used for PWM to generate waveforms or measure input signals. -- Basic Timer (BTim): BTim implements a 32-bit counter for system PCLK, providing 1-65536 prescaler. It can be used as a timer or drive DAC through its trigger output. -- Low Power Timer (LPTim): LPTim implements a 16-bit counter for system PCLK or low power clock, providing 1-128 prescaler. Used for system sleep/wake-up, can operate independently of system clock and provide wake-up signal after system enters sleep state. +- General Purpose Timer (GPTim): BTim implements a 16-bit counter for system + PCLK, providing 1-65536 prescaler. It has 4 input/output channels that can be + independently configured as input/output mode. GPTim can be used for PWM to + generate waveforms or measure input signals. +- Basic Timer (BTim): BTim implements a 32-bit counter for system PCLK, + providing 1-65536 prescaler. It can be used as a timer or drive DAC through + its trigger output. +- Low Power Timer (LPTim): LPTim implements a 16-bit counter for system PCLK or + low power clock, providing 1-128 prescaler. Used for system sleep/wake-up, can + operate independently of system clock and provide wake-up signal after system + enters sleep state. ## Driver Configuration -Select the HWTIMER devices to use in the {menuselection}`On-Chip Peripheral RTOS Drivers --> Enable Timer` menu. +Select the HWTIMER devices to use in the {menuselection}`On-Chip Peripheral RTOS +Drivers --> Enable Timer` menu. -The following macro switches indicate that LPTIM1, BTIM1, GPTIM2, and GPTIM3 devices are registered: +The following macro switches indicate that LPTIM1, BTIM1, GPTIM2, and GPTIM3 +devices are registered: ```c #define BSP_USING_TIM #define BSP_USING_LPTIM1 @@ -19,43 +29,47 @@ The following macro switches indicate that LPTIM1, BTIM1, GPTIM2, and GPTIM3 dev ``` ## Device Names -- `gptim`: `x` is the device number, such as `gptim1` and `gptim2`, corresponding to peripherals `GPTIM1` and `GPTIM2` respectively -- `btim`: `x` is the device number, such as `btim1`, `btim2`, corresponding to peripherals `BTIM1` and `BTIM2` respectively -- `lptim`: `x` is the device number, such as `lptim1`, `lptim2`, corresponding to peripherals `LPTIM1` and `LPTIM2` respectively -- `atim`: `x` is the device number, such as `atim1`, corresponding to peripheral `ATIM1` +- `gptim`: `x` is the device number, such as `gptim1` and `gptim2`, + corresponding to peripherals `GPTIM1` and `GPTIM2` respectively +- `btim`: `x` is the device number, such as `btim1`, `btim2`, corresponding + to peripherals `BTIM1` and `BTIM2` respectively +- `lptim`: `x` is the device number, such as `lptim1`, `lptim2`, + corresponding to peripherals `LPTIM1` and `LPTIM2` respectively +- `atim`: `x` is the device number, such as `atim1`, corresponding to + peripheral `ATIM1` ## Example Code ```c -// Find and open device +// Locate and open the device rt_device_t timer_dev = rt_device_find("gptim2"); rt_err_t err = rt_device_open(timer_dev, RT_DEVICE_FLAG_RDWR); -// Configure Timer -int freq=1000000; -rt_device_control(timer_dev, HWTIMER_CTRL_FREQ_SET, (void *)&freq); -int mode=HWTIMER_MODE_ONESHOT; -rt_device_control(timer_dev, HWTIMER_CTRL_MODE_SET, (void *)&mode); +// Configure the timer +int freq = 1000000; +rt_device_control(timer_dev, HWTIMER_CTRL_FREQ_SET, (void *)&freq); +int mode = HWTIMER_MODE_ONESHOT; +rt_device_control(timer_dev, HWTIMER_CTRL_MODE_SET, (void *)&mode); -// Prepare for timeout +// Register the timeout callback rt_device_set_rx_indicate(timer_dev, timeout_ind); -// Start timer -rt_hwtimerval_t t={3,500}; // 3 seconds and 500 microseconds -ret = rt_device_write(timer_dev, 0, &t, sizeof(t)); +// Start the timer +rt_hwtimerval_t t = {3, 500}; // 3 seconds and 500 microseconds +ret = rt_device_write(timer_dev, 0, &t, sizeof(t)); ... -// Interrupt callback +// Interrupt callback function static rt_err_t timeout_ind(rt_device_t dev, rt_size_t size) { rt_kprintf("Timeout \n"); } - ``` -[hwtimer]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/hwtimer/hwtimer +[hwtimer]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/hwtimer/hwtimer ## RT-Thread Reference Documentation -- [HWTIMER Device][hwtimer] \ No newline at end of file +- [HWTIMER Device][hwtimer] diff --git a/docs/source/en/drivers/touch.md b/docs/source/en/drivers/touch.md index 34168638b..58048e04c 100644 --- a/docs/source/en/drivers/touch.md +++ b/docs/source/en/drivers/touch.md @@ -1,50 +1,57 @@ # Touch Screen ## Introduction -For touch controller drivers, we have implemented a unified interface called "touch" rt_device that provides a simple framework for registering different touch controller drivers and automatically selecting the appropriate driver. -This chapter mainly introduces the internal framework functionality of Touch device and how to register a new touch controller to this framework. +For touch controller drivers, we have implemented a unified interface called +"touch" rt_device that provides a simple framework for registering different +touch controller drivers and automatically selecting the appropriate driver. +This chapter mainly introduces the internal framework functionality of Touch +device and how to register a new touch controller to this framework. Touch device implementation consists of 2 parts: - rt_device device (drv_touch.c) - - Registers a device named "touch" that provides interrupt callback registration and touch data reading interfaces - - Creates a task for slow communication with touch devices (such as initialization, reading touch point data, etc.) - - Performs caching, filtering (filtering duplicate points), and cache overflow packet dropping for touch data points read + - Registers a device named "touch" that provides interrupt callback + registration and touch data reading interfaces + - Creates a task for slow communication with touch devices (such as + initialization, reading touch point data, etc.) + - Performs caching, filtering (filtering duplicate points), and cache + overflow packet dropping for touch data points read - Specific touch device driver implementation - - Registers a new driver with touch_device and provides the following implementations: - - probe - Identify supported devices - - init - Initialization after device identification - - deinit - Deinitialization after device identification - - read_point - Read a valid data point (**Note: Return RT_EOK if there are still unread data points, otherwise return other values**) - - A semaphore - Used to block rt_device layer threads - - Also needs to implement internally: - - Touch interrupt detection - - Communication interface initialization - -![Figure 1: Touch driver software architecture](../../assets/touch_device_arch.png) -
-
-
-
-
-
+ - Registers a new driver with touch_device and provides the following + implementations: + - probe - Identify supported devices + - init - Initialization after device identification + - deinit - Deinitialization after device identification + - read_point - Read a valid data point (**Note: Return RT_EOK if there + are still unread data points, otherwise return other values**) + - A semaphore - Used to block rt_device layer threads + - Also needs to implement internally: + - Touch interrupt detection + - Communication interface initialization + +![Figure 1: Touch driver software +architecture](../../assets/touch_device_arch.png)





## Process for Adding New Touch Controller Code ## 1. Select the corresponding board project under example\\rt_driver -- This project contains a thread _touch_read_task_ that reads touch data and prints it +- This project contains a thread _touch_read_task_ that reads touch data and + prints it ## 2. Add new driver to compilation project - Add new touch controller code to directory _customer\\peripherals_ - - You can copy code from other existing drivers, then change the name, Slave_Address, read process, etc. to your own + - You can copy code from other existing drivers, then change the name, + Slave_Address, read process, etc. to your own ```{note} Note to modify the depend macro in the Kconfig file under the copied code directory ``` -- In _customer\\peripherals\\Kconfig_, add a hidden option for the newly added driver, for example: +- In _customer\\peripherals\\Kconfig_, add a hidden option for the newly added + driver, for example: ```c config TSC_USING_TMA525B bool default n ``` -- Add the previously added hidden touch controller switch to the board-level configuration screen module switch: +- Add the previously added hidden touch controller switch to the board-level + configuration screen module switch: ```c config LCD_USING_ED_LB55DSI13902_DSI_LB555 bool "1.39 round 454RGB*454 DSI LCD(ED-LB55DSI13902)" @@ -57,29 +64,32 @@ Touch device implementation consists of 2 parts: def_bool n endif ``` -- If using scons compilation, need to enter the project menuconfig selection menu, then select the newly added screen module, finally generating _.config_ and _rtconfig.h_ -- If using Keil compilation, you can also directly add source code (but still recommend the same method as scons compilation, so it will be automatically included when regenerating Keil project next time) +- If using scons compilation, need to enter the project menuconfig selection + menu, then select the newly added screen module, finally generating _.config_ + and _rtconfig.h_ +- If using Keil compilation, you can also directly add source code (but still + recommend the same method as scons compilation, so it will be automatically + included when regenerating Keil project next time) ## 3. Check pinmux for pins used by new touch controller and reset pin -- In the SDK's `drv_io.c`, functions _BSP_TP_PowerUp&BSP_TP_PowerDown_ perform power up/down and reset operations for touch controllers -
-
- +- In the SDK's `drv_io.c`, functions _BSP_TP_PowerUp&BSP_TP_PowerDown_ perform + power up/down and reset operations for touch controllers

## Touch Controller Debugging Suggestions - First check if power supply and reset pin status are normal -- Then check if communication interface waveforms are normal, such as whether I2C interface has ack -
- +- Then check if communication interface waveforms are normal, such as whether + I2C interface has ack
## TMA525B Touch Device Driver Implementation Example Code -TMA525B uses the falling edge of TOUCH_IRQ_PIN as trigger condition, I2C as communication interface at 400KHz speed, I2C read/write timeout of 5ms -This implementation releases semaphore in interrupt to make touch_device layer call its own read_point to get touch data -Also disables interrupt enable in interrupt, then re-enables interrupt enable after entering read_point, preventing too many interrupts from repeatedly releasing too many semaphores +TMA525B uses the falling edge of TOUCH_IRQ_PIN as trigger condition, I2C as +communication interface at 400KHz speed, I2C read/write timeout of 5ms This +implementation releases semaphore in interrupt to make touch_device layer call +its own read_point to get touch data Also disables interrupt enable in +interrupt, then re-enables interrupt enable after entering read_point, +preventing too many interrupts from repeatedly releasing too many semaphores ```c - static struct rt_i2c_bus_device *ft_bus = NULL; static struct touch_drivers tma525b_driver; @@ -95,7 +105,7 @@ static rt_err_t i2c_write(rt_uint8_t *buf, rt_uint16_t len) msgs.buf = buf; /* Send data pointer */ msgs.len = len; - if (rt_i2c_transfer(ft_bus, &msgs, 1) == 1) + if (rt_i2c_transfer(ft_bus, &msgs, 1) == 1) { res = RT_EOK; } @@ -154,23 +164,23 @@ static rt_err_t read_point(touch_msg_t p_msg) { if(touch_report[1] == 1) { - p_msg->event = TOUCH_EVENT_DOWN; + p_msg->event = TOUCH_EVENT_DOWN; } else { - p_msg->event = TOUCH_EVENT_UP; + p_msg->event = TOUCH_EVENT_UP; } - p_msg->x = touch_report[2]; - p_msg->y = touch_report[3]; + p_msg->x = touch_report[2]; + p_msg->y = touch_report[3]; - if(touch_report[4] > 1) + if(touch_report[4] > 1) return RT_EOK; //More pending touch data else return RT_EEMPTY; //No more touch data to be read } - p_msg->event = TOUCH_EVENT_NONE; //Read point fail + p_msg->event = TOUCH_EVENT_NONE; //Read point fail return RT_ERROR; } @@ -195,7 +205,7 @@ static rt_bool_t probe(void) rt_err_t err; ft_bus = (struct rt_i2c_bus_device *)rt_device_find(TOUCH_DEVICE_NAME); - if (RT_Device_Class_I2CBUS != ft_bus->parent.type) + if (RT_Device_Class_I2CBUS != ft_bus->parent.type) { ft_bus = NULL; } @@ -205,7 +215,7 @@ static rt_bool_t probe(void) } else { - LOG_I("bus not find\n"); + LOG_I("bus not found\n"); return RT_FALSE; } @@ -218,7 +228,7 @@ static rt_bool_t probe(void) .max_hz = 400000, }; - rt_i2c_configure(ft_bus, &configuration); + rt_i2c_configure(ft_bus, &configuration); } LOG_I("tma525b probe OK"); @@ -238,11 +248,11 @@ static struct touch_ops ops = static int rt_tma525b_init(void) { tma525b_driver.probe = probe; - tma525b_driver.ops = &ops; + tma525b_driver.ops = &ops; tma525b_driver.user_data = RT_NULL; tma525b_driver.isr_sem = rt_sem_create("tma525b", 0, RT_IPC_FLAG_FIFO); - rt_touch_drivers_register(&tma525b_driver); + rt_touch_drivers_register(&tma525b_driver); return 0; } @@ -252,21 +262,22 @@ INIT_COMPONENT_EXPORT(rt_tma525b_init);
## Touch Device Upper Layer Usage Example Code -Example registers interrupt callback to release semaphore, then semaphore drives reading touch data, then prints touch points +Example registers interrupt callback to release semaphore, then semaphore drives +reading touch data, then prints touch points ```c static struct rt_semaphore tp_sema; static rt_err_t tp_rx_indicate(rt_device_t dev, rt_size_t size) { - rt_sem_release(&tp_sema); + rt_sem_release(&tp_sema); return RT_EOK; } static void touch_read_task(void *parameter) { - rt_sem_init(&tp_sema, "tpsem", 0, RT_IPC_FLAG_FIFO); + rt_sem_init(&tp_sema, "tpsem", 0, RT_IPC_FLAG_FIFO); /*Open touch device*/ rt_device_t touch_device = NULL; @@ -275,17 +286,17 @@ static void touch_read_task(void *parameter) { if (RT_EOK == rt_device_open(touch_device, RT_DEVICE_FLAG_RDONLY)) { - touch_device->rx_indicate = tp_rx_indicate; + touch_device->rx_indicate = tp_rx_indicate; while (1) { rt_err_t err; struct touch_message touch_data; - err = rt_sem_take(&tp_sema, rt_tick_from_millisecond(500)); + err = rt_sem_take(&tp_sema, rt_tick_from_millisecond(500)); if (RT_EOK == err) { - rt_device_read(touch_device, 0, &touch_data, 1); + rt_device_read(touch_device, 0, &touch_data, 1); rt_kprintf("read data %d, [%d,%d]\r\n", touch_data.event, touch_data.x, touch_data.y); } } @@ -302,5 +313,5 @@ static void touch_read_task(void *parameter) } } +``` -``` \ No newline at end of file diff --git a/docs/source/en/drivers/uart.md b/docs/source/en/drivers/uart.md index e075afa42..225f4df39 100644 --- a/docs/source/en/drivers/uart.md +++ b/docs/source/en/drivers/uart.md @@ -1,8 +1,10 @@ # UART Device ## Driver Configuration -Select the UART devices to use in the {menuselection}`On-Chip Peripheral RTOS Drivers --> Enable UART` menu, and configure whether to support DMA. +Select the UART devices to use in the {menuselection}`On-Chip Peripheral RTOS +Drivers --> Enable UART` menu, and configure whether to support DMA. -The following macro switches indicate that UART1 and UART2 devices are enabled, and both support RX DMA: +The following macro switches indicate that UART1 and UART2 devices are enabled, +and both support RX DMA: ```c #define BSP_USING_UART @@ -17,35 +19,36 @@ Selecting DMA in menuconfig only means configuring the driver to support DMA, bu ``` ## Device Names -- `uart`, -where x is the device number, such as `uart1`, `uart2`, corresponding to the peripheral numbers being operated +- `uart`, where x is the device number, such as `uart1`, `uart2`, + corresponding to the peripheral numbers being operated ## Example Code + ```c -// Find and open device +// Locate and open the device rt_device_t uart_dev = rt_device_find("uart1"); -// RX use DMA +// Open the device with DMA-enabled reception rt_err_t err = rt_device_open(uart_dev, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_DMA_RX); -// Configure UART +// Configure UART parameters struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; -config.baudrate=115200; -rt_device_control(uart_dev, RT_DEVICE_CTRL_CONFIG, &config); +config.baudrate = 115200; +rt_device_control(uart_dev, RT_DEVICE_CTRL_CONFIG, &config); -// TX -uint8_t data=[1,2,3,4,5,6,7,8]; +// Transmission (TX) +uint8_t data[] = {1, 2, 3, 4, 5, 6, 7, 8}; rt_device_write(uart_dev, - -1, // Start offset, for UART, this is ignored. - data, - sizeof(data)); - -// RX + -1, // Starting offset; ignored for UART devices. + data, + sizeof(data)); + +// Reception (RX) #define BLOCK_SIZE 256 -uint8_t g_rx_data=[BLOCK_SIZE]; +uint8_t g_rx_data[BLOCK_SIZE]; static rt_sem_t rx_sem; -// Interrupt callback, try not issue read in interrupt context. +// Interrupt callback; avoid executing read operations within the ISR context. static rt_err_t uart_input(rt_device_t dev, rt_size_t size) { rt_sem_release(rx_sem); @@ -54,22 +57,21 @@ static rt_err_t uart_input(rt_device_t dev, rt_size_t size) ... -// Create semphore to communicate with IRQ context - rt_sem_create("uart_sem", 1, RT_IPC_FLAG_FIFO); -// Set RX indication functions +// Create a semaphore for synchronization with the ISR context +rx_sem = rt_sem_create("uart_sem", 0, RT_IPC_FLAG_FIFO); +// Register the reception indication callback rt_device_set_rx_indicate(uart_dev, uart_input); -// Wait fo RX interrupt. -rt_sem_take(rx_sem, 1000); -// Read up to BLOCK_SIZE, will return len actually read. -int len=rt_device_read(uart_dev, - -1, - g_rx_data, - BLOCK_SIZE); - +// Wait for the reception interrupt +rt_sem_take(rx_sem, 1000); +// Read up to BLOCK_SIZE; returns the actual number of bytes read. +int len = rt_device_read(uart_dev, + -1, + g_rx_data, + BLOCK_SIZE); ``` -[uart]: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/uart/uart_v1/uart - +[uart]: +https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/uart/uart_v1/uart ## RT-Thread Reference Documentation -- [UART Device][uart] \ No newline at end of file +- [UART Device][uart] diff --git a/docs/source/en/drivers/usbd.md b/docs/source/en/drivers/usbd.md index 5cd65ec7a..90fb405a8 100644 --- a/docs/source/en/drivers/usbd.md +++ b/docs/source/en/drivers/usbd.md @@ -1,9 +1,13 @@ # USB Device -USB controller driver includes device driver and host driver, we only enable the device driver. It has two layers: hardware access layer (HAL) and RT-Thread adaptation layer.
-HAL provides basic APIs for accessing USB controller peripheral registers. For details, please refer to the API documentation of USB HAL.
-The adaptation layer provides support for RT-Thread driver framework. Users can use RT-Thread POSIX driver interface for USB device programming. Please refer to the API documentation of RT-Thread driver.
-Main features include:
+USB controller driver includes device driver and host driver, we only enable the +device driver. It has two layers: hardware access layer (HAL) and RT-Thread +adaptation layer.
HAL provides basic APIs for accessing USB controller +peripheral registers. For details, please refer to the API documentation of USB +HAL.
The adaptation layer provides support for RT-Thread driver framework. +Users can use RT-Thread POSIX driver interface for USB device programming. +Please refer to the API documentation of RT-Thread driver.
Main features +include:
- Mstorage storage support - VCOM support - Composite device support @@ -15,12 +19,15 @@ Only SF32LB58X series supports USB 2.0 high speed mode, SF32LB55X/SF32LB56X only ## Driver Configuration -Hardware driver can be used as mstorage, ecm, hid, vcom. Functions and their peripherals can be selected for each project using menuconfig tool, usually saved in C header files. By default, configuration is saved as _rtconfig.h_. +Hardware driver can be used as mstorage, ecm, hid, vcom. Functions and their +peripherals can be selected for each project using menuconfig tool, usually +saved in C header files. By default, configuration is saved as _rtconfig.h_. -The following example shows flags defined in a project header file that uses MSTORAGE and VCOM. Steps to select configuration for BSP: +The following example shows flags defined in a project header file that uses +MSTORAGE and VCOM. Steps to select configuration for BSP: - Enter "menuconfig" in the command under the project - Select "RTOS --->" -- Select "On-chip Peripheral Driver--->" +- Select "On-chip Peripheral Driver--->" - Select "Enable USB Device" to enable USB driver, define macro BSP_USING_USBD ```c #define BSP_USING_USBD @@ -30,12 +37,16 @@ Steps to select configuration for operating system (in menuconfig main menu): - Select "RTOS"—> - Select "RT-Thread Components--->" - Select "Device Driver--->" -- Select "Using USB --->" -- Select "Enable USB device" Enable USB device mode, define RT_USING_USB_DEVICE +- Select "Using USB --->" +- Select "Enable USB device" Enable USB device mode, define RT_USING_USB_DEVICE - Enable "Enable composite device" -- Enable "Enable to use device as CDC device" Enable using device as CDC device USB can be used as CDC VCOM device, define RT_USB_DEVICE_CDC -- Enable "Enable to use device as Mass Storage device" Enable using device as mass storage device USB can be used as mstorage device, define RT_USB_DEVICE_MSTORAGE -- "msc class disk name" Enter storage device, usually we use flash, so enter mtd device name like "flash1" +- Enable "Enable to use device as CDC device" Enable using device as CDC device + USB can be used as CDC VCOM device, define RT_USB_DEVICE_CDC +- Enable "Enable to use device as Mass Storage device" Enable using device as + mass storage device USB can be used as mstorage device, define + RT_USB_DEVICE_MSTORAGE +- "msc class disk name" Enter storage device, usually we use flash, so enter mtd + device name like "flash1" ```c #define RT_USING_USB_DEVICE @@ -53,7 +64,11 @@ Steps to select configuration for operating system (in menuconfig main menu): #define RT_USB_MSTORAGE_DISK_NAME "flash1" ``` -After configuration, users need to include header files in all source code that needs to access the driver. +After configuration, users need to include header files in all source code that +needs to access the driver. ## Using USB Device -With the above configuration, when plugging in the USB interface, the PC can recognize a USB hard disk and a USB serial port, which can be used in the same way as other USB hard disks/serial ports. \ No newline at end of file +With the above configuration, when plugging in the USB interface, the PC can +recognize a USB hard disk and a USB serial port, which can be used in the same +way as other USB hard disks/serial ports. + diff --git a/docs/source/en/hal/adc.md b/docs/source/en/hal/adc.md index 382029233..0b6e11794 100644 --- a/docs/source/en/hal/adc.md +++ b/docs/source/en/hal/adc.md @@ -1,14 +1,15 @@ # ADC -ADC HAL provides basic APIs for accessing ADC peripheral registers. -Main features include: +ADC HAL provides basic APIs for accessing ADC peripheral registers. Main +features include: - Support up to 8 ADC channels. - 10-bit data (A0), 12-bit data (PRO). - DMA support. ## Using ADC HAL Driver -ADC supports 8 channels, with each bit change corresponding to approximately 1 millivolt, requiring individual calibration for each chip. -Test range: 0~ 1.1V on A0, 0 ~ 3.3V on PRO. +ADC supports 8 channels, with each bit change corresponding to approximately 1 +millivolt, requiring individual calibration for each chip. Test range: 0~ 1.1V +on A0, 0 ~ 3.3V on PRO. Example of using ADC HAL in polling mode: @@ -17,47 +18,47 @@ ADC_HandleTypeDef hadc; uint32_t channel, value, timeout; ADC_ChannelConfTypeDef ADC_ChanConf; -/* initial handle */ +/* * Initialize handle * */ hadc.Instance = hwp_gpadc1; #ifndef SF32LB55X hadc.Init.data_samp_delay = 2; hadc.Init.conv_width = 24; hadc.Init.sample_width = 22; #else -hadc.Init.clk_div = 31; // set frequency +hadc.Init.clk_div = 31; // Set frequency #endif -hadc.Init.adc_se = 1; // single channel +hadc.Init.adc_se = 1; // Single-ended mode hadc.Init.adc_force_on = 0; -hadc.Init.dma_en = 0; // no dma -hadc.Init.en_slot = 0; // default slot, update by enable and configure -hadc.Init.op_mode = 0; // single mode, not continous -/* initial ADC controller */ -ret = HAL_ADC_Init(&hadc); +hadc.Init.dma_en = 0; // DMA disabled +hadc.Init.en_slot = 0; // Default slot; updated via enable and configuration +hadc.Init.op_mode = 0; // Single conversion mode, not continuous +/* * Initialize ADC controller * */ +ret = HAL_ADC_Init(&hadc); -/* enable ADC */ +/* * Enable ADC * */ channel = 1; -HAL_ADC_EnableSlot(&hadc, channel, 1); +HAL_ADC_EnableSlot(&hadc, channel, 1); -/* configure ADC */ -rt_memset(&ADC_ChanConf, 0, sizeof(ADC_ChanConf)); +/* * Configure ADC * */ +rt_memset(&ADC_ChanConf, 0, sizeof(ADC_ChanConf)); ADC_ChanConf.Channel = channel; ADC_ChanConf.pchnl_sel = channel; ADC_ChanConf.slot_en = 1; -HAL_ADC_ConfigChannel(&hadc, &ADC_ChanConf); +HAL_ADC_ConfigChannel(&hadc, &ADC_ChanConf); -/* start ADC */ -HAL_ADC_Start(&hadc); +/* * Start ADC * */ +HAL_ADC_Start(&hadc); -/* Wait for the ADC to convert */ +/* * Wait for ADC conversion * */ timeout = 100; // 100 ms -HAL_ADC_PollForConversion(&hadc, tmieout); +HAL_ADC_PollForConversion(&hadc, tmieout); -/* Get ADC value */ -value = (rt_uint32_t)HAL_ADC_GetValue(&hadc, channel); +/* * Read ADC value * */ +value = (rt_uint32_t)HAL_ADC_GetValue(&hadc, channel); ... ``` ## API Reference -[](#hal-adc) +[] diff --git a/docs/source/en/hal/aes.md b/docs/source/en/hal/aes.md index 866ddcbde..1d640b02d 100644 --- a/docs/source/en/hal/aes.md +++ b/docs/source/en/hal/aes.md @@ -1,7 +1,8 @@ # AES -SIFLI has hardware implementation of AES encryption/decryption. It provides high performance on AES functions and is used in bootloader and DFU to decrypt received images. -It supports:
+SIFLI has hardware implementation of AES encryption/decryption. It provides high +performance on AES functions and is used in bootloader and DFU to decrypt +received images. It supports:
- Encryption and decryption.
- AES and SM4 algorithms.
- 128, 192 or 256 AES key length.
@@ -17,9 +18,8 @@ The input and output memory used by AES cannot be ITCM RAM or Retention RAM, ple Please refer to the following code as an example: ```c - -ALIGN(4) // Make sure g_key and g_nounce_counter 4bytes aligned -static uint8_t g_key[32] = // Key is defined by user, if use 256 AES length, it need to be 32 bytes +ALIGN(4) // Ensure 4-byte alignment for g_key and g_nounce_counter +static uint8_t g_key[32] = // User-defined key; 32 bytes required for AES-256 { 0x3D, 0xA5, 0xA4, 0x98, 0x6E, 0x90, 0xA7, 0x90, 0x1D, 0x97, 0x69, 0xAA, 0xF0, 0xDF, 0x32, 0xE4, @@ -35,26 +35,27 @@ static uint8_t g_nounce_counter[16]= uint8_t input_data[BUFFER_SIZE]; uint8_t output_data[BUFFER_SIZE]; -// Get input_data , this is not described in this code pieces. +// Input data acquisition is omitted in this code snippet. // Encryption HAL_AES_init(g_key, 32, g_nounce_counter, AES_MODE_CTR); -HAL_AES_run_IT(true, input_data, output_data, BUFFER_SIZE); // Run Async, interrupt will generate interrupt when done +HAL_AES_run_IT(true, input_data, output_data, BUFFER_SIZE); // Asynchronous execution; triggers an interrupt upon completion rt_thread_delay(1000); // Decryption -HAL_AES_init(g_key, 32, g_nounce_counter, AES_MODE_CTR); // Run Sync -HAL_AES_run(false, input_data, output_data, BUFFER_SIZE); // Function will block until Decryption finish. +HAL_AES_init(g_key, 32, g_nounce_counter, AES_MODE_CTR); // Synchronous execution +HAL_AES_run(false, input_data, output_data, BUFFER_SIZE); // Blocking call; returns after decryption completes .... void AES_IRQHandler(void) { - printf("AES function finished"); + printf("AES operation complete"); HAL_AES_IRQHandler(); } - ``` ## API Reference -[](#hal-aes) +[] + + diff --git a/docs/source/en/hal/aon.md b/docs/source/en/hal/aon.md index e5ddf22c7..19ddb73e4 100644 --- a/docs/source/en/hal/aon.md +++ b/docs/source/en/hal/aon.md @@ -1,10 +1,24 @@ # AON -HAL AON provides abstract software interface to operate hardware AON (Always On) module, used to control low power modes of various subsystems in the chip. The chip is divided into HPSYS and LPSYS subsystems (power domains), corresponding to HPAON ({c:macro}`hwp_hpsys_aon`) and LPAON ({c:macro}`hwp_lpsys_aon`) respectively. The control methods for both power domains are similar, and supported features include: -- PIN, RTC, LPTIM, MAILBOX and manual wakeup. LPSYS also supports LPCOMP and BLE wakeup. PIN wakeup can be level-triggered or edge-triggered. Manual wakeup means another core operates specific registers to wake up the designated core. - MAILBOX wakeup means waking up the corresponding core by triggering mailbox interrupt, for example, LPSYS can configure #L2H_MAILBOX to trigger MAILBOX interrupt to HPSYS, if HPSYS enables MAILBOX wakeup, it can be automatically awakened by this interrupt. -- HPSYS supports 4 wakeup PINs, LPSYS supports 6 wakeup PINs, all bound to fixed GPIO pins -- Supports LIGHT/DEEP/STANDBY three low power modes. In LIGHT and DEEP modes, digital modules will not power down, all registers and SRAM will be retained. In STANDBY mode, digital modules will power down, all registers will be lost, SRAM can be selectively retained. +HAL AON provides abstract software interface to operate hardware AON (Always On) +module, used to control low power modes of various subsystems in the chip. The +chip is divided into HPSYS and LPSYS subsystems (power domains), corresponding +to HPAON ({c:macro}`hwp_hpsys_aon`) and LPAON ({c:macro}`hwp_lpsys_aon`) +respectively. The control methods for both power domains are similar, and +supported features include: +- PIN, RTC, LPTIM, MAILBOX and manual wakeup. LPSYS also supports LPCOMP and BLE + wakeup. PIN wakeup can be level-triggered or edge-triggered. Manual wakeup + means another core operates specific registers to wake up the designated core. + MAILBOX wakeup means waking up the corresponding core by triggering mailbox + interrupt, for example, LPSYS can configure #L2H_MAILBOX to trigger MAILBOX + interrupt to HPSYS, if HPSYS enables MAILBOX wakeup, it can be automatically + awakened by this interrupt. +- HPSYS supports 4 wakeup PINs, LPSYS supports 6 wakeup PINs, all bound to fixed + GPIO pins +- Supports LIGHT/DEEP/STANDBY three low power modes. In LIGHT and DEEP modes, + digital modules will not power down, all registers and SRAM will be retained. + In STANDBY mode, digital modules will power down, all registers will be lost, + SRAM can be selectively retained. ````{note} Due to delay in PIN edge detection, if woken up by other wakeup sources when there's a wakeup PIN level change, the PIN wakeup flag in WSR register may still be 0 when AON interrupt occurs, and becomes 1 after a while. Since the corresponding GPIO edge detection is not ready yet, the PIN wakeup status in WSR register won't be cleared and will keep not sleeping while missing one GPIO interrupt for edge detection. If not using `SysTick_Handler` implemented in drv_common.c in SDK as SysTick interrupt service routine, it's recommended to add the following code in custom SysTick interrupt service routine. When edge-triggered wakeup PIN flag is found to be 1, manually trigger GPIO interrupt callback function once. @@ -46,24 +60,24 @@ Due to delay in PIN edge detection, if woken up by other wakeup sources when the ### SF32LB55X #### HPSYS -Wakeup PIN | GPIO | ------------------|----------------| - PIN0 | GPIO_A77 | - PIN1 | GPIO_A78 | - PIN2 | GPIO_A79 | - PIN3 | GPIO_A80 | +| Wakeup PIN | GPIO | +| ---------- | -------- | +| PIN0 | GPIO_A77 | +| PIN1 | GPIO_A78 | +| PIN2 | GPIO_A79 | +| PIN3 | GPIO_A80 | #### LPSYS -Wakeup PIN | GPIO | ------------------|----------------| - PIN0 | GPIO_B43 | - PIN1 | GPIO_B44 | - PIN2 | GPIO_B45 | - PIN3 | GPIO_B46 | - PIN4 | GPIO_B47 | - PIN5 | GPIO_B48 | +| Wakeup PIN | GPIO | +| ---------- | -------- | +| PIN0 | GPIO_B43 | +| PIN1 | GPIO_B44 | +| PIN2 | GPIO_B45 | +| PIN3 | GPIO_B46 | +| PIN4 | GPIO_B47 | +| PIN5 | GPIO_B48 | For detailed API documentation, refer to [AON](#hal-aes). @@ -73,21 +87,20 @@ For detailed API documentation, refer to [AON](#hal-aes). ```c void example(void) { - /* Enable LPTIM1 as wakeup source */ + /* Enable LPTIM1 as a wakeup source */ HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_LPTIM1, AON_PIN_MODE_HIGH); - /* Enable MAILBOX interrupt triggered by LPSYS as wakeup source */ + /* Enable the MAILBOX interrupt triggered by LPSYS as a wakeup source */ HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_LP2HP_IRQ, AON_PIN_MODE_HIGH); /* Enable manual wakeup triggered by LPSYS */ HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_LP2HP_REQ, AON_PIN_MODE_HIGH); - /* Enable PIN0 low level wakeup */ + /* Enable PIN0 low-level wakeup */ HAL_HPAON_EnableWakeupSrc(HPAON_WAKEUP_SRC_PIN0, AON_PIN_MODE_LOW); ... - - /* Configure HPSYS enter LIGHT mode */ + + /* Configure HPSYS to enter LIGHT mode */ HAL_HPAON_EnterLightSleep(0); } - ``` ### Query Wakeup PIN and Corresponding GPIO Pin @@ -97,39 +110,38 @@ void example(void) int8_t wakeup_pin; uint16_t *gpio_pin; GPIO_TypeDef *gpio; - - /* Query which wakeup pin is mapping to GPIO_A80, - if found return value >=0, otherwise, return -1 */ + + /* Query the wakeup pin mapped to GPIO_A80. + Returns value >= 0 if found; otherwise, returns -1. */ wakeup_pin = HAL_HPAON_QueryWakeupPin(hwp_gpio1, 80); - /* Query which GPIO PIN is mapping to wakeup pin0, - if found, return GPIO instance and pin id, otherwise return NULL */ - gpio = HAL_HPAON_QueryWakeupGpioPin(0, &pin); + /* Query the GPIO pin mapped to wakeup pin 0. + If found, returns the GPIO instance and pin ID; otherwise, returns NULL. */ + gpio = HAL_HPAON_QueryWakeupGpioPin(0, &pin); } - ``` + ## Using HAL LPAON ### Configure Sleep ```c void example(void) { - /* Enable LPTIM2 as wakeup source */ + /* Enable LPTIM2 as a wakeup source */ HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_LPTIM2, AON_PIN_MODE_HIGH); - /* Enable MAILBOX interrupt triggered by HPSYS as wakeup source */ + /* Enable the MAILBOX interrupt triggered by HPSYS as a wakeup source */ HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_HP2LP_IRQ, AON_PIN_MODE_HIGH); /* Enable manual wakeup triggered by HPSYS */ HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_HP2LP_REQ, AON_PIN_MODE_HIGH); - /* Enable PIN0 low level wakeup */ + /* Enable PIN0 low-level wakeup */ HAL_LPAON_EnableWakeupSrc(LPAON_WAKEUP_SRC_PIN0, AON_PIN_MODE_LOW); ... - - /* Configure LPSYS enter LIGHT mode */ + + /* Configure LPSYS to enter LIGHT mode */ HAL_LPAON_EnterLightSleep(0); } - ``` ### Query Wakeup PIN and Corresponding GPIO Pin @@ -139,16 +151,16 @@ void example(void) int8_t wakeup_pin; uint16_t *gpio_pin; GPIO_TypeDef *gpio; - - /* Query which wakeup pin is mapping to GPIO_B43, - if found return value >=0, otherwise, return -1 */ + + /* Query the wakeup pin mapped to GPIO_B43. + Returns value >= 0 if found; otherwise, returns -1. */ wakeup_pin = HAL_LPAON_QueryWakeupPin(hwp_gpio2, 43); - /* Query which GPIO PIN is mapping to wakeup pin0, - if found, return GPIO instance and pin id, otherwise return NULL */ - gpio = HAL_HPAON_QueryWakeupGpioPin(0, &pin); + /* Query the GPIO pin mapped to wakeup pin 0. + If found, returns the GPIO instance and pin ID; otherwise, returns NULL. */ + gpio = HAL_HPAON_QueryWakeupGpioPin(0, &pin); } - ``` ## API Reference -[](#hal-aon) +[] + diff --git a/docs/source/en/hal/atim.md b/docs/source/en/hal/atim.md index 4d1f6ac5e..f249e9d6f 100644 --- a/docs/source/en/hal/atim.md +++ b/docs/source/en/hal/atim.md @@ -1,55 +1,78 @@ # ATIM -ATIM (Advanced Timer) is based on a 32-bit counter, capable of timing, measuring input signal pulse length (input capture) or generating output waveforms (output compare and PWM). It supports 3 channels of complementary PWM output with dead-time protection, supports multi-channel PWM phase switching, and has 2 brake inputs for quickly switching output to safe state. The counter itself can count up, down, or up/down, with counting clock from system pclk or external input signal, and can be prescaled by 1~65536 times. ATIM has 6 channels that can be independently configured as input capture or output mode. Counting, input capture and output compare results can be notified to the system through interrupts or DMA. ATIM contains master-slave mode interface for multi-level cascading, implementing multi-level counting or synchronous triggering functions. +ATIM (Advanced Timer) is based on a 32-bit counter, capable of timing, measuring +input signal pulse length (input capture) or generating output waveforms (output +compare and PWM). It supports 3 channels of complementary PWM output with +dead-time protection, supports multi-channel PWM phase switching, and has 2 +brake inputs for quickly switching output to safe state. The counter itself can +count up, down, or up/down, with counting clock from system pclk or external +input signal, and can be prescaled by 1~65536 times. ATIM has 6 channels that +can be independently configured as input capture or output mode. Counting, input +capture and output compare results can be notified to the system through +interrupts or DMA. ATIM contains master-slave mode interface for multi-level +cascading, implementing multi-level counting or synchronous triggering +functions. ## ATIM Main Features: - 32-bit up, down, up/down auto-reload counter
-- 16-bit programmable (can be modified in real-time) prescaler, counter clock frequency division factor can be any value between 1~65536
+- 16-bit programmable (can be modified in real-time) prescaler, counter clock + frequency division factor can be any value between 1~65536
- 16-bit configurable repetition counter
-- Supports One Pulse Mode (OPM), automatically stops counter when repetition counting is complete
+- Supports One Pulse Mode (OPM), automatically stops counter when repetition + counting is complete
- 6 independent channels
- - Channels 1~3 can be configured as input or output mode, each channel can output two complementary PWM signals with dead-time protection
- - Channel 4 can be configured as input or output mode, can output single PWM
+ - Channels 1~3 can be configured as input or output mode, each channel can + output two complementary PWM signals with dead-time protection
+ - Channel 4 can be configured as input or output mode, can output single + PWM
- Channels 5~6 can be configured as output compare mode
- Input mode
- Rising/falling edge capture
- PWM pulse width and period capture (requires two channels)
- - Selectable from 4 input ports or 1 external trigger port, supports anti-jitter filtering and pre-frequency division
+ - Selectable from 4 input ports or 1 external trigger port, supports + anti-jitter filtering and pre-frequency division
- Output mode
- Force output high/low level
- Output high/low/toggle level when count reaches compare value
- PWM output with configurable pulse width and period
- - Multi-channel PWM combined output, can generate multiple PWM signals with mutual relationships
+ - Multi-channel PWM combined output, can generate multiple PWM signals with + mutual relationships
- Single pulse/retriggerable single pulse mode output
- Master-slave mode
- - Supports multiple GPT interconnection, can generate control signals as master device while being controlled by external input or other master devices as slave device
+ - Supports multiple GPT interconnection, can generate control signals as + master device while being controlled by external input or other master + devices as slave device
- Control modes include reset, trigger, gate, etc.
- Supports synchronous start, reset of multiple GPTs
- Encoder mode input, controls counter up/down counting
- Supports Hall sensor circuit for positioning
-- 2 brake inputs, supports anti-jitter filtering, can quickly put output in safe state. Brake signal sources include:
+- 2 brake inputs, supports anti-jitter filtering, can quickly put output in safe + state. Brake signal sources include:
- CPU exception
- Comparator
- External input
- Software trigger
- Generate interrupt/DMA when following events occur:
- - Update: counter up overflow/down underflow, counter initialization (by software or internal/external trigger)
- - Trigger event (counter start, stop, initialization or internal/external trigger counting)
+ - Update: counter up overflow/down underflow, counter initialization (by + software or internal/external trigger)
+ - Trigger event (counter start, stop, initialization or internal/external + trigger counting)
- Input capture
- Output compare
- Brake
- Commutation
-SF32LB58X HCPU has two ATIMs: ATIM1 and ATIM2. -SF32LB56X HCPU has one ATIM: ATIM1. +SF32LB58X HCPU has two ATIMs: ATIM1 and ATIM2. SF32LB56X HCPU has one ATIM: +ATIM1. For detailed ATIM interface, please refer to [TIM_EX](#hal-tim-ex) ## Using ATIM -The following ATIM usage is the same as GPT basic function usage, except setting Instance to ATIMx during initialization. -For specific usage, please refer to [](../hal/gpt.md) +The following ATIM usage is the same as GPT basic function usage, except setting +Instance to ATIMx during initialization. For specific usage, please refer to +[](../hal/gpt.md) ### Using ATIM HAL Interface for Timer Function ```c @@ -59,34 +82,34 @@ For specific usage, please refer to [](../hal/gpt.md) static GPT_HandleTypeDef TIM_Handle = {0}; TIM_Handle.Instance = (GPT_TypeDef *)hwp_atim1; - TIM_Handle.Init.Prescaler = HAL_RCC_GetPCLKFreq(CORE_ID_HCPU, 1) / FREQENCY; /*Prescaler is 16 bits, please select correct frequency*/ + TIM_Handle.Init.Prescaler = HAL_RCC_GetPCLKFreq(CORE_ID_HCPU, 1) / FREQENCY; /*The prescaler is 16 bits; ensure the correct frequency is selected.*/ TIM_Handle.core = CORE_ID_HCPU; - TIM_Handle.Init.CounterMode = GPT_COUNTERMODE_UP; /*GPTIM could support counter up/down, BTIM only support count up*/ + TIM_Handle.Init.CounterMode = GPT_COUNTERMODE_UP; /*GPTIM supports up/down counting; BTIM only supports up-counting.*/ TIM_Handle.Init.RepetitionCounter = 0; TIM_Handle.Init.Period = TIME_MS * FREQENCY / 1000; - if (HAL_GPT_Base_Init(&TIM_Handle) == HAL_OK) /*init timer*/ + if (HAL_GPT_Base_Init(&TIM_Handle) == HAL_OK) /*Initialize timer*/ { - HAL_NVIC_SetPriority(ATIM1_IRQn, 3, 0); /* set the TIMx priority */ - HAL_NVIC_EnableIRQ(ATIM1_IRQn); /* enable the TIMx global Interrupt */ - __HAL_GPT_CLEAR_FLAG(&TIM_Handle, GPT_FLAG_UPDATE); /* clear update flag */ - __HAL_GPT_URS_ENABLE(&TIM_Handle); /* enable update request source */ + HAL_NVIC_SetPriority(ATIM1_IRQn, 3, 0); /* Set TIMx priority */ + HAL_NVIC_EnableIRQ(ATIM1_IRQn); /* Enable TIMx global interrupt */ + __HAL_GPT_CLEAR_FLAG(&TIM_Handle, GPT_FLAG_UPDATE); /* Clear update flag */ + __HAL_GPT_URS_ENABLE(&TIM_Handle); /* Enable update request source */ } else { LOG_E("Timer init error"); return; } - if (HAL_GPT_Base_Start_IT(&TIM_Handle) != HAL_OK) /* start timer */ + if (HAL_GPT_Base_Start_IT(&TIM_Handle) != HAL_OK) /* Start timer */ { LOG_E("Timer start error"); return; } - /*atimer interrupt handler*/ + /*ATIM interrupt handler*/ void ATIM1_IRQHandler(void) { ENTER_INTERRUPT(); - HAL_GPT_IRQHandler(&TIM_Handle); + HAL_GPT_IRQHandler(&TIM_Handle); LEAVE_INTERRUPT(); } } @@ -104,31 +127,31 @@ ATIM PWM init code: gpt_Handle.core = CORE_ID_HCPU; gpt_Handle.Channel = GPT_CHANNEL_1; gpt_Handle.Init.CounterMode = GPT_COUNTERMODE_UP; - /*atimer base init*/ - if (HAL_GPT_Base_Init(&gpt_Handle) != HAL_OK) + /*Initialize ATIM base*/ + if (HAL_GPT_Base_Init(&gpt_Handle) != HAL_OK) { LOG_E("atimer base init failed"); return; } - /*atimer clock source select*/ + /*Select ATIM clock source*/ clock_config.ClockSource = GPT_CLOCKSOURCE_INTERNAL; - if (HAL_GPT_ConfigClockSource(&gpt_Handle, &clock_config) != HAL_OK) + if (HAL_GPT_ConfigClockSource(&gpt_Handle, &clock_config) != HAL_OK) { LOG_E("atimer clock init failed"); return; } - /*atimer pwm init*/ - if (HAL_GPT_PWM_Init(&gpt_Handle) != HAL_OK) + /*Initialize ATIM PWM*/ + if (HAL_GPT_PWM_Init(&gpt_Handle) != HAL_OK) { LOG_E("atimer pwm init failed"); return; } - /*atimer pwm channel config*/ + /*Configure ATIM PWM channel*/ oc_config.OCMode = GPT_OCMODE_PWM1; oc_config.Pulse = 0; oc_config.OCPolarity = GPT_OCPOLARITY_HIGH; oc_config.OCFastMode = GPT_OCFAST_DISABLE; - if (HAL_GPT_PWM_ConfigChannel(&gpt_Handle, &oc_config, GPT_CHANNEL_1) != HAL_OK) + if (HAL_GPT_PWM_ConfigChannel(&gpt_Handle, &oc_config, GPT_CHANNEL_1) != HAL_OK) { LOG_E("atimer pwm channel config failed"); return; @@ -147,16 +170,16 @@ ATIM PWM parameter set: rt_uint32_t GPT_clock, psc; GPT_clock = HAL_RCC_GetPCLKFreq(CORE_ID_HCPU, 1); - /* Convert nanosecond to frequency and duty cycle. 1s = 1 * 1000 * 1000 * 1000 ns */ + /* Convert nanoseconds to frequency and duty cycle. 1s = 10^9 ns */ GPT_clock /= 1000000UL; period = (unsigned long long)PWM_PERIOD * GPT_clock / 1000ULL; psc = period / MAX_PERIOD_ATM + 1; period = period / psc; - /*set atimer prescaler*/ - __HAL_GPT_SET_PRESCALER(&gpt_Handle, psc - 1); + /*Set ATIM prescaler*/ + __HAL_GPT_SET_PRESCALER(&gpt_Handle, psc - 1); /*set atimer auto reload*/ - __HAL_GPT_SET_AUTORELOAD(&gpt_Handle, period - 1); - /*set atimer pulse*/ + __HAL_GPT_SET_AUTORELOAD(&gpt_Handle, period - 1); + /*Set ATIM pulse*/ pulse = (unsigned long long)PWM_PULSE * GPT_clock / psc / 1000ULL; __HAL_GPT_SET_COMPARE(htim, GPT_CHANNEL_1, pulse - 1); @@ -176,14 +199,15 @@ ATIM PWM brake dead time set: bdt.Break2Filter = 0; bdt.Break2Polarity = 0; bdt.Break2State = 0; - bdt.DeadTime = 200; /*0~1023*/ + bdt.DeadTime = 200; /*Range: 0–1023*/ bdt.OffStateIDLEMode = 0; bdt.OffStateRunMode = 0; bdt.DeadTimePsc = 0; - HAL_TIMEx_ConfigBreakDeadTime(htim, &bdt); + HAL_TIMEx_ConfigBreakDeadTime(htim, &bdt); } ``` + ## API Reference -[](#hal-tim-ex) +[] diff --git a/docs/source/en/hal/audcodec.md b/docs/source/en/hal/audcodec.md index 504b5b289..52eb13275 100644 --- a/docs/source/en/hal/audcodec.md +++ b/docs/source/en/hal/audcodec.md @@ -1,43 +1,44 @@ # AUDCODEC -AUDCODEC (audio codec) completes AD/DA conversion of audio path data. Supported sampling rates include 8K, 12K, 16K, 24K, 32K, 48K, 11.025K, 22.05K, 44.1K, and supports gradual volume changes. +AUDCODEC (audio codec) completes AD/DA conversion of audio path data. Supported +sampling rates include 8K, 12K, 16K, 24K, 32K, 48K, 11.025K, 22.05K, 44.1K, and +supports gradual volume changes. ## Using AUDCODEC HAL Driver: HAL AUDCODEC sample for TX: ```c -AUDCODEC_HandleTypeDef *haudcodec = &audcodec; +AUDCODEC_HandleTypeDef *haudcodec = &audcodec; -bf0_enable_pll(44100, 1); //RCC ENABLE +bf0_enable_pll(44100, 1); // Enable RCC int res = HAL_AUDCODEC_Init(haudcodec); -HAL_AUDCODEC_Config_TChanel(haudcodec, 0, haudcodec->Init.dac_cfg); -res = HAL_AUDCODEC_Transmit_DMA(haudcodec, haudcodec->buf[HAL_AUDCODEC_DAC_CH1], haudcodec->bufSize, HAL_AUDCODEC_DAC_CH1); +HAL_AUDCODEC_Config_TChanel(haudcodec, 0, haudcodec->Init.dac_cfg); +res = HAL_AUDCODEC_Transmit_DMA(haudcodec, haudcodec->buf[HAL_AUDCODEC_DAC_CH1], haudcodec->bufSize, HAL_AUDCODEC_DAC_CH1); HAL_NVIC_EnableIRQ(AUDCODEC_DAC1_DMA_IRQ); __HAL_AUDCODEC_HP_ENABLE(haudcodec); HAL_AUDCODEC_Config_DACPath(haudcodec, 1); -HAL_AUDCODEC_Config_Analog_DACPath(haudcodec->Init.dac_cfg); +HAL_AUDCODEC_Config_Analog_DACPath(haudcodec->Init.dac_cfg); HAL_AUDCODEC_Config_DACPath(haudcodec, 0); - ``` HAL AUDCODEC sample for RX: ```c -AUDCODEC_HandleTypeDef *haudcodec = &audcodec; +AUDCODEC_HandleTypeDef *haudcodec = &audcodec; -bf0_enable_pll(44100, 1); //RCC ENABLE +bf0_enable_pll(44100, 1); // Enable RCC int res = HAL_AUDCODEC_Init(haudcodec); -HAL_AUDCODEC_Config_RChanel(haudcodec, 0, haudcodec->Init.adc_cfg); -res = HAL_AUDCODEC_Receive_DMA(haudcodec, haudcodec->buf[HAL_AUDCODEC_ADC_CH0], haudcodec->bufSize, HAL_AUDCODEC_ADC_CH0); +HAL_AUDCODEC_Config_RChanel(haudcodec, 0, haudcodec->Init.adc_cfg); +res = HAL_AUDCODEC_Receive_DMA(haudcodec, haudcodec->buf[HAL_AUDCODEC_ADC_CH0], haudcodec->bufSize, HAL_AUDCODEC_ADC_CH0); HAL_NVIC_EnableIRQ(AUDCODEC_ADC0_DMA_IRQ); HAL_AUCODEC_Refgen_Init(); -HAL_AUDCODEC_Config_Analog_ADCPath(haudcodec->Init.adc_cfg); +HAL_AUDCODEC_Config_Analog_ADCPath(haudcodec->Init.adc_cfg); -/* enable AUDCODEC at last*/ +/** Enable AUDCODEC last*/ __HAL_AUDCODEC_LP_ENABLE(haudcodec); - ``` + ## API Reference -[](#hal-audcodec) +[] diff --git a/docs/source/en/hal/audprc.md b/docs/source/en/hal/audprc.md index 612f93710..28271820d 100644 --- a/docs/source/en/hal/audprc.md +++ b/docs/source/en/hal/audprc.md @@ -1,17 +1,19 @@ # AUDPRC -AUDPRC (audio processor) completes specific data processing functions for audio paths. Main functions include:\ +AUDPRC (audio processor) completes specific data processing functions for audio +paths. Main functions include:\ - Audio sampling rate conversion\ - Audio equalizer EQ for matching output audio devices\ -- Audio mixing function, mixing audio from different sources for output, supports mixing audio of different sampling rates\ +- Audio mixing function, mixing audio from different sources for output, + supports mixing audio of different sampling rates\ - Supports data input/output from I2S/MEM/AUDCODEC\ -- Supports mono/stereo various data formats, including interleaving and de-interleaving of left and right channel data +- Supports mono/stereo various data formats, including interleaving and + de-interleaving of left and right channel data ## Using AUDPRC HAL Driver: HAL AUDPRC sample for TX: ```c - const audprc_src_table_t src_table[] = { {8000, 11025, 0, 0, 0, 0, 0, 0, 1, 0x2e709c60}, @@ -87,37 +89,36 @@ const audprc_src_table_t src_table[] = {48000, 32000, 1, 1, 0, 0, 0, 0, 1, 0x2fffd780}, {48000, 44100, 0, 0, 0, 0, 0, 0, 1, 0x45a84680}, }; -AUDPRC_HandleTypeDef *haprc = &aprc; +AUDPRC_HandleTypeDef *haprc = &aprc; AUDPRC_ChnlCfgTypeDef cfg; int res = HAL_AUDPRC_Init(haprc); cfg.dma_mask = 0; cfg.en = 1; -cfg.format = caps->udata.config.samplefmt == 16 ? 0 : 1; -if (cfg.format == 0) // only 16 bit support stereo - cfg.mode = caps->udata.config.channels == 1 ? 0 : 1; +cfg.format = caps->udata.config.samplefmt == 16 ? 0 : 1; +if (cfg.format == 0) // Stereo is only supported in 16-bit format + cfg.mode = caps->udata.config.channels == 1 ? 0 : 1; else cfg.mode = 0; -HAL_AUDPRC_Config_TChanel(haudprc, 3, &cfg); - -haudprc->Init.dac_cfg.src_hbf3_mode = src_table[i].hbf3_mode; -haudprc->Init.dac_cfg.src_hbf3_en = src_table[i].hbf3_en; -haudprc->Init.dac_cfg.src_hbf2_mode = src_table[i].hbf2_mode; -haudprc->Init.dac_cfg.src_hbf2_en = src_table[i].hbf2_en; -haudprc->Init.dac_cfg.src_hbf1_mode = src_table[i].hbf1_mode; -haudprc->Init.dac_cfg.src_hbf1_en = src_table[i].hbf1_en; -haudprc->Init.dac_cfg.src_sinc_en = src_table[i].sinc_en; -haudprc->Init.dac_cfg.sinc_ratio = src_table[i].sinc_ratio; -haudprc->Init.dac_cfg.src_ch_en = 3; -HAL_AUDPRC_Config_DACPath(haudprc, &(haudprc->Init.dac_cfg)); - -res = HAL_AUDPRC_Transmit_DMA(haudprc, haudprc->buf[HAL_AUDPRC_TX_CH0], haudprc->bufSize, HAL_AUDPRC_TX_CH0); +HAL_AUDPRC_Config_TChanel(haudprc, 3, &cfg); + +haudprc->Init.dac_cfg.src_hbf3_mode = src_table[i].hbf3_mode; +haudprc->Init.dac_cfg.src_hbf3_en = src_table[i].hbf3_en; +haudprc->Init.dac_cfg.src_hbf2_mode = src_table[i].hbf2_mode; +haudprc->Init.dac_cfg.src_hbf2_en = src_table[i].hbf2_en; +haudprc->Init.dac_cfg.src_hbf1_mode = src_table[i].hbf1_mode; +haudprc->Init.dac_cfg.src_hbf1_en = src_table[i].hbf1_en; +haudprc->Init.dac_cfg.src_sinc_en = src_table[i].sinc_en; +haudprc->Init.dac_cfg.sinc_ratio = src_table[i].sinc_ratio; +haudprc->Init.dac_cfg.src_ch_en = 3; +HAL_AUDPRC_Config_DACPath(haudprc, &(haudprc->Init.dac_cfg)); + +res = HAL_AUDPRC_Transmit_DMA(haudprc, haudprc->buf[HAL_AUDPRC_TX_CH0], haudprc->bufSize, HAL_AUDPRC_TX_CH0); HAL_NVIC_EnableIRQ(AUDPRC_TX0_DMA_IRQ); -/* enable AUDPRC at last*/ +/** Enable AUDPRC as the final step*/ __HAL_AUDPRC_ENABLE(haudprc); - ``` HAL AUDPRC sample for RX: @@ -129,31 +130,31 @@ int res = HAL_AUDPRC_Init(haprc); cfg.dma_mask = 0; cfg.en = 1; -cfg.format = caps->udata.config.samplefmt == 16 ? 0 : 1; -if (cfg.format == 0) // only 16 bit support stereo - cfg.mode = caps->udata.config.channels == 1 ? 0 : 1; +cfg.format = caps->udata.config.samplefmt == 16 ? 0 : 1; +if (cfg.format == 0) // Stereo is only supported in 16-bit format + cfg.mode = caps->udata.config.channels == 1 ? 0 : 1; else cfg.mode = 0; -HAL_AUDPRC_Config_RChanel(haudprc, 0, &cfg); - -haudprc->Init.adc_cfg.src_hbf3_mode = src_table[i].hbf3_mode; -haudprc->Init.adc_cfg.src_hbf3_en = src_table[i].hbf3_en; -haudprc->Init.adc_cfg.src_hbf2_mode = src_table[i].hbf2_mode; -haudprc->Init.adc_cfg.src_hbf2_en = src_table[i].hbf2_en; -haudprc->Init.adc_cfg.src_hbf1_mode = src_table[i].hbf1_mode; -haudprc->Init.adc_cfg.src_hbf1_en = src_table[i].hbf1_en; -haudprc->Init.adc_cfg.src_sinc_en = src_table[i].sinc_en; -haudprc->Init.adc_cfg.sinc_ratio = src_table[i].sinc_ratio; -haudprc->Init.adc_cfg.src_ch_en = 3; -HAL_AUDPRC_Config_ADCPath(haudprc, &(haudprc->Init.adc_cfg)); - -res = HAL_AUDPRC_Receive_DMA(haudprc, haudprc->buf[HAL_AUDPRC_RX_CH0], haudprc->bufSize, HAL_AUDPRC_RX_CH0); +HAL_AUDPRC_Config_RChanel(haudprc, 0, &cfg); + +haudprc->Init.adc_cfg.src_hbf3_mode = src_table[i].hbf3_mode; +haudprc->Init.adc_cfg.src_hbf3_en = src_table[i].hbf3_en; +haudprc->Init.adc_cfg.src_hbf2_mode = src_table[i].hbf2_mode; +haudprc->Init.adc_cfg.src_hbf2_en = src_table[i].hbf2_en; +haudprc->Init.adc_cfg.src_hbf1_mode = src_table[i].hbf1_mode; +haudprc->Init.adc_cfg.src_hbf1_en = src_table[i].hbf1_en; +haudprc->Init.adc_cfg.src_sinc_en = src_table[i].sinc_en; +haudprc->Init.adc_cfg.sinc_ratio = src_table[i].sinc_ratio; +haudprc->Init.adc_cfg.src_ch_en = 3; +HAL_AUDPRC_Config_ADCPath(haudprc, &(haudprc->Init.adc_cfg)); + +res = HAL_AUDPRC_Receive_DMA(haudprc, haudprc->buf[HAL_AUDPRC_RX_CH0], haudprc->bufSize, HAL_AUDPRC_RX_CH0); HAL_NVIC_EnableIRQ(AUDPRC_RX0_DMA_IRQ); -/* enable AUDPRC at last*/ +/** Enable AUDPRC as the final step**/ __HAL_AUDPRC_ENABLE(haudprc); - ``` ## API Reference -[](/api/hal/audprc.md) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/btim.md b/docs/source/en/hal/btim.md index 16e7615fc..22bec2d8e 100644 --- a/docs/source/en/hal/btim.md +++ b/docs/source/en/hal/btim.md @@ -1,25 +1,37 @@ -# BTIM +# Basic Timer (BTIM) -BTIM (Basic Timer) is based on a 32-bit up counter for timing functionality. The counting clock is system pclk or external input signal, and can be prescaled by 1~65536 times. Timing results can be notified to the system through interrupts or DMA. BTIM contains master-slave mode interface for multi-level cascading, implementing multi-level counting or synchronous triggering functions. +BTIM (Basic Timer) is based on a 32-bit up counter for timing functionality. The +counting clock is system pclk or external input signal, and can be prescaled by +1~65536 times. Timing results can be notified to the system through interrupts +or DMA. BTIM contains master-slave mode interface for multi-level cascading, +implementing multi-level counting or synchronous triggering functions. ## BTIM Main Features: - 32-bit up auto-reload counter
-- 16-bit programmable (can be modified in real-time) prescaler, counter clock frequency division factor can be any value between 1~65536
-- Supports One Pulse Mode (OPM), automatically stops counter when counting is complete
+- 16-bit programmable (can be modified in real-time) prescaler, counter clock + frequency division factor can be any value between 1~65536
+- Supports One Pulse Mode (OPM), automatically stops counter when counting is + complete
- Master-slave mode
- - Supports interconnection with BTIM and GPT, can generate control signals as master device while being controlled by external input or other master devices as slave device
+ - Supports interconnection with BTIM and GPT, can generate control signals + as master device while being controlled by external input or other master + devices as slave device
- Control modes include reset, trigger, gate, etc.
- Supports synchronous start, reset of multiple timers
-- Generate interrupt/DMA when counter overflow or initialization occurs (by software or internal/external trigger)
+- Generate interrupt/DMA when counter overflow or initialization occurs (by + software or internal/external trigger)
-SF32LB55X/56X/58X HCPU has two BTIMs: BTIM1 and BTIM2, LCPU has two BTIMs: BTIM3 and BTIM4. +SF32LB55X/56X/58X HCPU has two BTIMs: BTIM1 and BTIM2, LCPU has two BTIMs: BTIM3 +and BTIM4. For detailed BTIM interface, please refer to [TIM](#hal-tim) ## Using BTIM -The following BTIM usage is the same as GPT basic function usage, except setting Instance to BTIMx during initialization. -For specific usage, please refer to [](../hal/gpt.md) +The following BTIM usage is the same as GPT basic function usage, except setting +Instance to BTIMx during initialization. For specific usage, please refer to +[](../hal/gpt.md) + ## API Reference -[](#hal-tim) +[] diff --git a/docs/source/en/hal/busmon.md b/docs/source/en/hal/busmon.md index f75f72272..93d86686d 100644 --- a/docs/source/en/hal/busmon.md +++ b/docs/source/en/hal/busmon.md @@ -1,25 +1,36 @@ # BUSMON -BUSMON (Bus Monitor) module is used to monitor transmission behavior of various masters and slaves on the system AHB bus. BUSMON has 8 channels that can simultaneously select 8 groups of masters or slaves as observation targets, count the number of read/write operations performed by each observation target within their respective configured address spaces, and generate trigger signals to PTC module when the count reaches specific values. -The BUSMON module can be used to count block access frequency of external flash to find areas where cache frequently misses for optimization; it can also find who is modifying specific RAM addresses; it can also be used to observe memory bandwidth usage. Combined with PTC, BUSMON can generate interrupts when accessing specific address spaces, or trigger other peripherals when an observation target performs a specific number of bus operations, forming bus-peripheral hardware task chains. -BUSMON does not increase bus critical path length. +BUSMON (Bus Monitor) module is used to monitor transmission behavior of various +masters and slaves on the system AHB bus. BUSMON has 8 channels that can +simultaneously select 8 groups of masters or slaves as observation targets, +count the number of read/write operations performed by each observation target +within their respective configured address spaces, and generate trigger signals +to PTC module when the count reaches specific values. The BUSMON module can be +used to count block access frequency of external flash to find areas where cache +frequently misses for optimization; it can also find who is modifying specific +RAM addresses; it can also be used to observe memory bandwidth usage. Combined +with PTC, BUSMON can generate interrupts when accessing specific address spaces, +or trigger other peripherals when an observation target performs a specific +number of bus operations, forming bus-peripheral hardware task chains. BUSMON +does not increase bus critical path length. -BUSMON main features:
+BUSMON main features:
- 8 independently configurable channels can work simultaneously
- Supports all masters and slaves on the bus
- Arbitrarily configurable bus address space
- Can count read/write/read-write bus operations
- 31-bit counter, 24-bit comparator
-- Count overflow can automatically reset and restart, overflow can be queried
+- Count overflow can automatically reset and restart, overflow can be + queried
- 8 independent PTC trigger sources for channels
## Using Bus Monitor ```c - BUSMON_HandleTypeDef BusmonHandle; +BUSMON_HandleTypeDef BusmonHandle; volatile uint32_t temp; volatile uint32_t * p; - + // Initialize Bus Monitor { BusmonHandle.Init.Channel = 1; // Channel 1 @@ -27,18 +38,18 @@ BUSMON main features:
BusmonHandle.Init.SelFunc = HAL_BUSMON_HCPU_S; // Monitor HCPU BUS SLAVE BusmonHandle.Init.Max = 0x60010000; // Max address range BusmonHandle.Init.Min = 0x60000000; // Min address range - HAL_BUSMON_Init(&BusmonHandle); // Initialize the busmon - HAL_BUSMON_Enable(&BusmonHandle, 1); // Enable bus monitor + HAL_BUSMON_Init(&BusmonHandle); // Initialize the BUSMON + HAL_BUSMON_Enable(&BusmonHandle, 1); // Enable the bus monitor } - - p=*(uint32_t*)0x60000000; // Read from PSRAM between 0x60000000-0x60010000 100 times - for (int i=0;i<100;i++) { + + p=*(uint32_t*)0x60000000; // Perform 100 reads from PSRAM within the 0x60000000-0x60010000 range + for (int i=0;i<100;i++) { temp=*p; p++; } - HAL_BUSMON_GetCount(&BusmonHandle, (int32_t *)&temp); // temp is 100. + HAL_BUSMON_GetCount(&BusmonHandle, (int32_t *)&temp); // temp should be 100. printf("Count=%d\n", temp); ``` ## API Reference -[](../api/hal/busmon.md) +[] diff --git a/docs/source/en/hal/cache.md b/docs/source/en/hal/cache.md index 0acfe85a5..81d2f8606 100644 --- a/docs/source/en/hal/cache.md +++ b/docs/source/en/hal/cache.md @@ -1,7 +1,9 @@ # CACHE -HAL CACHE module provides statistical functionality for `HCPU CACHE MISS` rate, can individually or simultaneously count ICACHE and DCACHE miss rates. -Can also set address ranges for statistics, supports individual or simultaneous statistics for the following address regions: +HAL CACHE module provides statistical functionality for `HCPU CACHE MISS` rate, +can individually or simultaneously count ICACHE and DCACHE miss rates. Can also +set address ranges for statistics, supports individual or simultaneous +statistics for the following address regions: - QSPI1_4, address space: 0x10000000~0x13FFFFFF - QSPI2, address space: 0x64000000~0x67FFFFFF - QSPI3, address space: 0x68000000~0x6FFFFFFF @@ -9,12 +11,13 @@ Can also set address ranges for statistics, supports individual or simultaneous For detailed API documentation, refer to [CACHE](#hal-cache) + ## Using HAL CACHE ```c void enable(void) { - /* Enable ICACHE and DACHE miss rate profiling, range is QSPI1/2/4 memory space */ + /* * Enable ICACHE and DCACHE miss rate profiling for the QSPI1/2/4 memory space * */ HAL_CACHE_Enable(HAL_CACHE_ICACHE_QSPI1_4 | HAL_CACHE_ICACHE_QSPI2, HAL_CACHE_DCACHE_QSPI1_4 | HAL_CACHE_DCACHE_QSPI2); @@ -23,16 +26,16 @@ void read(void) { float irate; float drate; - /* read cache miss rate and reset counter */ - HAL_CACHE_GetMissRate(&irate, &drate, true); + /* * Read the cache miss rate and reset the counters * */ + HAL_CACHE_GetMissRate(&irate, &drate, true); } void disable(void) { - /* Disable ICACHE and DCACHE miss rate profiling */ + /* * Disable ICACHE and DCACHE miss rate profiling * */ HAL_CACHE_Disable(); } ``` ## API Reference -[](#hal-cache) \ No newline at end of file +[] diff --git a/docs/source/en/hal/crc.md b/docs/source/en/hal/crc.md index fa211f4f3..01ac2bc9f 100644 --- a/docs/source/en/hal/crc.md +++ b/docs/source/en/hal/crc.md @@ -1,10 +1,17 @@ # CRC -The CRC module can be used for CRC calculation with specific bit width, arbitrary generator polynomial, and arbitrary initial value. The minimum data input unit is a single byte, with no maximum byte limit. Single cycle can complete single-byte input calculation. CRC result can be obtained quickly after all data input is complete. Supports input data reversal and output data reversal. Supports input data of different valid bit widths. -- 7/8/16/32-bit CRC calculation, supports all mainstream formats for these bit widths +The CRC module can be used for CRC calculation with specific bit width, +arbitrary generator polynomial, and arbitrary initial value. The minimum data +input unit is a single byte, with no maximum byte limit. Single cycle can +complete single-byte input calculation. CRC result can be obtained quickly after +all data input is complete. Supports input data reversal and output data +reversal. Supports input data of different valid bit widths. +- 7/8/16/32-bit CRC calculation, supports all mainstream formats for these bit + widths - Arbitrary generator polynomial - Arbitrary initial value -- Input data supports single-byte/double-byte/three-byte/four-byte valid bit width +- Input data supports single-byte/double-byte/three-byte/four-byte valid bit + width - Input data bit reversal by byte/double-byte/four-byte high/low bit - Output data high/low bit reversal @@ -13,39 +20,40 @@ The following is a CRC code snippet: ```c { - CRC_HandleTypeDef CrcHandle; // CRC handle declaration - CrcHandle.Instance = CRC; // Initialize CRC handle - uint8_t g_test_data[]= { // Raw data + CRC_HandleTypeDef CrcHandle; // Declare CRC handle + CrcHandle.Instance = CRC; // Assign CRC instance + uint8_t g_test_data[]= { // Input data buffer 1,2,3,4,5,6,7,8,9,10 } - HAL_CRC_Init(&CrcHandle); // Initialize CRC module - HAL_CRC_Setmode(&CrcHandle, CRC_8_ITU); // Set CRC mode to CRC-8/ITU standard - uint32_t crc=HAL_CRC_Accumulate(&CrcHandle, // Calculate CRC result for g_test_data - &(g_test_data[offset]), sizeof(g_test_data)); - -} + HAL_CRC_Init(&CrcHandle); // Initialize the CRC peripheral + HAL_CRC_Setmode(&CrcHandle, CRC_8_ITU); // Configure for CRC-8/ITU standard + uint32_t crc=HAL_CRC_Accumulate(&CrcHandle, // Compute CRC for g_test_data + &(g_test_data[offset]), sizeof(g_test_data)); + +} ``` ## Using Fully Customized Initial Value and Polynomial ```c { - CRC_HandleTypeDef CrcHandle; // CRC handle declaration - CrcHandle.Instance = CRC; // Initialize CRC handle - uint8_t g_test_data[]= { // Raw data + CRC_HandleTypeDef CrcHandle; // Declare CRC handle + CrcHandle.Instance = CRC; // Assign CRC instance + uint8_t g_test_data[]= { // Input data buffer 1,2,3,4,5,6,7,8,9,10 } uint32_t init = 0xFF; // Initial value - uint32_t poly = 0x1D; // CRC polynomial + uint32_t poly = 0x1D; // Polynomial - HAL_CRC_Init(&CrcHandle); // Initialize CRC module - HAL_CRC_Setmode_Customized(hcrc, init, poly, CRC_8); // Set CRC mode to CRC-8 standard - uint32_t crc=HAL_CRC_Accumulate(&CrcHandle, // Calculate CRC result for g_test_data - &(g_test_data[offset]), sizeof(g_test_data)); + HAL_CRC_Init(&CrcHandle); // Initialize the CRC peripheral + HAL_CRC_Setmode_Customized(hcrc, init, poly, CRC_8); // Configure for custom CRC-8 parameters + uint32_t crc=HAL_CRC_Accumulate(&CrcHandle, // Compute CRC for g_test_data + &(g_test_data[offset]), sizeof(g_test_data)); } ``` + ## API Reference -[](../api/hal/crc.md) \ No newline at end of file +[] diff --git a/docs/source/en/hal/dma.md b/docs/source/en/hal/dma.md index db1cc2cd4..9b1a2eb48 100644 --- a/docs/source/en/hal/dma.md +++ b/docs/source/en/hal/dma.md @@ -1,18 +1,30 @@ # DMA -DMA has 2 instances, one in HCPU and one in LCPU, both supporting memory-to-memory, memory-to-peripheral, peripheral-to-memory, and peripheral-to-peripheral transfers. + +DMA has 2 instances, one in HCPU and one in LCPU, both supporting +memory-to-memory, memory-to-peripheral, peripheral-to-memory, and +peripheral-to-peripheral transfers. + ## Main Features - 8 independent configurable channels - - Each channel's DMA request can select 1 from 16 hardware requests, or be triggered by software - - Each channel supports 4 priority levels, with same priority resolved by channel number - - Supports memory-to-memory, memory-to-peripheral, peripheral-to-memory, peripheral-to-peripheral transfers - - Source and destination addresses independently support single byte/double byte/4-byte access, and both can independently select whether address auto-increment - - Supports circular buffer mode, automatically restarts after single transfer completion - - Each channel supports 3 event flags - transfer complete, half transfer, transfer error, each can independently generate interrupt requests - - Single configuration maximum transfer unit count is 65536, each unit is single byte/double byte/4-byte transfer according to different configurations + - Each channel's DMA request can select 1 from 16 hardware requests, or be + triggered by software + - Each channel supports 4 priority levels, with same priority resolved by + channel number + - Supports memory-to-memory, memory-to-peripheral, peripheral-to-memory, + peripheral-to-peripheral transfers + - Source and destination addresses independently support single byte/double + byte/4-byte access, and both can independently select whether address + auto-increment + - Supports circular buffer mode, automatically restarts after single transfer + completion + - Each channel supports 3 event flags - transfer complete, half transfer, + transfer error, each can independently generate interrupt requests + - Single configuration maximum transfer unit count is 65536, each unit is + single byte/double byte/4-byte transfer according to different configurations ```{only} SF32LB55X or SF32LB56X or SF32LB58X - - Single configuration transfer address range is limited within 1M bytes, i.e., during transfer process, source and destination addresses cannot cross 1M byte boundary (address bit31-bit20 cannot change) +- Single configuration transfer address range is limited within 1M bytes, i.e., during transfer process, source and destination addresses cannot cross 1M byte boundary (address bit31-bit20 cannot change) ``` ## DMAC Corresponding Peripheral Request ID @@ -294,19 +306,46 @@ DMA has 2 instances, one in HCPU and one in LCPU, both supporting memory-to-memo ``` ## DMA Example 1 -Memory-to-memory 4-byte transfer 4096 bytes. -```c - DMA_HandleTypeDef hdma; + HAL_StatusTypeDef err; + + uint32_t SrcAddress = 0x10000000; + uint32_t DstAddress = 0x20000000; + uint32_t Counts = 1024; //Transfer unit is word, so Counts= 4096 / 4 + + /* Init DMA configure*/ + hdma.Instance = DMA1_Channel6; + hdma.Init.Request = 0; //Request id is useless while memory to memory, just set to 0 + hdma.Init.Direction = DMA_MEMORY_TO_MEMORY; + hdma.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD; + hdma.Init.MemDataAlignment = DMA_MDATAALIGN_WORD; + hdma.Init.PeriphInc = DMA_PINC_ENABLE; + hdma.Init.MemInc = DMA_MINC_ENABLE; + hdma.Init.Mode = DMA_NORMAL; + hdma.Init.Priority = DMA_PRIORITY_MEDIUM; + + hdma.XferHalfCpltCallback = DMA_Xfer_Half_Callback_Func; + hdma.XferCpltCallback = DMA_Xfer_Complete_Callback_Func; + hdma.XferErrorCallback = DMA_Xfer_Error_Callback_Func; + + err = HAL_DMA_Init(&hdma); + if (err != HAL_OK) + return err; + + err = HAL_DMA_Start_IT(hadc->DMA_Handle, SrcAddress, DstAddress, Counts); + if (err != HAL_OK) + return err; +```c +DMA_HandleTypeDef hdma; HAL_StatusTypeDef err; uint32_t SrcAddress = 0x10000000; uint32_t DstAddress = 0x20000000; - uint32_t Counts = 1024; //Transfer unit is word, so Counts= 4096 / 4 - - /* Init DMA configure*/ + uint32_t Counts = 1024; // Transfer unit is word, so Counts = 4096 / 4 + + /* Initialize DMA configuration */ hdma.Instance = DMA1_Channel6; - hdma.Init.Request = 0; //Request id is useless while memory to memory, just set to 0 + hdma.Init.Request = 0; // Request ID is ignored for memory-to-memory transfers; set to 0. hdma.Init.Direction = DMA_MEMORY_TO_MEMORY; hdma.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD; hdma.Init.MemDataAlignment = DMA_MDATAALIGN_WORD; @@ -319,27 +358,26 @@ Memory-to-memory 4-byte transfer 4096 bytes. hdma.XferCpltCallback = DMA_Xfer_Complete_Callback_Func; hdma.XferErrorCallback = DMA_Xfer_Error_Callback_Func; - err = HAL_DMA_Init(&hdma); + err = HAL_DMA_Init(&hdma); if (err != HAL_OK) return err; - err = HAL_DMA_Start_IT(hadc->DMA_Handle, SrcAddress, DstAddress, Counts); + err = HAL_DMA_Start_IT(hadc->DMA_Handle, SrcAddress, DstAddress, Counts); if (err != HAL_OK) return err; - ``` + ## DMA Example 2 ADC module-to-memory 4-byte transfer 4096 bytes. ```c - - DMA_HandleTypeDef hdma; +DMA_HandleTypeDef hdma; HAL_StatusTypeDef err; uint32_t SrcAddress = 0x10000000; uint32_t DstAddress = 0x20000000; uint32_t Counts = 1024; //Transfer unit is word, so Counts= 4096 / 4 - + /* Init DMA configure*/ hdma.Instance = DMA1_Channel6; hdma.Init.Request = DMA_REQUEST_12; @@ -362,20 +400,20 @@ ADC module-to-memory 4-byte transfer 4096 bytes. err = HAL_DMA_Start_IT(hadc->DMA_Handle, SrcAddress, DstAddress, Counts); if (err != HAL_OK) return err; - ``` + + ## DMA Example 3 Memory-to-FLASH1 module 1-byte transfer 4096 bytes. ```c - - DMA_HandleTypeDef hdma; +DMA_HandleTypeDef hdma; HAL_StatusTypeDef err; uint32_t SrcAddress = 0x20000000; uint32_t DstAddress = hflash->Instance->DR; uint32_t Counts = 4096; //Transfer unit is byte, so Counts= 4096 / 1 - + /* Init DMA configure*/ hdma.Instance = DMA1_Channel6; hdma.Init.Request = DMA_REQUEST_0; @@ -398,8 +436,8 @@ Memory-to-FLASH1 module 1-byte transfer 4096 bytes. err = HAL_DMA_Start_IT(hadc->DMA_Handle, SrcAddress, DstAddress, Counts); if (err != HAL_OK) return err; - ``` ## API Reference -[](../api/hal/crc.md) +[] + diff --git a/docs/source/en/hal/dsi.md b/docs/source/en/hal/dsi.md index 789fdfa80..79a716b21 100644 --- a/docs/source/en/hal/dsi.md +++ b/docs/source/en/hal/dsi.md @@ -1,28 +1,38 @@ # DSI -DSI (MIPI DSI) module supports 1-lane or 2-lane DSI screens, currently supporting bandwidth configurations of 240/288/336/384/480Mbps, based on MIPI protocol version V1.1 (55x does not support Video mode). + +DSI (MIPI DSI) module supports 1-lane or 2-lane DSI screens, currently +supporting bandwidth configurations of 240/288/336/384/480Mbps, based on MIPI +protocol version V1.1 (55x does not support Video mode). ## Supported Color Output Formats - `RGB565 DSI` transmission order: [G3~G5R0~R4][B0~B4G0~G2] - `RGB888 DSI` transmission order: [R0~R7][G0~G7][B0~B7] -- `RGB565_SWAP DSI` transmission order (55X not supported): [B0~B4G0~G2][G3~G5R0~R4] +- `RGB565_SWAP DSI` transmission order (55X not supported): + [B0~B4G0~G2][G3~G5R0~R4] + +DSI module can work independently, but operating through LCDC encapsulated +interface can achieve optimal performance. -DSI module can work independently, but operating through LCDC encapsulated interface can achieve optimal performance. ```{note} On 55x, DSI needs multiple operations to complete the entire screen refresh, refreshing 2N lines each time (N varies depending on refresh area size), until the entire screen refresh is completed ``` -![Figure 1: Relationship between DSI module and LCDC module](../../assets/hal_dsi_arch.png) +![Figure 1: Relationship between DSI module and LCDC +module](../../assets/hal_dsi_arch.png) + + ## DSI Usage Example -Open DSI screen through LCDC interface, then draw a 100x100 rectangular area to LCD: +Open DSI screen through LCDC interface, then draw a 100x100 rectangular area to +LCD: -```c +```c static LCDC_HandleTypeDef hlcdc_rm69090; - + /*DSI LCD configuration*/ static const LCDC_InitTypeDef lcdc_int_cfg = { @@ -101,7 +111,7 @@ static const LCDC_InitTypeDef lcdc_int_cfg = /********************** * FUNCTIONS **********************/ - + __ROM_USED void LCDC1_IRQHandler(void) { /* enter interrupt */ @@ -126,7 +136,7 @@ void HAL_LCDC_SendLayerDataCpltCbk(LCDC_HandleTypeDef *lcdc) static void RM69090_Init_Seq(LCDC_HandleTypeDef *hlcdc) { ... - + //Sleep out HAL_LCDC_WriteU8Reg(hlcdc, 0x11, (uint8_t *)NULL, 0); @@ -170,9 +180,9 @@ static void main(int argc, char **argv) /*Turn on LCD board power supply*/ Poweron_LCD_Board(); - + memset(&hlcdc_rm69090, 0, sizeof(hlcdc_rm69090)); - + hlcdc_rm69090.Instance = hwp_lcdc; /*Set background layer color*/ @@ -200,7 +210,7 @@ static void main(int argc, char **argv) RM69090_Init_Seq(&hlcdc_rm69090); {//Read LCD id - + uint32_t rd_data = 0; HAL_LCDC_ReadU8Reg(&hlcdc_rm69090, 0x04, (uint8_t *)&rd_data, 4); @@ -214,7 +224,7 @@ static void main(int argc, char **argv) /*Fill framebuffer with single color*/ memset(p_framebuffer, 0xE0, 100*100*2); - + /*Assign framebuffer and area to layer*/ HAL_LCDC_LayerSetData(&hlcdc_rm69090, HAL_LCDC_LAYER_DEFAULT, (uint8_t *)p_framebuffer, 100, 100, 199, 199); @@ -247,9 +257,7 @@ static void main(int argc, char **argv) HAL_NVIC_DisableIRQ(LCDC_IRQ_NUM); } - - ``` ## API Reference -[](../api/hal/dsi.md) +[] diff --git a/docs/source/en/hal/efuse.md b/docs/source/en/hal/efuse.md index e2f7b35b3..488ef02ec 100644 --- a/docs/source/en/hal/efuse.md +++ b/docs/source/en/hal/efuse.md @@ -1,18 +1,22 @@ # EFUSE -`EFUSE HAL` driver provides high-level APIs to program and read efuse. -Main features include: -- 4 banks, each bank has 256 bits. -- Banks need to be programmed one by one, multiple banks can be read simultaneously, but HAL only supports reading one bank at a time. +`EFUSE HAL` driver provides high-level APIs to program and read efuse. Main +features include: +- 4 banks, each bank has 256 bits. +- Banks need to be programmed one by one, multiple banks can be read + simultaneously, but HAL only supports reading one bank at a time. ## Using EFUSE HAL Driver -First, call `HAL_EFUSE_Init` only once to initialize efuse. It should be called after setting sysclk/hclk/pclk. If sysclk/hclk/pclk are updated, `HAL_EFUSE_Init` needs to be called again to update related time registers. +First, call `HAL_EFUSE_Init` only once to initialize efuse. It should be called +after setting sysclk/hclk/pclk. If sysclk/hclk/pclk are updated, +`HAL_EFUSE_Init` needs to be called again to update related time registers. -Use `HAL_EFUSE_Write` to program efuse with specified data, use `HAL_EFUSE_Read` to read data from efuse. For example, +Use `HAL_EFUSE_Write` to program efuse with specified data, use `HAL_EFUSE_Read` +to read data from efuse. For example, ```c { - /* Initialize efuse*/ + /* Initialize eFuse */ HAL_EFUSE_Init(); uint8_t write_data[4]; @@ -20,15 +24,15 @@ Use `HAL_EFUSE_Write` to program efuse with specified data, use `HAL_EFUSE_Read` write_data[1] = 2; write_data[2] = 3; write_data[3] = 4; - /* write 4 bytes starting from bit32(bank0) */ + /* Write 4 bytes starting from bit 32 (Bank 0) */ HAL_EFUSE_Write(32, write_data, sizeof(write_data)); - + uint8_t read_data[4]; memset(read_data, 0, sizeof(read_data)); - /* read 4bytes starting from bit32(bank0) */ + /* Read 4 bytes starting from bit 32 (Bank 0) */ HAL_EFUSE_Read(32, read_data, sizeof(read_data)); } ``` ## API Reference -[](../api/hal/efuse.md) +[] diff --git a/docs/source/en/hal/epic.md b/docs/source/en/hal/epic.md index f112a10db..410501903 100644 --- a/docs/source/en/hal/epic.md +++ b/docs/source/en/hal/epic.md @@ -1,121 +1,156 @@ - -The HAL EPIC module provides an abstract software interface to operate the hardware EPIC module. EPIC is a 2D graphics engine with the following features: - -## Main Features - -- Alpha blending of two images and saving the result to an output buffer -- Rotating an image (foreground) around any point and blending the rotated image with a background image, saving the blended result to the output buffer -- Scaling (enlarge/reduce) the foreground image, blending the scaled image with the background, and saving the result to the output buffer -- Supports combined rotation and scaling in a single GPU operation without requiring an intermediate buffer -- Filling a given buffer with opaque or semi-transparent colors -- All graphics operations support both polling and interrupt modes -- Automatic color format conversion if input and output color formats differ -- The two images for blending can have different sizes and partially overlap; you can also specify a sub-region of the blended area as the output region -- The background and output images can share the same buffer, e.g., both using the frame buffer -- Input image format supports EZIP -- Supports fractional coordinate blending (not supported on 55X) - - -## Input/Output Limitations -| Feature | Supported Formats | 55X | 58X | 56X | 52X | -|--------------|----------------------------------|--------------------------|--------|--------|--------| -| Horizontal Scaling | All color formats supported by the chip | 3.8, shrink by 8x, enlarge by 256x, precision 1/256 | 10.16, shrink by 1024x, enlarge by 65536x, precision 1/65536 | Same as 58X | Same as 58X | -| Vertical Scaling | All color formats supported by the chip | Horizontal and vertical scaling factors must be the same | 10.16, shrink by 1024x, enlarge by 65536x, precision 1/65536,
horizontal and vertical scaling factors can differ | Same as 58X | Same as 58X | -| Rotation | All except EZIP, YUV
A4/A8 mask cannot rotate | [0 ~ 3600], unit is 0.1 degree | Same as 55X | Same as 55X | Same as 55X | -| Horizontal Mirror | All color formats supported by the chip | Supported | Supported | Supported | Supported | -| Vertical Mirror | All except EZIP format | Not supported | Not supported | Not supported | Supported | +# EPIC + +The HAL EPIC module provides abstract software interfaces for controlling the +hardware EPIC module. EPIC is a 2D graphics engine that supports the following +features: + +## Key Features + +- Alpha blending of two images with results saved to an output buffer. +- Rotation of a foreground image around an arbitrary center point, followed by + blending with a background image and saving the output to a buffer. +- Scaling (shrinking or enlarging) of a foreground image, followed by blending + with a background image and saving the output to a buffer. +- Integrated rotation followed by scaling in a single GPU operation, eliminating + the need for intermediate buffers. +- Filling an assigned buffer with opaque or translucent colors. +- Support for both polling and interrupt modes for all graphics operations. +- Automatic color format conversion when source and destination formats differ. +- Blending of two images with different sizes and partial overlap, with the + ability to specify a sub-region of the blended area for writing to the output + buffer. +- Reusability of the same buffer for both the background image and the output + (e.g., using the frame buffer for both). +- Support for EZIP input image format. +- Support for fractional coordinate blending (not supported by 55X). + +## Input and Output Constraints +| Functionality | Supported Formats | 55X | 58X | 56X | 52X | +| -------------------- | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------- | +| Horizontal Scaling | Color formats supported by all chips | 3.8 format (downscaling by 8x, upscaling by 256x, with 1/256 precision) | 10.16 format (downscaling by 1024x, upscaling by 65536x, with 1/65536 precision) | Same as 58X | Same as 58X | +| Vertical Scaling | Color formats supported by all chips | Fixed aspect ratio; horizontal and vertical scaling factors must be identical and cannot be configured independently | 10.16 format (downscaling by 1024x, upscaling by 65536x, with 1/65536 precision);
independent configuration from the horizontal scaling factor is supported | Same as 58X | Same as 58X | +| Rotation | Supported for all formats except EZIP and YUV;
rotation is also unsupported when A4/A8 are used as masks | [0 ~ 3600], in units of 0.1 degrees | Same as 55X | Same as 55X | Same as 55X | +| Horizontal Mirroring | Color formats supported by all chips | Supported | Supported | Supported | Supported | +| Vertical Mirroring | Supported for all formats except EZIP | Unsupported | Unsupported | Unsupported | Supported | ```{note} -- Rotation and scaling can be performed simultaneously, supporting the same or any anchor point. -- Mirroring supports any anchor point, but cannot be combined with rotation or scaling. -- The union of the foreground, background, and output regions must not exceed 1024*1024 pixels (the foreground refers to the image region after transformation around any anchor point, including the anchor and the original image). -> For example, after rotating and scaling the foreground image around an anchor point outside the image, the union with the background and output regions must not exceed 1024. - -![EPIC Limitation Explanation](../../assets/epic_limitation.png) +- Simultaneous rotation and scaling are supported using a common, arbitrary anchor point. +- Mirroring supports arbitrary anchor points but cannot be performed simultaneously with rotation or scaling. +- The union of the foreground, background, and output regions must not exceed 1024 * 1024 pixels. (The foreground refers to the image area after transformation around an arbitrary anchor point, including the anchor point and the original image area). +> For example, if a foreground image is rotated and scaled around an external anchor point, the union of its transformed area with the background and output regions must not exceed 1024 pixels in either dimension. +![EPIC Limitations](../../assets/epic_limitation.png) ``` ## Supported Color Formats -| Input Color Format Supported | 55X | 58X | 56X | 52X | -|-------------------------------------|--------|--------|--------|--------| -| RGB565/ARGB8565/RGB888/ARGB88888 | Y | Y | Y | Y | -| L8 | N | Y | Y | Y | -| A4/A8 (Mask, Overwrite, Fill) | N | Y | Y | Y | -| YUV (YUYV/UYVY/iYUV) | N | N | Y | Y | -| A2 (Fill) | N | N | N | Y | - - -| Output Color Format Supported | 55X | 58X | 56X | 52X | -|-------------------------------------|--------|--------|--------|--------| -| RGB565/ARGB8565/RGB888/ARGB88888 | Y | Y | Y | Y | - - -## Image Handling Recommendations -- Add a transparent (or background color) border around images to be rotated or scaled to prevent edge clipping and aliasing -- To avoid discontinuity during scaling, the scaling factor difference for continuous scaling should be greater than 1/256 (i.e., scaling precision should not exceed 1/256) -- Although rotation and scaling can be performed simultaneously, it is recommended to perform only one transformation at a time for better output quality -- When enlarging, use the top-left corner of the image as the anchor point to prevent anchor jitter -- EZIP format images cannot be used for rotation - -For detailed API documentation, refer to [EPIC](#hal-epic). - - -## Color Storage Format in SRAM - -| | bit31~bit24 | bit23~bit16 | bit15~bit8 | bit7~bit0 | -| ------ | ------ | ------ | ------ | ------ | -| RGB565 | / | / | R4~R0G5~G3 | G2~G0B4~B0 | -| ARGB8565 | / | A7 ~ A0 | R4~R0G5~G3 | G2~G0B4~B0 | -| RGB888 | / | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | -| ARGB8888 | A7 ~ A0 | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | -| A8 | D7 ~ D0 | C7~C0 | B7~B0 | A7~A0 | -| A4 | / | / | D3~D0C3~C0 | B3~B0A3~A0 | -| A2 | / | / | H1H0G1G0F1F0E1E0 | D1D0C1C0B1B0A1A0 | +| Supported Input Color Formats | 55X | 58X | 56X | 52X | +| ------------------------------- | --- | --- | --- | --- | +| RGB565/ARGB8565/RGB888/ARGB8888 | Y | Y | Y | Y | +| L8 | N | Y | Y | Y | +| A4/A8 (Mask, Overwrite, Fill) | N | Y | Y | Y | +| YUV (YUYV/UYVY/iYUV) | N | N | Y | Y | +| A2 (Fill) | N | N | N | Y | + + +| Supported Output Color Formats | 55X | 58X | 56X | 52X | +| ------------------------------- | --- | --- | --- | --- | +| RGB565/ARGB8565/RGB888/ARGB8888 | Y | Y | Y | Y | + + +## Recommendations for Image-Related Issues +- Add a border of transparent pixels (or pixels matching the background color) + around images intended for rotation or scaling to prevent edge clipping during + scaling and aliasing during rotation. +- To prevent discontinuities during continuous scaling, the difference between + scaling factors must exceed 1/256 (i.e., the scaling precision must be coarser + than 1/256). +- While rotation and scaling can be performed simultaneously, it is recommended + to execute only one transformation at a time to ensure optimal output image + quality. +- It is recommended to use the upper-left corner of the image as the anchor + point during magnification to prevent anchor jitter. +- Images in EZIP format do not support rotation. + +For detailed API specifications, please refer to [EPIC](#hal-epic). + + +## Color storage format in SRAM + +| | Bits [31:24] | Bits [23:16] | Bits [15:8] | bits 7–0 | +| -------- | ------------ | ------------ | ---------------- | ---------------- | +| RGB565 | / | / | R4~R0G5~G3 | G2~G0B4~B0 | +| ARGB8565 | / | A7 ~ A0 | R4~R0G5~G3 | G2~G0B4~B0 | +| RGB888 | / | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | +| ARGB8888 | A7 ~ A0 | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | +| A8 | D7 ~ D0 | C7 ~ C0 | B7 ~ B0 | A7 ~ A0 | +| A4 | / | / | D3~D0C3~C0 | B3~B0A3~A0 | +| A2 | / | / | H1H0G1G0F1F0E1E0 | D1D0C1C0B1B0A1A0 | ```{note} -Color data is stored tightly. In A2/A4/A8 formats, A–H represent pixel points (displayed from left to right). +Color data is stored contiguously. In A2, A4, and A8 formats, the letters A through H represent individual pixels (displayed from left to right). ``` ## Using HAL EPIC -First, call {c:func}`HAL_EPIC_Init` to initialize HAL EPIC. In the {c:type}`EPIC_HandleTypeDef` structure, specify the EPIC instance (i.e., the hardware EPIC module to use). The chip has only one EPIC instance: {c:macro}`hwp_epic`. -After initialization, you can call various graphics operation interfaces to process data. +First, call {c:func}`HAL_EPIC_Init` to initialize the HAL EPIC. You must specify +the EPIC instance (the designated EPIC hardware module) within the +{c:type}`EPIC_HandleTypeDef` structure. The SoC contains a single EPIC instance, +{c:macro}`hwp_epic`. Once initialized, various graphical operation interfaces +become available for data processing. -For example, +Example: ```c static EPIC_HandleTypeDef epic_handle; void init_epic(void) { // Initialize driver and enable EPIC IRQ - HAL_NVIC_SetPriority(EPIC_IRQn, 3, 0); - HAL_NVIC_EnableIRQ(EPIC_IRQn); - - epic_handle.Instance = hwp_epic; - HAL_EPIC_Init(&epic_handle); + HAL_NVIC_SetPriority(EPIC_IRQn, 3, 0); + HAL_NVIC_EnableIRQ(EPIC_IRQn); + + epic_handle.Instance = hwp_epic; + HAL_EPIC_Init(&epic_handle); } /* EPIC IRQ Handler */ void EPIC_IRQHandler(void) { - HAL_EPIC_IRQHandler(&epic_handle); + HAL_EPIC_IRQHandler(&epic_handle); } - ``` -{c:func}`HAL_EPIC_BlendStartEx_IT` is used for interrupt mode fill, blend, rotate, and scale operations. You need to call {c:func}`HAL_EPIC_IRQHandler` in the interrupt service routine to handle the interrupt. +The {c:func}`HAL_EPIC_BlendStartEx_IT` function is used for interrupt-driven +fill, blending, rotation, and scaling operations. The +{c:func}`HAL_EPIC_IRQHandler` must be called within the Interrupt Service +Routine (ISR) to handle the resulting interrupts. ### Blending Example -As shown in Figure 1, the `blend_img` example overlays part of an image onto a background: -1. The foreground image region is (10, 20)~(59,79), the background image region is (0,0)~(99,99), and the blend region is (5,10)~(44,59). All coordinates are in the same coordinate system. -2. The foreground image is blended with the background at opacity 100. - -After blending, the color values in the region (5,10)~(44,59) are sequentially written to the background buffer. The overlapping part (the crossed area, i.e., [10,20]~[44,59]) contains the blended color, while the non-overlapping part retains the original background color. - -Note that all data buffers point to the top-left pixel of the corresponding region. For example, p_fg_img->data points to the color value of the foreground image at (10,20), and output_img.data points to the top-left pixel of the output region, i.e., (5,10). -output_img.width and output_img.total_width: output_img.width is the width of the output region (44-5+1=40), while output_img.total_width is the width of the output buffer (100, since the buffer is 100x100). EPIC will skip the remaining 60 pixels after writing 40 pixels per line and continue to the next line. -fg_img and bg_img width and total_width have the same meaning. +Figure 1 and the following `blend_img` example demonstrate overlaying a portion +of an image onto a background: +1. The foreground image is located at coordinates (10, 20) to (59, 79), the + background image spans (0, 0) to (99, 99), and the blending region is defined + from (5, 10) to (44, 59). All coordinates are specified within a single + coordinate system. +2. The foreground image is blended with the background at an opacity of 100. + +After blending, color values for the (5, 10) to (44, 59) region are written +sequentially to the background buffer. Within this region, the area overlapping +the foreground (marked with an 'X', specifically from [10, 20] to [44, 59]) +reflects the blended color, while non-overlapping areas retain the original +background colors. + +Note that all data buffers refer to the storage address of the top-left pixel of +the corresponding region. For instance, p_fg_img->data points to the pixel at +(10, 20) of the foreground image, and output_img.data points to the top-left +pixel of the output region, which is (5, 10). Regarding the configuration of +output_img.width and output_img.total_width: output_img.width represents the +width of the output region (44 - 5 + 1 = 40), whereas output_img.total_width +represents the width of the entire output buffer. Since the output buffer +corresponds to a 100x100 graphic, output_img.total_width should be set to 100. +This ensures that after the EPIC writes 40 pixels for one row, it skips the +remaining 60 pixels before updating the next row. The width and total_width +parameters for fg_img and bg_img follow the same logic. ![Figure 1: Blending](../../assets/epic_blend.png) @@ -138,36 +173,36 @@ void blend_img(void) { EPIC_LayerConfigTypeDef layers[2]; - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; + EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; + EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; EPIC_LayerConfigTypeDef output_img; HAL_StatusTypeDef ret; uint32_t buffer_start_offset; - + /* foreground image, its coordinate (10,20)~(59,79), buffer size is 50*60 */ HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; - + p_fg_img->data = fg_img_buf; + p_fg_img->x_offset = 10; + p_fg_img->y_offset = 20; + p_fg_img->width = 50; + p_fg_img->height = 60; + p_fg_img->total_width = 50; + p_fg_img->color_mode = EPIC_COLOR_RGB565; + p_fg_img->alpha = 100; + /* background image, its coordinate (0,0)~(99,99), buffer size is 100*100 */ HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - + p_bg_img->data = bg_img_buf; + p_bg_img->x_offset = 0; + p_bg_img->y_offset = 0; + p_bg_img->width = 100; + p_bg_img->height = 100; + p_bg_img->total_width = 100; + p_bg_img->color_mode = EPIC_COLOR_RGB565; + /* output image, share the same buffer as bg_img_buf, output area is (5,10)~(44,59), buffer size is 100*100 */ - HAL_EPIC_LayerConfigInit(&output_img); + HAL_EPIC_LayerConfigInit(&output_img); /* topleft pixel is (5, 10), skip (10*100+5) pixels */ buffer_start_offset = (10 - 0) * 100 * 2 + (5 - 0) * 2; output_img.data = (uint8_t *)((uint32_t)bg_img_buf + buffer_start_offset); @@ -181,23 +216,30 @@ void blend_img(void) /* output buffer width, it's different from output_img.width */ output_img.total_width = 100; output_img.color_mode = EPIC_COLOR_RGB565; - + /* set complete callback, and start EPIC */ epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); + ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); /* check ret value if any error happens */ ... /* wait for completion */ sema_take(epic_sema); } - ``` ### Rotation Example -As shown in Figure 2, the `rotate_img` example rotates the foreground image at (10,20)~(59,79) clockwise by 30 degrees around its center, blends it with the background, and updates the corresponding region in the background buffer. Pixels outside the rotated region retain the background color. -Since the bounding rectangle of the rotated image expands ([x0,y0]~[x1,y1]), you can simply set the output region to the maximum; HAL will automatically calculate the bounding rectangle. If the background and output buffers are the same, only the pixels covered by the rotated region are updated. +As shown in Figure 2, the rotate_img example rotates a foreground image, located +at (10, 20) to (59, 79), by 30 degrees clockwise around its center. After +blending with the background, the color at the corresponding position in the +background buffer is updated. Pixels falling outside the rotated image boundary +retain their original background color. Since the bounding box of the graphic +expands after rotation (defining a new area [x0, y0] to [x1, y1]), the output +region can be set to the maximum size to ensure the rotated graphic is fully +displayed. The HAL will automatically calculate the final bounding box. When the +background buffer is also used as the output buffer, only the pixels covered by +the rotated region are updated. ![Figure 1: Rotation](../../assets/epic_rot.png) @@ -210,42 +252,42 @@ void rotate_img(void) { EPIC_LayerConfigTypeDef layers[2]; - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; + EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; + EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; EPIC_LayerConfigTypeDef output_img; HAL_StatusTypeDef ret; - + /* foreground image, its coordinate (10,20)~(59,79) before rotation, buffer size is 50*60 */ HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; + p_fg_img->data = fg_img_buf; + p_fg_img->x_offset = 10; + p_fg_img->y_offset = 20; + p_fg_img->width = 50; + p_fg_img->height = 60; + p_fg_img->total_width = 50; + p_fg_img->color_mode = EPIC_COLOR_RGB565; + p_fg_img->alpha = 100; /* foreground image is rotated by 30 degree around its center */ - p_fg_img->transform_cfg.angle = 300; - p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; - p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; - p_fg_img->transform_cfg.scale_x = EPIC_INPUT_SCALE_NONE; - p_fg_img->transform_cfg.scale_y = EPIC_INPUT_SCALE_NONE; + p_fg_img->transform_cfg.angle = 300; + p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; + p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; + p_fg_img->transform_cfg.scale_x = EPIC_INPUT_SCALE_NONE; + p_fg_img->transform_cfg.scale_y = EPIC_INPUT_SCALE_NONE; /* background image, its coordinate (0,0)~(99,99), buffer size is 100*100 */ HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - + p_bg_img->data = bg_img_buf; + p_bg_img->x_offset = 0; + p_bg_img->y_offset = 0; + p_bg_img->width = 100; + p_bg_img->height = 100; + p_bg_img->total_width = 100; + p_bg_img->color_mode = EPIC_COLOR_RGB565; + /* output image, its coordinate (0,0)~(99,99), share same buffer as background image */ - HAL_EPIC_LayerConfigInit(&output_img); + HAL_EPIC_LayerConfigInit(&output_img); output_img.data = bg_img_buf; output_img.x_offset = 0; output_img.y_offset = 0; @@ -253,11 +295,11 @@ void rotate_img(void) output_img.height = 100; output_img.total_width = 100; output_img.color_mode = EPIC_COLOR_RGB565; - - + + /* set complete callback, and start EPIC */ epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); + ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); /* check ret value if any error happens */ ... /* wait for completion */ @@ -267,14 +309,17 @@ void rotate_img(void) ### Scaling Example -As shown in Figure 3, the `scale_down_img` example scales the foreground image at (10,20)~(59,79) down to 71% of its original size in both horizontal and vertical directions, keeping the center point unchanged. -Similar to rotation, you can set the output region to the maximum. If the output buffer shares the background buffer, HAL will only update the pixels in the scaled region ([x0,y0]~[x1,y1]). +As shown in Figure 3, the scale_down_img example scales a foreground image at +(10, 20) to (59, 79) down to 71%% of its original size both horizontally and +vertically, while keeping the center point fixed. Similar to rotation, the +output region can be set to maximum; if the output buffer reuses the background +buffer, the HAL will only update color values within the scaled area ([x0, y0] +to [x1, y1]). ![Figure 1: Scaling](../../assets/epic_scaling.png) ```c - /* scale down the foreground image by 1.4 and blend it with background using 100 opacity (0 is transparent, 255 is opaque) * output data is written back to background image buffer, it can also output to another buffer like blend_img_1. * @@ -283,42 +328,42 @@ void scale_down_img(void) { EPIC_LayerConfigTypeDef layers[2]; - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; + EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; + EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; EPIC_LayerConfigTypeDef output_img; HAL_StatusTypeDef ret; - + /* foreground image, its coordinate (10,20)~(59,79) before scaling */ HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; + p_fg_img->data = fg_img_buf; + p_fg_img->x_offset = 10; + p_fg_img->y_offset = 20; + p_fg_img->width = 50; + p_fg_img->height = 60; + p_fg_img->total_width = 50; + p_fg_img->color_mode = EPIC_COLOR_RGB565; + p_fg_img->alpha = 100; /* no rotation, both X and Y direction are scaled down by 1.4, the image center is in the same position after scaling */ - p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; - p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; - p_fg_img->transform_cfg.scale_x = (EPIC_INPUT_SCALE_NONE*14)/10; - p_fg_img->transform_cfg.scale_y = p_fg_img->transform_cfg.scale_x; + p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; + p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; + p_fg_img->transform_cfg.scale_x = (EPIC_INPUT_SCALE_NONE*14)/10; + p_fg_img->transform_cfg.scale_y = p_fg_img->transform_cfg.scale_x; /* background image, its coordinate (0,0)~(99,99) */ HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - + p_bg_img->data = bg_img_buf; + p_bg_img->x_offset = 0; + p_bg_img->y_offset = 0; + p_bg_img->width = 100; + p_bg_img->height = 100; + p_bg_img->total_width = 100; + p_bg_img->color_mode = EPIC_COLOR_RGB565; + /* output image, its coordinate (0,0)~(99,99), share same buffer as background image */ - HAL_EPIC_LayerConfigInit(&output_img); + HAL_EPIC_LayerConfigInit(&output_img); output_img.data = bg_img_buf; output_img.x_offset = 0; output_img.y_offset = 0; @@ -327,10 +372,10 @@ void scale_down_img(void) output_img.total_width = 100; output_img.color_mode = EPIC_COLOR_RGB565; - + /* set complete callback, and start EPIC */ epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); + ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); /* check ret value if any error happens */ ... /* wait for completion */ @@ -339,10 +384,16 @@ void scale_down_img(void) ``` ### Solid Color Fill Example -For a 100x90 buffer, fill the region (20,10)~(39,49) with color RGB(99,107,123). The configured color is in RGB888 format, and the filled color format is RGB565; the hardware will convert the color format. -Opacity is 100; 255 is opaque, 0 is transparent. -Since the first pixel to fill is at (20,10), which is offset from the buffer start, the configured start address should be the offset address. total_width is the total width of the buffer (100), width is the width of the fill region (39-20+1=20). -After filling 20 pixels per line, the remaining 80 pixels are skipped, and the next line is filled, until the specified number of lines is filled. +A buffer of size 100x90 is filled with the color RGB(99, 107, 123) in the region +(20, 10) to (39, 49). The source color is configured in RGB888 format, while the +resulting fill uses RGB565 format; the hardware performs the color format +conversion automatically. Opacity is set to 100, where 255 is fully opaque and 0 +is transparent. Because the first filled pixel is at (20, 10) and is offset from +the buffer's start address, the configured start address must account for this +offset. The total_width is the full buffer width (100), and width is the filling +region width (39 - 20 + 1 = 20). After filling a row of 20 pixels, the hardware +skips the remaining 80 pixels and moves to the next row until the specified +number of rows is completed. ```c void fill_color(void) { @@ -350,7 +401,7 @@ void fill_color(void) uint32_t start_offset; HAL_StatusTypeDef ret; - HAL_EPIC_FillDataInit(¶m); + HAL_EPIC_FillDataInit(¶m); /* topleft pixel offset in the output buffer */ start_offset = 2 * (10 * 100 + 20); param.start = (uint8_t *)((uint32_t)output_buf + start_offset); @@ -371,11 +422,11 @@ void fill_color(void) /* opacity is 100 */ param.alpha = 100; - + /* check ret if any error happens */ /* set complete callback, and start EPIC */ epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_FillStart_IT(&epic_handle, ¶m); + ret = HAL_EPIC_FillStart_IT(&epic_handle, ¶m); /* check ret value if any error happens */ ... /* wait for completion */ @@ -383,429 +434,31 @@ void fill_color(void) } ``` -### Gradient Fill -Gradient fill supports setting the colors of four corners, then interpolating the colors in between. Use the `HAL_EPIC_FillGrad_IT` interface. +### Gradient Color Fill +Gradient color filling allows color settings for the four corners followed by +uniform interpolation using the `HAL_EPIC_FillGrad_IT` interface. ### Continuous Blending -The continuous blending interface is generally used for blending small images with the same rendering properties, such as overlaying multiple characters (with the same color, format, etc., only coordinates, size, and data address change). -This set of interfaces is simple and only supports CPU polling mode. - -Usage steps: -1. `HAL_EPIC_ContBlendStart` -- Start continuous blending for the first time -2. `HAL_EPIC_ContBlendRepeat` -- For the subsequent N blends after the first -3. `HAL_EPIC_ContBlendStop` -- Exit continuous blending mode - - -### Special Transformation Function -In some scenarios, you may need to change the foreground parameters after blending each small region. The `HAL_EPIC_TransStart` interface provides this capability, offering three parameters: `hor_path`, `ver_path`, and `user_data`, which control the output region stepping and allow changing the foreground image parameters. +The continuous blending interface is typically used to composite small images +with identical rendering attributes, such as rendering a sequence of characters +where color and format remain constant while coordinates, dimensions, and data +addresses vary. This interface is characterized by its streamlined functionality +and minimal code footprint, operating exclusively in CPU polling mode. + +The functions must be called in the following sequence: +1. `HAL_EPIC_ContBlendStart` -- Initializes the first continuous blending + operation. +2. `HAL_EPIC_ContBlendRepeat` -- Executes subsequent blending operations after + the initial start. +3. `HAL_EPIC_ContBlendStop` -- Terminates continuous blending mode. + +### Special Transformation Functions +In scenarios requiring foreground parameter updates for each blended sub-region, +the `HAL_EPIC_TransStart` interface provides a helper function. It utilizes +three parameters—`hor_path`, `ver_path`, and `user_data`—to control output +region stepping while enabling dynamic modification of foreground image +parameters. ## API Reference -[](#hal-epic) - -HAL EPIC模块提供抽象的软件接口操作硬件EPIC模块,EPIC为一个2D图形引擎,它支持的特性 - -## 主要特性 - -- alpha混叠两幅图片并保存到输出buffer -- 以任意点为中心旋转图片(前景图片), 将旋转后的图片与背景图片混叠,保存混叠后的结果到输出buffer -- 缩小/放到图片(前景图),将缩放后的图片与背景图混叠,保存混叠后的结果到输出buffer -- 一次GPU操作支持先旋转后缩放,不需要中间缓存buffer -- 在给定buffer中填充不透明或半透明色 -- 所有的图形操作支持轮询和中断模式 -- 输入和输出颜色格式不同即可实现颜色格式的自动转换 -- 混叠的两幅图大小可以不同并部分重叠,还可以指定混叠后区域的一部分作为输出区域写入输出buffer -- 背景图和输出图可以复用同一个buffer, 比如背景图和输出图都使用frame buffer -- 输入图片格式支持EZIP -- 支持小数坐标混叠(55X 不支持) - - -## 输入输出限制 -| 功能 |支持的格式 | 55X | 58X | 56X | 52X | -|----------- |---------------------------|--------------------------|--------|--------|--------| -|横向缩放 | 所有芯片能支持的颜色格式 |3.8, 即缩小8倍,放大256倍, 精度1/256 | 10.16, 即缩小1024倍,放大65536倍, 精度1/65536 | 同58X | 同58X | -|纵向缩放 | 所有芯片能支持的颜色格式 |横向纵向缩放倍数固定一样,不能分开配置 | 10.16, 即缩小1024倍,放大65536倍, 精度1/65536,
且可以和横向缩放系数不一样 | 同58X | 同58X | -|旋转 | 除EZIP、YUV格式之外
另外A4/A8做mask时不能旋转 | [0 ~ 3600], 单位为0.1度 | 同55X | 同55X | 同55X | -|水平镜像 | 所有芯片能支持的颜色格式 | 支持 | 支持 | 支持 | 支持 | -|垂直镜像 | 除EZIP格式之外 | 不支持 | 不支持 | 不支持 | 支持 | - - -```{note} -- 旋转和缩放支持同时进行,并且支持同一锚点, 支持任意锚点。 -- 镜像支持任意锚点,且不能和旋转、缩放同时进行。 -- 前景、背景、输出区域的并集不超过1024*1024像素(其中前景指绕任意锚点变形后的图像区域(包括锚点和旋转前图片)) ->例如, 前景图为绕图片外锚点旋转并放大后, 与背景、输出区域的并集不超过1024 - -![EPIC限制说明](../../assets/epic_limitation.png) - -``` - -## 颜色格式支持 -| 输入颜色格式支持 | 55X | 58X | 56X | 52X | -|--------------------------------|--------|--------|--------|--------| -|RGB565/ARGB8565/RGB888/ARGB88888| Y | Y | Y | Y | -|L8 | N | Y | Y | Y | -|A4/A8 (Mask,Overwrite,Fill) | N | Y | Y | Y | -|YUV(YUYV/UYVY/iYUV) | N | N | Y | Y | -|A2 (Fill) | N | N | N | Y | - - -| 输出颜色格式支持 | 55X | 58X | 56X | 52X | -|--------------------------------|--------|--------|--------|--------| -|RGB565/ARGB8565/RGB888/ARGB88888| Y | Y | Y | Y | - - -## 关图像问题的建议 -- 用于旋转或缩放的图像在最外一圈加上一些透明像素(或者背景色),防止缩放时出现切边和旋转时出现锯齿 -- 为防止缩放出现不连续,对于连续缩放场景缩放系数差值要大于1/256(即缩放精度不能超过1/256) -- 虽然旋转和缩放可以同时进行,但建议一次只执行一种变换以保证更好的输出图形质量 -- 放大时建议使用图片左上角作为锚点,防止出现锚点抖动 -- EZIP格式的图片不能用于旋转 - -详细的API说明请参考[EPIC](#hal-epic) 。 - - -## 颜色在sram的存储格式 - -| | bit31~bit25 | bit24~bit17 | bit16~bit8 | bit7~bit0 | -| ------ | ------ | ------ | ------ | ------ | -| RGB565 | / | / | R4~R0G5~G3 | G2~G0B4~B0 | -| ARGB8565 | / | A7 ~ A0 | R4~R0G5~G3 | G2~G0B4~B0 | -| RGB888 | / | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | -| ARGB8888 | A7 ~ A0 | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | -| A8 | D7 ~ D0 | C7~C0 | B7~B0 | A7~A0 | -| A4 | / | / | D3~D0C3~C0 | B3~B0A3~A0 | -| A2 | / | / | H1H0G1G0F1F0E1E0 | D1D0C1C0B1B0A1A0 | - -```{note} -颜色数据均是紧密存放,在A2/A4/A8格式中ABCDEFGH代表像素点(从左到右显示) -``` - -## 使用HAL EPIC - -首先调用 {c:func}`HAL_EPIC_Init` 初始化HAL EPIC. 在 {c:type}`EPIC_HandleTypeDef` 结构中需指定EPIC实例(即使用的EPIC硬件模块),芯片只有一个EPIC实例 {c:macro}`hwp_epic` 。 -初始化之后即可调用各种图形操作的接口处理数据。 - -例如, -```c -static EPIC_HandleTypeDef epic_handle; - -void init_epic(void) -{ // Initialize driver and enable EPIC IRQ - HAL_NVIC_SetPriority(EPIC_IRQn, 3, 0); - HAL_NVIC_EnableIRQ(EPIC_IRQn); - - epic_handle.Instance = hwp_epic; - HAL_EPIC_Init(&epic_handle); -} - -/* EPIC IRQ Handler */ -void EPIC_IRQHandler(void) -{ - HAL_EPIC_IRQHandler(&epic_handle); -} - -``` - -{c:func}`HAL_EPIC_BlendStartEx_IT` 用于中断模式的填充、混叠、旋转和缩放操作, 需要在中断服务程序中调用 {c:func}`HAL_EPIC_IRQHandler` 处理中断。 - - -### 混叠示例 -如图1所示,示例`blend_img`中将一个图片的一部分叠到一个背景上: -1. 前景图所在区域的坐标为(10, 20)~(59,79),背景图所在区域的坐标为(0,0)~(99,99), 混叠区域坐标为(5,10)~(44,59),所有坐标均为一个坐标系中的数值 -2. 前景图以100的透明度与背景混叠 - -混叠后(5,10)~(44,59)区域的颜色值被顺序写入到背景buffer,其中与前景重叠的部分(画叉的部分,即区域[10,20]~[44,59])为混叠后的颜色,非重叠部分则是保持背景图中本来的颜色。 - -需要注意的是所有的数据buffer均为对应区域左上角像素的存放地址,例如p_fg_img->data指向前景图的坐标(10,20)所在像素的颜色值,outout_img.data指向输出区域的左上角像素,即(5,10)的颜色值。 -output_img.width和output_img.total_width的设置,output_img.width表示输出区域的宽度,即44-5+1=40, -但output_img.total_width表示输出buffer的宽度,因为输出buffer对应的图形大小为100*100,所以output_img.total_width应设为100, -这样EPIC在写完一行40个像素的数据后,会跳过余下的60个像素,继续更新下一行的数据。 -fg_img和bg_img的width和total_width也是相同的含义。 - - -![Figure 1: Blending](../../assets/epic_blend.png) - - - - -```c -void epic_cplt_callback(EPIC_HandleTypeDef *epic) -{ - /* release the semaphore to indicate epic operation done */ - sema_release(epic_sema); -} - -/* blend the foreground with background image using 100 opacity (0 is transparent, 255 is opaque) - * output buffer is same as background image buffer, usually they're both frame buffer. - * - */ -void blend_img(void) -{ - EPIC_LayerConfigTypeDef layers[2]; - - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; - EPIC_LayerConfigTypeDef output_img; - HAL_StatusTypeDef ret; - uint32_t buffer_start_offset; - - /* foreground image, its coordinate (10,20)~(59,79), buffer size is 50*60 */ - HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; - - /* background image, its coordinate (0,0)~(99,99), buffer size is 100*100 */ - HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - - /* output image, share the same buffer as bg_img_buf, - output area is (5,10)~(44,59), buffer size is 100*100 */ - HAL_EPIC_LayerConfigInit(&output_img); - /* topleft pixel is (5, 10), skip (10*100+5) pixels */ - buffer_start_offset = (10 - 0) * 100 * 2 + (5 - 0) * 2; - output_img.data = (uint8_t *)((uint32_t)bg_img_buf + buffer_start_offset); - /* output area topleft coordinate */ - output_img.x_offset = 5; - output_img.y_offset = 10; - /* output area width */ - output_img.width = 40; - /* output area height */ - output_img.height = 50; - /* output buffer width, it's different from output_img.width */ - output_img.total_width = 100; - output_img.color_mode = EPIC_COLOR_RGB565; - - /* set complete callback, and start EPIC */ - epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); - /* check ret value if any error happens */ - ... - /* wait for completion */ - sema_take(epic_sema); -} - -``` - - -### 旋转示例 - -如图2所示,示例rotate_img将位于(10,20)~(59,79)的前景图以图中心为轴顺时针旋转30度,与背景图混叠后更新背景图对应位置的颜色,落在旋转后图形外的像素仍旧保持背景图的颜色。 -由于旋转后图形覆盖的矩形区域会扩大(即[x0,y0]~[x1,y1]),为了保证旋转后的图形能被完整的显示出来,可以简单的将输出区域设成最大,HAL将自动计算旋转后的矩形区域, -当背景图buffer与输出buffer相同时, 只会更新输出buffer中被旋转区域覆盖的像素点的颜色。 - -![Figure 1: Rotation](../../assets/epic_rot.png) - -```c -/* rotate the foreground image by 30 degree (clockwisely) and blend it with background using 100 opacity (0 is transparent, 255 is opaque) - * output data is written back to background image buffer, it can also output to another buffer like blend_img_1. - * - */ -void rotate_img(void) -{ - EPIC_LayerConfigTypeDef layers[2]; - - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; - - EPIC_LayerConfigTypeDef output_img; - HAL_StatusTypeDef ret; - - /* foreground image, its coordinate (10,20)~(59,79) before rotation, buffer size is 50*60 */ - HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; - /* foreground image is rotated by 30 degree around its center */ - p_fg_img->transform_cfg.angle = 300; - p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; - p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; - p_fg_img->transform_cfg.scale_x = EPIC_INPUT_SCALE_NONE; - p_fg_img->transform_cfg.scale_y = EPIC_INPUT_SCALE_NONE; - - - /* background image, its coordinate (0,0)~(99,99), buffer size is 100*100 */ - HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - - /* output image, its coordinate (0,0)~(99,99), share same buffer as background image */ - HAL_EPIC_LayerConfigInit(&output_img); - output_img.data = bg_img_buf; - output_img.x_offset = 0; - output_img.y_offset = 0; - output_img.width = 100; - output_img.height = 100; - output_img.total_width = 100; - output_img.color_mode = EPIC_COLOR_RGB565; - - - /* set complete callback, and start EPIC */ - epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); - /* check ret value if any error happens */ - ... - /* wait for completion */ - sema_take(epic_sema); -} -``` - -### 缩放示例 - -如图3所示,示例scale_down_img将位于(10,20)~(59,79)的前景图横向与纵向都缩小到原图的71%%,同时保持图中心点位置不变。 -类似旋转,也可以简单的将输出区域设成最大,如果输出buffer复用背景buffer,HAL将只更新缩小后区域(即[x0,y0]~[x1,y1])所包含的像素的颜色值。 - -![Figure 1: Scaling](../../assets/epic_scaling.png) - - -```c - -/* scale down the foreground image by 1.4 and blend it with background using 100 opacity (0 is transparent, 255 is opaque) - * output data is written back to background image buffer, it can also output to another buffer like blend_img_1. - * - */ -void scale_down_img(void) -{ - EPIC_LayerConfigTypeDef layers[2]; - - EPIC_LayerConfigTypeDef *p_bg_img = &layers[0]; - EPIC_LayerConfigTypeDef *p_fg_img = &layers[1]; - - EPIC_LayerConfigTypeDef output_img; - HAL_StatusTypeDef ret; - - /* foreground image, its coordinate (10,20)~(59,79) before scaling */ - HAL_EPIC_LayerConfigInit(p_fg_img); - p_fg_img->data = fg_img_buf; - p_fg_img->x_offset = 10; - p_fg_img->y_offset = 20; - p_fg_img->width = 50; - p_fg_img->height = 60; - p_fg_img->total_width = 50; - p_fg_img->color_mode = EPIC_COLOR_RGB565; - p_fg_img->alpha = 100; - /* no rotation, both X and Y direction are scaled down by 1.4, - the image center is in the same position after scaling */ - p_fg_img->transform_cfg.pivot_x = p_fg_img->width / 2; - p_fg_img->transform_cfg.pivot_y = p_fg_img->height / 2; - p_fg_img->transform_cfg.scale_x = (EPIC_INPUT_SCALE_NONE*14)/10; - p_fg_img->transform_cfg.scale_y = p_fg_img->transform_cfg.scale_x; - - - /* background image, its coordinate (0,0)~(99,99) */ - HAL_EPIC_LayerConfigInit(p_bg_img); - p_bg_img->data = bg_img_buf; - p_bg_img->x_offset = 0; - p_bg_img->y_offset = 0; - p_bg_img->width = 100; - p_bg_img->height = 100; - p_bg_img->total_width = 100; - p_bg_img->color_mode = EPIC_COLOR_RGB565; - - /* output image, its coordinate (0,0)~(99,99), share same buffer as background image */ - HAL_EPIC_LayerConfigInit(&output_img); - output_img.data = bg_img_buf; - output_img.x_offset = 0; - output_img.y_offset = 0; - output_img.width = 100; - output_img.height = 100; - output_img.total_width = 100; - output_img.color_mode = EPIC_COLOR_RGB565; - - - /* set complete callback, and start EPIC */ - epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_BlendStartEx_IT(&epic_handle, &layers, 2, &output_img); - /* check ret value if any error happens */ - ... - /* wait for completion */ - sema_take(epic_sema); -} -``` - -### 纯色填充示例 -一个大小为100*90的buffer,在其(20,10)~(39, 49)区域填充颜色RGB(99,107,123),配置的颜色值为RGB888格式,填充后的颜色格式为RGB565,硬件会作颜色格式转换。 -透明度为100,255表示不透明,0表示透明。 -因为填充的第一个像素位置为(20,10),相对buffer的首地址有偏移,配置的起始地址应为偏移后的地址,total_width为buffer的总宽度,即100,width为填充区域的宽度,即(39-20+1)=20, -填充完一行20个像素的颜色后,会跳过余下的80个颜色,转到下一行继续填充,直到填完指定行数。 -```c -void fill_color(void) -{ - EPIC_FillingCfgTypeDef param; - uint32_t start_offset; - HAL_StatusTypeDef ret; - - HAL_EPIC_FillDataInit(¶m); - /* topleft pixel offset in the output buffer */ - start_offset = 2 * (10 * 100 + 20); - param.start = (uint8_t *)((uint32_t)output_buf + start_offset); - /* filled color format RGB565 */ - param.color_mode = EPIC_COLOR_RGB565; - /* filling area width */ - param.width = 20; - /* filling area height */ - param.height = 40; - /* filling buffer total width */ - param.total_width = 100; - /* red part of RGB888 */ - param.color_r = 99; - /* green part of RGB888 */ - param.color_g = 107; - /* blue part of RGB888 */ - param.color_b = 123; - /* opacity is 100 */ - param.alpha = 100; - - - /* check ret if any error happens */ - /* set complete callback, and start EPIC */ - epic_handle.XferCpltCallback = epic_cplt_callback; - ret = HAL_EPIC_FillStart_IT(&epic_handle, ¶m); - /* check ret value if any error happens */ - ... - /* wait for completion */ - sema_take(epic_sema); -} -``` - -### 渐变色填充 -渐变色填充支持设置4个脚的颜色,然后中间均匀插值,使用`HAL_EPIC_FillGrad_IT`接口。 - -### 连续混叠 -连续混叠接口一般用于相同渲染属性的小图片的混叠,比如连续叠多个字(字的颜色、格式等都相同,只是坐标、高宽、数据地址发生变化)。 -这组接口的特点是功能简单、代码量小只有CPU polling模式, - -使用时需要依次调用: -1. `HAL_EPIC_ContBlendStart` -- 第一次启动连续混叠 -2. `HAL_EPIC_ContBlendRepeat` -- 除第一次外,之后的N次混叠 -3. `HAL_EPIC_ContBlendStop` -- 退出连续混叠模式 - - -### 特殊变形函数 -在有些场景下需要每混叠一小块区域就改变一下前景的参数,`HAL_EPIC_TransStart`接口就提供了这样一个帮助函数, 它提供了3个参数`hor_path`,`ver_path`,`user_data`,通过这3组参数来控制输出区域的步进,同时提供了改变前景图片参数的可能。 - - -## API参考 -[](#hal-epic) \ No newline at end of file +[] diff --git a/docs/source/en/hal/ext_dma.md b/docs/source/en/hal/ext_dma.md index d50ccfa02..8f42bd8dd 100644 --- a/docs/source/en/hal/ext_dma.md +++ b/docs/source/en/hal/ext_dma.md @@ -1,22 +1,32 @@ # EXTDMA -EXTDMA is in HCPU, used for efficient data transfer between memory-to-memory (especially data transfer related to PSRAM, more efficient than DMA memory-to-memory transfer), and can perform real-time lossy compression of images during transfer (52x does not support). + +EXTDMA is in HCPU, used for efficient data transfer between memory-to-memory +(especially data transfer related to PSRAM, more efficient than DMA +memory-to-memory transfer), and can perform real-time lossy compression of +images during transfer (52x does not support). + ## Main Features - - Both source and destination addresses use 4-byte access, and addresses must be 4-byte aligned, length must also be 4-byte aligned - - Source and destination addresses independently support BURST access (BURST1/4/8/16), and support automatic address increment - - Single configuration maximum transfer unit count is 2^20-1, each unit is 4-byte transfer, i.e., single maximum transfer 4M bytes + - Both source and destination addresses use 4-byte access, and addresses must + be 4-byte aligned, length must also be 4-byte aligned + - Source and destination addresses independently support BURST access + (BURST1/4/8/16), and support automatic address increment + - Single configuration maximum transfer unit count is 2^20-1, each unit is + 4-byte transfer, i.e., single maximum transfer 4M bytes - Supports 3 event flags - transfer complete, half transfer, transfer error - - Can be configured as image compression mode, supports RGB565/RGB888/ARGB8888 format input + - Can be configured as image compression mode, supports RGB565/RGB888/ARGB8888 + format input ## Compression Ratios for Various Color Formats (10 levels) - - rgb565 {1.33, 1.47, 1.6, 1.73, 1.87, 1.93, 2, 2.13, 2.26, 2.4} - - rgb888 {2, 2.2, 2.4, 2.6, 2.8, 2.9, 3, 3.2, 3.4, 3.6} - - argb8888 {2.67, 2.93, 3.2, 3.47, 3.73, 3.86, 4.0, 4.27, 4.53, 4.8} + - RGB565 {1.33, 1.47, 1.6, 1.73, 1.87, 1.93, 2, 2.13, 2.26, 2.4} + - RGB888 {2, 2.2, 2.4, 2.6, 2.8, 2.9, 3, 3.2, 3.4, 3.6} + - ARGB8888 {2.67, 2.93, 3.2, 3.47, 3.73, 3.86, 4.0, 4.27, 4.53, 4.8} ## EXTDMA Example 1 -Compress and transfer 100x100 size RGB888 image at address 0x20000000 to 0x60000000, compression level 1 (i.e., 2x) +Compress and transfer 100x100 size RGB888 image at address 0x20000000 to +0x60000000, compression level 1 (i.e., 2x) ```c static volatile HAL_StatusTypeDef endflag; @@ -24,12 +34,12 @@ static EXT_DMA_HandleTypeDef DMA_Handle = {0}; void EXTDMA_IRQHandler(void) { - /* enter interrupt */ + /* Enter ISR */ rt_interrupt_enter(); - HAL_EXT_DMA_IRQHandler(&DMA_Handle); + HAL_EXT_DMA_IRQHandler(&DMA_Handle); - /* leave interrupt */ + /* Exit ISR */ rt_interrupt_leave(); } @@ -50,11 +60,11 @@ void main(void) HAL_StatusTypeDef res = HAL_OK; uint32_t len; - /*Data copy config */ - DMA_Handle.Init.SrcInc = HAL_EXT_DMA_SRC_INC | HAL_EXT_DMA_SRC_BURST16; //Source address auto-increment and burst 16 - DMA_Handle.Init.DstInc = HAL_EXT_DMA_DST_INC | HAL_EXT_DMA_DST_BURST16; //Dest address auto-increment and burst 16 + /* Data copy configuration */ + DMA_Handle.Init.SrcInc = HAL_EXT_DMA_SRC_INC | HAL_EXT_DMA_SRC_BURST16; // Source address auto-increment and 16-beat burst + DMA_Handle.Init.DstInc = HAL_EXT_DMA_DST_INC | HAL_EXT_DMA_DST_BURST16; // Destination address auto-increment and 16-beat burst - /*Compression config */ + /* Compression configuration */ DMA_Handle.Init.cmpr_en = true; if(DMA_Handle.Init.cmpr_en) { @@ -66,20 +76,19 @@ void main(void) len = DMA_Handle.Init.col_num * DMA_Handle.Init.row_num * get_byte_per_pixel(DMA_Handle.Init.src_format) / 4; - res = HAL_EXT_DMA_Init(&DMA_Handle); + res = HAL_EXT_DMA_Init(&DMA_Handle); + + HAL_EXT_DMA_RegisterCallback(&DMA_Handle, HAL_EXT_DMA_XFER_CPLT_CB_ID, dma_done_cb); + HAL_EXT_DMA_RegisterCallback(&DMA_Handle, HAL_EXT_DMA_XFER_ERROR_CB_ID, dma_err_cb); - HAL_EXT_DMA_RegisterCallback(&DMA_Handle, HAL_EXT_DMA_XFER_CPLT_CB_ID, dma_done_cb); - HAL_EXT_DMA_RegisterCallback(&DMA_Handle, HAL_EXT_DMA_XFER_ERROR_CB_ID, dma_err_cb); - /* NVIC configuration for EXTDMA transfer complete interrupt */ HAL_NVIC_SetPriority(EXTDMA_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTDMA_IRQn); - HAL_EXT_DMA_Start_IT(&DMA_Handle, 0x20000000, 0x60000000, len); + HAL_EXT_DMA_Start_IT(&DMA_Handle, 0x20000000, 0x60000000, len); } - - ``` ## API Reference -[](../api/hal/ext_dma.md) +[] + diff --git a/docs/source/en/hal/ezip.md b/docs/source/en/hal/ezip.md index adc35d2b0..01906fcc0 100644 --- a/docs/source/en/hal/ezip.md +++ b/docs/source/en/hal/ezip.md @@ -1,26 +1,38 @@ - # EZIP -HAL EZIP module provides abstract software interface to operate hardware EZIP module. EZIP module supports decompression of ezip format data. -Supported features: -- AHB and EPIC output modes. AHB mode means decompressed data is saved to specified memory address. EPIC mode means decompressed data is sent to EPIC module, allowing EPIC to read ezip format image data for blending and scaling operations (rotation of ezip format data is not supported). - For EPIC output mode, users can use HAL EPIC interface to configure EPIC to read ezip format data. HAL EPIC will configure EZIP to enter EPIC output mode, users don't need to call HAL EZIP interface. +HAL EZIP module provides abstract software interface to operate hardware EZIP +module. EZIP module supports decompression of ezip format data. Supported +features: +- AHB and EPIC output modes. AHB mode means decompressed data is saved to + specified memory address. EPIC mode means decompressed data is sent to EPIC + module, allowing EPIC to read ezip format image data for blending and scaling + operations (rotation of ezip format data is not supported). For EPIC output + mode, users can use HAL EPIC interface to configure EPIC to read ezip format + data. HAL EPIC will configure EZIP to enter EPIC output mode, users don't need + to call HAL EZIP interface. - Can specify partial region of graphics for decompression output - Supports interrupt and polling modes - AHB mode supports LZ4 and GZIP4 decompression -- Except SF32LB55X, other chip series support decompression of EZIPA animation data. The ezipa_dec module in middleware provides higher-level software support based on EPIC and EZIP drivers. Usage reference ezipa_dec module header file +- Except SF32LB55X, other chip series support decompression of EZIPA animation + data. The ezipa_dec module in middleware provides higher-level software + support based on EPIC and EZIP drivers. Usage reference ezipa_dec module + header file For detailed API documentation, refer to [EZIP](#hal-ezip). ## Using HAL EZIP -First call `HAL_EZIP_Init` to initialize HAL_EZIP. Need to specify the EZIP hardware module used (i.e., EZIP instance) in `EZIP_HandleTypeDef`. The chip has only one EZIP instance, represented by `hwp_ezip`. -Initialization only needs to be done once, then `HAL_EZIP_Decode` and `HAL_EZIP_Decode_IT` can be called to decompress data. +First call `HAL_EZIP_Init` to initialize HAL_EZIP. Need to specify the EZIP +hardware module used (i.e., EZIP instance) in `EZIP_HandleTypeDef`. The chip has +only one EZIP instance, represented by `hwp_ezip`. Initialization only needs to +be done once, then `HAL_EZIP_Decode` and `HAL_EZIP_Decode_IT` can be called to +decompress data. ```{note} Source and destination addresses need to be 4-byte aligned ``` + For example, ```c static EZIP_HandleTypeDef ezip_handle; @@ -29,7 +41,7 @@ void init_ezip(void) { // Initialize driver and enable EZIP IRQ HAL_NVIC_SetPriority(EZIP_IRQn, 3, 0); HAL_NVIC_EnableIRQ(EZIP_IRQn); - + ezip_handle.instance = hwp_ezip ; HAL_EZIP_Init(&ezip_handle); } @@ -45,11 +57,11 @@ void example_ahb(void) uint16_t width = 68; uint16_t height = 37; - /* image size if 68*37, color format is ARGB565A, output entire image, output region is (0,0,)~(67,36) */ + /* Image size: 68*37; Format: ARGB565A; Output: full image; Region: (0,0) to (67,36) */ config.input = (uint8_t *)img; config.output = malloc(width * height * 3); memset(config.output, 0, width * height * 3); - + config.start_x = 0; config.start_y = 0; config.width = 68; @@ -57,13 +69,13 @@ void example_ahb(void) config.work_mode = HAL_EZIP_MODE_EZIP; config.output_mode = HAL_EZIP_OUTPUT_AHB; - res = HAL_EZIP_Decode(&ezip_handle, &config); - - /* image size if 68*37, color format is ARGB565A, output partial image, output region is (10,20)~(39,31) */ + res = HAL_EZIP_Decode(&ezip_handle, &config); + + /* Image size: 68*37; Format: ARGB565A; Output: partial image; Region: (10,20) to (39,31) */ config.input = (uint8_t *)img; config.output = malloc(width * height * 3); memset(config.output, 0, width * height * 3); - + config.start_x = 10; config.start_y = 20; config.width = 30; @@ -71,14 +83,14 @@ void example_ahb(void) config.work_mode = HAL_EZIP_MODE_EZIP; config.output_mode = HAL_EZIP_OUTPUT_AHB; - res = HAL_EZIP_Decode(&ezip_handle, &config); + res = HAL_EZIP_Decode(&ezip_handle, &config); } ``` ### AHB output (interrupt mode) ```c -/* EZIP IRQ ISR in vector table */ +/* EZIP Interrupt Service Routine in the vector table */ void EZIP_IRQHandler(void) { HAL_EZIP_IRQHandler(ezip_handle); @@ -99,7 +111,7 @@ void example_ahb_it(void) uint16_t width = 68; uint16_t height = 37; - /* image size if 68*37, color format is ARGB565A, output entire image, output region is (0,0,)~(67,36) */ + /* Image size: 68*37; Format: ARGB565A; Output: full image; Region: (0,0) to (67,36) */ config.input = (uint8_t *)img; config.output = malloc(width * height * 3); memset(config.output, 0, width * height * 3); @@ -112,14 +124,15 @@ void example_ahb_it(void) config.output_mode = HAL_EZIP_OUTPUT_AHB; ezip_done_flag = 0; - ezip->CpltCallback = ezip_done; - res = HAL_EZIP_Decode_IT(&ezip_handle, &config); - - /* wait for interrupt, ezip_done_flag is changed to 1 in ezip_done */ + ezip->CpltCallback = ezip_done; + res = HAL_EZIP_Decode_IT(&ezip_handle, &config); + + /* Wait for interrupt; ezip_done_flag is set to 1 in the completion callback */ while (0 == ezip_done_flag) { } } ``` ## API Reference -[](#hal-ezip) +[] + diff --git a/docs/source/en/hal/facc.md b/docs/source/en/hal/facc.md index e4a872bfb..1b21c1f14 100644 --- a/docs/source/en/hal/facc.md +++ b/docs/source/en/hal/facc.md @@ -1,6 +1,7 @@ -# FACC +# Flash Accumulator (FACC) -HAL FACC module provides hardware acceleration for 8bit/16bit convolution, FIR and IIR filtering. FIR and convolution also add support for CMSIS-DSP. +HAL FACC module provides hardware acceleration for 8bit/16bit convolution, FIR +and IIR filtering. FIR and convolution also add support for CMSIS-DSP. ```{note} 55x does not support this module. 58x has one FACC module each in HCPU/LCPU, 56x only provides one FACC module in HCPU. @@ -36,7 +37,7 @@ param = (FACC_ConfigTypeDef *)&iir_iir_param; // Parameter HAL_FACC_Config(&hfacc, param); HAL_FACC_SetCoeff(&hfacc, iir_iir_coef_b, (uint16_t)sizeof(iir_iir_coef_b), iir_iir_coef_a, (uint16_t)sizeof(iir_iir_coef_a), 0); // Input filter function coefficients HAL_FACC_Start(&hfacc, iir_iir_input, facc_out, sizeof(iir_iir_input)); // Start IIR calculation. Synchronous completion. - ``` ## API Reference -[](#hal-facc) +[] + diff --git a/docs/source/en/hal/fft.md b/docs/source/en/hal/fft.md index f2a154902..d4aaa6a8d 100644 --- a/docs/source/en/hal/fft.md +++ b/docs/source/en/hal/fft.md @@ -1,6 +1,7 @@ # FFT -HAL FFT module provides abstract software interface to operate hardware FFT module, implementing FFT and DCT transforms for fixed-point numbers. +HAL FFT module provides abstract software interface to operate hardware FFT +module, implementing FFT and DCT transforms for fixed-point numbers. ```{note} SF32LB55x does not support FFT @@ -14,7 +15,13 @@ For detailed API documentation, refer to [FFT](#hal-fft). ## Using HAL FFT -First call `HAL_FFT_Init` to initialize HAL_FFT. Need to specify the FFT hardware module used (i.e., FFT instance) in #FFT_HandleTypeDef. The number of FFT instances varies by chip. For example, SF32LB58x series has two FFT instances, #hwp_fft1 and #hwp_fft2, while SF32LB56x series has only one FFT instance, #hwp_fft1. Initialization only needs to be done once, then `HAL_FFT_StartFFT`, `HAL_FFT_StartDCT` and other functions can be called to process data. +First call `HAL_FFT_Init` to initialize HAL_FFT. Need to specify the FFT +hardware module used (i.e., FFT instance) in #FFT_HandleTypeDef. The number of +FFT instances varies by chip. For example, SF32LB58x series has two FFT +instances, #hwp_fft1 and #hwp_fft2, while SF32LB56x series has only one FFT +instance, #hwp_fft1. Initialization only needs to be done once, then +`HAL_FFT_StartFFT`, `HAL_FFT_StartDCT` and other functions can be called to +process data. ```{note} Source and destination addresses need to be 4-byte aligned, supporting same source and destination addresses @@ -32,9 +39,9 @@ void init_fft(void) { // Initialize driver and enable FFT IRQ HAL_NVIC_SetPriority(FFT1_IRQn, 3, 0); HAL_NVIC_EnableIRQ(FFT1_IRQn); - + HAL_RCC_EnableModule(RCC_MOD_FFT1); - + fft_handle.Instance = hwp_fft1 ; HAL_FFT_Init(&fft_handle); } @@ -102,7 +109,7 @@ void fft_example_it(void) fft_done_flag = 0; fft_handle.CpltCallback = fft_done; res = HAL_FFT_StartFFT_IT(&fft_handle, &config); - + /* wait for interrupt, fft_done_flag is changed to 1 in fft_done */ while (0 == fft_done_flag) { @@ -111,4 +118,4 @@ void fft_example_it(void) ``` ## API Reference -[](#hal-fft) \ No newline at end of file +[] diff --git a/docs/source/en/hal/gpio.md b/docs/source/en/hal/gpio.md index 5f3913706..c66eca8c7 100644 --- a/docs/source/en/hal/gpio.md +++ b/docs/source/en/hal/gpio.md @@ -1,12 +1,13 @@ - # GPIO -HAL GPIO module provides abstract software interface to operate hardware GPIO module. -HPSYS and LPSYS each have one GPIO module with supported features: +HAL GPIO module provides abstract software interface to operate hardware GPIO +module. HPSYS and LPSYS each have one GPIO module with supported features: - Output mode -- Input mode, can detect input level to trigger interrupt, supports high level, low level, rising edge, falling edge and both edge detection +- Input mode, can detect input level to trigger interrupt, supports high level, + low level, rising edge, falling edge and both edge detection -HPSYS hardware GPIO module is `hwp_gpio1` (or called GPIO_A), LPSYS hardware GPIO module is `hwp_gpio2` (or called GPIO_B). +HPSYS hardware GPIO module is `hwp_gpio1` (or called GPIO_A), LPSYS hardware +GPIO module is `hwp_gpio2` (or called GPIO_B). ```{note} If you need to set GPIO pins for other functions, or change pull-up/pull-down drive capability, please refer to pinmux settings [PINMUX](#hal-pinmux) @@ -16,7 +17,7 @@ For detailed API documentation, refer to [GPIO](#hal-gpio). ## Using GPIO HAL -### Output Mode +### Output mode Configure `GPIO1 pin10` (i.e., GPIO_A10) as output mode, output high level ```c void write_pin(void) @@ -25,13 +26,13 @@ void write_pin(void) GPIO_InitTypeDef GPIO_InitStruct; uint16_t pin = 10; - /* set GPIO1 pin10 to output mode */ + /* Configure GPIO1 pin 10 as output */ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT; GPIO_InitStruct.Pin = pin; GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(gpio, &GPIO_InitStruct); + HAL_GPIO_Init(gpio, &GPIO_InitStruct); - /* set pin to high */ + /* Drive the pin high */ HAL_GPIO_WritePin(gpio, pin, GPIO_PIN_SET); } ``` @@ -46,35 +47,35 @@ void read_pin(void) uint16_t pin = 10; GPIO_PinState state; - /* set GPIO1 pin10 to input mode */ + /* Configure GPIO1 pin 10 as input */ GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pin = pin; GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(gpio, &GPIO_InitStruct); + HAL_GPIO_Init(gpio, &GPIO_InitStruct); - /* read pin state */ + /* Read pin state */ state = HAL_GPIO_ReadPin(gpio, pin); } ``` + ### Input Mode (With Interrupt) Configure `GPIO1 pin10` (i.e., GPIO_A10) as input mode, both edge detection ```c - -/* GPIO1 IRQ Handler in vector table */ +/* GPIO1 IRQ Handler in the vector table */ void GPIO1_IRQHandler(void) { - for (uint32_t i = 0; i <= 41; i++) + for (uint32_t i = 0; i <= 41; i++) { HAL_GPIO_EXTI_IRQHandler(hwp_gpio1, i); } } -/* override the weak Callback to add user defined action, it's called by HAL_GPIO_EXTI_IRQHandler */ +/* Override the weak callback to implement user-defined actions; called by HAL_GPIO_EXTI_IRQHandler */ void HAL_GPIO_EXTI_Callback(GPIO_TypeDef *hgpio, uint16_t GPIO_Pin) { GPIO_PinState state; - + state = HAL_GPIO_ReadPin(hgpio, GPIO_Pin); } @@ -85,22 +86,22 @@ void detect_pin(void) uint16_t pin = 10; GPIO_PinState state; - /* set GPIO1 pin10 to input mode */ + /* Configure GPIO1 pin 10 as input */ GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pin = pin; GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(gpio, &GPIO_InitStruct); - - /* enable GPIO1 pin10 double edge detection */ + HAL_GPIO_Init(gpio, &GPIO_InitStruct); + + /* Enable dual-edge detection on GPIO1 pin 10 */ GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; GPIO_InitStruct.Pin = pin; GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(gpio, &GPIO_InitStruct); - + HAL_GPIO_Init(gpio, &GPIO_InitStruct); + /* Enable GPIO1 interrupt */ HAL_NVIC_SetPriority(GPIO1_IRQn, 5, 0); HAL_NVIC_EnableIRQ(GPIO1_IRQn); } ``` ## API Reference -[](#hal-gpio) +[] diff --git a/docs/source/en/hal/gpt.md b/docs/source/en/hal/gpt.md index 6e94e3761..365ec8eb9 100644 --- a/docs/source/en/hal/gpt.md +++ b/docs/source/en/hal/gpt.md @@ -1,35 +1,53 @@ # GPT -GPT (General Purpose Timer) is based on a 16-bit counter, capable of timing, measuring input signal pulse length (input capture) or generating output waveforms (output compare and PWM). The counter itself can count up, down, or up/down, with counting clock from system pclk or external input signal, and can be prescaled by 1~65536 times. GPT has 4 channels that can be independently configured as input capture or output mode. Counting, input capture and output compare results can be notified to the system through interrupts or DMA. GPT contains master-slave mode interface for multi-level cascading, implementing multi-level counting or synchronous triggering functions. +GPT (General Purpose Timer) is based on a 16-bit counter, capable of timing, +measuring input signal pulse length (input capture) or generating output +waveforms (output compare and PWM). The counter itself can count up, down, or +up/down, with counting clock from system pclk or external input signal, and can +be prescaled by 1~65536 times. GPT has 4 channels that can be independently +configured as input capture or output mode. Counting, input capture and output +compare results can be notified to the system through interrupts or DMA. GPT +contains master-slave mode interface for multi-level cascading, implementing +multi-level counting or synchronous triggering functions. ## GPT Main Features: - 16-bit up, down, up/down auto-reload counter, maximum count 65535
-- 16-bit programmable (can be modified in real-time) prescaler, counter clock frequency division factor can be any value between 1~65536
+- 16-bit programmable (can be modified in real-time) prescaler, counter clock + frequency division factor can be any value between 1~65536
- 8-bit configurable repetition counter
-- Supports One Pulse Mode (OPM), automatically stops counter when repetition counting is complete
-- 4 independent channels, can be configured as input or output mode respectively
+- Supports One Pulse Mode (OPM), automatically stops counter when repetition + counting is complete
+- 4 independent channels, can be configured as input or output mode respectively +
- Input mode
- Rising/falling edge capture
- PWM pulse width and period capture (requires two channels)
- - Selectable from 4 input ports or 1 external trigger port, supports anti-jitter filtering and pre-frequency division
+ - Selectable from 4 input ports or 1 external trigger port, supports + anti-jitter filtering and pre-frequency division
- Output mode
- Force output high/low level
- Output high/low/toggle level when count reaches compare value
- - PWM output with configurable pulse width and period
- - Multi-channel PWM combined output, can generate multiple PWM signals with mutual relationships
+ - PWM output with configurable pulse width and period
+ - Multi-channel PWM combined output, can generate multiple PWM signals with + mutual relationships
- Single pulse/retriggerable single pulse mode output
- Master-slave mode
- - Supports multiple GPT interconnection, can generate control signals as master device while being controlled by external input or other master devices as slave device
+ - Supports multiple GPT interconnection, can generate control signals as + master device while being controlled by external input or other master + devices as slave device
- Control modes include reset, trigger, gate, etc.
- Supports synchronous start, reset of multiple GPTs
- Encoder mode input, controls counter up/down counting
-- Generate interrupt/DMA when following events occur:
- - Update: counter up overflow/down underflow, counter initialization (by software or internal/external trigger)
- - Trigger event (counter start, stop, initialization or internal/external trigger counting)
+- Generate interrupt/DMA when following events occur:
+ - Update: counter up overflow/down underflow, counter initialization (by + software or internal/external trigger)
+ - Trigger event (counter start, stop, initialization or internal/external + trigger counting)
- Input capture
- Output compare
-SF32LB55X/56/58X HCPU has two GPTs: GPT1 and GPT2, LCPU has three GPTs: GPT3, GPT4 and GPT5. +SF32LB55X/56/58X HCPU has two GPTs: GPT1 and GPT2, LCPU has three GPTs: GPT3, +GPT4 and GPT5. ## GPT Interface Mainly divided into the following groups: @@ -37,71 +55,71 @@ Mainly divided into the following groups: - Using clock to output level - Using clock to output waveform (PWM) - Using clock to collect output level -- Using clock to generate pulses
-For detailed GPT interface, please refer to [TIM](#hal-tim) +- Using clock to generate pulses
For detailed GPT interface, please refer to + [TIM](#hal-tim) ## Using GPT The following is the usage of GPT basic functions: ```c - { +{ GPT_HandleTypeDef TIM_Handle = {0}; - + TIM_Handle.Instance = GPTIM1; // Use GPTIM1 TIM_Handle.Init.Prescaler = HAL_RCC_GetPCLKFreq(GPTIM1_CORE, 1) / 1000 - 1; // Set prescaler TIM_Handle.core = GPTIM1_CORE; // Clock source is from GPTIM1_CORE TIM_Handle.Init.CounterMode = GPT_COUNTERMODE_DOWN; // Count down TIM_Handle.Init.RepetitionCounter = 0; // One shot HAL_GPT_Base_Init(&TIM_Handle); // Initialize Timer - + HAL_NVIC_SetPriority(GPTIM1_IRQn, 3, 0); // Set the TIMx priority HAL_NVIC_EnableIRQ(GPTIM1_IRQn); // Enable the TIMx global Interrupt - + __HAL_GPT_SET_AUTORELOAD(&TIM_Handle, 1500); // Set timeout counter, based on Prescaler, it is 1.5 second __HAL_GPT_SET_MODE(&TIM_Handle,GPT_OPMODE_SINGLE); // Set timer to single mode HAL_GPT_Base_Start_IT(&TIM_Handle); // Start timer. ... } - + void GPTIM1_IRQHandler(void) { HAL_GPT_IRQHandler(&TIM_Handle); } - + void HAL_GPT_PeriodElapsedCallback(GPT_HandleTypeDef *htim) { printf("Timeout\n"); } ``` -The following is GPT PWM usage. There are more PWM usage examples in _rtos/rtthread/bsp/drv_pwm.c_ for reference. +The following is GPT PWM usage. There are more PWM usage examples in +_rtos/rtthread/bsp/drv_pwm.c_ for reference. ```c - GPT_HandleTypeDef TIM_Handle = {0}; +GPT_HandleTypeDef TIM_Handle = {0}; GPT_OC_InitTypeDef oc_config = {0}; GPT_ClockConfigTypeDef clock_config = {0}; TIM_Handle.Init.Prescaler = 0; TIM_Handle.Init.CounterMode = GPT_COUNTERMODE_UP; TIM_Handle.Init.Period = 0; - HAL_GPT_Base_Init(&TIM_Handle); // Initialize GPT handle - + HAL_GPT_Base_Init(&TIM_Handle); // Initialize GPT handle + clock_config.ClockSource = GPT_CLOCKSOURCE_INTERNAL; - HAL_GPT_ConfigClockSource(&TIM_Handle, &clock_config) != HAL_OK) // Configure the clock source - - HAL_GPT_PWM_Init(&TIM_Handle); // Initialize for PWM - + HAL_GPT_ConfigClockSource(&TIM_Handle, &clock_config) != HAL_OK) // Configure the clock source + + HAL_GPT_PWM_Init(&TIM_Handle); // Initialize for PWM + oc_config.OCMode = GPT_OCMODE_PWM1; oc_config.Pulse = 0; oc_config.OCPolarity = GPT_OCPOLARITY_HIGH; oc_config.OCFastMode = GPT_OCFAST_DISABLE; - HAL_GPT_PWM_ConfigChannel(tim, &oc_config, GPT_CHANNEL_1); // Configure PWM output to channel 1 - - __HAL_GPT_SET_AUTORELOAD(htim, period - 1); // Configure duty cycle number - HAL_GPT_GenerateEvent(htim, GPT_EVENTSOURCE_UPDATE); // Update frequency value - - HAL_GPT_PWM_Start(htim, GPT_CHANNEL_1); // Start PWM - + HAL_GPT_PWM_ConfigChannel(tim, &oc_config, GPT_CHANNEL_1); // Configure PWM output to channel 1 + + __HAL_GPT_SET_AUTORELOAD(htim, period - 1); // Set the auto-reload value + HAL_GPT_GenerateEvent(htim, GPT_EVENTSOURCE_UPDATE); // Trigger an update event to apply parameters + + HAL_GPT_PWM_Start(htim, GPT_CHANNEL_1); // Start PWM output ``` ## API Reference -[](#hal-tim) \ No newline at end of file +[] diff --git a/docs/source/en/hal/hash.md b/docs/source/en/hal/hash.md index 01d4c051e..49988203c 100644 --- a/docs/source/en/hal/hash.md +++ b/docs/source/en/hal/hash.md @@ -1,18 +1,23 @@ # Hash -The HASH engine is a computational accelerator for hash sequence algorithms. Users can select different hash algorithms to calculate hash values for specific data in memory. The HASH engine is faster than software algorithms and more flexible in configuration. Users can also implement multi-threaded HASH computation through custom initial vectors. The HASH engine supports the following algorithms: +The HASH engine is a computational accelerator for hash sequence algorithms. +Users can select different hash algorithms to calculate hash values for specific +data in memory. The HASH engine is faster than software algorithms and more +flexible in configuration. Users can also implement multi-threaded HASH +computation through custom initial vectors. The HASH engine supports the +following algorithms: - SHA1 - SHA224 -- SHA256 +- SHA256 - SM3 - + ## Using Hash HAL Driver -Hash supports both polling and interrupt modes, which can call different HASH interfaces. +Hash supports both polling and interrupt modes, which can call different HASH +interfaces. Example of Hash HAL polling with block processing: ```c - // Output result stored in g_temp, length is 20 bytes for SHA1, 32 bytes for other algorithms. uint8_t g_temp[32]; @@ -26,7 +31,7 @@ uint8_t g_temp[32]; else // Continue previous calculation, load previous run result HAL_HASH_init((uint32_t*)g_temp, HASH_ALGO_SHA1, i); - + if (i+SPLIT_THRESHOLDIRQ & HASH_DONE_STAT) { @@ -88,8 +92,9 @@ void AES_IRQHandler(void) // Output Hash to g_temp, length depends on different Hash algorithms. HAL_HASH_result(g_temp); - + ... ``` ## API Reference -[](#hal-aes) +[] + diff --git a/docs/source/en/hal/i2c.md b/docs/source/en/hal/i2c.md index 0256e616e..649a27991 100644 --- a/docs/source/en/hal/i2c.md +++ b/docs/source/en/hal/i2c.md @@ -1,34 +1,34 @@ - # I2C -I2C HAL provides basic APIs for accessing I2C peripheral registers. -Main features include: +The I2C HAL provides fundamental APIs for accessing I2C peripheral registers. +Key features include: - Master mode only (I2C Master). - - Supports up to 6 instances, with 3 on HCPU and 3 on LCPU. - - 10-bit and 7-bit address support. - - DMA/interrupt mode support - - Memory mode access - -## Using I2C HAL Driver -I2C supports DMA and interrupt modes, which need to be configured before I2C startup. + - Support for up to six instances, with three allocated to the HCPU and three + to the LCPU. + - Support for 7-bit and 10-bit addressing. + - Support for DMA and interrupt modes. + - Memory-mode access support. -Example of using I2C HAL with memory mode and polling: +## Using the I2C HAL Driver +The I2C HAL supports DMA and interrupt modes, which must be configured before +initializing the I2C peripheral. -```c +Example: Using I2C HAL in memory mode with polling: +```c I2C_HandleTypeDef i2c_Handle = {0}; uint16_t DevAddress, MemAddress, MemAddSize, Size; uint32_t Timeout; uint8_t *pData; -/* initial I2C controller */ +/* Initialize I2C controller */ i2c_Handle.Mode = HAL_I2C_MODE_MASTER; i2c_Handle.Instance = hwp_i2c1; i2c_Handle.core = CORE_ID_LCPU; i2c_Handle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; i2c_Handle.Init.ClockSpeed = 400000; i2c_Handle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; -ret = HAL_I2C_Init(&i2c_Handle); +ret = HAL_I2C_Init(&i2c_Handle); if (ret != HAL_OK) { return; @@ -42,18 +42,17 @@ Size = 256; Timeout = 100; // 100ms /* I2C Write */ -HAL_I2C_Mem_Write(&i2c_Handle, DevAddress, MemAddress, MemAddSize, pData, Size, Timeout); +HAL_I2C_Mem_Write(&i2c_Handle, DevAddress, MemAddress, MemAddSize, pData, Size, Timeout); /* I2C read */ -HAL_I2C_Mem_Read(&i2c_Handle, DevAddress, MemAddress, MemAddSize, pData,Size, Timeout); +HAL_I2C_Mem_Read(&i2c_Handle, DevAddress, MemAddress, MemAddSize, pData,Size, Timeout); ... ``` -Sample for using I2C HAL with register mode and DMA: +Example: Using I2C HAL in register mode with DMA: ```c - uint16_t DevAddress, Size; uint8_t *pData; I2C_HandleTypeDef handle = {0}; @@ -61,21 +60,21 @@ static struct dma_config i2c_dmarx; // allocated buffer for dma handle in I2C in static struct dma_config i2c_dmatx; struct dma_config dma_set; -/* initial I2C DMA info */ +/* Initialize I2C DMA configuration */ dma_set.dma_rcc = I2C1_DMA_RCC; dma_set.Instance = I2C1_DMA_INSTANCE; dma_set.dma_irq = I2C1_DMA_IRQ; dma_set.request = I2C1_DMA_REQUEST; -/* bind dma handle */ +/* Bind DMA handle */ //__HAL_LINKDMA(handle, hdmarx, i2c_dmarx); //__HAL_LINKDMA(handle, hdmatx, i2c_dmatx); -handle.hdmarx = &i2c_dmarx; -handle.hdmatx = &i2c_dmatx; -HAL_I2C_DMA_Init(&handle, &dma_set, &dma_set); +handle.hdmarx = &i2c_dmarx; +handle.hdmatx = &i2c_dmatx; +HAL_I2C_DMA_Init(&handle, &dma_set, &dma_set); -/* Enable RX dma interrupt by default */ +/* Enable RX DMA interrupt */ HAL_NVIC_SetPriority(dma_set.dma_irq, 0, 0); HAL_NVIC_EnableIRQ(dma_set.dma_irq); @@ -85,21 +84,21 @@ handle.Init.ClockSpeed = 400000; handle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; handle.core = CORE_ID_LCPU; handle.Mode = HAL_I2C_MODE_MASTER; -HAL_I2C_Init(&handle); +HAL_I2C_Init(&handle); /* I2C Write */ HAL_DMA_Init(handle.dma_tx); DevAddress = 0x76; // set slave i2c device id pData = malloc(256); Size = 256; -HAL_I2C_Master_Transmit_DMA(&handle, DevAddress,pData, Size); +HAL_I2C_Master_Transmit_DMA(&handle, DevAddress,pData, Size); -/* I2C read */ +/* I2C Read */ HAL_DMA_Init(handle.dma_rx); -HAL_I2C_Master_Receive_DMA(&handle, DevAddress,pData, Size); +HAL_I2C_Master_Receive_DMA(&handle, DevAddress,pData, Size); ... ``` ## API Reference -[](#hal-i2c) +[] diff --git a/docs/source/en/hal/i2s.md b/docs/source/en/hal/i2s.md index fa27fea19..296342173 100644 --- a/docs/source/en/hal/i2s.md +++ b/docs/source/en/hal/i2s.md @@ -1,11 +1,14 @@ - # I2S -I2S HAL provides basic APIs for accessing I2S peripheral registers. SF32LB55X has two instances I2S1/I2S2 (both in HPSYS), SF32LB58X has three instances I2S1/I2S2/I2S3 (I2S1 and I2S2 in HPSYS, I2S3 in LPSYS). -For I2S1, it only supports RX functionality, -For I2S2/I2S3, it supports both RX and TX. When using I2S2 RX, its clock comes from its TX, so if using I2S2 as RX, its TX also needs to be enabled to provide the clock. -SF32LB56X has only one full-featured I2S1, equivalent to I2S2 of SF32LB58X, supporting both RX and TX. -The clock of SF32LB55X can only be xtal48M, while SF32LB58X and SF32LB56X clocks can be either xtal48M or PLL. +I2S HAL provides basic APIs for accessing I2S peripheral registers. SF32LB55X +has two instances I2S1/I2S2 (both in HPSYS), SF32LB58X has three instances +I2S1/I2S2/I2S3 (I2S1 and I2S2 in HPSYS, I2S3 in LPSYS). For I2S1, it only +supports RX functionality, For I2S2/I2S3, it supports both RX and TX. When using +I2S2 RX, its clock comes from its TX, so if using I2S2 as RX, its TX also needs +to be enabled to provide the clock. SF32LB56X has only one full-featured I2S1, +equivalent to I2S2 of SF32LB58X, supporting both RX and TX. The clock of +SF32LB55X can only be xtal48M, while SF32LB58X and SF32LB56X clocks can be +either xtal48M or PLL. ```{note} SF32LB52X is the same as SF32LB56X. ``` @@ -17,13 +20,18 @@ Main features include: - Master/slave mode support. ## Using I2S HAL Driver -The following description uses a full-featured I2S as an example. When I2S is in master mode, the RX clock is provided by TX, so slave_mode in tx_cfg should be configured as 0, and slave_mode in rx_cfg should be configured as 1. -When I2S is in SLAVE mode, the clock is provided by external I2S, so slave_mode in both tx_cfg and rx_cfg should be configured as 1. -When using xtal48M as clock source, the bclk and lrclk timing may not meet the requirements of the peer I2S (this needs attention). When using PLL as clock source, the audcodec module needs to be enabled, and all audio modules must have consistent clocks. -You can refer to the implementation in drv_i2s. +The following description uses a full-featured I2S as an example. When I2S is in +master mode, the RX clock is provided by TX, so slave_mode in tx_cfg should be +configured as 0, and slave_mode in rx_cfg should be configured as 1. When I2S is +in SLAVE mode, the clock is provided by external I2S, so slave_mode in both +tx_cfg and rx_cfg should be configured as 1. When using xtal48M as clock source, +the bclk and lrclk timing may not meet the requirements of the peer I2S (this +needs attention). When using PLL as clock source, the audcodec module needs to +be enabled, and all audio modules must have consistent clocks. You can refer to +the implementation in drv_i2s. ```c - #define CLOCK_USING_XTAL 0 //PLL clock need open audcodec +#define CLOCK_USING_XTAL 0 //PLL clock need open audcodec #if CLOCK_USING_XTAL //crystal static CLK_DIV_T txrx_clk_div[9] = {{48000, 125, 125, 5}, {44100, 136, 136, 4}, {32000, 185, 190, 5}, {24000, 250, 250, 10}, {22050, 272, 272, 8}, {16000, 384, 384, 12}, {12000, 500, 500, 20}, {11025, 544, 544, 16}, { 8000, 750, 750, 30} @@ -74,7 +82,7 @@ static CLK_DIV_T txrx_clk_div[9] = {{48000, 64, 64, 2}, {44100, 64, 64, 2}, hi2s->Init.rx_cfg.lrck_invert = 0; hi2s->Init.rx_cfg.clk_div_index = 5;//for 16k samplerate hi2s->Init.rx_cfg.clk_div = &txrx_clk_div[hi2s->Init.rx_cfg.clk_div_index]; - + #if CLOCK_USING_XTAL __HAL_I2S_CLK_XTAL(hi2s); // xtal use 48M for asic @@ -104,10 +112,10 @@ static CLK_DIV_T txrx_clk_div[9] = {{48000, 64, 64, 2}, {44100, 64, 64, 2}, __HAL_I2S_TX_ENABLE(hi2s); /* Start I2S Receive with polling mode */ ret = HAL_I2S_Receive(hi2s, pData, EXAMPLE_I2S_TRANS_SIZE, 100); - + /*Check received data */ - // pData + // pData ``` ## API Reference -[](#hal-i2s) +[] diff --git a/docs/source/en/hal/index.md b/docs/source/en/hal/index.md index 5154ddec4..ca30e934a 100644 --- a/docs/source/en/hal/index.md +++ b/docs/source/en/hal/index.md @@ -5,10 +5,13 @@ :glob: * - ``` -The Hardware Abstraction Layer (HAL) defines chip hardware access interfaces that users can use to access underlying hardware resources. HAL interfaces are compatible across different chip series, facilitating application portability across different chip platforms. + +The Hardware Abstraction Layer (HAL) defines chip hardware access interfaces +that users can use to access underlying hardware resources. HAL interfaces are +compatible across different chip series, facilitating application portability +across different chip platforms. ```{only} SF32LB55X The SF32LB55x series has two CPUs: HCPU for high-performance computing and LCPU for executing power-sensitive tasks. Users can run high-performance processing on HCPU, such as graphics display, while implementing low-power functions on LCPU, such as BLE and sensor data processing. This allows HCPU to be shut down when processing low-power tasks, reducing system power consumption. @@ -26,11 +29,21 @@ The SF32LB52x series has two CPUs: HCPU for high-performance computing, and LCPU The SF32LB58x series has three CPUs: HCPU for high-performance computing, ACPU can be used for Audio DSP processing, and LCPU for executing power-sensitive tasks. Users can run high-performance processing on HCPU, such as graphics display, while implementing low-power functions on LCPU, such as BLE and sensor data processing. This allows HCPU to be shut down when processing low-power tasks, reducing system power consumption. ``` -Software running on HCPU can typically access LCPU hardware resources, but needs to ensure that LCPU is in an active running state and LCPU is not using these resources. When HCPU/ACPU software uses LCPU hardware, it needs to wake up LCPU first during sleep-wake cycles to ensure access to LCPU hardware resources, otherwise it will cause system access failures and crashes. -Software running on LCPU cannot use HCPU hardware resources and can only access some HCPU registers when HCPU/ACPU is in an active running state. This type of access is not recommended. +Software running on HCPU can typically access LCPU hardware resources, but needs +to ensure that LCPU is in an active running state and LCPU is not using these +resources. When HCPU/ACPU software uses LCPU hardware, it needs to wake up LCPU +first during sleep-wake cycles to ensure access to LCPU hardware resources, +otherwise it will cause system access failures and crashes. + +Software running on LCPU cannot use HCPU hardware resources and can only access +some HCPU registers when HCPU/ACPU is in an active running state. This type of +access is not recommended. + ## HAL Porting -The following functions need to be implemented when porting to other real-time operating systems: +The following functions need to be implemented when porting to other real-time +operating systems: + diff --git a/docs/source/en/hal/lcdc.md b/docs/source/en/hal/lcdc.md index 93515a990..bfe8b8cf7 100644 --- a/docs/source/en/hal/lcdc.md +++ b/docs/source/en/hal/lcdc.md @@ -1,28 +1,33 @@ - # LCDC -LCDC (LCD Controller) provides a unified interface for displays without needing to concern about specific physical connections like SPI, parallel interface, or other physical connections. Only the physical interface and parameters need to be configured during initialization, and afterwards a unified interface is used. +LCDC (LCD Controller) provides a unified interface for displays without needing +to concern about specific physical connections like SPI, parallel interface, or +other physical connections. Only the physical interface and parameters need to +be configured during initialization, and afterwards a unified interface is used. -Additionally, it supports layer alpha blending. Layers are as follows (in stacking order): +Additionally, it supports layer alpha blending. Layers are as follows (in +stacking order): - Solid color background - Layer 0 - Layer 1 (52x not supported) ## Supported Physical Interfaces: -|Name | 55X | 58X | 56X | 52X | -|--------------------|--------|--------|--------|--------| -|3SPI (1/2 data line)| Y | Y | Y | Y | -|4SPI (1/2 data line)| Y | Y | Y | Y | -|QAD-SPI | Y | Y | Y | Y | -|DSI Command Mode | Y | Y | N | N | -|DSI Video Mode | N | Y | N | N | -|AHB output to SRAM/PSRAM| Y | Y | Y | Y | -|DBI 8080-8bit | Y | Y | Y | Y | -|JDI | Y | Y | Y | Y | -|DPI | Y | Y | Y | Y | +| Name | 55X | 58X | 56X | 52X | +| --------------------------- | --- | --- | --- | --- | +| 3-wire SPI (1/2 data lines) | Y | Y | Y | Y | +| 4-wire SPI (1/2 data lines) | Y | Y | Y | Y | +| Quad-SPI | Y | Y | Y | Y | +| DSI Command Mode | Y | Y | N | N | +| DSI Video Mode | N | Y | N | N | +| AHB output to SRAM/PSRAM | Y | Y | Y | Y | +| 8-bit DBI 8080 | Y | Y | Y | Y | +| JDI | Y | Y | Y | Y | +| DPI | Y | Y | Y | N | + ## Supported Speeds: - - SPI (including 3SPI, 4SPI, QAD-SPI) speed = HCLK/divider, where divider is 2~255 + - SPI (including 3SPI, 4SPI, QAD-SPI) speed = HCLK/divider, where divider is + 2~255 - DSI only supports several speeds configured by DSI_Clock_Freq - DBI same as SPI @@ -42,39 +47,42 @@ Additionally, it supports layer alpha blending. Layers are as follows (in stacki - L8 (55x not supported) - RGB565_SWAP (55x not supported) -| | bit31~bit25 | bit24~bit17 | bit16~bit8 | bit7~bit0 | -| ------ | ------ | ------ | ------ | ------ | -| RGB332 | / | / | / |R2~R0G2~G0B1~B0| -| RGB565 | / | / | R4~R0G5~G3 | G2~G0B4~B0 | -| RGB565_SWAP| / | / | G2~G0B4~B0 | R4~R0G5~G3 | -| ARGB8565 | / | A7 ~ A0 | R4~R0G5~G3 | G2~G0B4~B0 | -| RGB888 | / | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | -| ARGB8888 | A7 ~ A0 | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | +| | bits 31–25 | bits 24–17 | bits 16–8 | bits 7–0 | +| ----------- | ---------- | ---------- | ---------- | --------------- | +| RGB332 | / | / | / | R2~R0G2~G0B1~B0 | +| RGB565 | / | / | R4~R0G5~G3 | G2~G0B4~B0 | +| RGB565_SWAP | / | / | G2~G0B4~B0 | R4~R0G5~G3 | +| ARGB8565 | / | A7 ~ A0 | R4~R0G5~G3 | G2~G0B4~B0 | +| RGB888 | / | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | +| ARGB8888 | A7 ~ A0 | R7 ~ R0 | G7 ~ G0 | B7 ~ B0 | ## Other Features - - Supports specified drawing area, and this area can arbitrarily intersect with the given output buffer area + - Supports specified drawing area, and this area can arbitrarily intersect + with the given output buffer area - Supports frame sync and line sync - - Supports synchronous & asynchronous (interrupt mode) data transmission interfaces + - Supports synchronous & asynchronous (interrupt mode) data transmission + interfaces + +![Figure 1: LCD output buffer, drawing area (ROI) refresh area on +LCD](../../assets/hal_lcdc.png) -![Figure 1: LCD output buffer, drawing area (ROI) refresh area on LCD](../../assets/hal_lcdc.png) ## LCDC Usage Example 1 Driving ST7789H2 display through 4SPI 1data interface ```c - static LCDC_InitTypeDef lcdc_int_cfg = { - .lcd_itf = LCDC_INTF_SPI_DCX_1DATA, //Choose 4SPI 1data interface - .freq = 24000000, //SPI clock 24MHz - .color_mode = LCDC_PIXEL_FORMAT_RGB565, //LCDC output color format RGB565 + .lcd_itf = LCDC_INTF_SPI_DCX_1DATA, // Select 4-line SPI 1-data interface + .freq = 24000000, // SPI clock: 24 MHz + .color_mode = LCDC_PIXEL_FORMAT_RGB565, // LCDC output color format: RGB565 .cfg = { .spi = { - .dummy_clock = 1, //Dummy clock between cmd & data in read mode - .syn_mode = HAL_LCDC_SYNC_VER, //TE sychronization mode - .vsyn_polarity = 0, //TE pin polarity - .vsyn_delay_us = 1000, //Delay 1ms to send frame buffer right after received TE signal - .hsyn_num = 0, //Hsyn num if syn_mode is HAL_LCDC_SYNC_VERHOR + .dummy_clock = 1, // Dummy clocks between command and data in read mode + .syn_mode = HAL_LCDC_SYNC_VER, // TE synchronization mode + .vsyn_polarity = 0, // TE pin polarity + .vsyn_delay_us = 1000, // Delay 1ms before sending frame buffer after TE signal + .hsyn_num = 0, // Hsync count if syn_mode is HAL_LCDC_SYNC_VERHOR }, }, @@ -88,18 +96,18 @@ __ROM_USED void LCDC1_IRQHandler(void) rt_interrupt_enter(); HAL_LCDC_IRQHandler(lcdc); - + rt_interrupt_leave(); } void HAL_LCDC_SendLayerDataCpltCbk(LCDC_HandleTypeDef *lcdc) { - /*Send layer data completed*/ + /* Layer data transmission complete */ } /** - * @brief Power on the LCD. + * @brief Powers on the LCD. * @param None * @retval None */ @@ -107,36 +115,36 @@ void ST7789H2_Init(LCDC_HandleTypeDef *hlcdc) { uint8_t parameter[14]; - //Initalize interface - memcpy(&hlcdc->Init, &lcdc_int_cfg, sizeof(LCDC_InitTypeDef)); + // Initialize interface + memcpy(&hlcdc->Init, &lcdc_int_cfg, sizeof(LCDC_InitTypeDef)); HAL_LCDC_Init(hlcdc); - //Generate a reset pulse to reset ST7789H2 + // Generate a reset pulse to reset the ST7789H2 HAL_LCDC_ResetLCD(hlcdc, LCDC_RESX_NEG_PULSE, 10); - /************* ST7789H2 initialize sequence start ************************/ - /*Sleep In Command */ + /************* ST7789H2 initialization sequence start ************************/ + /* Sleep In command */ HAL_LCDC_WriteU8Reg(hlcdc, ST7789H2_SLEEP_IN, (uint8_t *)NULL, 0); - /* Wait for 10ms */ + /* Wait 10ms */ HAL_Delay(10); - /* SW Reset Command */ + /* SW Reset command */ HAL_LCDC_WriteU8Reg(hlcdc, 0x01, (uint8_t *)NULL, 0); - /* Wait for 200ms */ + /* Wait 200ms */ HAL_Delay(200); - /* Sleep Out Command */ + /* Sleep Out command */ HAL_LCDC_WriteU8Reg(hlcdc, ST7789H2_SLEEP_OUT, (uint8_t *)NULL, 0); - /* Wait for 120ms */ + /* Wait 120ms */ HAL_Delay(120); ... - /************* ST7789H2 initialize sequence end ************************/ + /************* ST7789H2 initialization sequence end ************************/ } /** - * @brief ST7789H2 read mode should slow down SPI clock to 4MHz - * @param enable: false - write spi mode | true - read spi mode + * @brief In read mode, the ST7789H2 SPI clock should be reduced to 4 MHz. + * @param enable: false = write SPI mode, true = read SPI mode * @retval None */ void ST7789H2_ReadMode(LCDC_HandleTypeDef *hlcdc, bool enable) @@ -145,96 +153,93 @@ void ST7789H2_ReadMode(LCDC_HandleTypeDef *hlcdc, bool enable) { if (enable) { - HAL_LCDC_SetFreq(hlcdc, 4000000); //SPI clock is 4MHz on Read mode + HAL_LCDC_SetFreq(hlcdc, 4000000); // SPI clock is 4 MHz in read mode } else { - HAL_LCDC_SetFreq(hlcdc, lcdc_int_cfg.freq); //Restore normal frequency + HAL_LCDC_SetFreq(hlcdc, lcdc_int_cfg.freq); // Restore normal frequency } } } /** - * @brief Reads the selected LCD Register. + * @brief Reads the selected LCD register. * @param RegValue: Address of the register to read * @param ReadSize: Number of bytes to read - * @retval LCD Register Value. + * @retval LCD register value. */ uint32_t ST7789H2_ReadData(LCDC_HandleTypeDef *hlcdc, uint16_t RegValue, uint8_t ReadSize) { uint32_t rd_data = 0; - //Entry read mode + // Enter read mode ST7789H2_ReadMode(hlcdc, true); - HAL_LCDC_ReadU8Reg(hlcdc, RegValue, (uint8_t *)&rd_data, ReadSize); + HAL_LCDC_ReadU8Reg(hlcdc, RegValue, (uint8_t *)&rd_data, ReadSize); - //Recovery to normal mode + // Revert to normal mode ST7789H2_ReadMode(hlcdc, false); return rd_data; } /** - * @brief Set LCD & LCDC clip area + * @brief Sets the LCD and LCDC clip area. * @param hlcdc LCD controller handle - * @param Xpos0 - Clip area left coordinate, base on LCD top-left, same as below. - * @param Ypos0 - Clip area top coordinate - * @param Xpos1 - Clip area right coordinate - * @param Ypos1 - Clip area bottom coordinate + * @param Xpos0 - Left coordinate of the clip area (relative to LCD top-left). + * @param Ypos0 - Top coordinate of the clip area. + * @param Xpos1 - Right coordinate of the clip area. + * @param Ypos1 - Bottom coordinate of the clip area. */ void ST7789H2_SetRegion(LCDC_HandleTypeDef *hlcdc, uint16_t Xpos0, uint16_t Ypos0, uint16_t Xpos1, uint16_t Ypos1) { uint8_t parameter[4]; - //Set LCDC clip area + // Set LCDC clip area HAL_LCDC_SetROIArea(hlcdc, Xpos0, Ypos0, Xpos1, Ypos1); - //Set LCD clip area - parameter[0] = (Xpos0) >> 8; - parameter[1] = (Xpos0) & 0xFF; - parameter[2] = (Xpos1) >> 8; - parameter[3] = (Xpos1) & 0xFF; + // Set LCD clip area + parameter[0] = (Xpos0) >> 8; + parameter[1] = (Xpos0) & 0xFF; + parameter[2] = (Xpos1) >> 8; + parameter[3] = (Xpos1) & 0xFF; HAL_LCDC_WriteU8Reg(hlcdc, ST7789H2_CASET, parameter, 4); - parameter[0] = (Ypos0) >> 8; - parameter[1] = (Ypos0) & 0xFF; - parameter[2] = (Ypos1) >> 8; - parameter[3] = (Ypos1) & 0xFF; + parameter[0] = (Ypos0) >> 8; + parameter[1] = (Ypos0) & 0xFF; + parameter[2] = (Ypos1) >> 8; + parameter[3] = (Ypos1) & 0xFF; HAL_LCDC_WriteU8Reg(hlcdc, ST7789H2_RASET, parameter, 4); } /** - * @brief Send layer data to LCD + * @brief Sends layer data to the LCD. * @param hlcdc LCD controller handle - * @param RGBCode - Pointer to layer data - * @param Xpos0 - Layer data left coordinate, base on LCD top-left, same as below. - * @param Ypos0 - Layer data top coordinate - * @param Xpos1 - Layer data right coordinate - * @param Ypos1 - Layer data bottom coordinate + * @param RGBCode - Pointer to the layer data. + * @param Xpos0 - Left coordinate of the layer data (relative to LCD top-left). + * @param Ypos0 - Top coordinate of the layer data. + * @param Xpos1 - Right coordinate of the layer data. + * @param Ypos1 - Bottom coordinate of the layer data. */ void ST7789H2_WriteMultiplePixels(LCDC_HandleTypeDef *hlcdc, const uint8_t *RGBCode, uint16_t Xpos0, uint16_t Ypos0, uint16_t Xpos1, uint16_t Ypos1) { uint32_t size; - if ((Xpos0 > Xpos1) || (Ypos0 > Ypos1)) + if ((Xpos0 > Xpos1) || (Ypos0 > Ypos1)) { - //Invalid coordinates + // Invalid coordinates return; } - //Set default layer data + // Set default layer data HAL_LCDC_LayerSetData(hlcdc, HAL_LCDC_LAYER_DEFAULT, (uint8_t *)RGBCode, Xpos0, Ypos0, Xpos1, Ypos1); - //Write datas to LCD register + // Write data to LCD register via interrupt HAL_LCDC_SendLayerData2Reg_IT(hlcdc, 0x2c, 1); } - - - ``` ## API Reference -[](#hal-i2c) +[] diff --git a/docs/source/en/hal/lptim.md b/docs/source/en/hal/lptim.md index d4e25f323..2961f7a8a 100644 --- a/docs/source/en/hal/lptim.md +++ b/docs/source/en/hal/lptim.md @@ -1,13 +1,24 @@ +# Low-Power Timer (LPTIM) -# LPTIM - -The LPTIM (Low Power Timer) in this design is based on a 24-bit counter that can implement timing, output waveform generation (output compare and PWM), and system wake-up functions. The counter is an up-counter, and the counting clock can be the system's internal APB clock, low-power clock, or external input signals from the system. It can perform prescaling up to 128 times and cyclic counting up to 256 times. Output waveforms can be generated based on counting results, and it can generate interrupts to notify the CPU or generate wake-up signals to wake the system from low-power modes. When using external clocks as counting clocks, it can count and generate wake-up signals independent of internal clocks, allowing the system to shut down internal clocks. +The LPTIM (Low Power Timer) in this design is based on a 24-bit counter that can +implement timing, output waveform generation (output compare and PWM), and +system wake-up functions. The counter is an up-counter, and the counting clock +can be the system's internal APB clock, low-power clock, or external input +signals from the system. It can perform prescaling up to 128 times and cyclic +counting up to 256 times. Output waveforms can be generated based on counting +results, and it can generate interrupts to notify the CPU or generate wake-up +signals to wake the system from low-power modes. When using external clocks as +counting clocks, it can count and generate wake-up signals independent of +internal clocks, allowing the system to shut down internal clocks. ## LPTIM Main Features: -- 24-bit up-counter with automatic reload, maximum count 16777215 (Z0 is 16-bit with maximum count 65535)
+- 24-bit up-counter with automatic reload, maximum count 16777215 (Z0 is 16-bit + with maximum count 65535)
- Counting clock selection
- Internal clocks including APB clock, low-power clock, etc.
- - Selectable edge external input signals (IO port or comparator results), can use internal clock for debouncing filtering, or count independently without relying on internal clock
+ - Selectable edge external input signals (IO port or comparator results), + can use internal clock for debouncing filtering, or count independently + without relying on internal clock
- 8-level prescaling, counting clock division factor from 2^0 to 2^7
- 1~256 cycle counts
- Counting modes
@@ -27,7 +38,8 @@ The LPTIM (Low Power Timer) in this design is based on a 24-bit counter that can - Output compare
- External trigger (only generates interrupt, no wake-up signal)
-SF32LB55X/56X/58X HCPU has one LPTIM (LPTIM1), LCPU has two LPTIMs (LPTIM2 and LPTIM3). +SF32LB55X/56X/58X HCPU has one LPTIM (LPTIM1), LCPU has two LPTIMs (LPTIM2 and +LPTIM3). For detailed LPTIM interfaces, please refer to [LPTIM](#hal-lptim) @@ -35,8 +47,8 @@ For detailed LPTIM interfaces, please refer to [LPTIM](#hal-lptim) Here are the basic LPTIM function usages: ```c - LPTIM_HandleTypeDef TIM_Handle = {0}; - +LPTIM_HandleTypeDef TIM_Handle = {0}; + { ... HAL_LPTIM_InitDefault(&TIM_Handle); // Set default setting for LPTIM @@ -45,19 +57,19 @@ Here are the basic LPTIM function usages: HAL_NVIC_SetPriority(LPTIM1_IRQn, 3, 0); // Set the TIMx priority HAL_NVIC_EnableIRQ(LPTIM1_IRQn); // nable the TIMx global Interrupt - + __HAL_LPTIM_CLEAR_PRESCALER(tim, LPTIM_PRESCALER_DIV128); __HAL_LPTIM_SET_PRESCALER(tim, LPTIM_PRESCALER_DIV1); // Set prescale TIM_Handle.Mode = HAL_LPTIM_ONESHOT; // One shot timer HAL_LPTIM_Counter_Start_IT(&TIM_Handle, 1000); // Start timer to count 1000 from low power crystal source ... } - + void LPTIM1_IRQHandler(void) { HAL_LPTIM_IRQHandler(&TIM_Handle); } - + void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *htim) { printf("Timeout\n"); @@ -67,4 +79,4 @@ Here are the basic LPTIM function usages: For LPTIM PWM usage, please refer to _/rtos/rtthread/bsp/drv_pwm.c_. ## API Reference -[](#hal-lptim) +[] diff --git a/docs/source/en/hal/mailbox.md b/docs/source/en/hal/mailbox.md index 267a0754e..dc887d700 100644 --- a/docs/source/en/hal/mailbox.md +++ b/docs/source/en/hal/mailbox.md @@ -1,89 +1,97 @@ - # MAILBOX -The Mailbox HAL driver provides high-level APIs to use the hardware mailbox module. Each subsystem has a hardware mailbox module. It can be used to trigger interrupts to notify other subsystems or protect hardware resources shared by multiple subsystems. - -Main features include: -- Trigger interrupts to notify other subsystems. For example, HPSYS mailbox group 1 (#H2L_MAILBOX) is used to trigger LPSYS interrupts. -- Each mailbox group has 16 channels and can trigger all interrupts simultaneously. -- Mailbox interrupts can automatically wake up subsystems in _LIGHT/DEEP/STANDBY_ low-power modes. -- The Mailbox module has two mutex channels to protect shared resources. All subsystems can access them. - +The Mailbox HAL driver provides high-level APIs to use the hardware mailbox +module. Each subsystem has a hardware mailbox module. It can be used to trigger +interrupts to notify other subsystems or protect hardware resources shared by +multiple subsystems. +- Trigger interrupts to notify other subsystems. For example, HPSYS mailbox + group 1 (#H2L_MAILBOX) is used to trigger LPSYS interrupts. +- Each mailbox group has 16 channels and can trigger all interrupts + simultaneously. +- Mailbox interrupts can automatically wake up subsystems in + _LIGHT/DEEP/STANDBY_ low-power modes. +- The Mailbox module has two mutex channels to protect shared resources. All + subsystems can access them. ```{note} The mailbox module should be accessed when the owner subsystem is not in low-power mode, otherwise behavior is undefined. ``` -Available resources in HPSYS: -1. `H2L_MAILBOX` -1. `HMUTEX_CH1` -1. `HMUTEX_CH2` - -Available resources in LPSYS: -1. `L2H_MAILBOX` -1. `LMUTEX_CH1` -1. `LMUTEX_CH2` - -For detailed mailbox driver APIs, please refer to [mailbox](#hal-mailbox). +Main features include: +1. `H2L_MAILBOX` +1. `HMUTEX_CH1` +1. `HMUTEX_CH2` +1. `L2H_MAILBOX` +1. `LMUTEX_CH1` +1. `LMUTEX_CH2` ## Using Mailbox HAL Driver ### Notification Function -The mailbox notification function can be used by calling some macros, such as calling `__HAL_MAILBOX_TRIGGER_CHANNEL_IT` to trigger interrupts. Since mailbox register contents are lost after waking up from standby mode, it's recommended that the sender (i.e., owner) subsystem mask/unmask interrupts. - -In the following example, HCPU triggers an interrupt for LCPU: +The mailbox notification function can be used by calling some macros, such as +calling `__HAL_MAILBOX_TRIGGER_CHANNEL_IT` to trigger interrupts. Since mailbox +register contents are lost after waking up from standby mode, it's recommended +that the sender (i.e., owner) subsystem mask/unmask interrupts. ```c static MAILBOX_HandleTypeDef mailbox_handle; void hcpu_mailbox_ch1_init(void) { mailbox_handle.Instance = H2L_MAILBOX; - /* unmask HCPU2LCPU channel1 interrupt */ - __HAL_MAILBOX_UNMASK_CHANNEL_IT(&mailbox_handle, MAILBOX_CHANNEL_1); + /* Unmask HCPU2LCPU channel 1 interrupt */ + __HAL_MAILBOX_UNMASK_CHANNEL_IT(&mailbox_handle, MAILBOX_CHANNEL_1); } void hcpu_trigger_mailbox_ch1_interrupt(void) { - __HAL_MAILBOX_TRIGGER_CHANNEL_IT(&mailbox_handle, MAILBOX_CHANNEL_1); + __HAL_MAILBOX_TRIGGER_CHANNEL_IT(&mailbox_handle, MAILBOX_CHANNEL_1); } void lcpu_mailbox_ch1_init(void) { - /* set the mailbox priority */ + /* Set mailbox priority */ HAL_NVIC_SetPriority(HCPU2LCPU_IRQn, 3, 0); - /* enable the mailbox global Interrupt */ + /* Enable mailbox global interrupt */ HAL_NVIC_EnableIRQ(HCPU2LCPU_IRQn); } void lcpu_mailbox_isr(void) { uint32_t status; - status = __HAL_MAILBOX_GET_STATUS(&mailbox_handle); - - //do something according to status + status = __HAL_MAILBOX_GET_STATUS(&mailbox_handle); + + // Application logic based on status //... - + __HAL_MAILBOX_CLEAR_STATUS(status); } - ``` ### Mutex Function -The mutex function can be used by calling `HAL_MAILBOX_Lock` and `HAL_MAILBOX_UnLock`. Use `HAL_MAILBOX_Lock` to lock a mutex channel. If locking succeeds, it returns `MUTEX_UNLOCKED`, otherwise it returns which core is occupying the mutex channel. Use `HAL_MAILBOX_UnLock` to unlock a mutex channel. A channel can only be unlocked by the owner that previously locked the channel. The following example demonstrates HCPU locking and unlocking LPSYS mutex channel: +The mutex function can be used by calling `HAL_MAILBOX_Lock` and +`HAL_MAILBOX_UnLock`. Use `HAL_MAILBOX_Lock` to lock a mutex channel. If locking +succeeds, it returns `MUTEX_UNLOCKED`, otherwise it returns which core is +occupying the mutex channel. Use `HAL_MAILBOX_UnLock` to unlock a mutex channel. +A channel can only be unlocked by the owner that previously locked the channel. +The following example demonstrates HCPU locking and unlocking LPSYS mutex +channel: + ```c void test_hmutex_ch1(void) { MUTEX_HandleTypeDef handle; - + handle.Instance = HMUTEX_CH1; - core = HAL_MAILBOX_Lock(&handle, 0); - //core should be MUTEX_UNLOCKED - core = HAL_MAILBOX_Lock(&handle, 0); + core = HAL_MAILBOX_Lock(&handle, 0); + // core should be MUTEX_UNLOCKED + core = HAL_MAILBOX_Lock(&handle, 0); // core should be MUTEX_HCPU_LOCKED - HAL_MAILBOX_UnLock(&handle, 0); + HAL_MAILBOX_UnLock(&handle, 0); } ``` + ## API Reference -[](#hal-mailbox) +[] + diff --git a/docs/source/en/hal/mpi.md b/docs/source/en/hal/mpi.md index 59edfc83a..c2e0c7dd3 100644 --- a/docs/source/en/hal/mpi.md +++ b/docs/source/en/hal/mpi.md @@ -1,28 +1,37 @@ - # MPI -MPI HAL provides basic APIs for accessing MPI peripheral registers, which serves as FLASH/PSRAM controller on PRO. There are 2-level HAL interfaces: bf0_hal_mpi and bf0_hal_mpi_ex. -Hal_mpi is an interface for accessing hardware registers with minimal logic. For XIP mode, this file should be placed in RAM. Hal_mpi_ex is for basic NAND/NOR/PSRAM function wrappers, including initialization/page read/page write/sector erase and other functions. - -## Main Features Include: -- Supports up to 5 instances (MPI5 can be mounted to LCPU). -- Supports NAND/NOR/PSRAM. +The MPI HAL provides the primary APIs for accessing the Memory Peripheral +Interface (MPI) registers, which serve as the Flash/PSRAM controller on the PRO +core. The HAL is divided into two layers: `bf0_hal_mpi` and `bf0_hal_mpi_ex`. +`bf0_hal_mpi` provides low-level interfaces for hardware register access with +minimal logic; for XIP (Execute-In-Place) mode, this file should be placed in +RAM. `bf0_hal_mpi_ex` serves as a high-level wrapper for fundamental NAND, NOR, +and PSRAM operations, including initialization, page read/write, sector erase, +and other auxiliary functions. + +## Key features include: +- Support for up to 5 instances (with MPI5 mountable to the LCPU). +- Support for NAND, NOR, and PSRAM. - DMA support. -- Multi-chip support through register command tables. - -## Memory Address Mapping: - - MPI1: C-BUS from 0x10000000 to 0x11FFFFFF (total 32MB). S-BUS: from 0x60000000 to 0x61FFFFFF (total 32MB) - - MPI2: C-BUS from 0x12000000 to 0x13FFFFFF (total 32MB). S-BUS: from 0x62000000 to 0x63FFFFFF (total 32MB). - - MPI3: C-BUS from 0x14000000 to 0x17FFFFFF (total 64MB). S-BUS: from 0x64000000 to 0x67FFFFFF (total 64MB) - - MPI4: C-BUS from 0x18000000 to 0x1BFFFFFF (total 64MB). S-BUS: from 0x68000000 to 0x9FFFFFFF (total 896MB) - - MPI5: C-BUS from 0x1C000000 to 0x1FFFFFFF (total 64MB). - -## Using MPI HAL Driver -MPI can be used to control NOR-FLASH, NAND-FLASH, 8-LINE PSRAM, 16-LINE PSRAM. The following is an example for NOR-FLASH: +- Multi-chip support via a register command table. + +## Memory address mapping: + - MPI1: C-BUS from 0x10000000 to 0x11FFFFFF (32MB total). S-BUS from 0x60000000 + to 0x61FFFFFF (32MB total). + - MPI2: C-BUS from 0x12000000 to 0x13FFFFFF (32MB total). S-BUS from 0x62000000 + to 0x63FFFFFF (32MB total). + - MPI3: C-BUS from 0x14000000 to 0x17FFFFFF (64MB total). S-BUS from 0x64000000 + to 0x67FFFFFF (64MB total). + - MPI4: C-BUS from 0x18000000 to 0x1BFFFFFF (64MB total). S-BUS from 0x68000000 + to 0x9FFFFFFF (896MB total). + - MPI5: C-BUS from 0x1C000000 to 0x1FFFFFFF (64MB total). + +## Using the MPI HAL Driver +MPI can be used to control NOR Flash, NAND Flash, 8-line PSRAM, and 16-line +PSRAM. Below is an example for NOR Flash: ```c - -// register command table to support more flash chip +// Register command table to support additional Flash chips spi_flash_register_cmd(); QSPI_FLASH_CTX_T spi_flash_handle[FLASH_MAX_INSTANCE]; @@ -35,38 +44,37 @@ flash_cfg.line = 2; flash_cfg.base = MPI1_MEM_BASE; flash_dma.dma_rcc = FLASH1_DMA_RCC; // 0 -flash_dma.Instance = FLASH1_DMA_INSTANCE; //DMA1_Channel1 -flash_dma.dma_irq = FLASH1_DMA_IRQ; //DMAC1_CH1_IRQn -flash_dma.request = FLASH1_DMA_REQUEST; //DMA_REQUEST_0 +flash_dma.Instance = FLASH1_DMA_INSTANCE; // DMA1_Channel1 +flash_dma.dma_irq = FLASH1_DMA_IRQ; // DMAC1_CH1_IRQn +flash_dma.request = FLASH1_DMA_REQUEST; // DMA_REQUEST_0 -// init MPI hardware controller -flash_cfg.SpiMode = 0; // 0 for nor and 1 for nand, 2 for qspi psram, 3 for opi psram, 4 for hpi psram -res = HAL_FLASH_Init(&(spi_flash_handle[0]), &flash_cfg, &spi_flash_dma_handle[0], &flash_dma, BSP_GetFlash1DIV()); +// Initialize MPI hardware controller +flash_cfg.SpiMode = 0; // 0 for NOR, 1 for NAND, 2 for QSPI PSRAM, 3 for OPI PSRAM, 4 for HPI PSRAM +res = HAL_FLASH_Init(&(spi_flash_handle[0]), &flash_cfg, &spi_flash_dma_handle[0], &flash_dma, BSP_GetFlash1DIV()); if (res != HAL_OK) return error; -FLASH_HandleTypeDef hflash = &spi_flash_handle[0].handle; -// erase sector +FLASH_HandleTypeDef hflash = &spi_flash_handle[0].handle; +// Erase sector res = HAL_QSPIEX_SECT_ERASE(hflash, addr); -if (res < 0) +if (res < 0) return error; -// write a page +// Write a page res = HAL_QSPIEX_WRITE_PAGE(hflash, addr, buf, size); if (res != size) return error; -// read data, it can use AHB read +// Read data; AHB read can be used here res = nor_read_rom(hflash, addr, buf, size); ... ``` -The following is an example for NAND-FLASH: +Below is an example for NAND Flash: ```c - -// register command table to support more flash chip +// Register command table to support additional Flash chips spi_flash_register_cmd(); QSPI_FLASH_CTX_T spi_flash_handle[FLASH_MAX_INSTANCE]; @@ -79,36 +87,36 @@ flash_cfg.line = 2; flash_cfg.base = MPI4_MEM_BASE; flash_dma.dma_rcc = FLASH4_DMA_RCC; // 0 -flash_dma.Instance = FLASH4_DMA_INSTANCE; //DMA4_Channel1 -flash_dma.dma_irq = FLASH4_DMA_IRQ; //DMAC1_CH4_IRQn -flash_dma.request = FLASH4_DMA_REQUEST; //DMA_REQUEST_3 -// init QSPI hardware controller -flash_cfg.SpiMode = 1; // 0 for nor and 1 for nand, 2 for qspi psram, 3 for opi psram, 4 for hpi psram -res = HAL_FLASH_Init(&(spi_flash_handle[3]), &flash_cfg, &spi_flash_dma_handle[1], &flash_dma, BSP_GetFlash2DIV()); +flash_dma.Instance = FLASH4_DMA_INSTANCE; // DMA4_Channel1 +flash_dma.dma_irq = FLASH4_DMA_IRQ; // DMAC1_CH4_IRQn +flash_dma.request = FLASH4_DMA_REQUEST; // DMA_REQUEST_3 + +// Initialize QSPI hardware controller +flash_cfg.SpiMode = 1; // 0 for NOR, 1 for NAND, 2 for QSPI PSRAM, 3 for OPI PSRAM, 4 for HPI PSRAM +res = HAL_FLASH_Init(&(spi_flash_handle[3]), &flash_cfg, &spi_flash_dma_handle[1], &flash_dma, BSP_GetFlash2DIV()); if (res != HAL_OK) return error; -FLASH_HandleTypeDef hflash = &spi_flash_handle[3].handle; -// erase block, for nand, erase is block based +FLASH_HandleTypeDef hflash = &spi_flash_handle[3].handle; +// Erase block; for NAND, erase is block-based res = HAL_NAND_ERASE_BLK(hflash, addr); -if (res < 0) +if (res < 0) return error; -// write a page +// Write a page res = HAL_NAND_WRITE_WITHOOB(hflash, addr, buf, size, NULL, 0); if (res != size) return error; -// read data, nand can not use AHB read directly, it should use driver interface +// Read data; NAND cannot use AHB read directly and must use the driver interface res = HAL_NAND_READ_WITHOOB(hflash, addr, buf, size, NULL, 0); ... ``` -The following is an example for OPI PSRAM: +Below is an example for OPI PSRAM: ```c - QSPI_FLASH_CTX_T spi_flash_handle[FLASH_MAX_INSTANCE]; qspi_configure_t flash_cfg; @@ -119,49 +127,49 @@ flash_cfg.line = 0; flash_cfg.base = MPI2_MEM_BASE; flash_cfg.msize = 0x8; -// init MPI hardware controller -flash_cfg.SpiMode = 3; // 0 for nor and 1 for nand, 2 for qspi psram, 3 for opi psram, 4 for hpi psram -res = HAL_OPI_PSRAM_Init(handle, &qspi_cfg, 1); +// Initialize MPI hardware controller +flash_cfg.SpiMode = 3; // 0 for NOR, 1 for NAND, 2 for QSPI PSRAM, 3 for OPI PSRAM, 4 for HPI PSRAM +res = HAL_OPI_PSRAM_Init(handle, &qspi_cfg, 1); HAL_MPI_MR_WRITE(handle, 8, 3); -// clk and delay based on PSRAM datasheet +// Calculate clock and delay based on the PSRAM datasheet sys_clk = HAL_QSPI_GET_CLK(handle); sys_clk /= 2; -if (sys_clk <= 66 * 1000000) +if (sys_clk <= 66 * 1000000) w_lat = 3; -else if (sys_clk <= 109 * 1000000) +else if (sys_clk <= 109 * 1000000) w_lat = 4; -else if (sys_clk <= 133 * 1000000) +else if (sys_clk <= 133 * 1000000) w_lat = 5; -else if (sys_clk <= 166 * 1000000) +else if (sys_clk <= 166 * 1000000) w_lat = 6; -else if (sys_clk <= 200 * 1000000) +else if (sys_clk <= 200 * 1000000) w_lat = 7; else RT_ASSERT(0); if (fix_lat) - r_lat = w_lat * 2; //10; + r_lat = w_lat * 2; // 10; else - r_lat = w_lat; // = 6; //5; + r_lat = w_lat; // = 6; // 5; -/* configure AHB command */ +/* Configure AHB command */ HAL_FLASH_CFG_AHB_RCMD(handle, 7, r_lat - 1, 0, 0, 3, 7, 7); HAL_FLASH_SET_AHB_RCMD(handle, OPSRAM_RD); HAL_FLASH_CFG_AHB_WCMD(handle, 7, w_lat - 1, 0, 0, 3, 7, 7); HAL_FLASH_SET_AHB_WCMD(handle, OPSRAM_WR); HAL_MPI_SET_FIXLAT(handle, fix_lat, r_lat, w_lat); -//-------------------------INIT DONE ---------------------------// +//------------------------- INIT DONE ---------------------------// int *buf = (int *)MPI2_MEM_BASE; int i; -// Write psram memory -for(i=0; i<1000; i++) +// Write PSRAM memory +for(i=0; i<1000; i++) buf[i] = i*6543; -// Read psram +// Read PSRAM int value = *buf; // Read and Write @@ -173,4 +181,5 @@ memcpy(dst, src, 1000); ``` ## API Reference -[](../api/hal/mpi.md) +[] + diff --git a/docs/source/en/hal/nnacc.md b/docs/source/en/hal/nnacc.md index bc5953c18..4a6f729c9 100644 --- a/docs/source/en/hal/nnacc.md +++ b/docs/source/en/hal/nnacc.md @@ -1,32 +1,41 @@ - # NNACC -SiFli implements an NNACC (Neural Network Accelerator) to accelerate artificial intelligence on IoT devices. It can be used for speech/vision recognition applications and other AI applications using convolutional neural networks (CNNs). -Supports:
- - Supports CMSIS-NN, 8 times faster than ARM DSP implementation in CMSIS-NN.
+SiFli implements an NNACC (Neural Network Accelerator) to accelerate artificial +intelligence on IoT devices. It can be used for speech/vision recognition +applications and other AI applications using convolutional neural networks +(CNNs). Supports:
+ - Supports CMSIS-NN, 8 times faster than ARM DSP implementation in CMSIS-NN. +
- Can achieve low MIPS requirement keyword recognition.
## Driver Configuration -Firmware can use NNACC with CMSIS-NN enabled. Configuration is done using the menuconfig tool and typically saved in a C header file. By default, configuration is saved as rtconfig.h. -The following shows flags defined in a project header file that will enable NNACC support. +Firmware can use NNACC with CMSIS-NN enabled. Configuration is done using the +menuconfig tool and typically saved in a C header file. By default, +configuration is saved as rtconfig.h. The following shows flags defined in a +project header file that will enable NNACC support. ```{note} `SF32LB55X/56X` HCPU has one NNACC (NNACC1), SF32LB58X HCPU/LCPU each has one NNACC (NNACC1/NNACC2 respectively). ``` -Once configuration is done, users need to include the header file in all source code that needs to access the driver. +Once configuration is done, users need to include the header file in all source +code that needs to access the driver. ```c #define BSP_USING_CMSIS_NN #define BSP_USING_NN_ACC ``` +Once configuration is complete, the user must include the header file in all +source code that requires access to the driver. ## Using NNACC -SiFli SDK implements CNN functions in CMSIS-NN. Users can still use CMSIS-NN interfaces in their AI applications. For detailed introduction to Accelerator APIs, please refer to CNN Accelerator. -The following CMSIS-NN functions have acceleration from SiFli SDK: +SiFli SDK implements CNN functions in CMSIS-NN. Users can still use CMSIS-NN +interfaces in their AI applications. For detailed introduction to Accelerator +APIs, please refer to CNN Accelerator. The following CMSIS-NN functions have +acceleration from SiFli SDK: - arm_convolve_1x1_HWC_q7_fast_nonsquare - arm_convolve_HWC_q7_basic_nonsquare - arm_depthwise_separable_conv_HWC_q7_nonsquare ## API Reference -[](../api/hal/nnacc.md) +[] diff --git a/docs/source/en/hal/patch.md b/docs/source/en/hal/patch.md index a9151ceee..57ca538d5 100644 --- a/docs/source/en/hal/patch.md +++ b/docs/source/en/hal/patch.md @@ -1,28 +1,32 @@ - # PATCH -The PATCH module can be used to patch existing LCPU ROM data/code. Each PATCH entry can replace 4 bytes of data in ROM space (address must be 4-byte aligned). SIFLI chipsets have ROM code in LCPU that contains BLE stack, operating system, and other useful functions. If these codes have bugs, PATCH is used to fix them. When LCPU sleeps, those patch settings need to be saved to AON (Always On) memory and reapplied when LCPU wakes up from sleep. +The PATCH module can be used to patch existing LCPU ROM data/code. Each PATCH +entry can replace 4 bytes of data in ROM space (address must be 4-byte aligned). +SIFLI chipsets have ROM code in LCPU that contains BLE stack, operating system, +and other useful functions. If these codes have bugs, PATCH is used to fix them. +When LCPU sleeps, those patch settings need to be saved to AON (Always On) +memory and reapplied when LCPU wakes up from sleep. + ## Using PATCH The following code will save and apply patches. ```c - /*Power on or wake up*/ struct patch_entry_desc g_lcpu_patch_list[]= { { 0x0000DC14, 0xB91CF110 }, { 0x0000DEA4, 0xB8F2F110 } }; -HAL_PATCH_install((struct patch_entry_desc *)g_lcpu_patch_list(sizeof(g_lcpu_patch_list))/sizeof(struct patch_entry_desc)); +HAL_PATCH_install((struct patch_entry_desc *)g_lcpu_patch_list, sizeof(g_lcpu_patch_list) / sizeof(struct patch_entry_desc)); .. -/*before sleep, g_lcpu_patch_list should in AON memory section*/ +/*Before entering sleep mode, ensure g_lcpu_patch_list is located in the AON memory section[X266X]*/ uint32_t cer; -HAL_PATCH_save(g_lcpu_patch_list, g_lcpu_patch_list(sizeof(g_lcpu_patch_list))/sizeof(struct patch_entry_desc), &cer); +HAL_PATCH_save(g_lcpu_patch_list, sizeof(g_lcpu_patch_list) / sizeof(struct patch_entry_desc), &cer); .. - ``` ## API Reference -[](../api/hal/patch.md) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/pcd.md b/docs/source/en/hal/pcd.md index 4926d7fa9..4ffb6c363 100644 --- a/docs/source/en/hal/pcd.md +++ b/docs/source/en/hal/pcd.md @@ -1,21 +1,29 @@ -# USBC +# USB-C -The USB Device Module (also known as Peripheral Controller Device, PCD) module implements USB device functionality between the Full-Speed USB 2.0 bus and APB bus. +The USB Device Module (also known as Peripheral Controller Device, PCD) module +implements USB device functionality between the Full-Speed USB 2.0 bus and APB +bus. ## PCD Key Features - - USB SF32LB55x/56x specification version 2.0 Full-Speed compatible, SF32LB58x supports USB 2.0 High-Speed transmission. + - USB SF32LB55x/56x specification version 2.0 Full-Speed compatible, SF32LB58x + supports USB 2.0 High-Speed transmission. - Configurable endpoint count up to 8 endpoints. - - Cyclic Redundancy Check (CRC) generation/verification, Non-Return-to-Zero Inverted (NRZI) encoding/decoding and bit stuffing. -Please note that PCD is tested with RT-Thread USB device stack, with composite device configuration including USB Mass Storage and USB CDC UART. + - Cyclic Redundancy Check (CRC) generation/verification, Non-Return-to-Zero + Inverted (NRZI) encoding/decoding and bit stuffing. Please note that PCD is + tested with RT-Thread USB device stack, with composite device configuration + including USB Mass Storage and USB CDC UART. ## Using PCD -PCD can only be tested with upper-layer USB device stack. At HAL level, SiFli SDK provides support for: +PCD can only be tested with upper-layer USB device stack. At HAL level, SiFli +SDK provides support for: - USBD hardware module initialization. - EP0 read/write. - EPx read/write. - USB interrupt handler. - - Endpoint halt/unhalt. -Upper-layer USB device stack can call USB device functions and implement callbacks defined by the PCD HAL module. For detailed usage of PCD, please refer to RT-Thread SiFli USB driver tools (in _/rtos/rtthread/bsp/sifli/drivers/drv_usbd.c_) + - Endpoint halt/unhalt. Upper-layer USB device stack can call USB device + functions and implement callbacks defined by the PCD HAL module. For detailed + usage of PCD, please refer to RT-Thread SiFli USB driver tools (in + _/rtos/rtthread/bsp/sifli/drivers/drv_usbd.c_) ## API Reference -[](../api/hal/pcd.md) +[] diff --git a/docs/source/en/hal/pdm.md b/docs/source/en/hal/pdm.md index c8c693db0..bd2c8cd24 100644 --- a/docs/source/en/hal/pdm.md +++ b/docs/source/en/hal/pdm.md @@ -1,6 +1,8 @@ # PDM -The PDM (Pulse Density Modulation) module is used to filter PDM signals output from external PDM microphones, convert them to PCM signals, and provide them to the CPU for subsequent processing. +The PDM (Pulse Density Modulation) module is used to filter PDM signals output +from external PDM microphones, convert them to PCM signals, and provide them to +the CPU for subsequent processing. ## Supported Configurations - Mono (left/right), stereo @@ -13,8 +15,10 @@ The PDM (Pulse Density Modulation) module is used to filter PDM signals output f - 8-bit + mono - 16-bit + mono - 32-bit + mono: Upper 8 bits are 0, actual valid data is lower 24 bits - - 16-bit + stereo: Left and right channels each occupy 16 bits forming one 32-bit data (supports left/right channel swapping) - - 32-bit + stereo: Only supports left and right channels stored in separate 2 buffers + - 16-bit + stereo: Left and right channels each occupy 16 bits forming one + 32-bit data (supports left/right channel swapping) + - 32-bit + stereo: Only supports left and right channels stored in separate 2 + buffers ## Example PDM1 mono 16KHz, 16-bit depth, using DMA to read 1024 bytes of data @@ -63,5 +67,7 @@ void pdm_receive(void) ... ``` + ## API Reference -[](../api/hal/pdm.md) +[] + diff --git a/docs/source/en/hal/pinmux.md b/docs/source/en/hal/pinmux.md index f9de34c1e..8cef0a108 100644 --- a/docs/source/en/hal/pinmux.md +++ b/docs/source/en/hal/pinmux.md @@ -1,31 +1,39 @@ # PINMUX -HAL PINMUX provides abstract software interfaces to operate the hardware PINMUX module, setting pin functions and pull-up/pull-down attributes. -The chip has two PINMUX instances: PINMUX1 (`hwp_pinmux1`) in the HPSYS domain and PINMUX2 (`hwp_pinmux2`) in the LPSYS domain. -PINMUX1's pin list is found in `pin_pad_hcpu`, with available pin functions referenced in `pin_pad_func_hcpu`. Similarly, PINMUX2's pin list is found in `pin_pad_lcpu`, with pin function definitions found in `pin_pad_func_lcpu`. +HAL PINMUX provides abstract software interfaces to operate the hardware PINMUX +module, setting pin functions and pull-up/pull-down attributes. The chip has two +PINMUX instances: PINMUX1 (`hwp_pinmux1`) in the HPSYS domain and PINMUX2 +(`hwp_pinmux2`) in the LPSYS domain. PINMUX1's pin list is found in +`pin_pad_hcpu`, with available pin functions referenced in `pin_pad_func_hcpu`. +Similarly, PINMUX2's pin list is found in `pin_pad_lcpu`, with pin function +definitions found in `pin_pad_func_lcpu`. -Starting from 56x series chips (excluding 55x, 58x), any GPIO in the pinmux functionality can serve as an I/O pin for any I2C/UART/PWM in the current system. +Starting from 56x series chips (excluding 55x, 58x), any GPIO in the pinmux +functionality can serve as an I/O pin for any I2C/UART/PWM in the current +system. For detailed API documentation, refer to [](#hal-pinmux) ## Difference Between GPIO and PINMUX Modules -Physically, GPIO needs to connect to the external world through the pinmux module, as shown in the figure: -![Figure 1: Relationship between pinmux module and GPIO module](../../assets/relation_of_gpio_pinmux.png) +Physically, GPIO needs to connect to the external world through the pinmux +module, as shown in the figure: ![Figure 1: Relationship between pinmux module +and GPIO module](../../assets/relation_of_gpio_pinmux.png) ## Using HAL PINMUX ```c void pin_func_set_example(void) { - /* set HCPU PA10 and PA14 for I2C */ + /* Configure HCPU PA10 and PA14 for I2C1 */ HAL_PIN_Set(PAD_PA10, I2C1_SCL, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA14, I2C1_SDA, PIN_PULLUP, 1); - - /* set LCPU PB12 and PB14 for UART4 */ + + /* Configure LCPU PB12 and PB14 for UART4 */ HAL_PIN_Set(PAD_PB12, USART4_TXD, PIN_PULLUP, 0); HAL_PIN_Set(PAD_PB14, USART4_RXD, PIN_PULLUP, 0); } ``` ## API Reference -[](#hal-pinmux) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/pmu.md b/docs/source/en/hal/pmu.md index b32256e0c..a9670383c 100644 --- a/docs/source/en/hal/pmu.md +++ b/docs/source/en/hal/pmu.md @@ -1,15 +1,19 @@ # PMU -HAL PMU provides abstract software interfaces to operate the hardware PMU (Power Management Unit) module, offering the following functionality: +HAL PMU provides abstract software interfaces to operate the hardware PMU (Power +Management Unit) module, offering the following functionality: - Set chip power supply parameters - Set low-power clock parameters -- Configure chip to enter shutdown mode and set wake-up sources. In shutdown mode, the chip can be awakened by PIN and RTC. The mapping relationship between wake-up PINs and GPIO pins is the same as the wake-up PINs in LPSYS sleep mode, see [](aon.md) +- Configure chip to enter shutdown mode and set wake-up sources. In shutdown + mode, the chip can be awakened by PIN and RTC. The mapping relationship + between wake-up PINs and GPIO pins is the same as the wake-up PINs in LPSYS + sleep mode, see [](aon.md) - SF32LB52X supports charging, with related interfaces such as #HAL_PMU_ChgInit For detailed API documentation, refer to [PMU](#hal-pmu) ```{note} - - `HAL_PMU_CheckBootMode` needs to be executed at every startup to get the boot mode and clear the corresponding status. If the PMU status is not cleared when waking up from shutdown state, `HAL_PMU_EnterHibernate` cannot be called to shut down again +- `HAL_PMU_CheckBootMode` needs to be executed at every startup to get the boot mode and clear the corresponding status. If the PMU status is not cleared when waking up from shutdown state, `HAL_PMU_EnterHibernate` cannot be called to shut down again - After executing `HAL_PMU_EnterHibernate`, the chip will not shut down immediately. It may delay up to one LP Clock cycle before shutting down. During this time, the CPU can continue executing instructions and responding to interrupts. To avoid accidentally executing operations after interrupt triggers, it is recommended to disable interrupts before calling `HAL_PMU_EnterHibernate`. `HAL_PMU_EnterHibernate` itself will be an infinite loop that never exits ``` @@ -24,7 +28,7 @@ void shutdown(void) /* Enable RTC wakeup */ HAL_PMU_EnableRtcWakeup(); /* Disable Interrupt */ - + /* Shutdown, can be wakeup by PIN0 and RTC */ HAL_PMU_EnterHibernate(); } @@ -46,17 +50,17 @@ static PMU_ChgHandleTypeDef pmu_chg_handle; static void pmu_chg_callback(PMU_ChgHandleTypeDef *handle, uint32_t status) { - if (status & (1 << PMU_CHG_IRQ_VBUS_RDY)) + if (status & (1 << PMU_CHG_IRQ_VBUS_RDY)) { printf("vbus: %d", HAL_PMU_ChgReadStatus(handle, PMU_CHG_IRQ_VBUS_RDY)); } - if (status & (1 << PMU_CHG_IRQ_EOC)) + if (status & (1 << PMU_CHG_IRQ_EOC)) { printf("eoc: %d", HAL_PMU_ChgReadStatus(handle, PMU_CHG_IRQ_EOC)); } - if (status & (1 << PMU_CHG_IRQ_VBAT_HIGH)) + if (status & (1 << PMU_CHG_IRQ_VBAT_HIGH)) { printf("vbat high: %d", HAL_PMU_ChgReadStatus(handle, PMU_CHG_IRQ_VBAT_HIGH)); } @@ -67,30 +71,30 @@ void config_charger(void) PMU_ChgCalParamTypeDef cal_param; uint32_t current; uint32_t volt; - - //config calibration data for charger, calibration is saved in EFUSE + + // Configure charger calibration data; calibration values are stored in EFUSE //cal_param.cc_mn = xxx; //cal_param.cc_mp = xxx; //cal_param.bg = xxx; //cal_param.cv_vctrl = xxx; //cal_param.rep_vctrl = xxx; - status = HAL_PMU_ChgInit(&pmu_chg_handle, &cal_param); - - // config CC current - current = 300; //300mA - current = HAL_PMU_ChgConfigCcCurrent(&pmu_chg_handle, current); - - // config target voltage - volt = 4300; //4300mV - volt = HAL_PMU_ChgConfigTargetVolt(&pmu_chg_handle, volt); - - // enable IRQ and register callback - HAL_PMU_ChgRegisterCallback(&pmu_chg_handle, pmu_chg_callback); - status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_VBUS_RDY, PMU_CHG_IRQ_TRIG_MODE_DOUBLE_EDGE); + status = HAL_PMU_ChgInit(&pmu_chg_handle, &cal_param); + + // Configure Constant Current (CC) mode current + current = 300; // 300mA + current = HAL_PMU_ChgConfigCcCurrent(&pmu_chg_handle, current); + + // Configure target voltage + volt = 4300; // 4300mV + volt = HAL_PMU_ChgConfigTargetVolt(&pmu_chg_handle, volt); + + // Enable IRQs and register callback + HAL_PMU_ChgRegisterCallback(&pmu_chg_handle, pmu_chg_callback); + status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_VBUS_RDY, PMU_CHG_IRQ_TRIG_MODE_DOUBLE_EDGE); RT_ASSERT(HAL_OK == status); - status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_VBAT_HIGH, PMU_CHG_IRQ_TRIG_MODE_POS_EDGE); + status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_VBAT_HIGH, PMU_CHG_IRQ_TRIG_MODE_POS_EDGE); RT_ASSERT(HAL_OK == status); - status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_EOC, PMU_CHG_IRQ_TRIG_MODE_POS_EDGE); + status = HAL_PMU_ChgConfigIRQ(&pmu_chg_handle, PMU_CHG_IRQ_EOC, PMU_CHG_IRQ_TRIG_MODE_POS_EDGE); RT_ASSERT(HAL_OK == status); HAL_NVIC_SetPriority(PMUC_IRQn, 5, 0); @@ -98,5 +102,8 @@ void config_charger(void) } ``` + ## API Reference -[](#hal-pmu) +[] + + diff --git a/docs/source/en/hal/psram.md b/docs/source/en/hal/psram.md index 9480c008e..6a51699d6 100644 --- a/docs/source/en/hal/psram.md +++ b/docs/source/en/hal/psram.md @@ -1,10 +1,12 @@ # PSRAM -PSRAM HAL provides basic APIs for accessing PSRAM peripheral registers. -This module only exists in the A0 series. After the PRO version, PSRAM functionality is replaced by the MPI module, and the HAL layer no longer exists independently. +PSRAM HAL provides basic APIs for accessing PSRAM peripheral registers. This +module only exists in the A0 series. After the PRO version, PSRAM functionality +is replaced by the MPI module, and the HAL layer no longer exists independently. ## Using PSRAM -After initialization, PSRAM memory can be accessed by CPU and DMA like normal SRAM memory, as shown below: +After initialization, PSRAM memory can be accessed by CPU and DMA like normal +SRAM memory, as shown below: ```c // Initial PSRAM hardware before using it @@ -34,5 +36,7 @@ memcpy(dst, src, 1000); // Close device, keep it open for more users. ``` + ## API Reference -[](../api/hal/psram.md) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/qspi.md b/docs/source/en/hal/qspi.md index d819c987e..f6c278477 100644 --- a/docs/source/en/hal/qspi.md +++ b/docs/source/en/hal/qspi.md @@ -1,7 +1,11 @@ # QSPI -QSPI HAL provides basic APIs for accessing QSPI peripheral registers, used as flash controller on A0. There are 2-level HAL interfaces: bf0_hal_qspi and bf0_hal_qspi_ex. -Hal_qspi is used for accessing hardware register interfaces, containing only minimal logic. For XIP mode, this file should be placed in RAM. Hal_qspi_ex is used for basic NAND/NOR functional wrappers, including page read/page write/sector erase and other functions. +QSPI HAL provides basic APIs for accessing QSPI peripheral registers, used as +flash controller on A0. There are 2-level HAL interfaces: bf0_hal_qspi and +bf0_hal_qspi_ex. Hal_qspi is used for accessing hardware register interfaces, +containing only minimal logic. For XIP mode, this file should be placed in RAM. +Hal_qspi_ex is used for basic NAND/NOR functional wrappers, including page +read/page write/sector erase and other functions. ## Key Features Include: - Supports up to 4 instances (QSPI4 can be mounted to LCPU). @@ -10,39 +14,40 @@ Hal_qspi is used for accessing hardware register interfaces, containing only min - Multi-chip support through register command tables. ## Memory Address Mapping: - - QSPI1: memory from 0x10000000 to 0x11FFFFFF (total 32MB). - - QSPI2: memory from 0x64000000 to 0x67FFFFFF (total 64MB). + - QSPI1: memory from 0x10000000 to 0x11FFFFFF (total 32MB). + - QSPI2: memory from 0x64000000 to 0x67FFFFFF (total 64MB). - QSPI3: memory from 0x68000000 to 0x6FFFFFFF (total 128MB). - QSPI4: memory from 0x12000000 to 0x13FFFFFF (total 32MB). ## Using QSPI HAL Driver -QSPI can be used to control NOR-FLASH, NAND-FLASH, 4-LINE PSRAM. The following is an example for NOR-FLASH: +QSPI can be used to control NOR-FLASH, NAND-FLASH, 4-LINE PSRAM. The following +is an example for NOR-FLASH: ```c -// register command table to support more flash chip +// Register the command table to support additional Flash chips spi_flash_register_cmd(); QSPI_FLASH_CTX_T spi_flash_handle[FLASH_MAX_INSTANCE]; qspi_configure_t flash_cfg = FLASH1_CONFIG; struct dma_config flash_dma = FLASH1_DMA_CONFIG; -// init QSPI hardware controller -flash_cfg.SpiMode = 0; // 0 for nor and 1 for nand -res = HAL_FLASH_Init(&(spi_flash_handle[0]), &flash_cfg, &spi_flash_dma_handle[0], &flash_dma, BSP_GetFlash1DIV()); +// Initialize the QSPI hardware controller +flash_cfg.SpiMode = 0; // 0 for NOR, 1 for NAND +res = HAL_FLASH_Init(&(spi_flash_handle[0]), &flash_cfg, &spi_flash_dma_handle[0], &flash_dma, BSP_GetFlash1DIV()); if (res != HAL_OK) return error; -// erase sector +// Erase sector res = nor_sector_erase(hflash, addr); -if (res < 0) +if (res < 0) return error; -// write a page +// Write a page res = nor_write_page(hflash, addr, buf, size); if (res != size) return error; -// read data, it can use AHB read +// Read data; AHB read is supported res = nor_read_rom(hflash, addr, buf, size); ... @@ -81,4 +86,5 @@ res = nand_read_page(hflash, addr, buf, size); ``` ## API Reference -[bf0_hal_qspi.h](hal-qspi) \ No newline at end of file +[bf0_hal_qspi.h](hal-qspi) + diff --git a/docs/source/en/hal/rcc.md b/docs/source/en/hal/rcc.md index dc87b7bd9..8978d8b0b 100644 --- a/docs/source/en/hal/rcc.md +++ b/docs/source/en/hal/rcc.md @@ -1,29 +1,38 @@ -# RCC +# Reset and Clock Control -HAL_RCC (Reset and Clock Control) module can control system and peripheral clocks. It can set system or specific IP clocks to use different clocks with different frequencies. It can also issue resets to the system or specific IPs. +HAL_RCC (Reset and Clock Control) module can control system and peripheral +clocks. It can set system or specific IP clocks to use different clocks with +different frequencies. It can also issue resets to the system or specific IPs. -SF32LB52X supports dynamic frequency and voltage scaling to reduce power consumption, with corresponding interface `HAL_RCC_HCPU_ConfigHCLK`. This interface selects the appropriate voltage mode based on the frequency to be configured. When the set frequency is higher than 48MHz, DLL1 will automatically be used as the system clock. When the set frequency is lower than or equal to 48MHz, other DLLs except DLL1 need to be disabled before calling this function, and DLL1 will be automatically disabled by the function. +SF32LB52X supports dynamic frequency and voltage scaling to reduce power +consumption, with corresponding interface `HAL_RCC_HCPU_ConfigHCLK`. This +interface selects the appropriate voltage mode based on the frequency to be +configured. When the set frequency is higher than 48MHz, DLL1 will automatically +be used as the system clock. When the set frequency is lower than or equal to +48MHz, other DLLs except DLL1 need to be disabled before calling this function, +and DLL1 will be automatically disabled by the function. ## Using RCC ```c { #include "bf0_hal.h" - + ... HAL_RCC_HCPU_reset(HCPU_RESET_MODULES, 1); // Reset HCPU on-chip peripherals HAL_Delay(10); HAL_RCC_HCPU_reset(HCPU_RESET_MODULES, 0); - + HAL_RCC_HCPU_ClockSelect(RCC_CLK_MOD_UART4, RCC_CLK_USART_HXT48); // Switch UART4 to use 48M external Crystal. - + HAL_RCC_HCPU_ClockSelect(RCC_CLK_MOD_SYS, RCC_SYSCLK_HXT48); // Switch system to use 48M external Crystal. HAL_RCC_HCPU_EnableDLL1(192000000); // Enable DLL1 to use 192MHz HAL_RCC_HCPU_ClockSelect(RCC_CLK_MOD_SYS, RCC_SYSCLK_DLL1); // Switch system clock to DLL1 ... -} +} ``` + ## API Reference -[](../api/hal/rcc.md) +[] diff --git a/docs/source/en/hal/rng.md b/docs/source/en/hal/rng.md index 979dc63bc..21e8b0c97 100644 --- a/docs/source/en/hal/rng.md +++ b/docs/source/en/hal/rng.md @@ -1,16 +1,20 @@ -# RNG +# Random Number Generator (RNG) + +The RNG (Random Number Generator) module inside SiFli chipsets is used to +generate random number seeds and random numbers. It is recommended that users +use their own random algorithms to generate random numbers for better +randomness, while using hardware-generated random numbers as seeds. -The RNG (Random Number Generator) module inside SiFli chipsets is used to generate random number seeds and random numbers. It is recommended that users use their own random algorithms to generate random numbers for better randomness, while using hardware-generated random numbers as seeds. ## Using RNG ```c { #include "bf0_hal.h" - + ... RNG_HandleTypeDef RngHandle; - + if (HAL_RNG_Init(&RngHandle) == HAL_OK) { // Initialize RNG module uint32_t value = 0; if (HAL_RNG_Generate(&RngHandle, &value, 1)== HAL_OK) // Generate random seed @@ -19,8 +23,9 @@ The RNG (Random Number Generator) module inside SiFli chipsets is used to genera printf("Generated Random number %d\n", value); } ... -} +} ``` ## API Reference -[](../api/hal/rng.md) +[] + diff --git a/docs/source/en/hal/rtc.md b/docs/source/en/hal/rtc.md index 4e2a9a29f..bd8588722 100644 --- a/docs/source/en/hal/rtc.md +++ b/docs/source/en/hal/rtc.md @@ -1,24 +1,37 @@ # RTC -The embedded RTC (Real-Time Counter) in SiFli chipsets is an independent Binary Coded Decimal (BCD) timer counter. The RTC core consists of counter, prescaler, clock divider, alarm data registers, etc. Like any standard RTC chip, the embedded RTC can be used to provide full-featured software-based calendar and alarm functions. Of course, more work needs to be done on the software side rather than the hardware side. When using RTC chips, you only need to read or write separate date-time registers. In SiFli chipsets, we need to do more than this because separate date-time registers do not exist. +The embedded RTC (Real-Time Counter) in SiFli chipsets is an independent Binary +Coded Decimal (BCD) timer counter. The RTC core consists of counter, prescaler, +clock divider, alarm data registers, etc. Like any standard RTC chip, the +embedded RTC can be used to provide full-featured software-based calendar and +alarm functions. Of course, more work needs to be done on the software side +rather than the hardware side. When using RTC chips, you only need to read or +write separate date-time registers. In SiFli chipsets, we need to do more than +this because separate date-time registers do not exist. -Resetting or waking up the MCU from sleep/standby mode does not reinitialize the RTC. If there is battery backup on the battery backup (VBAT) pin, it can better preserve the current date and time. All VDD of SiFli chipsets can be turned off, but battery backup keeps the RTC and backup domain running even when the entire MCU core can be completely shut down. Therefore, time remains unchanged or is not lost during power-off and sleep modes. +Resetting or waking up the MCU from sleep/standby mode does not reinitialize the +RTC. If there is battery backup on the battery backup (VBAT) pin, it can better +preserve the current date and time. All VDD of SiFli chipsets can be turned off, +but battery backup keeps the RTC and backup domain running even when the entire +MCU core can be completely shut down. Therefore, time remains unchanged or is +not lost during power-off and sleep modes. Key features of SiFli RTC: - Programmable prescaler. - 18-bit programmable counter for long-term wake-up. - Two independent clock sources: PCLK1 for APB2 interface and RTC clock. -- Programming interface supports dates between 1970-1-1 to 2099-12-31. -For detailed RTC driver API, please refer to [RTC](#hal-rtc). +- Programming interface supports dates between 1970-1-1 to 2099-12-31. For + detailed RTC driver API, please refer to [RTC](#hal-rtc). ## Using RTC -The following code will initialize RTC registers and later use them as timestamps. +The following code will initialize RTC registers and later use them as +timestamps. ```c - { // Set time to January 7, 2020, 16:02:15 +{ // Set time to January 7, 2020, 16:02:15 RTC_TimeTypeDef RTC_TimeStruct = {0}; RTC_DateTypeDef RTC_DateStruct = {0}; - + RTC_TimeStruct.Seconds = 15; RTC_TimeStruct.Minutes = 2; RTC_TimeStruct.Hours = 16; @@ -29,7 +42,7 @@ The following code will initialize RTC registers and later use them as timestamp HAL_RTC_SetTime(&RTC_Handler, &RTC_TimeStruct, RTC_FORMAT_BIN); HAL_RTC_SetDate(&RTC_Handler, &RTC_DateStruct, RTC_FORMAT_BIN); } - + { // Get current date and time. RTC_TimeTypeDef RTC_TimeStruct = {0}; RTC_DateTypeDef RTC_DateStruct = {0}; @@ -40,24 +53,24 @@ The following code will initialize RTC registers and later use them as timestamp The following code will use RTC for alarm service. ```c - - void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) // Weak symbol implement the interrupt of Alarm. +void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) // Weak function implementation for the Alarm interrupt. { printf("Alarm interrupt\n"); } ... - // Set alarm at 18:30:00 + // Configure alarm for 18:30:00 RTC_AlarmTypeDef sAlarm; sAlarm.AlarmTime.Hours = 18; sAlarm.AlarmTime.Minutes = 30; sAlarm.AlarmTime.Seconds = 0; - HAL_RTC_SetAlarm(&RTC_Handler, &sAlarm, RTC_FORMAT_BIN); + HAL_RTC_SetAlarm(&RTC_Handler, &sAlarm, RTC_FORMAT_BIN); ... - - // Disable alarm - HAL_RTC_DeactivateAlarm(&RTC_Handler); + + // Disable the alarm + HAL_RTC_DeactivateAlarm(&RTC_Handler); ``` ## API Reference -[](#hal-rtc) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/spi.md b/docs/source/en/hal/spi.md index 98ca4a8d5..24494cd96 100644 --- a/docs/source/en/hal/spi.md +++ b/docs/source/en/hal/spi.md @@ -1,21 +1,25 @@ # SPI -Supports 4 SPI interfaces, with 2 on HCPU (SPI1, SPI2) and 2 on LCPU (SPI3, SPI4). +Supports 4 SPI interfaces, with 2 on HCPU (SPI1, SPI2) and 2 on LCPU (SPI3, +SPI4). ## Key Features - - Provides receive-only, transmit-only, and simultaneous transmit-receive modes, with each mode supporting polling, interrupt, and DMA methods + - Provides receive-only, transmit-only, and simultaneous transmit-receive + modes, with each mode supporting polling, interrupt, and DMA methods ## Configurable Options - Master/slave - - Shared data line for transmit/receive, or separate 2 data lines for transmit/receive + - Shared data line for transmit/receive, or separate 2 data lines for + transmit/receive - Data width: supports 8-bit/16-bit - Clock polarity, data sampling edge - - Frame format: supports Motorola Serial Peripheral Interface (SPI), Texas Instruments Synchronous Serial Protocol (SSP), National Semiconductor Microwire + - Frame format: supports Motorola Serial Peripheral Interface (SPI), Texas + Instruments Synchronous Serial Protocol (SSP), National Semiconductor + Microwire ## Example 1 SPI1 as master, transmitting 1000 bytes of data ```c - static void spi1_send_example(void) { SPI_HandleTypeDef spi_Handle = {0}; @@ -23,8 +27,8 @@ static void spi1_send_example(void) uint8_t * txBuff = 0x2000c000; uint32_t txBuffLenInBytes = 1000; uint32_t tx_timeout_tick = 5000; - - + + rt_uint32_t SPI_APB_CLOCK = HAL_RCC_GetPCLKFreq(CORE_ID_HCPU, 1); spi_Handle.Instance = SPI1; @@ -50,8 +54,9 @@ static void spi1_send_example(void) NVIC_DisableIRQ(SPI1_IRQn); } - ``` + ## API Reference -[](../api/hal/spi.md) \ No newline at end of file +[] + diff --git a/docs/source/en/hal/syscfg.md b/docs/source/en/hal/syscfg.md index 1ecd0b185..2c914af4b 100644 --- a/docs/source/en/hal/syscfg.md +++ b/docs/source/en/hal/syscfg.md @@ -1,16 +1,19 @@ -# SYSCFG +# System Configuration (SYSCFG) -The SYSCFG (SYStem ConFiG) module is used to configure system functions, including security mode and SWD interface. It can also be used to obtain system information such as chipset ID, boot mode, etc. The Syscfg module is implemented using MACROs, and users need to include `bf0_hal.h`. +The SYSCFG (SYStem ConFiG) module is used to configure system functions, +including security mode and SWD interface. It can also be used to obtain system +information such as chipset ID, boot mode, etc. The Syscfg module is implemented +using MACROs, and users need to include `bf0_hal.h`. ## Using SYSCFG ```c { #include "bf0_hal.h" - + ... printf("Boot mode is in %d mode\n", __HAL_SYSCFG_GET_BOOT_MODE()?"uart loop":"normal"); - + // Following code is A0 only { printf("Serial ID=%d\n", __HAL_SYSCFG_GET_SID()); @@ -27,8 +30,9 @@ The SYSCFG (SYStem ConFiG) module is used to configure system functions, includi __HAL_SYSCFG_CLEAR_SECURITY(); ... } -} +} ``` ## API Reference [bf0_hal.h](hal-syscfg) + diff --git a/docs/source/en/hal/tsen.md b/docs/source/en/hal/tsen.md index dd89b6749..83e06c003 100644 --- a/docs/source/en/hal/tsen.md +++ b/docs/source/en/hal/tsen.md @@ -1,42 +1,46 @@ # TSEN -TSEN (Temperature SENsor) is used to measure the current temperature of the chip. Both HCPU and LCPU can use this module to get the current temperature of the chipset. It can generate an interrupt when measurement data is ready. +TSEN (Temperature SENsor) is used to measure the current temperature of the +chip. Both HCPU and LCPU can use this module to get the current temperature of +the chipset. It can generate an interrupt when measurement data is ready. ## Using TSEN The following code will measure the chipset temperature without interrupts. ```c - int temperature; +int temperature; TSEN_HandleTypeDef TsenHandle; /*##-1- Initialize TSEN peripheral #######################################*/ - HAL_TSEN_Init(&TsenHandle); - temperature = HAL_TSEN_Read(&TsenHandle); - printf("Sync: Current temperature is %d degree\n", temperature); - + HAL_TSEN_Init(&TsenHandle); + temperature = HAL_TSEN_Read(&TsenHandle); + printf("Sync: Current temperature is %d Celsius\n", temperature); ``` -The following code will measure the chipset temperature and generate an interrupt when the measurement is ready. +The following code will measure the chipset temperature and generate an +interrupt when the measurement is ready. ```c - - void TSEN_IRQHandler(void) +void TSEN_IRQHandler(void) { LOG_I("IRQ Fired"); - HAL_TSEN_IRQHandler(&TsenHandle); + HAL_TSEN_IRQHandler(&TsenHandle); } int temperature; TSEN_HandleTypeDef TsenHandle; /*##-1- Initialize TSEN peripheral #######################################*/ - HAL_TSEN_Init(&TsenHandle); - if (HAL_TSEN_Read_IT(&TsenHandle) == HAL_TSEN_STATE_BUSY) + HAL_TSEN_Init(&TsenHandle); + if (HAL_TSEN_Read_IT(&TsenHandle) == HAL_TSEN_STATE_BUSY) { int count = 0; - while (HAL_TSEN_GetState(&TsenHandle) != HAL_TSEN_STATE_READY); + while (HAL_TSEN_GetState(&TsenHandle) != HAL_TSEN_STATE_READY); } - printf("Async: Current temperature is %d degree\n", TsenHandle.temperature); + printf("Async: Current temperature is %d Celsius\n", TsenHandle.temperature); ``` + ## API Reference -[](../api/hal/tsen.md) +[] + + diff --git a/docs/source/en/hal/uart.md b/docs/source/en/hal/uart.md index 4dff5469a..d8bcb4017 100644 --- a/docs/source/en/hal/uart.md +++ b/docs/source/en/hal/uart.md @@ -1,37 +1,47 @@ # UART -The Universal Asynchronous Receiver Transmitter (UART) module provides a flexible way to perform full-duplex data exchange with external devices requiring industry-standard NRZ asynchronous serial data format. The UART offers a very wide range of baud rates using a programmable baud rate generator. It supports modem operations (CTS/RTS) and DMA (Direct Memory Access) for high-speed communication. +The Universal Asynchronous Receiver Transmitter (UART) module provides a +flexible way to perform full-duplex data exchange with external devices +requiring industry-standard NRZ asynchronous serial data format. The UART offers +a very wide range of baud rates using a programmable baud rate generator. It +supports modem operations (CTS/RTS) and DMA (Direct Memory Access) for +high-speed communication. -## UART Key Features - - Configurable 16 or 8 oversampling methods to provide flexibility between speed and clock tolerance. - - Widely programmable transmit and receive baud rates up to 3 Mbit/s - - Programmable data word length (7, 8 or 9 bits) - - Configurable stop bits (1 or 2 stop bits) - - Continuous communication using DMA - - Communication control/error detection flags - - Parity control: transmit parity bit, check parity of received data bytes - -Note that the UART FIFO size in SiFli chipsets is 1 byte. It is strongly recommended to use DMA in the RX direction. +Key Features + - Configurable oversampling (by 16 or 8) provides flexibility between + transmission speed and clock tolerance. + - Programmable baud rates up to 3 Mbit/s. + - Programmable data word length (7, 8, or 9 bits). + - Configurable stop bits (1 or 2 bits). + - Continuous communication via DMA. + - Communication control and error detection flags. + - Parity control: Supports parity bit generation for transmission and parity + checking for received data. -## Using UART -The following example shows UART TX and RX. For UART DMA usage, please refer to `drv_usart.c` in the RTOS Sifli BSP folder (_rtos/rtthread/bsp/sifli/drivers_) as an example. +Note: The UART FIFO size in SiFli chipsets is 1 byte. It is highly recommended +to use DMA for RX operations. + + +## UART Key Features +Note that the UART FIFO size in SiFli chipsets is 1 byte. It is strongly +recommended to use DMA in the RX direction. ```c { #include "bf0_hal.h" - void USART4_IRQHandler(void) // Implement for UART interrupt handler + void USART4_IRQHandler(void) // UART interrupt handler implementation { - if ((__HAL_UART_GET_FLAG(&(uart->handle), UART_FLAG_RXNE) != RESET) && - (__HAL_UART_GET_IT_SOURCE(&(uart->handle), UART_IT_RXNE) != RESET)) - printf("Get UART %c", __HAL_UART_GETC(&(uart->handle))); + if ((__HAL_UART_GET_FLAG(&(uart->handle), UART_FLAG_RXNE) != RESET) && + (__HAL_UART_GET_IT_SOURCE(&(uart->handle), UART_IT_RXNE) != RESET)) + printf("Get UART %c", __HAL_UART_GETC(&(uart->handle))); } - + ... - + UART_HandleTypeDef UartHandle; - + UartHandle.Instance = USART4; UartHandle.Init.BaudRate = 1000000; @@ -42,19 +52,23 @@ The following example shows UART TX and RX. For UART DMA usage, please refer to UartHandle.Init.Mode = UART_MODE_TX_RX; UartHandle.Init.OverSampling = UART_OVERSAMPLING_16; if (UartHandle.Init.Parity) - UartHandle.Init.WordLength = UART_WORDLENGTH_9B; // If parity is odd/even, parity should +1 - if (HAL_UART_Init(&UartHandle) == HAL_OK) // Initialize UART + UartHandle.Init.WordLength = UART_WORDLENGTH_9B; // If parity is enabled, word length must be incremented. + if (HAL_UART_Init(&UartHandle) == HAL_OK) // Initialize UART { - HAL_UART_Transmit(&UartHandle, "UART Tx example", 15, 0xFFFF); // UART TX + HAL_UART_Transmit(&UartHandle, "UART Tx example", 15, 0xFFFF); // UART TX } - + NVIC_EnableIRQ(USART4_IRQn); // Enable UART interrupt - __HAL_UART_ENABLE_IT(&(uart->handle), UART_IT_RXNE); // Enable UART RXNE interrupt source. - - // Type on other side of UART will trigger UART interrupt for RX. + __HAL_UART_ENABLE_IT(&(uart->handle), UART_IT_RXNE); // Enable UART RXNE interrupt source. + + // Data received from the peer device will trigger the UART RX interrupt. ... -} +} ``` -## API Reference -[](#hal-uart) + +## Using UART +The following example shows UART TX and RX. For UART DMA usage, please refer to +`drv_usart.c` in the RTOS Sifli BSP folder (_rtos/rtthread/bsp/sifli/drivers_) +as an example. + diff --git a/docs/source/en/hal/wdt.md b/docs/source/en/hal/wdt.md index 4e4715329..b2ca160f0 100644 --- a/docs/source/en/hal/wdt.md +++ b/docs/source/en/hal/wdt.md @@ -1,19 +1,33 @@ -# WDT +# Watchdog Timer (WDT) -WDT (WatchDog Timer) is an APB slave peripheral that can be used to prevent system deadlock caused by component or program conflicts in SiFli chips. Both HCPU and LCPU have dedicated WatchDog timers. It can generate interrupts as Non-Maskable Interrupts (NMI) or reset subsystems. WatchDog can independently reset LCPU or HCPU subsystems. The chip also provides a system-level Watchdog (IWDT) that can reset the entire chip. +WDT (WatchDog Timer) is an APB slave peripheral that can be used to prevent +system deadlock caused by component or program conflicts in SiFli chips. Both +HCPU and LCPU have dedicated WatchDog timers. It can generate interrupts as +Non-Maskable Interrupts (NMI) or reset subsystems. WatchDog can independently +reset LCPU or HCPU subsystems. The chip also provides a system-level Watchdog +(IWDT) that can reset the entire chip. ## Working Mechanism ### Counter -WatchDog has 2 counters (count1 and count2) that count down from preset timeout values to zero. The counters are based on a 32K clock, decrementing every 1/32768 seconds. When counter count1 reaches zero, either a system reset or interrupt occurs depending on the selected output response mode. Users can restart the counter to its initial value or stop it. The process of restarting the watchdog counter is sometimes called "Pet Watchdog" or "Kick the Dog". +WatchDog has 2 counters (count1 and count2) that count down from preset timeout +values to zero. The counters are based on a 32K clock, decrementing every +1/32768 seconds. When counter count1 reaches zero, either a system reset or +interrupt occurs depending on the selected output response mode. Users can +restart the counter to its initial value or stop it. The process of restarting +the watchdog counter is sometimes called "Pet Watchdog" or "Kick the Dog". ### Interrupt -The WatchDog can be programmed to generate an interrupt when count1 times out, while count2 starts counting. If the interrupt is not cleared, the system resets when count2 times out; if the interrupt is cleared before the second timeout (count2 reaches 0), count1 is reset, count2 is reset, and counting starts again. +The WatchDog can be programmed to generate an interrupt when count1 times out, +while count2 starts counting. If the interrupt is not cleared, the system resets +when count2 times out; if the interrupt is cleared before the second timeout +(count2 reaches 0), count1 is reset, count2 is reset, and counting starts again. ```{note} IWDT does not generate interrupts; it directly resets the chip ``` ### System Reset -WatchDog can also be programmed to directly generate a system reset. The HCPU or LCPU subsystem resets after counter count1 decrements to 0. +WatchDog can also be programmed to directly generate a system reset. The HCPU or +LCPU subsystem resets after counter count1 decrements to 0. ```{note} SF32LB55X has three WDTs: HCPU WDT1, LCPU WDT2, and one system IWDT. WDT1/2 provide interrupt functionality and can only reset HCPU/LCPU subsystems when triggered. IWDT cannot provide interrupt functionality, but can reset the entire chip when triggered. The WDT clock for 55X can be selected from RC10K/32K LXT. @@ -24,8 +38,8 @@ SF32LB55X has three WDTs: HCPU WDT1, LCPU WDT2, and one system IWDT. WDT1/2 prov The following code will start the WatchDog timer without generating interrupts. ```c - WDT_HandleTypeDef WdtHandle; - +WDT_HandleTypeDef WdtHandle; + // Initialize Watchdog timer. { WdtHandle.Init.Reload = (uint32_t)g_tmout * 32768 ; // Counter is based on 32K clock, g_tmout is in seconds @@ -33,24 +47,24 @@ The following code will start the WatchDog timer without generating interrupts. __HAL_WDT_INT(&WdtHandle, 0); // Set to reset only, do not generate interrupt } __HAL_WDT_START(&WdtHandle); // Start watchdog timer. - + ... - + HAL_WDT_Refresh(&WdtHandle); // Kick watchdog - + HAL_Delay(g_tmout+1); // If do not kick watchdog before g_tmout, reset will happen. HAL_WDT_Refresh(&WdtHandle); // This will not reach, as watchdog reset system. - + ... __HAL_WDT_STOP(&WdtHandle); // Stop watchdog timer. - ``` -The following code will start the WatchDog timer and generate an interrupt after the first counter reaches 0. +The following code will start the WatchDog timer and generate an interrupt after +the first counter reaches 0. ```c - WDT_HandleTypeDef WdtHandle; - +WDT_HandleTypeDef WdtHandle; + // Watchdog interrupt, It is a non-maskable interrupt void WDT_IRQHandler(void) { @@ -65,18 +79,21 @@ The following code will start the WatchDog timer and generate an interrupt after __HAL_WDT_INT(&WdtHandle, 1); // Generate interrupt when g_tmout1 times out before you kick interrupt } __HAL_WDT_START(&WdtHandle); // Start watchdog timer. - + ... - + HAL_WDT_Refresh(&WdtHandle); // If kick before g_tmout1, it will NOT generate interrupt - + HAL_Delay(g_tmout1+g_tmout2+1); // If kick after g_tmout1, interrupt will generate. HAL_WDT_Refresh(&WdtHandle); // This could reach if you kick watchdog in interrupt. - + ... - + __HAL_WDT_STOP(&WdtHandle); // Stop watchdog timer. ``` + + ## API Reference -[](../api/hal/wdt.md) \ No newline at end of file +[] + diff --git a/docs/source/en/index.md b/docs/source/en/index.md index 5a88655df..94ddab5fb 100644 --- a/docs/source/en/index.md +++ b/docs/source/en/index.md @@ -1,5 +1,7 @@ # SiFli-SDK Programming Guide -SiFli-SDK is a software development framework customized based on RT-Thread, which enables rapid development of applications running on SiFli Technology chip platforms. +SiFli-SDK is a software development framework customized based on RT-Thread, +which enables rapid development of applications running on SiFli Technology chip +platforms. ```{only} SF32LB55X This document describes how to use the SDK on SF32LB55x chips. @@ -16,14 +18,19 @@ This document describes how to use the SDK on SF32LB58x chips. This document describes how to use the SDK on SF32LB52x chips. ``` -The SDK uses Kconfig as the software configuration tool and SCons for command-line compilation. It can also generate projects for Keil, Eclipse, and GNU Makefile for compilation and debugging, and supports generating MS Visual Studio projects for PC simulation. +The SDK uses Kconfig as the software configuration tool and SCons for +command-line compilation. It can also generate projects for Keil, Eclipse, and +GNU Makefile for compilation and debugging, and supports generating MS Visual +Studio projects for PC simulation. The SDK features the following characteristics: - Hardware Abstraction Layer (HAL) for accessing chipset hardware\ - This component is independent of the Real-Time Operating System (RTOS) and can be integrated with different RTOS or used without an RTOS. + This component is independent of the Real-Time Operating System (RTOS) and can + be integrated with different RTOS or used without an RTOS. - RT-thread device drivers - LVGL GUI library\ - Deep optimization of LVGL, utilizing the chip's built-in GPU to accelerate graphics rendering, achieving smooth graphical interface effects + Deep optimization of LVGL, utilizing the chip's built-in GPU to accelerate + graphics rendering, achieving smooth graphical interface effects - BT/BLE protocol stack and other middleware, including: - HFP/A2DP host protocol stack and application interfaces - PAN protocol stack and corresponding TCP/IP protocol stack integration @@ -33,8 +40,9 @@ The SDK features the following characteristics: - File system support on NOR and NAND flash - USB device stack with comprehensive USB class support - Secure Boot\ - Provides firmware updates through secure transmission and encrypted firmware updates. The SDK includes scripts responsible for firmware encryption, signing, and transmission. - + Provides firmware updates through secure transmission and encrypted firmware + updates. The SDK includes scripts responsible for firmware encryption, + signing, and transmission. ```{toctree} :hidden: @@ -53,4 +61,5 @@ example/index api/index contribute/index copyright/index -``` \ No newline at end of file +``` + diff --git a/docs/source/en/middleware/audio_server.md b/docs/source/en/middleware/audio_server.md index defe7c813..a2040101e 100644 --- a/docs/source/en/middleware/audio_server.md +++ b/docs/source/en/middleware/audio_server.md @@ -1,3 +1,5 @@ # Audio Server Usage Instructions -Please refer to [Audio Server Design Document](../extra/audio_server_en.pdf) \ No newline at end of file +Please refer to [Audio Server Design Document](/extra/audio_server.pdf) + + diff --git a/docs/source/en/middleware/battery_calculator.md b/docs/source/en/middleware/battery_calculator.md index c9a1d7367..c89815179 100644 --- a/docs/source/en/middleware/battery_calculator.md +++ b/docs/source/en/middleware/battery_calculator.md @@ -1,15 +1,22 @@ # Battery Calculator -The battery calculator module is used to calculate the current battery percentage based on battery voltage values. It considers both charging and discharging states, uses different battery curve tables, and implements a multi-level filtering algorithm to improve the accuracy and stability of battery level calculation. +The battery calculator module is used to calculate the current battery +percentage based on battery voltage values. It considers both charging and +discharging states, uses different battery curve tables, and implements a +multi-level filtering algorithm to improve the accuracy and stability of battery +level calculation. ## Features -- **Dual Curve Support**: Supports separate battery voltage curves for charging and discharging states +- **Dual Curve Support**: Supports separate battery voltage curves for charging + and discharging states - **Multi-level Filtering Algorithm**: - Primary Filter: Threshold-based jump filtering - Secondary Filter: Weighted average smoothing (optional) -- **Charge/Discharge State Detection**: Automatically recognizes current charging state and switches corresponding curves -- **Linear Interpolation Calculation**: Performs precise percentage calculation within curve tables +- **Charge/Discharge State Detection**: Automatically recognizes current + charging state and switches corresponding curves +- **Linear Interpolation Calculation**: Performs precise percentage calculation + within curve tables ## Core Structure @@ -85,27 +92,15 @@ uint8_t battery_calculator_get_percent(battery_calculator_t *calc, **Example**: ```c uint32_t voltage = 38000; // 3.8V -uint8_t percentage = battery_calculator_get_percent(&battery_calc, voltage); +uint8_t percentage = battery_calculator_get_percent(&battery_calc, voltage); rt_kprintf("Battery: %d%%\n", percentage); ``` ## Usage Example First, enable the required macro switches in menuconfig -1. Enable the ADC to read the battery voltage. -![Battery Calculator](../../assets/enable_adc.png) -2. Enable battery calculator function -![Battery Calculator](../../assets/battery_open1.png) -3. Enable charge -![Battery Calculator](../../assets/battery_open2.png) -4. Select the charging chip for your board. If not available, use simple charge -![Battery Calculator](../../assets/battery_open4.png) -5. Configure plug/unplug detection pin corresponding to your board's detection pin -![Battery Calculator](../../assets/battery_open3.png) -6. Select the polarity of the plug/unplug detection pin for the current board (choose according to actual situation). -![Battery Calculator](../../assets/charge_pin_2.png) -Selecting this option means enabling the `BSP_CHARGER_INT_PIN_ACTIVE_HIGH` macro. This macro defines the polarity of the charger detection pin. When `BSP_CHARGER_INT_PIN_ACTIVE_HIGH` is defined, it indicates that the charger insertion state is represented by a high level. When this macro is not defined, the default is to use a low level to represent the charger insertion state. -![Battery Calculator](../../assets/charge_pin.png) + + ### Complete Application Layer Example Code ```c @@ -127,21 +122,21 @@ void battery_monitor_task(void *parameter) .secondary_filter_weight_pre = 90, // Previous voltage weight 90% .secondary_filter_weight_cur = 10 // Current voltage weight 10% }; - + battery_calculator_init(&battery_calc, &calc_config); - + while (1) { // 2. Read ADC voltage value rt_device_t battery_device = rt_device_find("bat1"); rt_adc_cmd_read_arg_t read_arg; read_arg.channel = 7; - + rt_adc_enable((rt_adc_device_t)battery_device, read_arg.channel); rt_thread_mdelay(300); rt_uint32_t voltage = rt_adc_read((rt_adc_device_t)battery_device, read_arg.channel); rt_adc_disable((rt_adc_device_t)battery_device, read_arg.channel); - + // 3. Calculate battery percentage uint8_t percentage = battery_calculator_get_percent(&battery_calc, voltage); @@ -154,39 +149,45 @@ void battery_monitor_task(void *parameter) ### Filter Threshold Settings -| Parameter | Recommended Value | Description | -|------|--------|------| -| `charge_filter_threshold` | 50mV | Voltage jump threshold in charging state | -| `discharge_filter_threshold` | 30mV | Voltage jump threshold in discharging state | -| `filter_count` | 3 | Number of consecutive times threshold must be exceeded to update | +| Parameter | Recommended Value | Description | +| ---------------------------- | ----------------- | ---------------------------------------------------------------- | +| `charge_filter_threshold` | 50 mV | Voltage jump threshold in charging state | +| `discharge_filter_threshold` | 30 mV | Voltage jump threshold in discharging state | +| `filter_count` | 3 | Number of consecutive times threshold must be exceeded to update | ### Secondary Filter Parameters -| Parameter | Recommended Value | Description | -|------|--------|------| -| `secondary_filter_enabled` | true | Whether to enable secondary filter | -| `secondary_filter_weight_pre` | 90 | Historical voltage weight (0-100) | -| `secondary_filter_weight_cur` | 10 | Current voltage weight (0-100) | +| Parameter | Recommended Value | Description | +| ----------------------------- | ----------------- | ---------------------------------- | +| `secondary_filter_enabled` | true | Whether to enable secondary filter | +| `secondary_filter_weight_pre` | 90 | Historical voltage weight (0-100) | +| `secondary_filter_weight_cur` | 10 | Current voltage weight (0-100) | **Note**: `weight_pre + weight_cur = 100` ## Battery Curve Table Configuration -**Important Note**: The default battery curve table provided in the board directory is only a reference example and may not be suitable for the actual battery currently in use. To ensure the accuracy of battery level calculation, **it is strongly recommended to obtain matching battery voltage-capacity curve data from the battery manufacturer**and configure the corresponding lookup table according to the actual curve. +**Important Note**: The default battery curve table provided in the board +directory is only a reference example and may not be suitable for the actual +battery currently in use. To ensure the accuracy of battery level calculation, +**it is strongly recommended to obtain matching battery voltage-capacity curve +data from the battery manufacturer**and configure the corresponding lookup table +according to the actual curve. Battery curve table interface description: 1. **Charging curve table** - Variable name: `charging_curve_table` - Type: `const battery_lookup_point_t[]` - - Description: Defines the voltage-percentage relationship during battery charging state, with voltage values arranged in descending order + - Description: Defines the voltage-percentage relationship during battery + charging state, with voltage values arranged in descending order 2. **Discharging curve table** - Variable name: `discharge_curve_table` - Type: `const battery_lookup_point_t[]` - - Description: Defines the voltage-percentage relationship during battery discharging state, with voltage values arranged in descending order + - Description: Defines the voltage-percentage relationship during battery + discharging state, with voltage values arranged in descending order Battery curve tables are defined in `battery_table.c` in the following format: - ```c const battery_lookup_point_t chargeing_curve_table[] = { { 100, 41808}, // 4.18V -> 100% @@ -209,24 +210,33 @@ const battery_lookup_point_t chargeing_curve_table[] = { ## Important Notes -1. **Initialization Order**: Must call `battery_calculator_init()` before using `battery_calculator_get_percent()` +1. **Initialization Order**: Must call `battery_calculator_init()` before using + `battery_calculator_get_percent()` 2. **Voltage Units**: All voltage values use millivolts (mV) as the unit -3. **Curve Table Requirements**: Curve table must be sorted by voltage from high to low -4. **Charging State Detection**: Module automatically detects charging state through `CHARGE_DETECT_PIN` -5. **Filter Parameter Adjustment**: Adjust filter parameters according to actual battery characteristics and application scenarios +3. **Curve Table Requirements**: Curve table must be sorted by voltage from high + to low +4. **Charging State Detection**: Module automatically detects charging state + through `CHARGE_DETECT_PIN` +5. **Filter Parameter Adjustment**: Adjust filter parameters according to actual + battery characteristics and application scenarios ## FAQ -**Q: Battery level jumps too quickly?** -A: Increase filter threshold or increase `filter_count` value, or enable secondary filter and increase historical weight. +**Q: Battery level jumps too quickly?**\ +A: Increase filter threshold or increase `filter_count` value, or enable +secondary filter and increase historical weight. -**Q: Battery level display is inaccurate?** -A: Check if the battery curve table matches actual battery characteristics. Recalibrate curve points if necessary. +**Q: Battery level display is inaccurate?**\ +A: Check if the battery curve table matches actual battery characteristics. +Recalibrate curve points if necessary. -**Q: How to disable secondary filter?** +**Q: How to disable secondary filter?**\ A: Set `secondary_filter_enabled = false`. -**Q: Battery level value stuck at a fixed number?** -A: The current battery algorithm has the following logic processing: in charging state, battery level is not allowed to decrease, and in discharging state, battery level is not allowed to increase. When such abnormal situations occur, the battery level will remain at the current value for stabilization. You can check the log to confirm whether "Current status" matches the real state. If they don't match, you need to adjust the `BSP_CHARGER_INT_PIN_ACTIVE_HIGH` macro. - - +**Q: Battery level value stuck at a fixed number?** A: The current battery +algorithm has the following logic processing: in charging state, battery level +is not allowed to decrease, and in discharging state, battery level is not +allowed to increase. When such abnormal situations occur, the battery level will +remain at the current value for stabilization. You can check the log to confirm +whether "Current status" matches the real state. If they don't match, you need +to adjust the `BSP_CHARGER_INT_PIN_ACTIVE_HIGH` macro. diff --git a/docs/source/en/middleware/ble/ble.md b/docs/source/en/middleware/ble/ble.md index 8f4000565..9421d26b2 100644 --- a/docs/source/en/middleware/ble/ble.md +++ b/docs/source/en/middleware/ble/ble.md @@ -1,10 +1,17 @@ # Bluetooth Low Energy Service -Silfi Bluetooth is divided into two parts: one is the Bluetooth LE (BLE) service, which provides standard Bluetooth LE APIs and enhanced services for user development; the other is a fully tested BLE 5.2 protocol stack with host and controller components. - -The BLE service runs on HCPU or LCPU. It provides standard Generic Access Profile (GAP) APIs. It also provides a series of sibles BLE services to help users easily develop GATT services, clients, and GAP. Additionally, the Bluetooth LE service provides multiple GATT-based services. The BLE protocol stack runs on the Bluetooth stack core (LCPU), and HCPU can communicate with the BLE service through inter-core communication mechanisms such as hardware mailbox. - -![](../../../assets/ble_structure.png) +Silfi Bluetooth is divided into two parts: one is the Bluetooth LE (BLE) +service, which provides standard Bluetooth LE APIs and enhanced services for +user development; the other is a fully tested BLE 5.2 protocol stack with host +and controller components. + +The BLE service runs on HCPU or LCPU. It provides standard Generic Access +Profile (GAP) APIs. It also provides a series of sibles BLE services to help +users easily develop GATT services, clients, and GAP. Additionally, the +Bluetooth LE service provides multiple GATT-based services. The BLE protocol +stack runs on the Bluetooth stack core (LCPU), and HCPU can communicate with the +BLE service through inter-core communication mechanisms such as hardware +mailbox. ```{toctree} :maxdepth: 1 @@ -17,12 +24,15 @@ ble_profile.md ## BLE Service Configuration -Users can enable the Bluetooth LE service using the menuconfig tool. Configuration is typically saved in C header files. By default, the configuration is saved as rtconfig.h. +Users can enable the Bluetooth LE service using the menuconfig tool. +Configuration is typically saved in C header files. By default, the +configuration is saved as rtconfig.h. The following example shows flags defined in a project header file: ```c #define BSP_BLE_SIBLES ``` +After configuration is complete, users need to include the header file in all +source code that requires access to data services. Users can also use menuconfig +to enable BLE services. ![](../../../assets/ble_menuconfig.png) -After configuration is complete, users need to include the header file in all source code that requires access to data services. Users can also use menuconfig to enable BLE services. -![](../../../assets/ble_menuconfig.png) \ No newline at end of file diff --git a/docs/source/en/middleware/ble/ble_gap.md b/docs/source/en/middleware/ble/ble_gap.md index 95c7d6739..acf486543 100644 --- a/docs/source/en/middleware/ble/ble_gap.md +++ b/docs/source/en/middleware/ble/ble_gap.md @@ -1,14 +1,24 @@ # GAP -The Generic Access Profile (GAP) defines device discovery, link management, and related security procedures. In BLE, several modes and procedures are defined for different scenarios: - -- Broadcast mode and observation procedure. This mode and procedure are suitable for connectionless communication scenarios, such as beacons. - - A device in broadcast mode is called a broadcaster. It will send non-connectable advertisements with specified data. - - A device implementing the observation procedure is called an observer. It will scan non-connectable advertisements to obtain data. -- Discovery mode and procedure, connection mode and procedure. These two sets of modes and procedures are for link establishment in different scenarios, such as directed connection and normal connection. - - A device that accepts link establishment is called a peripheral. It will send connectable or directed connectable advertisements. - - A device that initiates link establishment is called a central. It will scan advertisements and connect to a specified peer address through advertisements. -- Pairing mode and procedure. The mode and procedure are to set the link to different security levels. +The Generic Access Profile (GAP) defines device discovery, link management, and +related security procedures. In BLE, several modes and procedures are defined +for different scenarios: +- Broadcast mode and observation procedure. This mode and procedure are suitable + for connectionless communication scenarios, such as beacons. + - A device in broadcast mode is called a broadcaster. It will send + non-connectable advertisements with specified data. + - A device implementing the observation procedure is called an observer. It + will scan non-connectable advertisements to obtain data. +- Discovery mode and procedure, connection mode and procedure. These two sets of + modes and procedures are for link establishment in different scenarios, such + as directed connection and normal connection. + - A device that accepts link establishment is called a peripheral. It will + send connectable or directed connectable advertisements. + - A device that initiates link establishment is called a central. It will + scan advertisements and connect to a specified peer address through + advertisements. +- Pairing mode and procedure. The mode and procedure are to set the link to + different security levels. GAP provides peripheral APIs to manage advertising, connection, and security. @@ -16,43 +26,72 @@ For GAP API details, please refer to @ref GAP. ## Bluetooth Low Energy Address Types -Bluetooth LE has 4 address types: - 1. Public device address, assigned by SIG, is a unique address. - 1. Static random device address is randomly generated and should not change during power cycles. The highest 2 bits should be 0x11. - 1. Private device address is used to protect device addresses and can be changed within minutes. Devices using private device addresses must have an identity address, which can be either a public address or a static random address. - 1. Resolvable private device address, generated by the local Identity Resolving Key (IRK). It can be resolved by peer devices that have the IRK. The IRK will be exchanged during bonding. The highest 2 bits should be 0x01. - 1. Non-resolvable private device address is randomly generated. It cannot be resolved. The highest 2 bits should be 0x00. +Bluetooth LE has 4 address types: 1. Public device address, assigned by SIG, is +a unique address. 1. Static random device address is randomly generated and +should not change during power cycles. The highest 2 bits should be 0x11. 1. +Private device address is used to protect device addresses and can be changed +within minutes. Devices using private device addresses must have an identity +address, which can be either a public address or a static random address. 1. +Resolvable private device address, generated by the local Identity Resolving Key +(IRK). It can be resolved by peer devices that have the IRK. The IRK will be +exchanged during bonding. The highest 2 bits should be 0x01. 1. Non-resolvable +private device address is randomly generated. It cannot be resolved. The highest +2 bits should be 0x00. Users can use these 4 address types in different scenarios: - In general cases, public addresses or static random addresses should be used. -- In security-sensitive connectable situations, resolvable private device addresses should be used. -- In security-sensitive non-connectable situations, non-resolvable private addresses should be used. +- In security-sensitive connectable situations, resolvable private device + addresses should be used. +- In security-sensitive non-connectable situations, non-resolvable private + addresses should be used. ## Advertising -Bluetooth LE has 40 physical channels (indexed from 0~39) from 2.4GHz - 2.4835Hz, where channels 37, 38, and 39 are allocated for advertising. Advertisements sent sequentially on channels 37, 38, or 39 are called advertising events. -The distance between two starts of adjacent advertising events is called the advertising interval. Channels can be configured through the advertising parameter channel_map to any of channels 37, 38, 39. +Bluetooth LE has 40 physical channels (indexed from 0~39) from 2.4GHz - +2.4835Hz, where channels 37, 38, and 39 are allocated for advertising. +Advertisements sent sequentially on channels 37, 38, or 39 are called +advertising events. The distance between two starts of adjacent advertising +events is called the advertising interval. Channels can be configured through +the advertising parameter channel_map to any of channels 37, 38, 39. ![](../../../assets/advertisement_channel.png) -If the interval is smaller, the advertising is denser, and the central device can more easily scan the advertisement or connect faster, while power consumption is higher. -In contrast, the larger the interval, the lower the power consumption, but scanning or connecting will be more difficult. +If the interval is smaller, the advertising is denser, and the central device +can more easily scan the advertisement or connect faster, while power +consumption is higher. In contrast, the larger the interval, the lower the power +consumption, but scanning or connecting will be more difficult. -A special case is high duty cycle directed connectable advertising. Directed advertising is sent to a specified peer address device, making it carry the peer address instead of advertising data or scan response data. -High duty cycle expects the peer device to quickly initiate link establishment and advertise at a very high frequency. In this case, no advertising interval is used. Due to the high frequency, the advertising duration cannot exceed 1.28s. +A special case is high duty cycle directed connectable advertising. Directed +advertising is sent to a specified peer address device, making it carry the peer +address instead of advertising data or scan response data. High duty cycle +expects the peer device to quickly initiate link establishment and advertise at +a very high frequency. In this case, no advertising interval is used. Due to the +high frequency, the advertising duration cannot exceed 1.28s. ![](../../../assets/directed_adv.png) ## Connection Parameters -In the controller, the device that initiates link establishment is called the master, and the device that accepts link establishment is called the slave. After link establishment, connection events are used to exchange data packets. -During a connection event, master and slave alternately send and receive data. The master sends data first and receives data, while the slave receives data and responds with data. In a normal connection event, both master and slave should send at least one data packet. +In the controller, the device that initiates link establishment is called the +master, and the device that accepts link establishment is called the slave. +After link establishment, connection events are used to exchange data packets. +During a connection event, master and slave alternately send and receive data. +The master sends data first and receives data, while the slave receives data and +responds with data. In a normal connection event, both master and slave should +send at least one data packet. There are many parameters that affect connection behavior: -- The length of a connection event is called CE length. The parameters max_ce_len and min_ce_len determine the length. -- The distance between two consecutive connection events is called the connection interval. -- Slave latency allows the slave to not respond to the master in some connection events. For example, if slave latency is 2, the slave can respond to the master every two connection events. -- The maximum interval between two data receptions is called supervision timeout. If no data is received within this interval, it indicates an abnormal connection. There are many reasons for timeout, such as one device being out of range, a device suddenly shutting down, or stack corruption. +- The length of a connection event is called CE length. The parameters + max_ce_len and min_ce_len determine the length. +- The distance between two consecutive connection events is called the + connection interval. +- Slave latency allows the slave to not respond to the master in some connection + events. For example, if slave latency is 2, the slave can respond to the + master every two connection events. +- The maximum interval between two data receptions is called supervision + timeout. If no data is received within this interval, it indicates an abnormal + connection. There are many reasons for timeout, such as one device being out + of range, a device suddenly shutting down, or stack corruption. ![](../../../assets/connection_parameter.png) Connection Parameters @@ -60,41 +99,61 @@ There are many parameters that affect connection behavior: ## Throughput and Low Power Consumption -Throughput can be simply calculated by Dsize (data size transmitted in one connection event) * Dcount (connection event count per second, 1/connection_interval). The larger Dsize and Dcount, the higher the throughput. -Dcount is only determined by the connection interval; the smaller the interval, the larger the count. The minimum connection interval is 7.5 ms, and typically 15 - 48 ms for high throughput. -Dsize is more complex, and users can improve it using the following methods: - - Ensure both master and slave support the Data Length Extension (DLE) feature, which is an optional feature after Bluetooth Core Specification 4.2. This feature allows the maximum packet size to increase from 27 bytes to 251 bytes. Each packet has certain headers, and when Dsize increases, the number of packets decreases, and header overhead is reduced. - ![](../../../assets/dle.png) - - - Ensure both master and slave support the 2M PHY feature supported by Bluetooth Core Specification 5.0. This feature allows the physical rate to increase from 1M to 2M. - - - Prepare sufficient data for transmission. From the connection parameter description, master and slave alternately send and receive data. If there is no more data to send, the connection event ends. Data requires some time to prepare; - if the controller has no data to transmit in sequence, data can only be transmitted in the next connection event. For example, if the host sends one packet and needs the slave to respond before sending the next packet, two connection events can only send one packet. - But if the host sends two packets and then needs the slave to respond, two connection events can send two packets. - ![](../../../assets/slave_respond.png) - -If no data needs to be transmitted, devices can change parameters to enter low-power transmission mode. There are 2 methods: - 1. Use a larger connection interval, for example, changing the connection interval from 30 to 500 ms. This method can reduce both master and slave transmission power. - However, there will be some delay when switching back to high throughput intervals. Typically, connection interval switching requires at least 6 connection events. If switching from 500 ms to 30 ms, the first 3 seconds (500 * 6) still use the 500 ms interval. - 2. Enable slave latency, allowing the slave to skip several connection events to respond. It can solve the delay issue, but the host cannot save transmission power. For example, set interval to 30 ms and slave latency to 20. - Then the master transmits every 30 ms, while the slave transmits every 600 ms. When the slave wants to send data, it can only respond every 30 ms. +Throughput can be simply calculated by Dsize (data size transmitted in one +connection event) * Dcount (connection event count per second, +1/connection_interval). The larger Dsize and Dcount, the higher the throughput. +Dcount is only determined by the connection interval; the smaller the interval, +the larger the count. The minimum connection interval is 7.5 ms, and typically +15 - 48 ms for high throughput. Dsize is more complex, and users can improve it +using the following methods: - Ensure both master and slave support the Data +Length Extension (DLE) feature, which is an optional feature after Bluetooth +Core Specification 4.2. This feature allows the maximum packet size to increase +from 27 bytes to 251 bytes. Each packet has certain headers, and when Dsize +increases, the number of packets decreases, and header overhead is reduced. +![](../../../assets/dle.png) + + - Ensure both master and slave support the 2M PHY feature supported by Bluetooth Core Specification 5.0. This feature allows the physical rate to increase from 1M to 2M. + + - Prepare sufficient data for transmission. From the connection parameter description, master and slave alternately send and receive data. If there is no more data to send, the connection event ends. Data requires some time to prepare; + if the controller has no data to transmit in sequence, data can only be transmitted in the next connection event. For example, if the host sends one packet and needs the slave to respond before sending the next packet, two connection events can only send one packet. + But if the host sends two packets and then needs the slave to respond, two connection events can send two packets. + ![](../../../assets/slave_respond.png) +If no data needs to be transmitted, devices can change parameters to enter +low-power transmission mode. There are 2 methods: 1. Use a larger connection +interval, for example, changing the connection interval from 30 to 500 ms. This +method can reduce both master and slave transmission power. However, there will +be some delay when switching back to high throughput intervals. Typically, +connection interval switching requires at least 6 connection events. If +switching from 500 ms to 30 ms, the first 3 seconds (500 * 6) still use the 500 +ms interval. 2. Enable slave latency, allowing the slave to skip several +connection events to respond. It can solve the delay issue, but the host cannot +save transmission power. For example, set interval to 30 ms and slave latency to +20. Then the master transmits every 30 ms, while the slave transmits every 600 +ms. When the slave wants to send data, it can only respond every 30 ms. ## SMP -The Security Manager Profile (SMP) defines protocols and behaviors for generating and distributing security keys and encrypting links with these keys. Related APIs are integrated with GAP. There are four functions in SMP: - - Pairing: Creating shared keys. - - Bonding: Storing keys created by pairing and used for subsequent connections. After bonding, two devices become a trusted device pair. - - Authentication: Verifying that two devices have the same keys. - - Encryption: Encrypting the link to ensure secure communication. +The Security Manager Profile (SMP) defines protocols and behaviors for +generating and distributing security keys and encrypting links with these keys. +Related APIs are integrated with GAP. There are four functions in SMP: - +Pairing: Creating shared keys. - Bonding: Storing keys created by pairing and +used for subsequent connections. After bonding, two devices become a trusted +device pair. - Authentication: Verifying that two devices have the same keys. - +Encryption: Encrypting the link to ensure secure communication. -As shown in the SMP flow diagram, the master can initiate a pairing request to trigger the pairing procedure, while the slave can initiate a security request to request the master to initiate a pairing request. +As shown in the SMP flow diagram, the master can initiate a pairing request to +trigger the pairing procedure, while the slave can initiate a security request +to request the master to initiate a pairing request. ![](../../../assets/smp_flow.png) SMP Flow -In the SIFLI BLE SDK, for the slave role, most procedures are encapsulated in the stack, and users only need to handle #BLE_GAP_BOND_IND and #BLE_GAP_ENCRYPT_IND. +In the SIFLI BLE SDK, for the slave role, most procedures are encapsulated in +the stack, and users only need to handle #BLE_GAP_BOND_IND and +#BLE_GAP_ENCRYPT_IND. -The default authentication method is just works. To modify the pairing authentication method to passkey entry or numeric comparison, -you need to call the following function to set the SDK's IO capabilities: +The default authentication method is just works. To modify the pairing +authentication method to passkey entry or numeric comparison, you need to call +the following function to set the SDK's IO capabilities: ```c uint8_t connection_manager_set_bond_cnf_iocap(uint8_t iocap) ``` @@ -102,7 +161,9 @@ Also call the function to set pairing confirmation to BOND_PENDING: ```c uint8_t connection_manager_set_bond_ack(uint8_t state) ``` -When BOND_PENDING is set, users need to handle the #CONNECTION_MANAGER_BOND_AUTH_INFOR message to reply to the corresponding pairing event: +When BOND_PENDING is set, users need to handle the +#CONNECTION_MANAGER_BOND_AUTH_INFOR message to reply to the corresponding +pairing event: ```c case CONNECTION_MANAGER_BOND_AUTH_INFOR: { @@ -152,17 +213,15 @@ case CONNECTION_MANAGER_BOND_AUTH_INFOR: - Advertising -To enable advertising, users need to: - 1. Create advertising with specified parameters. - 1. Set advertising data and scan response data. - 1. Start advertising with duration. +To enable advertising, users need to: 1. Create advertising with specified +parameters. 1. Set advertising data and scan response data. 1. Start advertising +with duration. ```c - static uint8_t adv_idx; /** advertising data format. Flag refers to @ble_gap_adv_type. - + * ------------------------------------------------------------------ * | Length(1B) | Flag(1B) | Value | Value | ... | Value | * ------------------------------------------------------------------ @@ -188,16 +247,16 @@ int app_advertising_evt_handler(uint16_t event_id, uint8_t *data, uint16_t len, // Set advertising data. ret = ble_gap_set_adv_data(adv_data); LOG("Set adv data result %d", ret); - + // Set scan response data. ble_gap_set_scan_rsp_data(scan_rsp); LOG("Set scan rsp result %d", ret); - + adv_start.actv_idx = ind->actv_idx; adv_start.duration = 0; adv_start.max_adv_evt = 0; - + ret = ble_gap_start_advertising(&adv_start); LOG("start adv result %d", ret); break; @@ -259,7 +318,7 @@ void app_start_advertising(void *para) adv_para.prim_cfg.adv_intv_min = 0x20; adv_para.prim_cfg.chnl_map = 0x07; adv_para.prim_cfg.phy = GAP_PHY_TYPE_LE_1M; - + // Create advertising. ret = ble_gap_create_advertising(¶); LOG("Create ADV result %d", ret); @@ -270,26 +329,28 @@ void app_stop_advertising(void *para) { ble_gap_adv_stop_t stop_req; uint8_t ret; - + stop_req.actv_idx = adv_idx; ble_gap_stop_advertising(&stop_req) LOG("Stop ADV result %d", ret); } BLE_EVENT_REGISTER(sibles_advertising_evt_handler, NULL); - ``` + - Connection -Acting as a peripheral role, users only need to enable advertising and wait for the central device to connect. +Acting as a peripheral role, users only need to enable advertising and wait for +the central device to connect. -Besides data transmission, the following sub-procedures are also important in GAP: - 1. Connection parameter update procedure. The peripheral may need the central to modify some parameters, such as connection interval and supervision timeout, to balance high throughput and low power consumption. - 2. Disconnection procedure. Disconnect from the central device. +Besides data transmission, the following sub-procedures are also important in +GAP: 1. Connection parameter update procedure. The peripheral may need the +central to modify some parameters, such as connection interval and supervision +timeout, to balance high throughput and low power consumption. 2. Disconnection +procedure. Disconnect from the central device. ```c - static uint8_t conn_idx; int app_connection_evt_handler(uint16_t event_id, uint8_t *data, uint16_t len, uint32_t context) @@ -335,7 +396,7 @@ void app_update_connection_parameter(void *para) { ble_gap_update_conn_param_t conn_para; uint8_t ret; - + // Request new parameters. conn_para.conn_idx = conn_idx; conn_para.intv_min = 0x20; @@ -344,7 +405,7 @@ void app_update_connection_parameter(void *para) conn_para.time_out = 500; conn_para.ce_len_min = 20; conn_para.ce_max_len = 100; - + ret = ble_gap_update_conn_param(&conn_para); LOG("Update conn parameter ret %d", ret); } @@ -352,15 +413,14 @@ void app_update_connection_parameter(void *para) void app_disconnect(void *para) { ble_gap_disconnect_t disc_cmd; - + disc_cmd.conn_idx = conn_idx; disc_cmd.reason = 0x13; - + ret = ble_gap_disconnect(&disc_cmd); LOG("Disconnect ret %d", ret); - + } BLE_EVENT_REGISTER(app_connection_evt_handler, NULL); - -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/ble/ble_profile.md b/docs/source/en/middleware/ble/ble_profile.md index 776ceeab7..c1c61bf7d 100644 --- a/docs/source/en/middleware/ble/ble_profile.md +++ b/docs/source/en/middleware/ble/ble_profile.md @@ -2,11 +2,12 @@ Sibles provides multiple GATT-based BLE profiles to accelerate user development. + ```{toctree} :titlesonly: ble_profile_ancs.md ble_profile_serial.md +``` -``` \ No newline at end of file diff --git a/docs/source/en/middleware/ble/ble_profile_ancs.md b/docs/source/en/middleware/ble/ble_profile_ancs.md index 109347c30..b1d5476b7 100644 --- a/docs/source/en/middleware/ble/ble_profile_ancs.md +++ b/docs/source/en/middleware/ble/ble_profile_ancs.md @@ -1,78 +1,95 @@ # ANCS Client ## ANCS Introduction -Apple Notification Center Service (ANCS) is a GATT service in iOS devices. This service can notify accessories of notifications in iOS devices, called Notification Provider (NP). -The local device acts as an accessory, called Notification Consumer (NC). +Apple Notification Center Service (ANCS) is a GATT service in iOS devices. This +service can notify accessories of notifications in iOS devices, called +Notification Provider (NP). The local device acts as an accessory, called +Notification Consumer (NC). NP has 3 characteristics: - 1. Notification Source - After NC enables CCCD, the notification source characteristic will send notifications with categoryID and count. - ![Notification Data Format](../../../assets/formatOfGATTNotifications_2x.png) - Event ID notifies NC whether a notification is added, modified, or removed. - - - EventFlags notify the specificity of the notification. NC can decide whether to notify the user or just filter. - - CategoryID notifies the category of notification, such as incoming call, news, or message. - - CategoryCount notifies the count of notifications present in the notification center. + After NC enables CCCD, the notification source characteristic will send + notifications with categoryID and count. ![Notification Data + Format](../../../assets/formatOfGATTNotifications_2x.png) Event ID notifies NC + whether a notification is added, modified, or removed. + + - EventFlags notify the specificity of the notification. NC can decide + whether to notify the user or just filter. + - CategoryID notifies the category of notification, such as incoming call, + news, or message. + - CategoryCount notifies the count of notifications present in the + notification center. - NotificationUID is a 32-bit ID used to identify the category. - - 2. Control Point and Data Source - NC can write commands to the control point to interact with NP to get details or perform actions. There are 3 commands: + NC can write commands to the control point to interact with NP to get details + or perform actions. There are 3 commands: - - Get Notification Attributes. This command allows NC to retrieve mode details of notifications from Notification.![Get Notification Attributes Command Format](../../../assets/formatOfAGetNotificationAttributesCommand_2x.png) + - Get Notification Attributes. This command allows NC to retrieve mode details + of notifications from Notification.![Get Notification Attributes Command + Format](../../../assets/formatOfAGetNotificationAttributesCommand_2x.png) - - CommandID should be set to 0 - NotificationUID from the notification source notification. - - AttributeIDs are the notification attributes that NC wants to get more details about. + - AttributeIDs are the notification attributes that NC wants to get more + details about. - - ![Response Format for Get Notification Attributes Command](../../../assets/formatOfAResponseToAGetNotificationAttributesCommand_2x.png) + ![Response Format for Get Notification Attributes + Command](../../../assets/formatOfAResponseToAGetNotificationAttributesCommand_2x.png) - - CommandID, Notification UID, Attribute_ID are all the same as the Get Notification Attributes command. - - Attribute length and attribute are the length and data associated with the attribute ID. The data includes details. + - CommandID, Notification UID, Attribute_ID are all the same as the Get + Notification Attributes command. + - Attribute length and attribute data are associated with specific + Attribute IDs. The data contains detailed information. - - Get App Attributes. This command allows NC to retrieve details of installed apps. - ![Get App Attributes Command Format](../../../assets/formatOfAGetAppAttributesCommand_2x.png) + - Get App Attributes. This command allows NC to retrieve details of + installed apps. ![Get App Attributes Command + Format](../../../assets/formatOfAGetAppAttributesCommand_2x.png) - CommandID should be set to 1 - - APP Identifier is the string ID obtained from the notification APP_ID attribute. It represents the APP ID registered in iOS. + - APP Identifier is the string ID obtained from the notification APP_ID + attribute. It represents the APP ID registered in iOS. - - APP AttributeIDs are the APP attributes that NC wants to get more details about. - ![Response Format for Get App Attributes Command](../../../assets/formatOfAResponseToAGetAppAttributesCommand_2x.png) + - APP AttributeIDs are the APP attributes that NC wants to get more + details about. ![Response Format for Get App Attributes + Command](../../../assets/formatOfAResponseToAGetAppAttributesCommand_2x.png) - - CommandID, APP Identifier are the same as the Get APP Attributes command. + - CommandID, APP Identifier are the same as the Get APP Attributes + command. - - Attribute length and attribute are the length and data associated with the attribute ID. The data includes details. + - Attribute length and attribute data are associated with specific + Attribute IDs. The data contains detailed information. - - -- 3. Perform Notification Action. - This command allows NC to perform a predetermined action on a specific iOS notification. There are two actions: +- 3. Perform Notification Action. This command allows NC to perform a + predetermined action on a specific iOS notification. There are two actions: - 1. Positive action - 2. Negative action - ​ iOS will perform behavior based on the action, but UI behavior depends on iOS and the notification. For example, if the notification is an incoming call, the positive action might answer it, while the negative action might reject it. But the behavior may change in other notifications. - + ​ iOS will perform behavior based on the action, but UI behavior depends on + iOS and the notification. For example, if the notification is an incoming + call, the positive action might answer it, while the negative action might + reject it. But the behavior may change in other notifications. ## Implementing ANCS NC -Sibles ANCS provides APIs to search for ANCS in iOS devices and configure notification attributes. Users only need to do the following: - 1. Configure expected notification and APP attributes and associated lengths. - 2. After receiving APP_ID attribute information, use the relevant API to get APP attributes. - 3. Use the perform action API to execute actions for specified attributeID. +Sibles ANCS provides APIs to search for ANCS in iOS devices and configure +notification attributes. Users only need to do the following: 1. Configure +expected notification and APP attributes and associated lengths. 2. After +receiving APP_ID attribute information, use the relevant API to get APP +attributes. 3. Use the perform action API to execute actions for specified +attributeID. For ANCS API details, please refer to @ref ANCS. Here is sample code: ```c - int app_ancs_event_handler(uint16_t event_id, uint8_t *data, uint16_t len, uint32_t context) { @@ -117,7 +134,7 @@ int app_ancs_event_handler(uint16_t event_id, uint8_t *data, uint16_t len, uint3 { // Get APP attribute ble_ancs_get_app_attr(app_id, value->len + 1); - + } else if (value->attr_id == BLE_ANCS_NOTIFICATION_ATTR_ID_MESSAGE) { @@ -144,5 +161,4 @@ int app_ancs_event_handler(uint16_t event_id, uint8_t *data, uint16_t len, uint3 // Register event to listen to ANCS events. BLE_EVENT_REGISTER(app_ancs_event_handler, NULL); - -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/ble/ble_profile_serial.md b/docs/source/en/middleware/ble/ble_profile_serial.md index c3cf2e913..30c279d61 100644 --- a/docs/source/en/middleware/ble/ble_profile_serial.md +++ b/docs/source/en/middleware/ble/ble_profile_serial.md @@ -1,34 +1,32 @@ # Serial Transfer Service -The serial transfer service allows users to simply and quickly transfer serial data via BLE. +The serial transfer service allows users to simply and quickly transfer serial +data via BLE. -The service UUID is 7369666c-695f-7364-0000-0000000000000. It has two characteristics: - - Serial Transfer Configuration: UUID 7369666c-695f-7364-0001-0000000000000 (notify required). - - Serial Transfer Data: UUID 7369666c-695f-7364-0002-0000000000000 (readable, writable, and notifiable) +The service UUID is 7369666c-695f-7364-0000-0000000000000. It has two +characteristics: - Serial Transfer Configuration: UUID +7369666c-695f-7364-0001-0000000000000 (notify required). - Serial Transfer Data: +UUID 7369666c-695f-7364-0002-0000000000000 (readable, writable, and notifiable) The configuration characteristic has not been used yet. The data characteristic is used to transfer serial data. Its data format is: -![](../../../assets/ble_serail_data.png) - - CateID: categoryID for different users. - - Flag: for fragmentation. - - 0x00: Complete packet. - - 0x01: First packet. - - 0x02: Continue packet. - - 0x03: Last packet. - - Length: Packet length, only available when flag equals 0x00. - - Data: serial data. - +![](../../../assets/ble_serail_data.png) - CateID: categoryID for different +users. - Flag: for fragmentation. - 0x00: Complete packet. - 0x01: First packet. +- 0x02: Continue packet. - 0x03: Last packet. - Length: Packet length, only +available when flag equals 0x00. - Data: serial data. + ## Implementing Serial Data Transfer -Users only need to negotiate and confirm the categoryID with the client and ensure that this ID is different from other users in the device. Then data can be transferred. +Users only need to negotiate and confirm the categoryID with the client and +ensure that this ID is different from other users in the device. Then data can +be transferred. For serial transfer API details, please refer to @ref Serial_tran. Here is sample code: ```c - // Make sure the categoryID is different from other IDs in local. #define APP_BLE_SERIAL_ID 0x1F @@ -41,9 +39,9 @@ void ble_app_serial_callback(uint8_t conn_idx, ble_serial_tran_data_t *data) // The cateID should be the same as registered ID APP_BLE_SERIAL_ID. LOG_I("cateID(%d), data(%d) %s\r\n", data->cateID, data->len, data->data); // Handle data from peer device start. - + // Handle data from peer device end. - + // Prepare send data to client send_data.cateID = APP_BLE_SERIAL_ID; send_data.len = sizeof(test_data); @@ -54,8 +52,6 @@ void ble_app_serial_callback(uint8_t conn_idx, ble_serial_tran_data_t *data) // Register user defined categoryID and associated callback. BLE_SERIAL_TRAN_EXPORT(APP_BLE_SERIAL_ID, ble_app_serial_callback); - - ``` -*/ \ No newline at end of file +*/ diff --git a/docs/source/en/middleware/ble/ble_service.md b/docs/source/en/middleware/ble/ble_service.md index d47808c24..b94a4b5e6 100644 --- a/docs/source/en/middleware/ble/ble_service.md +++ b/docs/source/en/middleware/ble/ble_service.md @@ -1,14 +1,15 @@ + # Sibles Service -Sibles service provides GATT service APIs that tools can use to automatically generate GATT service databases. Sibles service also provides simple GATT client and advertising APIs. +Sibles service provides GATT service APIs that tools can use to automatically +generate GATT service databases. Sibles service also provides simple GATT client +and advertising APIs. ```{toctree} :titlesonly: ble_service_gatt.md ble_service_adv.md - - ``` -For Sibles service API details, please refer to @ref sibles_service. \ No newline at end of file +For Sibles service API details, please refer to @ref sibles_service. diff --git a/docs/source/en/middleware/ble/ble_service_adv.md b/docs/source/en/middleware/ble/ble_service_adv.md index a25e4c2b5..486857d79 100644 --- a/docs/source/en/middleware/ble/ble_service_adv.md +++ b/docs/source/en/middleware/ble/ble_service_adv.md @@ -1,17 +1,20 @@ + # Sibles Advertising -Sibles advertising provides simple APIs based on GAP advertising APIs. Users can configure some parameters and then start advertising. +Sibles advertising provides simple APIs based on GAP advertising APIs. Users can +configure some parameters and then start advertising. - Configure advertising mode to determine advertising behavior. - SIBLES_ADV_CONNECT_MODE: Start connectable advertising to establish links. - SIBLES_ADV_BROADCAST_MODE: Start non-connectable broadcast advertising. - - SIBLES_ADV_DIRECTED_CONNECT_MODE: Start directed advertising for dedicated link establishment. -- Configure parameters for each mode, such as interval, duration, and whether to repeat. + - SIBLES_ADV_DIRECTED_CONNECT_MODE: Start directed advertising for dedicated + link establishment. +- Configure parameters for each mode, such as interval, duration, and whether to + repeat. - Set advertising data and scan response data to the provided structure. - + Here is an example: ```c - // Declare app advertising context SIBLES_ADVERTISING_CONTEXT_DECLAR(g_app_advertising_context); @@ -79,7 +82,7 @@ static void app_advertising_start(void) para.evt_handler = app_advertising_event; - + ret = sibles_advertising_init(g_app_advertising_context, ¶); if (ret == SIBLES_ADV_NO_ERR) { @@ -87,6 +90,4 @@ static void app_advertising_start(void) } } - - -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/ble/ble_service_gatt.md b/docs/source/en/middleware/ble/ble_service_gatt.md index acc3a4ceb..9b6d5106f 100644 --- a/docs/source/en/middleware/ble/ble_service_gatt.md +++ b/docs/source/en/middleware/ble/ble_service_gatt.md @@ -2,29 +2,45 @@ ## GATT -The Generic Attribute Profile (GATT) uses the Attribute Protocol (ATT) to define a service framework for transmitting data. GATT defines two roles: client and server. -- The server builds a service database according to ATT data format and responds to commands and requests from the client. -- The client discovers the server's database and sends commands and requests to the server. -- GATT defines procedures for discovering, reading, writing, notifying, and indicating between client and server to exchange data. +The Generic Attribute Profile (GATT) uses the Attribute Protocol (ATT) to define +a service framework for transmitting data. GATT defines two roles: client and +server. +- The server builds a service database according to ATT data format and responds + to commands and requests from the client. +- The client discovers the server's database and sends commands and requests to + the server. +- GATT defines procedures for discovering, reading, writing, notifying, and + indicating between client and server to exchange data. An attribute data consists of 4 parts: -- Attribute handle: the index that specifies the attribute. The value ranges from 0x0001 to 0xFFFF. -- Attribute type: description of the attribute handle through 16-bit/128-bit UUID. The UUID can be SIG-assigned or user-defined. +- Attribute handle: the index that specifies the attribute. The value ranges + from 0x0001 to 0xFFFF. +- Attribute type: description of the attribute handle through 16-bit/128-bit + UUID. The UUID can be SIG-assigned or user-defined. - Attribute value: the data of the attribute. - Attribute permissions: indicate whether the attribute can be read or written. ![](../../../assets/att_format.png) -Based on attributes, the service framework hierarchy is: profile, service, included service, and characteristic. -- A profile is a high-level concept consisting of one or more services. It defines the behavior for accessing services. -- A service consists of several included services and characteristics. It defines the data format and related behaviors. -- An included service refers to other service definitions that exist on the server. -- A characteristic describes detailed data format and behavior. It contains characteristic declaration, characteristic value, and characteristic descriptors. +Based on attributes, the service framework hierarchy is: profile, service, +included service, and characteristic. +- A profile is a high-level concept consisting of one or more services. It + defines the behavior for accessing services. +- A service consists of several included services and characteristics. It + defines the data format and related behaviors. +- An included service refers to other service definitions that exist on the + server. +- A characteristic describes detailed data format and behavior. It contains + characteristic declaration, characteristic value, and characteristic + descriptors. ![](../../../assets/gatt_hierarchy.png) -The following is an example of the Battery Service. The Battery Service is to notify clients of battery changes. Therefore, this service has a battery level characteristic with readable and notify properties. -The client can write the Client Characteristic Configuration Descriptor (CCCD) to enable notifications. Then the Battery Service will notify battery level. +The following is an example of the Battery Service. The Battery Service is to +notify clients of battery changes. Therefore, this service has a battery level +characteristic with readable and notify properties. The client can write the +Client Characteristic Configuration Descriptor (CCCD) to enable notifications. +Then the Battery Service will notify battery level. ![](../../../assets/att_example.png) @@ -33,14 +49,17 @@ The client can write the Client Characteristic Configuration Descriptor (CCCD) t ## Implementing GATT Service -Sibles GATT service provides formatted APIs that can be generated by tools. Users can also customize GATT services through APIs following these steps: -1. Build GATT service and register to SIBLEs GATT service. The service will automatically save the allocated GATT handle of the user GATT service from the Bluetooth stack. -1. Register set/get callbacks to respond to client commands. SIBLEs GATT service will notify users of client requests with the specified handle. +Sibles GATT service provides formatted APIs that can be generated by tools. +Users can also customize GATT services through APIs following these steps: +1. Build GATT service and register to SIBLEs GATT service. The service will + automatically save the allocated GATT handle of the user GATT service from + the Bluetooth stack. +1. Register set/get callbacks to respond to client commands. SIBLEs GATT service + will notify users of client requests with the specified handle. The following is an example of Battery Service: ```c - // Battery Service Attributes Indexes which are mapped to GATT handles. enum { @@ -164,7 +183,7 @@ void ble_bass_init(ble_bass_callback callback, uint8_t battery_lvl) if (env->state == BASS_STATE_IDLE) { sibles_register_svc_t svc; - + // Provide battery database. svc.att_db = (struct attm_desc *)&bas_att_db; svc.num_entry = BAS_IDX_NB; @@ -178,8 +197,6 @@ void ble_bass_init(ble_bass_callback callback, uint8_t battery_lvl) env->bas_lvl = battery_lvl; env->callback = callback; } - - ``` ## Message Flow @@ -198,4 +215,4 @@ void ble_bass_init(ble_bass_callback callback, uint8_t battery_lvl) - Indication -![](../../../assets/gatt_indication.png) \ No newline at end of file +![](../../../assets/gatt_indication.png) diff --git a/docs/source/en/middleware/bt_a2dp_sink_profile.md b/docs/source/en/middleware/bt_a2dp_sink_profile.md index f3b8bfb16..e58b76f3a 100644 --- a/docs/source/en/middleware/bt_a2dp_sink_profile.md +++ b/docs/source/en/middleware/bt_a2dp_sink_profile.md @@ -1,153 +1,209 @@ # BT_A2DP -A2DP (Advanced Audio Distribution Profile) is a Bluetooth audio transmission protocol, typically used for Bluetooth headsets. A2DP protocol audio data is transmitted over ACL Link, which is different from voice data transmitted over SCO. A2DP does not include remote control functionality; for remote control functionality, refer to the AVRCP protocol. AVDTP defines the parameter negotiation, establishment, and transmission process of data stream handles between Bluetooth devices, as well as the forms of signaling entities exchanged. This protocol is the foundational protocol of the A2DP framework. - -A2DP aims to transmit high-quality audio streams over Bluetooth connections. The basic compression algorithm it uses is SBC, which is used to reduce the size of audio data while maintaining high sound quality. SBC is a mandatory compression algorithm that must be supported. In addition to SBC, A2DP can also support other advanced codecs such as AAC and LHDC, but support for these codecs depends on the device itself. - -The implementation of A2DP depends on GAVDP and GAP, and the stream connection establishment process is defined in GAVDP. The protocol dependencies of A2DP are shown in the following figure: -![A2DP Stack](../../assets/a2dp_arch.png) - -In A2DP, two different roles are defined: SRC (source) and SNK (sink). SRC sends audio data, and SNK receives audio data. Their corresponding protocol models are as follows: -![A2DP Stack](../../assets/a2dp_stack.png) - -The main roles included in the A2DP Profile are: +A2DP (Advanced Audio Distribution Profile) is a Bluetooth audio transmission +protocol, typically used for Bluetooth headsets. A2DP protocol audio data is +transmitted over ACL Link, which is different from voice data transmitted over +SCO. A2DP does not include remote control functionality; for remote control +functionality, refer to the AVRCP protocol. AVDTP defines the parameter +negotiation, establishment, and transmission process of data stream handles +between Bluetooth devices, as well as the forms of signaling entities exchanged. +This protocol is the foundational protocol of the A2DP framework. - source(SRC): Device that sends audio data - sink(SNK): Device that receives audio data -A2DP is built on top of the AVDTP transport protocol. AVDTP specifies how connections are established. Once the connection is established, audio data can be sent and received after compression. Audio data is bidirectional. The data transmission and reception process of A2DP based on AVDTP is shown in the following figure: -![A2DP Stack](../../assets/a2dp_transport_data.png) - -Here's a general summary of the entire process: -1. UL collects PCM data, then sends it to A2DP. A2DP compresses it into a specific audio format through codec PCM lib (SBC, MPEG-1,2 Audio, MPEG-2,4 AAC, ATRAC family or custom encoder pcm lib), then passes it to AVDTP. AVDTP forwards it to L2CAP, L2CAP forwards it to HCI through ACL format, then reaches the BT chip and is transmitted out through RF. -2. The BT chip receives data through RF, then passes it to HCI through ACL, then to L2CAP. L2CAP passes it to AVDTP, AVDTP passes it to A2DP. A2DP receives compressed data from remote, then decompresses it into PCM data through codec pcm lib (SBC, MPEG-1,2 Audio, MPEG-2,4 AAC, ATRAC family or custom encoder pcm lib), and then passes it to the sound card for playback. +A2DP aims to transmit high-quality audio streams over Bluetooth connections. The +basic compression algorithm it uses is SBC, which is used to reduce the size of +audio data while maintaining high sound quality. SBC is a mandatory compression +algorithm that must be supported. In addition to SBC, A2DP can also support +other advanced codecs such as AAC and LHDC, but support for these codecs depends +on the device itself. + +The implementation of A2DP depends on GAVDP and GAP, and the stream connection +establishment process is defined in GAVDP. The protocol dependencies of A2DP are +shown in the following figure: ![A2DP Stack]{1} +1. UL collects PCM data, then sends it to A2DP. A2DP compresses it into a + specific audio format through codec PCM lib (SBC, MPEG-1,2 Audio, MPEG-2,4 + AAC, ATRAC family or custom encoder pcm lib), then passes it to AVDTP. AVDTP + forwards it to L2CAP, L2CAP forwards it to HCI through ACL format, then + reaches the BT chip and is transmitted out through RF. +2. The BT chip receives data through RF, then passes it to HCI through ACL, then + to L2CAP. L2CAP passes it to AVDTP, AVDTP passes it to A2DP. A2DP receives + compressed data from remote, then decompresses it into PCM data through codec + pcm lib (SBC, MPEG-1,2 Audio, MPEG-2,4 AAC, ATRAC family or custom encoder + pcm lib), and then passes it to the sound card for playback. ## AVDTP Introduction -AVDTP (A/V Distribution Transport Protocol) is the audio/video distribution transport protocol, mainly used for transmitting audio/video data. The architecture diagram in the entire protocol stack is as follows: -![A2DP Stack](../../assets/avdtp_arch.png) +AVDTP (A/V Distribution Transport Protocol) is the audio/video distribution +transport protocol, mainly used for transmitting audio/video data. The +architecture diagram in the entire protocol stack is as follows: ![A2DP +Stack](../../assets/avdtp_arch.png) 1. AVDTP Terminology Introduction - Stream: Streaming media data between two point-to-point devices. - - Source (SRC) and Sink (SNK): SRC is the sender of audio/video, SNK is the receiver of audio/video. - - Initiator (INT) and Acceptor (ACP): The device that initiates the process acts as the initiator, and the device that accepts the initiation is the acceptor. Note that INT and ACP are independent of the SRC and SNK defined by the upper-layer application. In a CMD and RESPONSE exchange, the one sending CMD is the INT role, and the one returning RESPONSE is the ACP role, so their roles will be constantly switching dynamically. - - Application and Transport Service Capabilities: Functions of application services and transport services. Application service capabilities include negotiation, configuration of audio source device codec, content protection system, etc.; transport service capabilities include datagram segmentation and reassembly, packet loss detection, etc. - - Services, Service Categories, and Service Parameters: Services, service categories, and service parameters. - - Media Packets, Recovery Packets, and Reporting Packets: Streaming media packets, data recovery packets, and report packets. - - Stream End Point (SEP): Stream endpoint, an application that exposes available transport services and A/V capabilities to negotiate a stream. - - Stream Context (SC): Stream context. Refers to a common understanding of stream configuration reached by two peer devices during stream setup, including selected services, parameters, and transport channel allocation. - - Stream Handle (SH): Stream handle. An independent identifier allocated after the connection is established between SRC and SNK, representing the upper layer's reference to the stream. - - Stream End Point Identifier (SEID): Stream endpoint identifier, cross-device reference to a specific device. + - Source (SRC) and Sink (SNK): SRC is the sender of audio/video, SNK is the + receiver of audio/video. + - Initiator (INT) and Acceptor (ACP): The device that initiates the process + acts as the initiator, and the device that accepts the initiation is the + acceptor. Note that INT and ACP are independent of the SRC and SNK defined + by the upper-layer application. In a CMD and RESPONSE exchange, the one + sending CMD is the INT role, and the one returning RESPONSE is the ACP + role, so their roles will be constantly switching dynamically. + - Application and Transport Service Capabilities: Functions of application + services and transport services. Application service capabilities include + negotiation, configuration of audio source device codec, content protection + system, etc.; transport service capabilities include datagram segmentation + and reassembly, packet loss detection, etc. + - Services, Service Categories, and Service Parameters: Services, service + categories, and service parameters. + - Media Packets, Recovery Packets, and Reporting Packets: Streaming media + packets, data recovery packets, and report packets. + - Stream End Point (SEP): Stream endpoint, an application that exposes + available transport services and A/V capabilities to negotiate a stream. + - Stream Context (SC): Stream context. Refers to a common understanding of + stream configuration reached by two peer devices during stream setup, + including selected services, parameters, and transport channel allocation. + - Stream Handle (SH): Stream handle. An independent identifier allocated + after the connection is established between SRC and SNK, representing the + upper layer's reference to the stream. + - Stream End Point Identifier (SEID): Stream endpoint identifier, + cross-device reference to a specific device. - Stream End Point State: Stream endpoint state. - - Transport Session: Transport session. Within the A/V transport layer, between paired AVDTP entities, streams can be decomposed into one, two, or up to three transport sessions. - - Transport Session Identifier (TSID): Transport session identifier. Represents a reference to a transport session. - - Transport Channel: Transport channel. Transport channel refers to the abstraction of the lower-layer bearer program of the A/V transport layer, always corresponding to the L2CAP channel. - - Transport Channel Identifier (TCID): Transport channel identifier. Represents a reference to a transport channel. + - Transport Session: Transport session. Within the A/V transport layer, + between paired AVDTP entities, streams can be decomposed into one, two, or + up to three transport sessions. + - Transport Session Identifier (TSID): Transport session identifier. + Represents a reference to a transport session. + - Transport Channel: Transport channel. Transport channel refers to the + abstraction of the lower-layer bearer program of the A/V transport layer, + always corresponding to the L2CAP channel. + - Transport Channel Identifier (TCID): Transport channel identifier. + Represents a reference to a transport channel. - Reserved for Future Additions (RFA): Reserved for future additions. - Reserved for Future Definitions (RFD): Reserved for future definitions. - -2. AVDTP Packet Format -AVDTP mainly has two types of packets: signal packets on the signal channel and media packets on the media channel. -![A2DP Stack](../../assets/avdtp_signal_packet.png) -The above is the Signal header format, which can be seen to have 3 packet formats: -  1) Single packet -  2) Start packet, generally used for the first packet when packet size > MTU -  3) Continue packet and end packet, generally used for continue and end packets when packet size > MTU -Let's explain the parameters: - - Transaction Label: Transport label, 4 bits, filled by INT role, ACP must return the same value - - Packet Type: Packet type, with the following types: -![A2DP Stack](../../assets/avdtp_transaction_label.png) -Message Type: Message type, with the following types: -![A2DP Stack](../../assets/avdtp_message_type.png) -Signal Identifier: Signaling identifier, with the following values: -![A2DP Stack](../../assets/avdtp_signal_identifer.png) -NOSP = Number Of Signal Packets: Start packet will indicate how many subsequent packets need to be transmitted - -3. AVDTP Signal Commands -There are the following types of signaling commands: -![A2DP Stack](../../assets/avdtp_signal_identifer.png) - -Before explaining specific commands, let's first explain Service Capabilities, as these will be used, so we'll explain them in advance. -The Service Capabilities format is as follows: -![A2DP Stack](../../assets/avdtp_service_capability.png) -This part is also similar to TLV (Type Length Value) type, where Service Category is the TYPE, with the following values: -![A2DP Stack](../../assets/avdtp_service_capability_value.png) -Length Of Service Capabilities (LOSC) is similar to length, which is the length of subsequent Service Capabilities Information Elements. -Service Capabilities Information Elements are specific values. This requires extensive discussion. Here we'll mainly explain Media Codec Capabilities. -![A2DP Stack](../../assets/avdtp_media_codec_capability.png) -Media Type has the following values: -![A2DP Stack](../../assets/avdtp_media_type.png) -Media Codec Type has the following values: -![A2DP Stack](../../assets/avdtp_media_codec.png) -The Media Codec Specific Information Elements in this part are some upper-layer codec information, for example, the following figure shows SBC: -![A2DP Stack](../../assets/avdtp_sbc_media_codec.png) - -- 3.1 AVDTP Signal Commands -Each AVDTP endpoint will register one or more SEPs, identified by SEID. This command is to obtain the peer's SEP information, including SEID (SEP ID), In Use (whether in use), Media Type (Audio, Media, MultiMedia), TSEP (role is Sink or Source) -The process is as follows: -![A2DP Stack](../../assets/avdtp_discover.png) - -- 3.2 Get Capabilities -This command uses SEID to obtain the peer's Capabilities. Capabilities have been introduced previously. Let's look at the program flow: -![A2DP Stack](../../assets/avdtp_get_capability.png) - -- 3.3 Get All Capabilities -This command is used to replace Get Capabilities, also using SEID to obtain the peer's Capabilities. Capabilities have been introduced previously. Let's look at the program flow: -![A2DP Stack](../../assets/avdtp_get_all_capability.png) - -- 3.4 Set Configuration Command -After obtaining Capabilities, this part is to select specific function parameters. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_set_configure.png) - -- 3.5 Get Stream Configuration -This command is used to obtain configuration based on SEID. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_get_configure.png) - -- 3.6 Stream Establishment -This command is used to open a SEID, i.e., establish media channel. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_stream_establishment.png) - -- 3.7 Stream Start -This command is used to start media transmission of a SEID, i.e., start playing music. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_stream_start.png) - -- 3.8 Stream Suspend -This command is used to pause media transmission, i.e., pause music. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_suspend.png) - -- 3.9 Stream Release -This command is used to close media transmission. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_release.png) + +2. AVDTP Packet Format AVDTP mainly has two types of packets: signal packets on + the signal channel and media packets on the media channel. ![A2DP + Stack](../../assets/avdtp_signal_packet.png) The above is the Signal header + format, which can be seen to have 3 packet formats: 1) Single packet 2) Start + packet, generally used for the first packet when packet size > MTU 3) + Continue packet and end packet, generally used for continue and end packets + when packet size > MTU Let's explain the parameters: + - Transaction Label: Transport label, 4 bits, filled by INT role, ACP must + return the same value + - Packet Type: Packet type, with the following types: ![A2DP + Stack](../../assets/avdtp_transaction_label.png) Message Type: Message + type, with the following types: ![A2DP + Stack](../../assets/avdtp_message_type.png) Signal Identifier: Signaling + identifier, with the following values: ![A2DP + Stack](../../assets/avdtp_signal_identifer.png) NOSP = Number Of Signal + Packets: Start packet will indicate how many subsequent packets need to be + transmitted + +3. AVDTP Signal Commands There are the following types of signaling commands: + ![A2DP Stack](../../assets/avdtp_signal_identifer.png) + +Before explaining specific commands, let's first explain Service Capabilities, +as these will be used, so we'll explain them in advance. The Service +Capabilities format is as follows: ![A2DP +Stack](../../assets/avdtp_service_capability.png) This part is also similar to +TLV (Type Length Value) type, where Service Category is the TYPE, with the +following values: ![A2DP Stack](../../assets/avdtp_service_capability_value.png) +Length Of Service Capabilities (LOSC) is similar to length, which is the length +of subsequent Service Capabilities Information Elements. Service Capabilities +Information Elements are specific values. This requires extensive discussion. +Here we'll mainly explain Media Codec Capabilities. ![A2DP +Stack](../../assets/avdtp_media_codec_capability.png) Media Type has the +following values: ![A2DP Stack](../../assets/avdtp_media_type.png) Media Codec +Type has the following values: ![A2DP Stack](../../assets/avdtp_media_codec.png) +The Media Codec Specific Information Elements in this part are some upper-layer +codec information, for example, the following figure shows SBC: ![A2DP +Stack](../../assets/avdtp_sbc_media_codec.png) + +- 3.1 AVDTP Signal Commands Each AVDTP endpoint will register one or more SEPs, + identified by SEID. This command is to obtain the peer's SEP information, + including SEID (SEP ID), In Use (whether in use), Media Type (Audio, Media, + MultiMedia), TSEP (role is Sink or Source) The process is as follows: ![A2DP + Stack](../../assets/avdtp_discover.png) + +- 3.2 Get Capabilities This command uses SEID to obtain the peer's Capabilities. + Capabilities have been introduced previously. Let's look at the program flow: + ![A2DP Stack](../../assets/avdtp_get_capability.png) + +- 3.3 Get All Capabilities This command is used to replace Get Capabilities, + also using SEID to obtain the peer's Capabilities. Capabilities have been + introduced previously. Let's look at the program flow: ![A2DP + Stack](../../assets/avdtp_get_all_capability.png) + +- 3.4 Set Configuration Command After obtaining Capabilities, this part is to + select specific function parameters. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_set_configure.png) + +- 3.5 Get Stream Configuration This command is used to obtain configuration + based on SEID. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_get_configure.png) + +- 3.6 Stream Establishment This command is used to open a SEID, i.e., establish + media channel. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_stream_establishment.png) + +- 3.7 Stream Start This command is used to start media transmission of a SEID, + i.e., start playing music. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_stream_start.png) + +- 3.8 Stream Suspend This command is used to pause media transmission, i.e., + pause music. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_suspend.png) + +- 3.9 Stream Release This command is used to close media transmission. The + program flow is as follows: ![A2DP Stack](../../assets/avdtp_release.png) ## A2DP Introduction -A2DP (Advanced Audio Distribution Profile) is a Bluetooth high-quality audio transmission protocol used for transmitting mono and stereo music (generally used for stereo in A2DP), with typical applications being Bluetooth headsets. A2DP does not include remote control functionality; for remote control functionality, refer to the AVRCP protocol. -1. Audio Codec -In the above process, we mentioned the need for Audio codec algorithms. In the A2DP protocol, there are the following specifications: -![A2DP Stack](../../assets/a2dp_codec.png) -First, all devices are mandatorily required to have SBC codec algorithm, which is a lossy algorithm with sound quality similar to MP3. Additionally, it supports 3 optional algorithms: MPEG-1,2 audio/MPEG-2,4 AAC, ATRAC family. Of course, there are also some custom extension codec algorithms, such as the popular APTX, LDAC, etc. -1.1 SBC Codec -SBC is a mandatory protocol specified by Bluetooth. The Codec Specific Information Elements are defined as follows: -![A2DP Stack](../../assets/a2dp_sbc_codec.png) -Sampling Frequency: This part is the sampling frequency. The Source end is mandatorily required to support either 44.1KHz or 48KHz, while Sink requires support for both 44.1KHz and 48KHz. Each value corresponds to the following: -![A2DP Stack](../../assets/a2dp_sbc_sample_frequency.png) -Channel Mode: Number of channels. Sink requires full support, while Source only mandatorily requires support for Mono, others are optional: -![A2DP Stack](../../assets/a2dp_sbc_channel_mode.png) -Block Length: -![A2DP Stack](../../assets/a2dp_sbc_block_length.png) -Subbands: -![A2DP Stack](../../assets/a2dp_sbc_subbands.png) -Allocation Method: -![A2DP Stack](../../assets/a2dp_sbc_allocation_method.png) -Minimum Bitpool Value: -Maximum Bitpool Value: In playback devices, you can set SBC encoding quality. This value is called bitpool, approximately 1 bitpool = 6-7 kbit/s. SBC is a low-complexity encoding format with slightly lower sound quality at the same bitrate. According to comparisons on websites, SBC at the highest 328kbit/s has sound quality approximately between 224 kbit/s and 256 kbit/s MP3. Additionally, improper settings, poor signal, devices not supporting high bitpool, etc., can all cause transmission bitrate to drop and reduce sound quality. The sound quality of the headset or speaker itself is also a very important factor. The following shows bitrates for different bitpools: -![A2DP Stack](../../assets/a2dp_sbc_bitpool.png) +A2DP (Advanced Audio Distribution Profile) is a Bluetooth high-quality audio +transmission protocol used for transmitting mono and stereo music (generally +used for stereo in A2DP), with typical applications being Bluetooth headsets. +A2DP does not include remote control functionality; for remote control +functionality, refer to the AVRCP protocol. +1. Audio Codec In the above process, we mentioned the need for Audio codec + algorithms. In the A2DP protocol, there are the following specifications: + ![A2DP Stack](../../assets/a2dp_codec.png) First, all devices are mandatorily + required to have SBC codec algorithm, which is a lossy algorithm with sound + quality similar to MP3. Additionally, it supports 3 optional algorithms: + MPEG-1,2 audio/MPEG-2,4 AAC, ATRAC family. Of course, there are also some + custom extension codec algorithms, such as the popular APTX, LDAC, etc. 1.1 + SBC Codec SBC is a mandatory protocol specified by Bluetooth. The Codec + Specific Information Elements are defined as follows: ![A2DP + Stack](../../assets/a2dp_sbc_codec.png) Sampling Frequency: This part is the + sampling frequency. The Source end is mandatorily required to support either + 44.1KHz or 48KHz, while Sink requires support for both 44.1KHz and 48KHz. + Each value corresponds to the following: ![A2DP + Stack](../../assets/a2dp_sbc_sample_frequency.png) Channel Mode: Number of + channels. Sink requires full support, while Source only mandatorily requires + support for Mono, others are optional: ![A2DP + Stack](../../assets/a2dp_sbc_channel_mode.png) Block Length: ![A2DP + Stack](../../assets/a2dp_sbc_block_length.png) Subbands: ![A2DP + Stack](../../assets/a2dp_sbc_subbands.png) Allocation Method: ![A2DP + Stack](../../assets/a2dp_sbc_allocation_method.png) Minimum Bitpool Value: + Maximum Bitpool Value: In playback devices, you can set SBC encoding quality. + This value is called bitpool, approximately 1 bitpool = 6-7 kbit/s. SBC is a + low-complexity encoding format with slightly lower sound quality at the same + bitrate. According to comparisons on websites, SBC at the highest 328kbit/s + has sound quality approximately between 224 kbit/s and 256 kbit/s MP3. + Additionally, improper settings, poor signal, devices not supporting high + bitpool, etc., can all cause transmission bitrate to drop and reduce sound + quality. The sound quality of the headset or speaker itself is also a very + important factor. The following shows bitrates for different bitpools: ![A2DP + Stack](../../assets/a2dp_sbc_bitpool.png) # Sifli SDK A2DP Introduction -This document is based on the Sifli SDK and introduces how to use basic A2DP functions as an A2DP sink role. -The involved files are as follows: +This document is based on the Sifli SDK and introduces how to use basic A2DP +functions as an A2DP sink role. The involved files are as follows: - bts2_app_interface - bts2_app_av - bts2_app_av_snk - + ## A2DP Sink Initialization -- A2DP initialization functions: bt_av_init, bt_avsnk_init, will first initialize A2DP, then initialize A2DP sink -- A2DP sink service enable function: bt_avsnk_open, enables A2DP sink functionality +- A2DP initialization functions: bt_av_init, bt_avsnk_init, will first + initialize A2DP, then initialize A2DP sink +- A2DP sink service enable function: bt_avsnk_open, enables A2DP sink + functionality ```c //Initialize A2DP @@ -251,25 +307,34 @@ static void bt_avsnk_init_data(bts2s_avsnk_inst_data *inst, bts2_app_stru *bts2_ ``` ## A2DP Sink Device Connection -The following process describes how A2DP sink discovers, connects, and plays music from remote devices. -1. The first step is to discover available A2DP source devices (e.g., phones, computers) nearby. To do this, A2DP sink can perform a search for nearby devices, then use SDP to retrieve A2DP source services from those devices that support the A2DP source role. -2. Select an A2DP source device to connect to. Initiate an ACL connection to the selected device. -3. A2DP connection. Once the ACL connection is created, A2DP sink can initiate an L2CAP connection for the A2DP signal channel. After connecting to the A2DP signal channel, a series of A2DP commands need to be initiated, then A2DP sink can initiate an L2CAP connection for the A2DP media channel. +The following process describes how A2DP sink discovers, connects, and plays +music from remote devices. +1. The first step is to discover available A2DP source devices (e.g., phones, + computers) nearby. To do this, A2DP sink can perform a search for nearby + devices, then use SDP to retrieve A2DP source services from those devices + that support the A2DP source role. +2. Select an A2DP source device to connect to. Initiate an ACL connection to the + selected device. +3. A2DP connection. Once the ACL connection is created, A2DP sink can initiate + an L2CAP connection for the A2DP signal channel. After connecting to the A2DP + signal channel, a series of A2DP commands need to be initiated, then A2DP + sink can initiate an L2CAP connection for the A2DP media channel. 4. Play audio sent by the A2DP source. 5. Either A2DP sink or A2DP source can terminate the connection at any time. -This section won't reorganize the connection process from HCI to L2CAP to AVDTP, but will directly show the AVDTP and A2DP interaction: -![A2DP Stack](../../assets/a2dp_connect.png) -Step 1) Development board initiates AVDTP discover command to query SEIDs supported by the phone, phone responds -Step 2) Development board gets SEP configurable information based on SEID, phone responds -Step 3) Development board sets playback parameters (sampling rate, number of channels, bit width, etc.), phone responds -Step 4) Development board opens SEP, phone responds -Step 5) Phone sends Start instruction to prepare for music playback, development board responds -Step 6) Phone sends music -Step 7) Phone pauses playback, development board responds -Step 8) Phone closes SEP, development board responds - -- A2DP sink device connection interface: - //Users can call the following interface to connect A2DP + This section won't reorganize the connection process from HCI to L2CAP to + AVDTP, but will directly show the AVDTP and A2DP interaction: ![A2DP + Stack](../../assets/a2dp_connect.png) Step 1) Development board initiates + AVDTP discover command to query SEIDs supported by the phone, phone responds + Step 2) Development board gets SEP configurable information based on SEID, + phone responds Step 3) Development board sets playback parameters (sampling + rate, number of channels, bit width, etc.), phone responds Step 4) + Development board opens SEP, phone responds Step 5) Phone sends Start + instruction to prepare for music playback, development board responds Step 6) + Phone sends music Step 7) Phone pauses playback, development board responds + Step 8) Phone closes SEP, development board responds + +- A2DP sink device connection interface: //Users can call the following + interface to connect A2DP - bts2_app_interface connection interface: bt_interface_conn_ext - bts2_app_av_snk connection interface: bt_avsnk_conn_2_src ```c @@ -347,9 +412,9 @@ void bt_av_conn(BTS2S_BD_ADDR *bd_addr, uint8_t peer_role) av_conn_req(bts2_task_get_app_task_id(), *bd_addr, peer_role_1, local_role); } ``` - -- A2DP sink device disconnection interface: - //Users can call the following interface to disconnect A2DP + +- A2DP sink device disconnection interface: //Users can call the following + interface to disconnect A2DP - bts2_app_interface disconnection interface: bt_interface_disc_ext - bts2_app_av_snk disconnection interface: bt_avsnk_disc_by_addr ```c @@ -385,19 +450,20 @@ void bt_avsnk_disc_by_addr(BTS2S_BD_ADDR *bd_addr, BOOL is_close) } } ``` - + - A2DP sink event handling: - A2DP sink connection status callback event - A2DP sink connection success: BT_NOTIFY_A2DP_PROFILE_CONNECTED - A2DP sink connection disconnected: BT_NOTIFY_A2DP_PROFILE_DISCONNECTED - A2DP sink playback status callback event - A2DP sink receives play command from remote: BT_NOTIFY_A2DP_START_IND - - A2DP sink receives pause command from remote: BT_NOTIFY_A2DP_SUSPEND_IND - - A2DP sink receives audio data from remote: BT_NOTIFY_A2DP_MEDIA_DATA_IND + - A2DP sink receives pause command from remote: + BT_NOTIFY_A2DP_SUSPEND_IND + - A2DP sink receives audio data from remote: + BT_NOTIFY_A2DP_MEDIA_DATA_IND -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: +:::{note} Note: The address parameters passed by the two interfaces need to be +converted accordingly. ::: ```c // After calling the A2DP connection API, the A2DP connection success message is notified to the user // Users need to implement the hdl function to receive notify events, e.g.: bt_notify_handle @@ -562,8 +628,10 @@ static void bt_av_sbc_cfg_para_select(bts2s_av_inst_data *inst, uint16_t con_idx } ``` ## A2DP Function Usage Demo -- First, register the handler function to receive notify events during project initialization -- Input the MAC address of the phone to connect, wait for connection success message +- First, register the handler function to receive notify events during project + initialization +- Input the MAC address of the phone to connect, wait for connection success + message - Play music on phone ```c int bt_sifli_notify_a2dp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -599,7 +667,7 @@ int bt_sifli_notify_a2dp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t da //Received audio data from remote device, users implement corresponding handling functions, pass data to audio decode module for decoding then output to hardware for playback break; } - + default: return -1; } @@ -680,4 +748,4 @@ bt_interface_conn_ext((unsigned char *)(mac), BT_PROFILE_A2DP); // @endcode */ -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_a2dp_source_profile.md b/docs/source/en/middleware/bt_a2dp_source_profile.md index 968d92b0d..e1325f93a 100644 --- a/docs/source/en/middleware/bt_a2dp_source_profile.md +++ b/docs/source/en/middleware/bt_a2dp_source_profile.md @@ -1,155 +1,188 @@ # BT_A2DP_SOURCE -A2DP (Advanced Audio Distribution Profile) is a Bluetooth audio transmission protocol, typically used for Bluetooth headphones. A2DP protocol's audio data is transmitted over ACL Link, which is distinguished from voice data transmitted over SCO. A2DP does not include remote control functionality; remote control functionality refers to the AVRCP protocol. AVDTP defines the parameter negotiation, establishment, and transmission process of data stream handles between Bluetooth devices, as well as the signaling entity formats that are mutually exchanged. This protocol is the foundation protocol of the A2DP framework. - -A2DP is designed to transmit high-quality audio streams over Bluetooth connections. The basic compression algorithm it uses is SBC, which is used to reduce the size of audio data while maintaining high sound quality. SBC is a mandatory compression algorithm that must be supported. In addition to SBC, A2DP can also support other advanced codecs such as AAC, LHDC, etc., but support for these codecs depends on the device's own support capabilities. - -A2DP implementation relies on GAVDP and GAP, where GAVDP defines the stream connection establishment process. The protocol dependency relationship of A2DP is shown in the following diagram: -![A2DP Stack](../../assets/a2dp_arch.png) - -In A2DP, two different roles are defined: SRC (source) and SNK (sink). SRC sends audio data, SNK receives audio data. The corresponding protocol model is as follows: -![A2DP Stack](../../assets/a2dp_stack.png) - -The main roles included in A2DP Profile are: +A2DP (Advanced Audio Distribution Profile) is a Bluetooth audio transmission +protocol, typically used for Bluetooth headphones. A2DP protocol's audio data is +transmitted over ACL Link, which is distinguished from voice data transmitted +over SCO. A2DP does not include remote control functionality; remote control +functionality refers to the AVRCP protocol. AVDTP defines the parameter +negotiation, establishment, and transmission process of data stream handles +between Bluetooth devices, as well as the signaling entity formats that are +mutually exchanged. This protocol is the foundation protocol of the A2DP +framework. - source (SRC): device that sends audio data - sink (SNK): device that receives audio data -A2DP is built on the foundation of the AVDTP transport protocol. AVDTP specifies how connections are established. After the connection is established, audio data can be sent and received after compression. Audio data is bidirectional. The A2DP data transmission and reception process based on AVDTP is shown in the following diagram: -![A2DP Stack](../../assets/a2dp_transport_data.png) - -Overall summary of the entire process: -1. UL collects PCM data and sends it to A2DP. A2DP compresses it into specific audio formats through codec PCM lib (SBC, MPEG-1,2 Audio MPEG-2,4 AAC ATRAC family, or custom encoder pcm lib), then hands it to AVDTP. AVDTP transfers it to L2CAP, L2CAP transfers it to HCI through ACL format, then reaches the BT chip and transmits via RF. -2. BT chip receives incoming data via RF, then transfers it to HCI through ACL, then to L2CAP, L2CAP to AVDTP, AVDTP to A2DP. A2DP receives compressed data from the remote device, which is then decompressed into PCM data through codec pcm lib (SBC, MPEG-1,2 Audio MPEG-2,4 AAC ATRAC family, or custom encoder pcm lib), and then handed to the sound card for playback. +A2DP is designed to transmit high-quality audio streams over Bluetooth +connections. The basic compression algorithm it uses is SBC, which is used to +reduce the size of audio data while maintaining high sound quality. SBC is a +mandatory compression algorithm that must be supported. In addition to SBC, A2DP +can also support other advanced codecs such as AAC, LHDC, etc., but support for +these codecs depends on the device's own support capabilities. + +A2DP implementation relies on GAVDP and GAP, where GAVDP defines the stream +connection establishment process. The protocol dependency relationship of A2DP +is shown in the following diagram: ![A2DP Stack]{1} +1. UL collects PCM data and sends it to A2DP. A2DP compresses it into specific + audio formats through codec PCM lib (SBC, MPEG-1,2 Audio MPEG-2,4 AAC ATRAC + family, or custom encoder pcm lib), then hands it to AVDTP. AVDTP transfers + it to L2CAP, L2CAP transfers it to HCI through ACL format, then reaches the + BT chip and transmits via RF. +2. BT chip receives incoming data via RF, then transfers it to HCI through ACL, + then to L2CAP, L2CAP to AVDTP, AVDTP to A2DP. A2DP receives compressed data + from the remote device, which is then decompressed into PCM data through + codec pcm lib (SBC, MPEG-1,2 Audio MPEG-2,4 AAC ATRAC family, or custom + encoder pcm lib), and then handed to the sound card for playback. ## AVDTP Introduction -AVDTP (A/V Distribution Transport Protocol) is an audio/video distribution transport protocol, mainly used for transmitting audio/video data. The architecture diagram of the entire protocol stack is as follows: -![A2DP Stack](../../assets/avdtp_arch.png) - +AVDTP (A/V Distribution Transport Protocol) is an audio/video distribution +transport protocol, mainly used for transmitting audio/video data. The +architecture diagram of the entire protocol stack is as follows: ![A2DP +Stack](../../assets/avdtp_arch.png) 1. AVDTP Terminology Introduction - Stream: Streaming data between two point-to-point devices. - - Source (SRC) and Sink (SNK): SRC is the sender of audio/video, SNK is the receiver of audio/video. - - Initiator (INT) and Acceptor (ACP): The device that initiates the process acts as the initiator, and the device that accepts the initiation is the acceptor. Note that INT and ACP are independent of the SRC and SNK defined by the upper application. In a CMD and RESPONSE, the device sending the CMD is the INT role, and the device responding with RESPONSE is the ACP role, so their roles will be dynamically switching. - - Application and Transport Service Capabilities: Application service and transport service capabilities. Application service capabilities include negotiating and configuring codec of source devices, content protection systems, etc.; transport service capabilities include data packet segmentation and reassembly, packet loss detection, etc. - - Services, Service Categories, and Service Parameters: Services, service categories, service parameters. - - Media Packets, Recovery Packets, and Reporting Packets: Media packets, data recovery packets, report packets. - - Stream End Point (SEP): Stream endpoint, which is an application that exposes available transport services and A/V capabilities for negotiating a stream. - - Stream Context (SC): Stream context. Refers to the common understanding of stream configuration reached by two peer devices during the stream setup process, including selected services, parameters, and transport channel allocation. - - Stream Handle (SH): Stream handle. An independent identifier allocated after SRC and SNK establish a connection, representing the upper layer's reference to the stream. - - Stream End Point Identifier (SEID): Stream endpoint identifier, cross-device reference for specific devices. + - Source (SRC) and Sink (SNK): SRC is the sender of audio/video, SNK is the + receiver of audio/video. + - Initiator (INT) and Acceptor (ACP): The device that initiates the process + acts as the initiator, and the device that accepts the initiation is the + acceptor. Note that INT and ACP are independent of the SRC and SNK defined + by the upper application. In a CMD and RESPONSE, the device sending the CMD + is the INT role, and the device responding with RESPONSE is the ACP role, + so their roles will be dynamically switching. + - Application and Transport Service Capabilities: Application service and + transport service capabilities. Application service capabilities include + negotiating and configuring codec of source devices, content protection + systems, etc.; transport service capabilities include data packet + segmentation and reassembly, packet loss detection, etc. + - Services, Service Categories, and Service Parameters: Services, service + categories, service parameters. + - Media Packets, Recovery Packets, and Reporting Packets: Media packets, data + recovery packets, report packets. + - Stream End Point (SEP): Stream endpoint, which is an application that + exposes available transport services and A/V capabilities for negotiating a + stream. + - Stream Context (SC): Stream context. Refers to the common understanding of + stream configuration reached by two peer devices during the stream setup + process, including selected services, parameters, and transport channel + allocation. + - Stream Handle (SH): Stream handle. An independent identifier allocated + after SRC and SNK establish a connection, representing the upper layer's + reference to the stream. + - Stream End Point Identifier (SEID): Stream endpoint identifier, + cross-device reference for specific devices. - Stream End Point State: Stream endpoint state. - - Transport Session: Transport session. Within the A/V transport layer, streams can be decomposed into one, two, or multiple three transport sessions between paired AVDTP entities. - - Transport Session Identifier (TSID): Transport session identifier. Represents a reference to a transport session. - - Transport Channel: Transport channel. Transport channel refers to the abstraction of the underlying bearer program of the A/V transport layer, always corresponding to L2CAP channels. - - Transport Channel Identifier (TCID): Transport channel identifier. Represents a reference to a transport channel. + - Transport Session: Transport session. Within the A/V transport layer, + streams can be decomposed into one, two, or multiple three transport + sessions between paired AVDTP entities. + - Transport Session Identifier (TSID): Transport session identifier. + Represents a reference to a transport session. + - Transport Channel: Transport channel. Transport channel refers to the + abstraction of the underlying bearer program of the A/V transport layer, + always corresponding to L2CAP channels. + - Transport Channel Identifier (TCID): Transport channel identifier. + Represents a reference to a transport channel. - Reserved for Future Additions (RFA): Reserved for future additions. - Reserved for Future Definitions (RFD): Reserved for future definitions. - -2. AVDTP Packet Format -AVDTP mainly has two types of packets: signal packets on the signal channel and media packets on the media channel. -![A2DP Stack](../../assets/avdtp_signal_packet.png) -The above is the Signal header format, which can be seen to have 3 packet formats: -  1) Single packet -  2) Start packet, generally used for the first packet when packet size > MTU fragmentation -  3) Continue packet and end packet, generally used for continue packets and end packets when packet size > MTU -The following explains the parameters: - - Transaction Label: Transport identifier, 4 bits, filled by the INT role, ACP must return the same value - - Packet Type: Packet type, with the following types: -![A2DP Stack](../../assets/avdtp_transaction_label.png) -Message Type: Message type, with the following types: -![A2DP Stack](../../assets/avdtp_message_type.png) -Signal Identifier: Signaling identifier, with the following values: -![A2DP Stack](../../assets/avdtp_signal_identifer.png) -NOSP = Number Of Signal Packets: Start packet will inform how many subsequent packets need to be transmitted - -3. AVDTP Signal Commands -There are the following signaling commands in total: -![A2DP Stack](../../assets/avdtp_signal_identifer.png) - -Before explaining specific commands, let's first lay some groundwork by explaining Service Capabilities, which will all be used, so we'll explain them in advance. -The Service Capabilities format is as follows: -![A2DP Stack](../../assets/avdtp_service_capability.png) -This part is also similar to the TLV (Type Length Value) type, where Service Category is TYPE, with values as follows: -![A2DP Stack](../../assets/avdtp_service_capability_value.png) -Where Length Of Service Capabilities (LOSC) is similar to length, i.e., the length of the subsequent Service Capabilities Information Elements. -Service Capabilities Information Elements are specific values, which require a large section to explain. Here we mainly explain Media Codec Capabilities. -![A2DP Stack](../../assets/avdtp_media_codec_capability.png) -Where Media Type has the following values: -![A2DP Stack](../../assets/avdtp_media_type.png) -Where Media Codec Type has the following values: -![A2DP Stack](../../assets/avdtp_media_codec.png) -The Media Codec Specific Information Elements in this part are some upper-layer codec information, such as the following figure for SBC: -![A2DP Stack](../../assets/avdtp_sbc_media_codec.png) - -- 3.1 AVDTP Signal Commands -Each AVDTP endpoint will register one or more SEPs, identified by SEID. This command is to obtain the SEP information of the peer, including SEID (SEP ID), In Use (whether it is being used), Media Type (Audio, Media, MultiMedia), TSEP (whether the role is Sink or Source) -The process is as follows: -![A2DP Stack](../../assets/avdtp_discover.png) - -- 3.2 Get Capabilities -This command uses SEID to obtain the peer's Capabilities. The Capabilities have been introduced before. Let's look at the program flow: -![A2DP Stack](../../assets/avdtp_get_capability.png) - -- 3.3 Get All Capabilities -This command is used to replace Get Capabilities, also using SEID to obtain the peer's Capabilities. The Capabilities have been introduced before. Let's look at the program flow: -![A2DP Stack](../../assets/avdtp_get_all_capability.png) - -- 3.4 Set Configuration Command -After obtaining Capabilities, this part selects specific functional parameters. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_set_configure.png) - -- 3.5 Get Stream Configuration -This command is used to obtain configuration based on SEID. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_get_configure.png) - -- 3.6 Stream Establishment -This command is used to open a certain SEID, i.e., establish a media channel. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_stream_establishment.png) - -- 3.7 Stream Start -This command is used to start media transmission for a SEID, i.e., start playing music. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_stream_start.png) - -- 3.8 Stream Suspend -This command is used to pause media transmission, i.e., pause music. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_suspend.png) - -- 3.9 Stream Release -This command is used to close media transmission. The program flow is as follows: -![A2DP Stack](../../assets/avdtp_release.png) + +2. AVDTP Packet Format AVDTP mainly has two types of packets: signal packets on + the signal channel and media packets on the media channel. ![A2DP + Stack](../../assets/avdtp_signal_packet.png) The above is the Signal header + format, which can be seen to have 3 packet formats: 1) Single packet 2) Start + packet, generally used for the first packet when packet size > MTU + fragmentation 3) Continue packet and end packet, generally used for continue + packets and end packets when packet size > MTU The following explains the + parameters: + - Transaction Label: Transport identifier, 4 bits, filled by the INT role, + ACP must return the same value + - Packet Type: Packet type, with the following types: ![A2DP + Stack](../../assets/avdtp_transaction_label.png) Message Type: Message + type, with the following types: ![A2DP + Stack](../../assets/avdtp_message_type.png) Signal Identifier: Signaling + identifier, with the following values: ![A2DP + Stack](../../assets/avdtp_signal_identifer.png) NOSP = Number Of Signal + Packets: Start packet will inform how many subsequent packets need to be + transmitted + +3. AVDTP Signal Commands There are the following signaling commands in total: + ![A2DP Stack](../../assets/avdtp_signal_identifer.png) + +Before explaining specific commands, let's first lay some groundwork by +explaining Service Capabilities, which will all be used, so we'll explain them +in advance. The Service Capabilities format is as follows: ![A2DP +Stack](../../assets/avdtp_service_capability.png) This part is also similar to +the TLV (Type Length Value) type, where Service Category is TYPE, with values as +follows: ![A2DP Stack](../../assets/avdtp_service_capability_value.png) Where +Length Of Service Capabilities (LOSC) is similar to length, i.e., the length of +the subsequent Service Capabilities Information Elements. Service Capabilities +Information Elements are specific values, which require a large section to +explain. Here we mainly explain Media Codec Capabilities. ![A2DP +Stack](../../assets/avdtp_media_codec_capability.png) Where Media Type has the +following values: ![A2DP Stack](../../assets/avdtp_media_type.png) Where Media +Codec Type has the following values: ![A2DP +Stack](../../assets/avdtp_media_codec.png) The Media Codec Specific Information +Elements in this part are some upper-layer codec information, such as the +following figure for SBC: ![A2DP Stack](../../assets/avdtp_sbc_media_codec.png) + +- 3.1 AVDTP Signal Commands Each AVDTP endpoint will register one or more SEPs, + identified by SEID. This command is to obtain the SEP information of the peer, + including SEID (SEP ID), In Use (whether it is being used), Media Type (Audio, + Media, MultiMedia), TSEP (whether the role is Sink or Source) The process is + as follows: ![A2DP Stack](../../assets/avdtp_discover.png) + +- 3.2 Get Capabilities This command uses SEID to obtain the peer's Capabilities. + The Capabilities have been introduced before. Let's look at the program flow: + ![A2DP Stack](../../assets/avdtp_get_capability.png) + +- 3.3 Get All Capabilities This command is used to replace Get Capabilities, + also using SEID to obtain the peer's Capabilities. The Capabilities have been + introduced before. Let's look at the program flow: ![A2DP + Stack](../../assets/avdtp_get_all_capability.png) + +- 3.4 Set Configuration Command After obtaining Capabilities, this part selects + specific functional parameters. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_set_configure.png) + +- 3.5 Get Stream Configuration This command is used to obtain configuration + based on SEID. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_get_configure.png) + +- 3.6 Stream Establishment This command is used to open a certain SEID, i.e., + establish a media channel. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_stream_establishment.png) + +- 3.7 Stream Start This command is used to start media transmission for a SEID, + i.e., start playing music. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_stream_start.png) + +- 3.8 Stream Suspend This command is used to pause media transmission, i.e., + pause music. The program flow is as follows: ![A2DP + Stack](../../assets/avdtp_suspend.png) + +- 3.9 Stream Release This command is used to close media transmission. The + program flow is as follows: ![A2DP Stack](../../assets/avdtp_release.png) ## A2DP Introduction -A2DP (Advanced Audio Distribution Profile) is a Bluetooth high-quality audio transmission protocol used for transmitting mono and stereo music (generally used for stereo dual-channel in A2DP), typically applied to Bluetooth headphones. A2DP does not include remote control functionality; remote control functionality refers to the AVRCP protocol. - -1. Audio Codec -In the above process, we also mentioned the need for Audio codec algorithms. In the A2DP protocol, there are the following regulations: -![A2DP Stack](../../assets/a2dp_codec.png) -First, all devices are mandatorily required to have SBC codec algorithm, which is a lossy algorithm with sound quality comparable to MP3. Additionally, it supports 3 optional algorithms: MPEG-1,2 audio/MPEG-2,4 AAC, ATRAC family. Of course, there are also some custom extended codec algorithms, such as the popular APTX, LDAC, etc. - -1.1 SBC Codec -SBC is a protocol mandatorily required to be supported by Bluetooth. The Codec Specific Information Elements are defined as follows: -![A2DP Stack](../../assets/a2dp_sbc_codec.png) -Sampling Frequency: This part is the sampling frequency. The Source end mandatorily requires support for either 44.1KHz or 48KHz, while Sink requires support for both 44.1KHz and 48KHz. The corresponding values are as follows: -![A2DP Stack](../../assets/a2dp_sbc_sample_frequency.png) -Channel Mode: Number of channels. Sink requires full support, while Source only mandatorily requires support for Mono, others are optional: -![A2DP Stack](../../assets/a2dp_sbc_channel_mode.png) -Block Length: Block length -![A2DP Stack](../../assets/a2dp_sbc_block_length.png) -Subbands: Subbands -![A2DP Stack](../../assets/a2dp_sbc_subbands.png) -Allocation Method: Allocation method -![A2DP Stack](../../assets/a2dp_sbc_allocation_method.png) -Minimum Bitpool Value: -Maximum Bitpool Value: In playback devices, you can set SBC encoding quality, this value is called bitpool, approximately 1 bitpool = 6~7 kbit/s. SBC is an encoding format with relatively low complexity and slightly inferior sound quality at the same bit rate. According to comparisons on this website, the highest 328kbit/s SBC sound quality is approximately between 224 kbit/s to 256 kbit/s MP3. Additionally, improper settings, poor signal, device not supporting high bitpool, etc., will cause transmission bit rate to decrease and sound quality to deteriorate. The sound quality of the headphones or speakers themselves is also a very important factor. The following are bit rates for different bitpools: -![A2DP Stack](../../assets/a2dp_sbc_bitpool.png) +A2DP (Advanced Audio Distribution Profile) is a Bluetooth high-quality audio +transmission protocol used for transmitting mono and stereo music (generally +used for stereo dual-channel in A2DP), typically applied to Bluetooth +headphones. A2DP does not include remote control functionality; remote control +functionality refers to the AVRCP protocol. +1. Audio Codec In the above process, we also mentioned the need for Audio codec + algorithms. In the A2DP protocol, there are the following regulations: ![A2DP + Stack](../../assets/a2dp_codec.png) First, all devices are mandatorily + required to have SBC codec algorithm, which is a lossy algorithm with sound + quality comparable to MP3. Additionally, it supports 3 optional algorithms: + MPEG-1,2 audio/MPEG-2,4 AAC, ATRAC family. Of course, there are also some + custom extended codec algorithms, such as the popular APTX, LDAC, etc. # Sifli SDK A2DP Introduction -This document is mainly based on Sifli SDK, introducing how to use basic A2DP functions as an A2DP source role. -Related files include: +This document is mainly based on Sifli SDK, introducing how to use basic A2DP +functions as an A2DP source role. Related files include: - bts2_app_interface - bts2_app_av - bts2_app_av_src - + ## A2DP Source Initialization -- A2DP initialization functions: bt_av_init, bt_avsrc_init, will first initialize A2DP, then initialize A2DP source +- A2DP initialization functions: bt_av_init, bt_avsrc_init, will first + initialize A2DP, then initialize A2DP source ```c //Initialize A2DP @@ -233,15 +266,23 @@ static void bt_avsrc_init_data(bts2s_av_inst_data *inst, bts2_app_stru *bts2_app ``` ## A2DP Source Device Connection -The following process describes how A2DP source discovers, connects to, and plays music. -1. The first step is to discover available A2DP sink devices (e.g., headphones, speakers) in the vicinity. For this, the A2DP source can perform a search on nearby devices, then use SDP to retrieve A2DP sink services from those devices that support the A2DP sink role. -2. Select an A2DP sink device to connect to. Choose the device to connect to and initiate an ACL connection. -3. A2DP connection. Once the ACL connection is established, the A2DP source can initiate an L2CAP connection for the A2DP signal channel. After connecting to the A2DP signal channel, a series of A2DP commands need to be initiated, then the A2DP source can initiate an L2CAP connection for the A2DP media channel. +The following process describes how A2DP source discovers, connects to, and +plays music. +1. The first step is to discover available A2DP sink devices (e.g., headphones, + speakers) in the vicinity. For this, the A2DP source can perform a search on + nearby devices, then use SDP to retrieve A2DP sink services from those + devices that support the A2DP sink role. +2. Select an A2DP sink device to connect to. Choose the device to connect to and + initiate an ACL connection. +3. A2DP connection. Once the ACL connection is established, the A2DP source can + initiate an L2CAP connection for the A2DP signal channel. After connecting to + the A2DP signal channel, a series of A2DP commands need to be initiated, then + the A2DP source can initiate an L2CAP connection for the A2DP media channel. 4. A2DP source starts playing music. 5. A2DP sink or A2DP source can terminate the connection at any time. -- A2DP source device connection interface: - //Users can call the following interface to connect A2DP +- A2DP source device connection interface: //Users can call the following + interface to connect A2DP - bts2_app_interface connection interface: bt_interface_conn_to_source_ext - bts2_app_av_src connection interface: bt_avsrc_conn_2_snk ```c @@ -320,9 +361,9 @@ void bt_av_conn(BTS2S_BD_ADDR *bd_addr, uint8_t peer_role) av_conn_req(bts2_task_get_app_task_id(), *bd_addr, peer_role_1, local_role); } ``` - -- A2DP source device disconnection interface: - //Users can call the following interface to disconnect A2DP + +- A2DP source device disconnection interface: //Users can call the following + interface to disconnect A2DP - bts2_app_interface disconnection interface: bt_interface_disc_ext - bts2_app_av_src disconnection interface: bt_avsnk_disc_by_addr ```c @@ -574,18 +615,20 @@ static uint16_t bt_avsrc_send_data(struct rt_ringbuffer *rb) return bytes_rd; } ``` - + - A2DP source event handling: - A2DP source connection status callback events: - A2DP source connection successful: BT_NOTIFY_A2DP_PROFILE_CONNECTED - - A2DP source connection disconnected: BT_NOTIFY_A2DP_PROFILE_DISCONNECTED + - A2DP source connection disconnected: + BT_NOTIFY_A2DP_PROFILE_DISCONNECTED - A2DP sink playback status callback events - - A2DP source receives response to play command sent to peer: BT_NOTIFY_A2DP_START_CFM - - A2DP source receives response to pause command sent to peer: BT_NOTIFY_A2DP_SUSPEND_CFM + - A2DP source receives response to play command sent to peer: + BT_NOTIFY_A2DP_START_CFM + - A2DP source receives response to pause command sent to peer: + BT_NOTIFY_A2DP_SUSPEND_CFM -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: +:::{note} Note: The address parameters passed by the two interfaces need to be +converted accordingly. ::: ```c // After calling the API to connect A2DP, the A2DP connection successful message is sent to the user through notify // Users need to implement hdl functions to receive notify events, such as: bt_notify_handle @@ -743,9 +786,11 @@ The search interface is: bt_interface_start_inquiry - A2DP source search event: BT_NOTIFY_COMMON_DISCOVER_IND ## A2DP Functionality Usage Demo -- First, during project initialization, register the processing function for receiving notify events +- First, during project initialization, register the processing function for + receiving notify events - Search for connectable devices -- Enter the MAC address of the phone to connect to, wait for connection success message +- Enter the MAC address of the phone to connect to, wait for connection success + message - Phone plays music ```c int bt_sifli_notify_a2dp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -777,7 +822,7 @@ int bt_sifli_notify_a2dp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t da //Received suspend response from peer device, users implement their own corresponding processing functions break; } - + default: return -1; } @@ -865,4 +910,4 @@ bt_interface_start_inquiry(); // Connect to headphones: 001bdcf4b6bd unsigned char mac[6] = {0x00,0x1b,0xdc,0xf4,0xb6,0xbd} bt_interface_conn_to_source_ext((unsigned char *)(mac), BT_PROFILE_A2DP); -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_avrcp_profile.md b/docs/source/en/middleware/bt_avrcp_profile.md index 82d98db47..91b1b9bf2 100644 --- a/docs/source/en/middleware/bt_avrcp_profile.md +++ b/docs/source/en/middleware/bt_avrcp_profile.md @@ -1,152 +1,183 @@ # BT_AVRCP -AVRCP (Audio/Video Remote Control Profile) defines the characteristics and processes for communication between Bluetooth devices and audio/video control functions, and is also used for remote control of audio/video devices. The underlying transport is based on the AVCTP transport protocol. This Profile defines the AV/C digital command control set. Commands and information are transmitted through the AVCTP (Audio/Video Control Transport Protocol) protocol. Browsing functionality is through the second channel of AVCTP rather than AV/C. Media information transmission is through the BIP (Bluetooth Basic Imaging Profile) protocol based on the OBEX protocol. - +AVRCP (Audio/Video Remote Control Profile) defines the characteristics and +processes for communication between Bluetooth devices and audio/video control +functions, and is also used for remote control of audio/video devices. The +underlying transport is based on the AVCTP transport protocol. This Profile +defines the AV/C digital command control set. Commands and information are +transmitted through the AVCTP (Audio/Video Control Transport Protocol) protocol. +Browsing functionality is through the second channel of AVCTP rather than AV/C. +Media information transmission is through the BIP (Bluetooth Basic Imaging +Profile) protocol based on the OBEX protocol. ## AVCTP Introduction -1. AVCTP Protocol Architecture -The AVCTP protocol describes the format and mechanism for exchanging Audio/Video control signals between Bluetooth devices. It is a general protocol, with specific control information implemented by its designated protocols (such as AVRCP). AVCTP itself only specifies the general format of control commands and responses. - -Several important points: -  (1) AVCTP is based on point-to-point L2CAP connections. -  (2) Each AVCTP connection should support both AVRCP CT and TG functionality. -  (3) There may be multiple AVCTP connections between two devices, but each AVCTP connection has a unique PSM value. -  (4) Each AVCTP packet should be transmitted in one L2CAP packet. -  (5) The same transaction Label on different L2CAP channels belongs to different messages. That is, packets on two L2CAP channels are unrelated and cannot belong to the same message. -![AVCTP Architect](../../assets/avctp_arch.png) - -2. AVCTP Packet Format -AVCTP packet format is divided into two types: -  1) Unfragmented (smaller than L2CAP MTU) -  2) Fragmented (larger than L2CAP MTU) -The following introduces the format of each type: -  1) Unfragmented (smaller than L2CAP MTU) -![AVCTP Packet](../../assets/avctp_packet.png) - - Transaction label field: (octet 0, bits 7-4) Transport identifier, provided by upper layer; - - - Packet_type field: (octet 0, bits 3 and 2) This part 00b indicates unfragmented; +1. AVCTP Protocol Architecture The AVCTP protocol describes the format and + mechanism for exchanging Audio/Video control signals between Bluetooth + devices. It is a general protocol, with specific control information + implemented by its designated protocols (such as AVRCP). AVCTP itself only + specifies the general format of control commands and responses. + +Several important points: (1) AVCTP is based on point-to-point L2CAP +connections. (2) Each AVCTP connection should support both AVRCP CT and TG +functionality. (3) There may be multiple AVCTP connections between two devices, +but each AVCTP connection has a unique PSM value. (4) Each AVCTP packet should +be transmitted in one L2CAP packet. (5) The same transaction Label on different +L2CAP channels belongs to different messages. That is, packets on two L2CAP +channels are unrelated and cannot belong to the same message. ![AVCTP +Architect](../../assets/avctp_arch.png) + + +2. AVCTP Packet Format AVCTP packet format is divided into two types: 1) + Unfragmented (smaller than L2CAP MTU) 2) Fragmented (larger than L2CAP MTU) + The following introduces the format of each type: 1) Unfragmented (smaller + than L2CAP MTU) ![AVCTP Packet](../../assets/avctp_packet.png) + - Transaction label field: (octet 0, bits 7-4) Transport identifier, provided + by upper layer; + + - Packet_type field: (octet 0, bits 3 and 2) This part 00b indicates + unfragmented; - C/R: (octet 0, bit 1) 0 represents command, 1 represents response - - PID: bit (octet 0, bit 0) Set to 0 in command, set to 0 in response represents normal PID + - PID: bit (octet 0, bit 0) Set to 0 in command, set to 0 in response + represents normal PID + + - Profile Identifier (PID): This part fills in 16-bit UUID, such as AVRCP + UUID 0x110e. The subsequent Message Information is the upper layer protocol + data - - Profile Identifier (PID): This part fills in 16-bit UUID, such as AVRCP UUID 0x110e. The subsequent Message Information is the upper layer protocol data +2) Fragmented (larger than L2CAP MTU) Fragmented data packet format has three +types in total: ![AVCTP Start Packet](../../assets/avctp_start_packet.png) +![AVCTP Continue Packet](../../assets/avctp_continue_packet.png) ![AVCTP End +Packet](../../assets/avctp_end_packet.png) Here we only introduce two aspects, +others are consistent with unfragmented: Packet_type: Start packet is 01b, +continue packet 10b, end packet is 11b Number of AVCTP Packets: Indicates the +total number of fragmented packets, including this start packet, so the number +of this packet must be greater than 1. -    2) Fragmented (larger than L2CAP MTU) -Fragmented data packet format has three types in total: -    ![AVCTP Start Packet](../../assets/avctp_start_packet.png) -    ![AVCTP Continue Packet](../../assets/avctp_continue_packet.png) -    ![AVCTP End Packet](../../assets/avctp_end_packet.png) -    Here we only introduce two aspects, others are consistent with unfragmented: -        Packet_type: Start packet is 01b, continue packet 10b, end packet is 11b -        Number of AVCTP Packets: Indicates the total number of fragmented packets, including this start packet, so the number of this packet must be greater than 1. ## AVRCP Introduction -1. AVRCP Protocol Architecture -![AVRCP ARCH](../../assets/avrcp_arch.png) -AVRCP Profile defines two roles: - - CT (controller devices) - Controller is a device that initiates transactions by sending command frames to target devices, such as headphones, speakers, car Bluetooth devices. - - TG (target devices) - Target is a device that receives command frames sent by the controller and generates corresponding response frames, such as mobile phones. - -2. AVRCP Connection -AVCTP connection is divided into two channels: Control channel and Browsing channel, with different corresponding L2CAP PSMs. The control channel PSM is 0x0017, AVCTP browsing channel PSM is 0x001B. Both controller and target roles can initiate connections on both channels. Note that AVCTP browsing part based on L2CAP cannot use basic mode, Enhanced Retransmission Mode is required, and AVCTP browsing channel connection can only be initiated when both sides support AVCTP browsing. -The entire establishment process follows these flows: -![AVRCP Controller Connect](../../assets/avrcp_connect_ct.png) -![AVRCP Target Connect](../../assets/avrcp_connect_tg.png) -![AVRCP Mult Connect](../../assets/avrcp_connect_mult.png) - -3. AVRCP Disconnection -Disconnection can be operated from AVRCP controller or target role. Note that if there is an AVCTP browsing connection, disconnect the AVCTP browsing channel connection first. The entire process is as follows: -![AVRCP Disconnect](../../assets/avrcp_disconnect.png) - -4. AVRCP AV/C Command Format - 4.1 VENDOR DEPENDENT Format -  1) Command header format: -  ![AVRCP Vendor Command](../../assets/avrcp_vendor_command.png) -  Ctype: This is the command type, divided into 5 types in total. Generally, we use 3 types in AVRCP protocol: CONTROL control command, STATUS get status command, NOTIFY notification command. The types are as follows: -  ![AVRCP Vendor Ctype](../../assets/avrcp_vendor_ctype.png) -  Subunit_type: Subunit type, with the following definitions. Generally use PANEL in AVRCP -  ![AVRCP Vendor Subunit](../../assets/avrcp_vendor_subunit.png) -  Subunit_id: This part we generally fill 0 -  Opcode: We only need to know what the specific command opcode is. VENDOR DEPENDENT value is 0. -  Company ID: This part needs to fill in the Bluetooth SIG ID -  2) Response header format: -  ![AVRCP Response Header](../../assets/avrcp_response_header.png) -  As you can see, command and response formats are exactly the same. We won't repeat other parameters. Let's talk about Response values: -  ![AVRCP Response status](../../assets/avrcp_response_status.png) - - 4.2 PASS THROUGH Format -  1) Command: -  ![AVRCP Pass Through Command](../../assets/avrcp_pass_through_command.png) - -  1) Response: -  ![AVRCP Pass Through Response](../../assets/avrcp_pass_through_response.png) - -  We won't introduce others in detail, only Operation_ID and state_flag -   Operation_ID: Operation ID -   ![AVRCP Pass Through Operation ID](../../assets/avrcp_pass_through_operation_id.png) -   ![AVRCP Pass Through Operation ID](../../assets/avrcp_pass_through_operation_id_1.png) -   ![AVRCP Pass Through Operation ID](../../assets/avrcp_pass_through_operation_id_2.png) -   ![AVRCP Pass Through Operation ID](../../assets/avrcp_pass_through_operation_id_3.png) - -   State_flag: Simply put, it's divided into press and release actions. When sending, this value is 0 for press and 1 for release - - 4.3 AVRCP Specific Commands -  AVRCP specific commands include the following: -  ![AVRCP Special Command](../../assets/avrcp_special_command_0.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_1.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_2.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_3.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_4.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_5.png) -  ![AVRCP Special Command](../../assets/avrcp_special_command_6.png) - -  1) Get Capabilities -  ![AVRCP Get Capability](../../assets/avrcp_get_capability.png) -  This is sent by AVRCP controller to target to get the capabilities of the peer device, including company name and supported events. -  ![AVRCP Get Capability Packet](../../assets/avrcp_get_capability_packet.png) -  Get company ID response format: -  ![AVRCP Get Capability Company](../../assets/avrcp_get_capability_cpmpany.png) -  Get supported event response format: -  ![AVRCP Get Capability Event](../../assets/avrcp_get_capability_event.png) -  Where EventID includes: -  ![AVRCP Event Support](../../assets/avrcp_event_support.png) -  In practical applications, we generally only use Get Capability for event to get the events supported by the peer, facilitating notify registration. As you can see in the above figure, it supports playback status change, track change, and player setting change. - -  2) Get PlayStatus -  This command is sent by controller to target to get playback status. The return value includes total song length, current song progress, and playback status, totaling 9 bytes (4 bytes song length, 4 bytes current progress, 1 byte playback status) -  ![AVRCP Get Play Status](../../assets/avrcp_get_play_status.png) - -  3) Register Notification -  This is CT registering messages with TG, then TG will notify when there are corresponding updates. The specific messages are those we mentioned earlier in get capability with event (Note: each registration is only valid once, need to re-register after receiving change): -  ![AVRCP Register Notify](../../assets/avrcp_register_notify.png) -  ![AVRCP Register Notify](../../assets/avrcp_register_notify_1.png) - -  Let's talk about each EVENT ID below: -  EVENT_PLAYBACK_STATUS_CHANGED: Playback status change, with the following values: -  ![AVRCP Play Status Register Notify](../../assets/avrcp_play_status_notify.png) -  EVENT_TRACK_CHANGED: Track name change -  EVENT_TRACK_REACHED_END: Track reached end -  EVENT_TRACK_REACHED_START: Track start -  EVENT_PLAYBACK_POS_CHANGED: Track playback progress change -  ![AVRCP Playback Pos Change Notify](../../assets/avrcp_playback_pos_change.png) -  EVENT_BATT_STATUS_CHANGED: Battery status change, with the following values: -  ![AVRCP Batt Status Change Notify](../../assets/avrcp_batt_status_change.png) - -  4) Metadata Attributes for Current Media Item -  This is mainly for getting song information (including name/album name/artist name/song index/total number of songs, etc.) -  ![AVRCP Get Element](../../assets/avrcp_get_element.png) -  AttributeID list is as follows: -  ![AVRCP Get Element Attribute](../../assets/avrcp_get_element_attribute.png) +1. AVRCP Protocol Architecture ![AVRCP ARCH](../../assets/avrcp_arch.png) AVRCP + Profile defines two roles: + - CT (controller devices) Controller is a device that initiates transactions + by sending command frames to target devices, such as headphones, speakers, + car Bluetooth devices. + - TG (target devices) Target is a device that receives command frames sent + by the controller and generates corresponding response frames, such as + mobile phones. + +2. AVRCP Connection AVCTP connection is divided into two channels: Control + channel and Browsing channel, with different corresponding L2CAP PSMs. The + control channel PSM is 0x0017, AVCTP browsing channel PSM is 0x001B. Both + controller and target roles can initiate connections on both channels. Note + that AVCTP browsing part based on L2CAP cannot use basic mode, Enhanced + Retransmission Mode is required, and AVCTP browsing channel connection can + only be initiated when both sides support AVCTP browsing. The entire + establishment process follows these flows: ![AVRCP Controller + Connect](../../assets/avrcp_connect_ct.png) ![AVRCP Target + Connect](../../assets/avrcp_connect_tg.png) ![AVRCP Mult + Connect](../../assets/avrcp_connect_mult.png) + + +3. AVRCP Disconnection Disconnection can be operated from AVRCP controller or + target role. Note that if there is an AVCTP browsing connection, disconnect + the AVCTP browsing channel connection first. The entire process is as + follows: ![AVRCP Disconnect](../../assets/avrcp_disconnect.png) + +4. AVRCP AV/C Command Format 4.1 VENDOR DEPENDENT Format 1) Command header + format: ![AVRCP Vendor Command](../../assets/avrcp_vendor_command.png) Ctype: + This is the command type, divided into 5 types in total. Generally, we use 3 + types in AVRCP protocol: CONTROL control command, STATUS get status command, + NOTIFY notification command. The types are as follows: ![AVRCP Vendor + Ctype](../../assets/avrcp_vendor_ctype.png) Subunit_type: Subunit type, with + the following definitions. Generally use PANEL in AVRCP ![AVRCP Vendor + Subunit](../../assets/avrcp_vendor_subunit.png) Subunit_id: This part we + generally fill 0 Opcode: We only need to know what the specific command + opcode is. VENDOR DEPENDENT value is 0. Company ID: This part needs to fill + in the Bluetooth SIG ID 2) Response header format: ![AVRCP Response + Header](../../assets/avrcp_response_header.png) As you can see, command and + response formats are exactly the same. We won't repeat other parameters. + Let's talk about Response values: ![AVRCP Response + status](../../assets/avrcp_response_status.png) + +4.2 PASS THROUGH Format 1) Command: ![AVRCP Pass Through +Command](../../assets/avrcp_pass_through_command.png) + +1) Response: ![AVRCP Pass Through +Response](../../assets/avrcp_pass_through_response.png) + +We won't introduce others in detail, only Operation_ID and state_flag +Operation_ID: Operation ID ![AVRCP Pass Through Operation +ID](../../assets/avrcp_pass_through_operation_id.png) ![AVRCP Pass Through +Operation ID](../../assets/avrcp_pass_through_operation_id_1.png) ![AVRCP Pass +Through Operation ID](../../assets/avrcp_pass_through_operation_id_2.png) +![AVRCP Pass Through Operation +ID](../../assets/avrcp_pass_through_operation_id_3.png) + +State_flag: Simply put, it's divided into press and release actions. When +sending, this value is 0 for press and 1 for release + +4.3 AVRCP Specific Commands AVRCP specific commands include the following: +![AVRCP Special Command](../../assets/avrcp_special_command_0.png) ![AVRCP +Special Command](../../assets/avrcp_special_command_1.png) ![AVRCP Special +Command](../../assets/avrcp_special_command_2.png) ![AVRCP Special +Command](../../assets/avrcp_special_command_3.png) ![AVRCP Special +Command](../../assets/avrcp_special_command_4.png) ![AVRCP Special +Command](../../assets/avrcp_special_command_5.png) ![AVRCP Special +Command](../../assets/avrcp_special_command_6.png) + +1) Get Capabilities ![AVRCP Get +Capability](../../assets/avrcp_get_capability.png) This is sent by AVRCP +controller to target to get the capabilities of the peer device, including +company name and supported events. ![AVRCP Get Capability +Packet](../../assets/avrcp_get_capability_packet.png) Get company ID response +format: ![AVRCP Get Capability +Company](../../assets/avrcp_get_capability_cpmpany.png) Get supported event +response format: ![AVRCP Get Capability +Event](../../assets/avrcp_get_capability_event.png) Where EventID includes: +![AVRCP Event Support](../../assets/avrcp_event_support.png) In practical +applications, we generally only use Get Capability for event to get the events +supported by the peer, facilitating notify registration. As you can see in the +above figure, it supports playback status change, track change, and player +setting change. + + +2) Get PlayStatus This command is sent by controller to target to get playback +status. The return value includes total song length, current song progress, and +playback status, totaling 9 bytes (4 bytes song length, 4 bytes current +progress, 1 byte playback status) ![AVRCP Get Play +Status](../../assets/avrcp_get_play_status.png) + +3) Register Notification This is CT registering messages with TG, then TG will +notify when there are corresponding updates. The specific messages are those we +mentioned earlier in get capability with event (Note: each registration is only +valid once, need to re-register after receiving change): ![AVRCP Register +Notify](../../assets/avrcp_register_notify.png) ![AVRCP Register +Notify](../../assets/avrcp_register_notify_1.png) + +Let's talk about each EVENT ID below: EVENT_PLAYBACK_STATUS_CHANGED: Playback +status change, with the following values: ![AVRCP Play Status Register +Notify](../../assets/avrcp_play_status_notify.png) EVENT_TRACK_CHANGED: Track +name change EVENT_TRACK_REACHED_END: Track reached end +EVENT_TRACK_REACHED_START: Track start EVENT_PLAYBACK_POS_CHANGED: Track +playback progress change ![AVRCP Playback Pos Change +Notify](../../assets/avrcp_playback_pos_change.png) EVENT_BATT_STATUS_CHANGED: +Battery status change, with the following values: ![AVRCP Batt Status Change +Notify](../../assets/avrcp_batt_status_change.png) + +4) Metadata Attributes for Current Media Item This is mainly for getting song +information (including name/album name/artist name/song index/total number of +songs, etc.) ![AVRCP Get Element](../../assets/avrcp_get_element.png) +AttributeID list is as follows: ![AVRCP Get Element +Attribute](../../assets/avrcp_get_element_attribute.png) # Sifli SDK AVRCP Introduction -This document is mainly based on Sifli SDK, introducing how to use basic AVRCP functions. -Related files include: +This document is mainly based on Sifli SDK, introducing how to use basic AVRCP +functions. Related files include: - bts2_app_interface - bts2_app_avrcp - + ## bt_avrcp Initialization -- AVRCP initialization function: bt_avrcp_int, initializes AVRCP related states and assigns initial values to flags +- AVRCP initialization function: bt_avrcp_int, initializes AVRCP related states + and assigns initial values to flags - AVRCP service enable function: bt_avrcp_open, enables AVRCP profile ```c @@ -218,11 +249,20 @@ void bt_avrcp_open(void) ``` ## AVRCP Device Connection -The following process describes how AVRCP CT discovers, connects to, and uses AVRCP TG services. -1. The first step is to discover available AVRCP TG devices in the vicinity. For this, AVRCP CT can perform a search on nearby devices, then use SDP to retrieve AVRCP TG services from those devices that support the AVRCP TG role. -2. Select an AVRCP TG device to connect to. Choose the device to connect to and initiate an ACL connection. -3. AVRCP connection. Once the ACL connection is established, AVRCP CT should initiate the AVRCP L2CAP connection. -4. After AVRCP is connected, it needs to first query the capabilities supported by the peer (the peer may also query the capabilities supported by this end and register corresponding notification events), then register corresponding notification events before using corresponding functions (such as controlling music pause/play, volume adjustment, etc.). +The following process describes how AVRCP CT discovers, connects to, and uses +AVRCP TG services. +1. The first step is to discover available AVRCP TG devices in the vicinity. For + this, AVRCP CT can perform a search on nearby devices, then use SDP to + retrieve AVRCP TG services from those devices that support the AVRCP TG role. +2. Select an AVRCP TG device to connect to. Choose the device to connect to and + initiate an ACL connection. +3. AVRCP connection. Once the ACL connection is established, AVRCP CT should + initiate the AVRCP L2CAP connection. +4. After AVRCP is connected, it needs to first query the capabilities supported + by the peer (the peer may also query the capabilities supported by this end + and register corresponding notification events), then register corresponding + notification events before using corresponding functions (such as controlling + music pause/play, volume adjustment, etc.). 5. AVRCP TG and AVRCP CT can terminate the connection at any time. - AVRCP device connection interface: @@ -285,7 +325,7 @@ void bt_avrcp_conn_2_dev(BTS2S_BD_ADDR *bd, BOOL is_target) } } ``` - + - AVRCP device disconnection interface: - bts2_app_interface disconnection interface: bt_interface_disc_ext - bts2_app_avrcp disconnection interface: bt_avrcp_disc_2_dev @@ -317,15 +357,14 @@ void bt_avrcp_disc_2_dev(BTS2S_BD_ADDR *bd_addr) } } ``` - + - AVRCP event handling: - AVRCP connection status callback events: - AVRCP connection successful: BT_NOTIFY_AVRCP_PROFILE_CONNECTED - AVRCP connection failed: BT_NOTIFY_AVRCP_PROFILE_DISCONNECTED -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: +:::{note} Note: The address parameters passed by the two interfaces need to be +converted accordingly. ::: ```c // After calling the API to connect AVRCP, the AVRCP connection successful message is sent to the user through notify // Users need to implement hdl functions to receive notify events, such as: bt_notify_handle @@ -465,8 +504,10 @@ void bt_interface_avrcp_get_element_attributes_request(U8 media_attribute); void bt_interface_avrcp_get_play_status_request(void); ## AVRCP Functionality Usage Demo -- First, during project initialization, register the processing function for receiving notify events -- Enter the MAC address of the phone to connect to, wait for connection success message +- First, during project initialization, register the processing function for + receiving notify events +- Enter the MAC address of the phone to connect to, wait for connection success + message - Play phone music, control phone play/pause ```c int bt_sifli_notify_avrcp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -542,7 +583,7 @@ int bt_sifli_notify_avrcp_event_hdl(uint16_t event_id, uint8_t *data, uint16_t d //Users implement their own corresponding processing functions, based on media_attribute can determine what information was obtained break; } - + default: return -1; } @@ -626,4 +667,4 @@ bt_interface_conn_ext((unsigned char *)(mac), BT_PROFILE_AVRCP); bt_interface_avrcp_pause(); @endcode */ -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_gatt.md b/docs/source/en/middleware/bt_gatt.md index 7d22ae8f3..9c973f6e9 100644 --- a/docs/source/en/middleware/bt_gatt.md +++ b/docs/source/en/middleware/bt_gatt.md @@ -1,17 +1,21 @@ # GATT over BR/EDR -GATT is a general specification for sending and receiving short data segments over Bluetooth connections. These short data segments are called attributes. GATT over BR/EDR mainly transmits data through BR/EDR L2CAP. - -This document is mainly based on Sifli SDK, introducing basic functionality support for GATT over BR/EDR. Related files include: -- bts2_app_interface -- bts2_app_bt_gatt +GATT is a general specification for sending and receiving short data segments +over Bluetooth connections. These short data segments are called attributes. +GATT over BR/EDR mainly transmits data through BR/EDR L2CAP. +This document is mainly based on Sifli SDK, introducing basic functionality +support for GATT over BR/EDR. Related files include: +- bts2_app_interface +- bts2_app_bt_gatt ## GATT Basic Functionality -- The main purpose of GATT over BR/EDR is to reuse BLE services, so GATT mainly registers BLE UUIDs to BR/EDR SDP +- The main purpose of GATT over BR/EDR is to reuse BLE services, so GATT mainly + registers BLE UUIDs to BR/EDR SDP - bts2_app_interface registration interface: bt_interface_bt_gatt_reg - Event after successful registration: BT_NOTIFY_GATT_REGISTER_RESPONSE - bts2_app_interface unregistration interface: bt_interface_bt_gatt_unreg - Event after successful unregistration: BT_NOTIFY_GATT_UNREGISTER_RESPONSE - - bts2_app_interface L2CAP MTU change interface: bt_interface_bt_gatt_mtu_changed + - bts2_app_interface L2CAP MTU change interface: + bt_interface_bt_gatt_mtu_changed - Event after MTU value change: BT_NOTIFY_GATT_CHANGE_MTU_RESPONSE ```c //register notify event handle function start @@ -114,4 +118,4 @@ typedef struct U8 att_uuid_len; U8 *att_uuid; } br_att_sdp_data_t; -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_hfp_ag_profile.md b/docs/source/en/middleware/bt_hfp_ag_profile.md index 880413203..08e378531 100644 --- a/docs/source/en/middleware/bt_hfp_ag_profile.md +++ b/docs/source/en/middleware/bt_hfp_ag_profile.md @@ -1,27 +1,44 @@ # HFP_AG -HFP (Hands-Free Profile) is a Bluetooth hands-free protocol that allows Bluetooth devices to control phone calls on peer Bluetooth devices, such as Bluetooth headsets controlling phone call answering, hanging up, rejecting, voice dialing, etc. Data interaction between the two Bluetooth ends in HFP is communicated through predefined AT commands. HFP defines two roles: Audio Gateway (AG) and Hands-Free component (HF): -- Audio Gateway (AG): This device serves as the gateway for audio input/output. Typical gateway devices are mobile phones -- Hands-Free component (HF): This device serves as the remote audio input/output mechanism for the audio gateway and can provide several remote control functions. Typical hands-free component devices are car systems and Bluetooth headsets -![HFP Role](../../assets/HFP_ARCH.png) +HFP (Hands-Free Profile) is a Bluetooth hands-free protocol that allows +Bluetooth devices to control phone calls on peer Bluetooth devices, such as +Bluetooth headsets controlling phone call answering, hanging up, rejecting, +voice dialing, etc. Data interaction between the two Bluetooth ends in HFP is +communicated through predefined AT commands. HFP defines two roles: Audio +Gateway (AG) and Hands-Free component (HF): +- Audio Gateway (AG): This device serves as the gateway for audio input/output. + Typical gateway devices are mobile phones +- Hands-Free component (HF): This device serves as the remote audio input/output + mechanism for the audio gateway and can provide several remote control + functions. Typical hands-free component devices are car systems and Bluetooth + headsets ![HFP Role](../../assets/HFP_ARCH.png) - AT command rules: - One command line can only represent one AT command - - < cr > abbreviation for carriage return, equivalent to the enter key, ASCII code is 0x0D - - < lf > abbreviation for NL line feed, new line, equivalent to the line feed key, ASCII code is 0x0A + - < cr > abbreviation for carriage return, equivalent to the enter key, + ASCII code is 0x0D + - < lf > abbreviation for NL line feed, new line, equivalent to the line + feed key, ASCII code is 0x0A - HF -> AG sends AT command format: < AT command >< cr > - - AG -> HF sends AT command format: < cr >< lf >result code< cr >< lf > - - If the AT command result code sent by AG to HF is a message reply, it must be followed by an OK message, unless the reply is a +CME ERROR message, where the following parameters represent the reason for failure. + - AG -> HF sends AT command format: < cr >< lf >result code< cr >< lf > + - If the AT command result code sent by AG to HF is a message reply, it must + be followed by an OK message, unless the reply is a +CME ERROR message, + where the following parameters represent the reason for failure. -This document is mainly based on Sifli SDK, introducing how to use basic functions of AG role. Related files include: +This document is mainly based on Sifli SDK, introducing how to use basic +functions of AG role. Related files include: - bts2_app_interface - bts2_app_hfp_ag - ## HFP_AG Initialization -- AG initialization function: bt_hfp_ag_app_init, assigns initial values to AG-related states and flags -- AG service startup function: bt_hfp_start_profile_service, configures +BRSF related attributes, users can adjust corresponding feature values according to requirements -- AT cmd: - - +BRSF: AG support features (Bluetooth Retrieve Supported Features) +- AG initialization function: bt_hfp_ag_app_init, assigns initial values to + AG-related states and flags +- AG service startup function: bt_hfp_start_profile_service, configures +BRSF + related attributes, users can adjust corresponding feature values according to + requirements +- AT command: + - +BRSF: AG supported features (Bluetooth Retrieve Supported Features) - Format: +BRSF:< AG support features > - - After the HF side sends its supported features to the AG side, the AG end must also send its supported features to HF through "+BRSF:< AG support features >". + - After the HF side sends its supported features to the AG side, the AG end + must also send its supported features to HF through "+BRSF:< AG support + features >". ```c U32 features = (U32)(HFP_AG_FEAT_ECNR | \ HFP_AG_FEAT_INBAND | \ @@ -50,47 +67,52 @@ U32 features = (U32)(HFP_AG_FEAT_ECNR | \ #define HFP_AG_FEAT_HF_IND 0x00000400 /* HF Indicators */ #define HFP_AG_FEAT_ESCO 0x00000800 /* eSCO S4 (and T2) setting supported */ -/* Proprietary features: using 31 ~ 16 bits */ +/* Proprietary features: using bits 16–31 */ #define HFP_AG_FEAT_BTRH 0x00010000 /* CCAP incoming call hold */ -#define HFP_AG_FEAT_UNAT 0x00020000 /* Pass unknown AT commands to app */ +#define HFP_AG_FEAT_UNAT 0x00020000 /* Pass unknown AT commands to application */ #define HFP_AG_FEAT_NOSCO 0x00040000 /* No SCO control performed by BTA AG */ #define HFP_AG_FEAT_NO_ESCO 0x00080000 /* Do not allow or use eSCO */ #define HFP_AG_FEAT_VOIP 0x00100000 /* VoIP call */ ``` - ## HFP_AG Device Connection -When LM Link and RFCOMM Connection already exist, user behavior or other internal events that want to use HFP service need to first establish SLC (Service Level Connection). Establishing SLC connection requires the following 5 phases: +When LM Link and RFCOMM Connection already exist, user behavior or other +internal events that want to use HFP service need to first establish SLC +(Service Level Connection). Establishing SLC connection requires the following 5 +phases: 1. Supported features exchange (AT+BRSF) 2. Codec Negotiation (AT+BAC) 3. AG Indicators (AT+CIND, AT+CMER, +CIEV, AT+CHLD) 4. HF Indicators (AT+BIND, AT+BIEV) -5. End of Service Level Connection -![HFP Connect Progress](../../assets/hfp_connect_progress.png) -- AT cmd: +5. End of Service Level Connection ![HFP Connect + Progress](../../assets/hfp_connect_progress.png) +- AT command: - AT+BAC: (Bluetooth Available Codecs) - Format: AT+BAC=< codec_id1 >,< codec_id2 > - HF side informs AG side which encoding methods are supported - codec: CVSD and msbc -- AT cmd: - - AT+CIND: (Standard indicator update AT command) +- AT command: + - AT+CIND: Indicator Control - Format: - - AT+CIND=? Test command. HF obtains indicator index values and ranges supported by AG side. Must be requested at least once before sending indicator-related commands (AT+CIND? or AT_CMER). + - AT+CIND=? Test command. HF obtains indicator index values and ranges + supported by AG side. Must be requested at least once before sending + indicator-related commands (AT+CIND? or AT_CMER). - AT+CIND? Read command, HF reads current indicator values from AG side -- AT cmd: - - +CIEV: unsolicited result code (Standard indicator events reporting unsolicited result code) +- AT command: + - +CIEV: unsolicited result code (Standard indicator events reporting + unsolicited result code) - Format: +CIEV: < ind >,< value > - - When AG indicators change, AG needs to actively notify HF side using +ciev AT cmd - ![indicator type](../../assets/HFP_AG_INDICATOR.png) + - When AG indicators change, AG needs to actively notify HF side using +ciev + AT cmd ![indicator type](../../assets/HFP_AG_INDICATOR.png) - AG device connection interface: - bts2_app_interface connection interface: bt_interface_conn_to_source_ext - bts2_app_hfp_ag connection interface: bt_hfp_connect_profile - + - AG device disconnection interface: - bts2_app_hfp_ag disconnection interface: bt_hfp_disconnect_profile - -- AG connection status callback events: - - AG connection successful: BT_NOTIFY_AG_PROFILE_CONNECTED - - AG connection failed: BT_NOTIFY_AG_PROFILE_DISCONNECTED + +- AG connection status callback events: - AG connection successful: + BT_NOTIFY_AG_PROFILE_CONNECTED - AG connection failed: + BT_NOTIFY_AG_PROFILE_DISCONNECTED ```c // After calling the API to connect AG role, the AG connection success message is sent to user through notify // Users need to implement hdl functions to receive notify events, such as: bt_notify_handle @@ -133,12 +155,13 @@ int bt_sifli_notify_hfp_ag_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: -- During AG SLC connection process, event when receiving AT+CIND=? cmd from HF: BT_NOTIFY_AG_GET_INDICATOR_STATUS_REQ +:::{note} Note: The address parameters passed by the two interfaces need to be +converted accordingly. ::: +- During AG SLC connection process, event when receiving AT+CIND=? cmd from HF: + BT_NOTIFY_AG_GET_INDICATOR_STATUS_REQ - AG needs to reply to event: BT_NOTIFY_AG_GET_INDICATOR_STATUS_REQ - - bts2_app_interface indicator status reply interface: bt_interface_get_all_indicator_info_res + - bts2_app_interface indicator status reply interface: + bt_interface_get_all_indicator_info_res - bts2_app_hfp_ag indicator status reply interface: bt_hfp_ag_cind_response ```c typedef struct @@ -174,30 +197,40 @@ typedef struct cind_status.callheld = 0; bt_interface_get_all_indicator_info_res(&cind_status); ``` - ## HFP_AG Basic Functionality Usage ### Call Audio Establishment -Audio Connection in HFP specification usually refers to SCO/eSCO voice path connection. Before SCO/eSCO, HF (AT+BCC) needs to notify AG to first select codec algorithm. -- AT cmd: +Audio Connection in HFP specification usually refers to SCO/eSCO voice path +connection. Before SCO/eSCO, HF (AT+BCC) needs to notify AG to first select +codec algorithm. +- AT command: - AT+BCC: Bluetooth Codec Connection - Format: AT+BCC - HF sends to AG, triggers AG to initiate codec connection process - - If AG decides to initiate codec connection process, reply OK; otherwise ERROR. After replying OK, AG side will send +BCS:< codec_id > and HF side replies: AT+BCS=< codec_id >. After that, eSCO link is established -- AT cmd: + - If AG decides to initiate codec connection process, reply OK; otherwise + ERROR. After replying OK, AG side will send +BCS:< codec_id > and HF side + replies: AT+BCS=< codec_id >. After that, eSCO link is established +- AT command: - AT+BCS: Bluetooth Codec Selection - Format: AT+BCS=< codec_id > - +BCS: Bluetooth Codec Selection - Format: +BCS:< codec_id > - codec: (codec_id=1) CVSD and (codec_id=2) msbc - - Before AG establishes eSCO, it will send command +BCS:< codec_id > to HF. HF side replies: AT+BCS=< codec_id >. If both AG and HF support this ID, the secondary link will be established. But if ID is not supported, HF will respond with AT+BAC and its available codecs. If (e)SCO link cannot be established, AG will restart the Codec Connection establishment process. Before Codec connection establishment, CVSD encoding will be enabled. - + - Before AG establishes eSCO, it will send command +BCS:< codec_id > to HF. + HF side replies: AT+BCS=< codec_id >. If both AG and HF support this ID, + the secondary link will be established. But if ID is not supported, HF + will respond with AT+BAC and its available codecs. If (e)SCO link cannot + be established, AG will restart the Codec Connection establishment + process. Before Codec connection establishment, CVSD encoding will be + enabled. #### Sifli HFP_AG Connect/Disconnect Call Audio -- bts2_app_interface call audio connection interface: bt_interface_ag_audio_switch +- bts2_app_interface call audio connection interface: + bt_interface_ag_audio_switch - bts2_app_hfp_ag call audio connection interface: bt_hfp_connect_audio -- bts2_app_interface call audio disconnection interface: bt_interface_ag_audio_switch +- bts2_app_interface call audio disconnection interface: + bt_interface_ag_audio_switch - bts2_app_hfp_ag call audio disconnection interface: bt_hfp_disconnect_audio ```c - // Call audio establishment connection interface bt_interface_ag_audio_switch parameters: type 0:connect audio type 1:disconnect audio + device mac address +// Call audio establishment connection interface bt_interface_ag_audio_switch parameters: type 0:connect audio type 1:disconnect audio + device mac address // Call audio connection successful BT_NOTIFY_COMMON_SCO_CONNECTED event: sco type (distinguish HF or AG) status (status) // For specific structure explanation, please refer to relevant descriptions in interface static int bt_notify_handle(uint16_t type, uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -234,26 +267,35 @@ int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` - ### AG Phone Status Update -- AT cmd: - - AT+CIND: (Standard indicator update AT command) +- AT command: + - AT+CIND: Indicator Control - Format: - - AT+CIND=? Test command. HF obtains indicator index values and ranges supported by AG side. Must be requested at least once before sending indicator-related commands (AT+CIND? or AT_CMER). + - AT+CIND=? Test command. HF obtains indicator index values and ranges + supported by AG side. Must be requested at least once before sending + indicator-related commands (AT+CIND? or AT_CMER). - AT+CIND? Read command, HF reads current indicator values from AG side -- AT cmd: - - +CIEV: unsolicited result code (Standard indicator events reporting unsolicited result code) +- AT command: + - +CIEV: unsolicited result code (Standard indicator events reporting + unsolicited result code) - Format: +CIEV: < ind >,< value > - - When AG indicators change, AG needs to actively notify HF side using +ciev AT cmd -- AT cmd: - - AT+CLCC: Standard list current calls command + - When AG indicators change, AG needs to actively notify HF side using +ciev + AT cmd +- AT command: + - AT+CLCC: List Current Calls - Format: AT+CLCC - +CLCC: Standard list current calls command - - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< type > - - HF requests current call information list, AG side replies current call information list through "+CLCC". If there are currently no calls, AG side must also reply with OK command. - -Once the phone AG end call status changes, AG should notify HF of the current changed call status. For example, after an incoming call, Bluetooth headset HF end answers, call status changes, AG side +CIEV:2,1 notifies HF to reject or AG hangs up, AG side +CIEV:2,0 notifies HF end. -- call Status + - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< + type > + - HF requests current call information list, AG side replies current call + information list through "+CLCC". If there are currently no calls, AG side + must also reply with OK command. + +Once the phone AG end call status changes, AG should notify HF of the current +changed call status. For example, after an incoming call, Bluetooth headset HF +end answers, call status changes, AG side +CIEV:2,1 notifies HF to reject or AG +hangs up, AG side +CIEV:2,0 notifies HF end. +- Call Status - 0: No calls (held or active) - 1: Call is present (active or held) - callsetup status @@ -263,17 +305,20 @@ Once the phone AG end call status changes, AG should notify HF of the current ch - 3: Outgoing call setup in alerting state - callheld status - 0: No call held - - 1: Call is placed on hold or active/held calls swapped - - 2: Call on hold, no active call -- Incoming call state transition: - - call_idle <----> call_incoming <-----> call_active <----> call_idle -- Outgoing call state transition: - - call_idle <----> call_outgoing_dialing ----> call_outgoing_alerting <-----> call_active <----> call_idle - - call_idle <----> call_outgoing_dialing ----> call_outgoing_alerting <-----> call_idle - + - 1: Call placed on hold or active/held calls swapped + - 2: Call on hold with no active call +- Incoming call state transition: + - call_idle <----> call_incoming <-----> call_active <----> call_idle +- Outgoing call state transition: + - call_idle <----> call_outgoing_dialing ----> call_outgoing_alerting + <-----> call_active <----> call_idle + - call_idle <----> call_outgoing_dialing ----> call_outgoing_alerting + <-----> call_idle #### Sifli AG Update Phone Information -- bts2_app_interface phone status update interface: bt_interface_phone_state_changed -- bts2_app_hfp_ag phone status update interface: bt_hfp_ag_call_state_update_listener +- bts2_app_interface phone status update interface: + bt_interface_phone_state_changed +- bts2_app_hfp_ag phone status update interface: + bt_hfp_ag_call_state_update_listener ```c typedef struct { @@ -286,97 +331,99 @@ typedef struct U8 phone_number[1]; } HFP_CALL_INFO_T; -// a call incoming +// Incoming call HFP_CALL_INFO_T call_info; call_info.num_active = 0; call_info.num_held = 0; call_info.callsetup_state = 1; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call active +// Active call HFP_CALL_INFO_T call_info; call_info.num_active = 1; call_info.num_held = 0; call_info.callsetup_state = 0; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call idle +// Idle call HFP_CALL_INFO_T call_info; call_info.num_active = 0; call_info.num_held = 0; call_info.callsetup_state = 0; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call outgoing dialing +// Outgoing call: Dialing HFP_CALL_INFO_T call_info; call_info.num_active = 0; call_info.num_held = 0; call_info.callsetup_state = 2; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call outgoing alerting +// Outgoing call: Alerting HFP_CALL_INFO_T call_info; call_info.num_active = 0; call_info.num_held = 0; call_info.callsetup_state = 3; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call active +// Active call HFP_CALL_INFO_T call_info; call_info.num_active = 1; call_info.num_held = 0; call_info.callsetup_state = 0; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); -// a call idle +// Idle call HFP_CALL_INFO_T call_info; call_info.num_active = 0; call_info.num_held = 0; call_info.callsetup_state = 0; call_info.phone_type = 0x81; char *str = "1234567"; -bmemcpy(&call_info.phone_number, str, strlen(str) + 1); +bmemcpy(&call_info.phone_number, str, strlen(str) + 1); call_info.phone_len = strlen(str) + 1; -bt_interface_phone_state_changed(&call_info); +bt_interface_phone_state_changed(&call_info); ``` - ### AG Information Synchronization Processing -- AT cmd: - - +CIEV: unsolicited result code (Standard indicator events reporting unsolicited result code) +- AT command: + - +CIEV: unsolicited result code (Standard indicator events reporting + unsolicited result code) - Format: +CIEV: < ind >,< value > - - When AG indicators change, AG needs to actively notify HF side using +ciev AT cmd + - When AG indicators change, AG needs to actively notify HF side using +ciev + AT cmd - Indicator status value update - When AG end indicators change, AG needs to actively update status - - bts2_app_interface status update interface: bt_interface_indicator_status_changed + - bts2_app_interface status update interface: + bt_interface_indicator_status_changed - bts2_app_hfp_ag status update interface: bt_hfp_ag_ind_status_update - - Common indicator types are shown in the following figure: - ![Figure 1: indicator type](../../assets/HFP_AG_INDICATOR.png) + - Common indicator types are shown in the following figure: ![Figure 1: + indicator type](../../assets/HFP_AG_INDICATOR.png) - Service status update demo: ```c typedef struct @@ -401,44 +448,25 @@ ind_info.ind_type = HFP_AG_CIND_SERVICE_TYPE; ind_info.ind_val = 3; bt_interface_indicator_status_changed(&ind_info); ``` - -##### AG Local Number Synchronization -- AT cmd: - - AT+CNUM: Subscriber Number Information - - Format: AT+CNUM - - This command is used to query local number - - +CNUM: Subscriber Number Information - - Format: +CNUM: ,< number >,< type >[,, < service >] - - After AG receives this request, it will reply the phone's local number to HF side through +CNUM. -- Event when receiving HF end request for local number: BT_NOTIFY_AG_GET_LOCAL_PHONE_INFO_REQ -- Interface to reply local number: - - bts2_app_interface local number reply interface: bt_interface_local_phone_info_res - - bts2_app_hfp_ag local number reply interface: bt_hfp_ag_cnum_response -```c -typedef struct -{ - char phone_number[PHONE_NUM_LEN]; - U8 type; -} hfp_phone_number_t; - -hfp_phone_number_t local_phone_num; -char *str = "19396395979"; -bmemcpy(&local_phone_num.phone_number, str, strlen(str)); -local_phone_num.type = 0x81; -bt_interface_local_phone_info_res(&local_phone_num); -``` - #### AG All Call Status Information -- AT cmd: +- AT command: - AT+CLCC: Standard list current calls command - Format: AT+CLCC - +CLCC: Standard list current calls command - - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< type > - - HF requests current call information list, AG side replies current call information list through "+CLCC". If there are currently no calls, AG side must also reply with OK command. -- Event when receiving HF end request for all call status information: BT_NOTIFY_AG_GET_ALL_REMT_CALLS_INFO_REQ + - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< + type > + - HF requests current call information list, AG side replies current call + information list through "+CLCC". If there are currently no calls, AG side + must also reply with OK command. + - Upon receiving this request, the AG returns the local phone number to the + HF using the +CNUM response. +- Event when receiving HF end request for all call status information: + BT_NOTIFY_AG_GET_ALL_REMT_CALLS_INFO_REQ - Interface to reply all call status information: - - bts2_app_interface all call status information interface: bt_interface_remote_call_info_res - - bts2_app_hfp_ag all call status information interface: bt_hfp_ag_remote_calls_res_hdl + - bts2_app_interface all call status information interface: + bt_interface_remote_call_info_res + - bts2_app_hfp_ag all call status information interface: + bt_hfp_ag_remote_calls_res_hdl ```c typedef struct { @@ -485,69 +513,146 @@ calls.num_call = 1; calls.calls = &call_info; bt_interface_remote_call_info_res((hfp_remote_calls_info_t *)calls); ``` +#### Status information for all AG calls +- AT command: + - AT+CLCC: List Current Calls + - Format: AT+CLCC + - +CLCC: Standard list current calls command + - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< + type > + - HF requests current call information list, AG side replies current call + information list through "+CLCC". If there are currently no calls, AG side + must also reply with OK command. +- Received the event from the HF (Hands-Free) unit requesting status information + for all calls: BT_NOTIFY_AG_GET_ALL_REMT_CALLS_INFO_REQ +- Interface for reporting the status of all calls: + - Interface for retrieving status information for all calls in + bts2_app_interface: bt_interface_remote_call_info_res + - Interface for retrieving status information for all calls in + bts2_app_hfp_ag: bt_hfp_ag_remote_calls_res_hdl +```c +typedef struct +{ + // Number of calls + U8 num_call; + hfp_phone_call_info_t *calls; +} hfp_remote_calls_info_t; +typedef struct +{ + // Call index (starts from 1) + U8 call_idx; + // Call direction: 0 = Outgoing, 1 = Incoming + U8 call_dir; + // 0: Active + // 1: Held + // 2: Dialing (outgoing calls only) + // 3: Alerting (outgoing calls only) + // 4: Incoming (incoming calls only) + // 5: Waiting (incoming calls only) + // 6: Call held by Response and Hold + U8 call_status; + // Call mode: 0 (Voice), 1 (Data), 2 (FAX) + U8 call_mode; + // Multi-party call flag: 0 = Not a multi-party call, 1 = Multi-party call + U8 call_mtpty; + // Phone number and number type + hfp_phone_number_t phone_info; +} hfp_phone_call_info_t; + +hfp_phone_call_info_t call_info; +bmemset(&call_info, 0x00, sizeof(hfp_phone_call_info_t)); +call_info.call_idx = 1; +call_info.call_dir = 1; +call_info.call_status = 1; +call_info.call_mode = 0; +call_info.call_mtpty = 0; +char *str = "123456"; +bmemcpy(&call_info.phone_info.phone_number, str, strlen(str) + 1); +call_info.phone_info.type = 0x81; + +hfp_remote_calls_info_t calls; +calls.num_call = 1; +calls.calls = &call_info; +bt_interface_remote_call_info_res((hfp_remote_calls_info_t *)calls); +``` ### HFP_AG Phone Related Functions -- AT cmd: - - AT+CLIP: Calling Line Identification notification +- AT command: + - AT+CLIP: Calling Line Identification Presentation - Format: AT+CLIP=(0/1) - +CLIP: Calling Line Identification notification - Format: +CLIP: < number >,< type > - - Enable or disable caller ID notification. When enabled, AG side sends current incoming call number and type to HF through "+CLIP" command during incoming calls -- AT cmd: + - Enable or disable caller ID notification. When enabled, AG side sends + current incoming call number and type to HF through "+CLIP" command during + incoming calls +- AT command: - AT+CCWA: Three-Way Call Handling - Format: AT+CCWA=(0/1) - Enable or disable three-way call waiting reminder - +CCWA: Call Waiting Notification - Format: +CCWA: < number >,< type > - - When enabled, if there's already one connected call and another call comes in, AG will send +CCWA -- AT cmd: + - When enabled, if there's already one connected call and another call comes + in, AG will send +CCWA +- AT command: - ATD: Dial call req - Format: ATDdd…dd - HF actively requests to make a call - AT+BLDN: Bluetooth Last Dialed Number - Format: AT+BLDN - - Request AG side to redial the last call. After receiving this request, AG initiates a call based on the most recently dialed number. -- AT cmd: - - ATA: call answer + - Request AG side to redial the last call. After receiving this request, AG + initiates a call based on the most recently dialed number. +- AT command: + - ATA: Answer Call - Format: ATA - - Answer call. When connected, +CIEV:< call_ind >, < 1 > and +CIEV:< call_setup_ind >, < 0 > appear -- AT cmd: - - AT+CHUP: Reject an Incoming Call/Terminate a Call Process + - Answer call. When connected, +CIEV:< call_ind >, < 1 > and +CIEV:< + call_setup_ind >, < 0 > appear +- AT command: + - AT+CHUP: Hang up Call - Format: AT+CHUP - - Reject or hang up call, +CIEV:< call_setup_ind >, < 0 > / +CIEV:< call_ind >, < 0 > appears + - Reject or hang up call, +CIEV:< call_setup_ind >, < 0 > / +CIEV:< call_ind + >, < 0 > appears - Phone related functions - Event when receiving HF end answer call: BT_NOTIFY_AG_ANSWER_CALL_REQ - Event when receiving HF end hang up call: BT_NOTIFY_AG_HANGUP_CALL_REQ - - Event when receiving HF end control call volume: BT_NOTIFY_AG_VOLUME_CHANGE + - Event when receiving HF end control call volume: + BT_NOTIFY_AG_VOLUME_CHANGE - Event when receiving HF end make call: BT_NOTIFY_AG_MAKE_CALL_REQ - - When receiving make call request, need to check number validity, reply check result + - When receiving make call request, need to check number validity, reply + check result - bts2_app_interface result reply interface: bt_interface_make_call_res - bts2_app_hfp_ag result reply interface: bt_hfp_ag_at_result_res - During call, event when receiving DTMF key: BT_NOTIFY_AG_RECV_DTMF_KEY -- AT cmd: +- AT command: - AT+VGM: Gain of Microphone - Format: AT+VGM=< gain > - - +VGM: Gain of Microphone + - +VGM: Microphone gain - Format: +VGM:< gain > - Adjust MIC volume in audio path, value range 0~15 -- AT cmd: - - AT+VGS: Gain of Speaker +- AT command: + - AT+VGS: Speaker gain - Format: AT+VGS=< gain > - - +VGS: Gain of Speaker + - +VGS: Speaker gain - Format: +VGS:< gain > - Adjust speaker volume in audio path, value range 0~15 - Active volume control interface: - - bts2_app_interface speaker volume control interface: bt_interface_set_speaker_volume + - bts2_app_interface speaker volume control interface: + bt_interface_set_speaker_volume - bts2_app_hfp_hf speaker volume control interface: bt_hfp_hf_update_spk_vol - - bts2_app_hfp_hf microphone volume control interface: bt_hfp_hf_update_mic_vol - - Volume setting processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_VGS/HFP_HF_AT_VGM) + - bts2_app_hfp_hf microphone volume control interface: + bt_hfp_hf_update_mic_vol + - Volume setting processing result event: BT_NOTIFY_HF_AT_CMD_CFM with + cmd_id (HFP_HF_AT_VGS/HFP_HF_AT_VGM) - Active speaker volume control: - - bts2_app_interface speaker volume control interface: bt_interface_spk_vol_change_req - - bts2_app_hfp_ag speaker volume control interface: bt_hfp_ag_spk_vol_control + - bts2_app_interface speaker volume control interface: + bt_interface_spk_vol_change_req + - bts2_app_hfp_ag speaker volume control interface: + bt_hfp_ag_spk_vol_control - Active microphone volume control: - - bts2_app_interface microphone volume control interface: bt_interface_mic_vol_change_req - - bts2_app_hfp_ag microphone volume control interface: bt_hfp_ag_mic_vol_control + - bts2_app_interface microphone volume control interface: + bt_interface_mic_vol_change_req + - bts2_app_hfp_ag microphone volume control interface: + bt_hfp_ag_mic_vol_control ```c //register notify event handle function start //step1: Call connection interface, AG connection success message: BT_NOTIFY_AG_PROFILE_CONNECTED @@ -757,4 +862,4 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); //register notify event handle function end -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_hfp_hf_profile.md b/docs/source/en/middleware/bt_hfp_hf_profile.md index 2633cd332..26b0fecea 100644 --- a/docs/source/en/middleware/bt_hfp_hf_profile.md +++ b/docs/source/en/middleware/bt_hfp_hf_profile.md @@ -1,27 +1,43 @@ # HFP_HF -HFP (Hands-Free Profile) is a Bluetooth hands-free protocol that allows Bluetooth devices to control phone calls on peer Bluetooth devices, such as Bluetooth headsets controlling phone call answering, hanging up, rejecting, voice dialing, etc. Data interaction between the two Bluetooth ends in HFP is communicated through predefined AT commands. HFP defines two roles: Audio Gateway (AG) and Hands-Free component (HF): -- Audio Gateway (AG): This device serves as the gateway for audio input/output. Typical gateway devices are mobile phones -- Hands-Free component (HF): This device serves as the remote audio input/output mechanism for the audio gateway and can provide several remote control functions. Typical hands-free component devices are car systems and Bluetooth headsets -![HFP Role](../../assets/HFP_ARCH.png) +HFP (Hands-Free Profile) is a Bluetooth hands-free protocol that allows +Bluetooth devices to control phone calls on peer Bluetooth devices, such as +Bluetooth headsets controlling phone call answering, hanging up, rejecting, +voice dialing, etc. Data interaction between the two Bluetooth ends in HFP is +communicated through predefined AT commands. HFP defines two roles: Audio +Gateway (AG) and Hands-Free component (HF): +- Audio Gateway (AG): This device serves as the gateway for audio input/output. + Typical gateway devices are mobile phones +- Hands-Free component (HF): This device serves as the remote audio input/output + mechanism for the audio gateway and can provide several remote control + functions. Typical hands-free component devices are car systems and Bluetooth + headsets ![HFP Role](../../assets/HFP_ARCH.png) - AT command rules: - One command line can only represent one AT command - - < cr > abbreviation for carriage return, equivalent to the enter key, ASCII code is 0x0D - - < lf > abbreviation for NL line feed, new line, equivalent to the line feed key, ASCII code is 0x0A + - < cr > abbreviation for carriage return, equivalent to the enter key, + ASCII code is 0x0D + - < lf > abbreviation for NL line feed, new line, equivalent to the line + feed key, ASCII code is 0x0A - HF -> AG sends AT command format: < AT command >< cr > - - AG -> HF sends AT command format: < cr >< lf >result code< cr >< lf > - - If the AT command result code sent by AG to HF is a message reply, it must be followed by an OK message, unless the reply is a +CME ERROR message, where the following parameters represent the reason for failure. + - AG -> HF sends AT command format: < cr >< lf >result code< cr >< lf > + - If the AT command result code sent by AG to HF is a message reply, it must + be followed by an OK message, unless the reply is a +CME ERROR message, + where the following parameters represent the reason for failure. -This document is mainly based on Sifli SDK, introducing how to use basic functions of HF role. Related files include: +This document is mainly based on Sifli SDK, introducing how to use basic +functions of HF role. Related files include: - bts2_app_interface - bts2_app_hfp_hf - ## HFP_HF Initialization -- HF initialization function: bt_hfp_hf_init, assigns initial values to HF-related states and flags -- HF service startup function: bt_hfp_hf_start_enb, configures AT+BRSF related attributes, users can adjust corresponding feature values according to requirements -- AT cmd: +- HF initialization function: bt_hfp_hf_init, assigns initial values to + HF-related states and flags +- HF service startup function: bt_hfp_hf_start_enb, configures AT+BRSF related + attributes, users can adjust corresponding feature values according to + requirements +- AT command: - AT+BRSF: HF support features (Bluetooth Retrieve Supported Features) - Format: AT+BRSF=< HF support features > - - When establishing connection, HF side sends its supported features to AG side + - When establishing connection, HF side sends its supported features to AG + side ```c #define HFP_HF_LOCAL_FEATURES ( HFP_HF_FEAT_ECNR | \ HFP_HF_FEAT_3WAY | \ @@ -52,42 +68,51 @@ This document is mainly based on Sifli SDK, introducing how to use basic functio #define HFP_HF_FEAT_UNAT 0x1000 #define HFP_HF_FEAT_VOIP 0x2000 /* VoIP call */ ``` - ## HFP_HF Device Connection -AG devices and HF devices establishing connection and making calls will roughly go through the following four phases. Next, we will focus on introducing the Service Level Connection and Audio Connection processes according to the Specification. -1. LMP link: First establish LMP Link, there is no fixed master or slave in HFP connection -2. RFCOMM Connection: Then establish serial port emulation data link channel for HF to transmit user data to AG (including modem control signals and AT commands), AG parses AT commands and sends corresponding responses to HF through the serial port emulation -3. Service Level Connection: Service level connection is the foundation for application layer HF <<>> AG control and interaction information. +AG devices and HF devices establishing connection and making calls will roughly +go through the following four phases. Next, we will focus on introducing the +Service Level Connection and Audio Connection processes according to the +Specification. +1. LMP link: First establish LMP Link, there is no fixed master or slave in HFP + connection +2. RFCOMM Connection: Then establish serial port emulation data link channel for + HF to transmit user data to AG (including modem control signals and AT + commands), AG parses AT commands and sends corresponding responses to HF + through the serial port emulation +3. Service Level Connection: Service level connection is the foundation for + application layer HF <<>> AG control and interaction information. - Service Level Connection establishment - Service Level Connection release -4. Synchronous Connection/Audio Connection: SCO/eSCO call connection usually refers to voice data connection - - Codec Connection - - Wide Band Speech Connection - +4. Synchronous Connection/Audio Connection: SCO/eSCO call connection usually + refers to voice data connection + - Codec connection + - Wideband speech connection ### SLC (Service Level Connection) Establishment Process -When LM Link and RFCOMM Connection already exist, user behavior or other internal events that want to use HFP service need to first establish SLC (Service Level Connection). Establishing SLC connection requires the following 5 phases: +When LM Link and RFCOMM Connection already exist, user behavior or other +internal events that want to use HFP service need to first establish SLC +(Service Level Connection). Establishing SLC connection requires the following 5 +phases: 1. Supported features exchange (AT+BRSF) 2. Codec Negotiation (AT+BAC) 3. AG Indicators (AT+CIND, AT+CMER, +CIEV, AT+CHLD) 4. HF Indicators (AT+BIND, AT+BIEV) -5. End of Service Level Connection -![HFP Connect Progress](../../assets/hfp_connect_progress.png) +5. End of Service Level Connection ![HFP Connect + Progress](../../assets/hfp_connect_progress.png) ### Sifli HFP_HF Connect/Disconnect Device - HF device connection interface: - bts2_app_interface connection interface: bt_interface_conn_ext - - bts2_app_hfp_hf connection interface: bt_hfp_hf_start_connecting - + - bts2_app_hfp_hf connection interface: bt_hfp_hf_start_connecting + - HF device disconnection interface: - bts2_app_interface disconnection interface: bt_interface_disc_ext - bts2_app_hfp_hf disconnection interface: bt_hfp_hf_start_disc - + - HF connection status callback events: - HF connection successful: BT_NOTIFY_HF_PROFILE_CONNECTED - - HF connection failed: BT_NOTIFY_HF_PROFILE_DISCONNECTED -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: + - HF connection failed: BT_NOTIFY_HF_PROFILE_DISCONNECTED :::{note} Note: + The address parameters passed by the two interfaces need to be converted + accordingly. ::: ```c // After calling the API to connect HF role, the HF connection success message is sent to user through notify // Users need to implement hdl functions to receive notify events, such as: bt_notify_handle @@ -130,24 +155,33 @@ int bt_sifli_notify_hfp_hf_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` - ## HFP_HF Basic Functionality Usage ### Call Audio Establishment -Audio Connection in HFP specification usually refers to SCO/eSCO voice path connection. Before SCO/eSCO, HF (AT+BCC) needs to notify AG to first select codec algorithm. -- AT cmd: +Audio Connection in HFP specification usually refers to SCO/eSCO voice path +connection. Before SCO/eSCO, HF (AT+BCC) needs to notify AG to first select +codec algorithm. +- AT command: - AT+BCC: Bluetooth Codec Connection - Format: AT+BCC - HF sends to AG, triggers AG to initiate codec connection process - - If AG decides to initiate codec connection process, reply OK; otherwise ERROR. After replying OK, AG side will send +BCS:< codec_id > and HF side replies: AT+BCS=< codec_id >. After that, eSCO link is established - + - If AG decides to initiate codec connection process, reply OK; otherwise + ERROR. After replying OK, AG side will send +BCS:< codec_id > and HF side + replies: AT+BCS=< codec_id >. After that, eSCO link is established #### Sifli HFP_HF Connect/Disconnect Call Audio -- bts2_app_interface call audio connect/disconnect interface: bt_interface_audio_switch -- bts2_app_hfp_hf call audio connect/disconnect interface: bt_hfp_hf_audio_transfer -- Prerequisites for successful call audio establishment: phone end call status is not idle; because when call is idle, phone end will reject AT+BCC request to establish SCO. -- Call audio encoding includes: CVSD and msbc, interface to control whether msbc codec is enabled: bt_interface_set_wbs_status -- After call audio is successfully established, need to call audio_open; after call audio is disconnected or HF is disconnected, need to call audio_close. Related implementation can be found in: hfp_audio_api +- bts2_app_interface call audio connect/disconnect interface: + bt_interface_audio_switch +- bts2_app_hfp_hf call audio connect/disconnect interface: + bt_hfp_hf_audio_transfer +- Prerequisites for successful call audio establishment: phone end call status + is not idle; because when call is idle, phone end will reject AT+BCC request + to establish SCO. +- Call audio encoding includes: CVSD and msbc, interface to control whether msbc + codec is enabled: bt_interface_set_wbs_status +- After call audio is successfully established, need to call audio_open; after + call audio is disconnected or HF is disconnected, need to call audio_close. + Related implementation can be found in: hfp_audio_api ```c - // Call audio establishment connection interface bt_interface_audio_switch parameters: type 0:connect audio type 1:disconnect audio +// Call audio establishment connection interface bt_interface_audio_switch parameters: type 0:connect audio type 1:disconnect audio // Call audio connection successful BT_NOTIFY_COMMON_SCO_CONNECTED event: sco type (distinguish HF or AG) status (status) // For specific structure explanation, please refer to relevant descriptions in interface static int bt_notify_handle(uint16_t type, uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -184,25 +218,27 @@ int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` - ### Call Audio Volume Control -- AT cmd: +- AT command: - AT+VGM: Gain of Microphone - Format: AT+VGM=< gain > - - +VGM: Gain of Microphone + - +VGM: Microphone gain - Format: +VGM:< gain > - Adjust MIC volume in audio path, value range 0~15 -- AT cmd: - - AT+VGS: Gain of Speaker +- AT command: + - AT+VGS: Speaker gain - Format: AT+VGS=< gain > - - +VGS: Gain of Speaker + - +VGS: Speaker gain - Format: +VGS:< gain > - Adjust speaker volume in audio path, value range 0~15 - Active volume control interface: - - bts2_app_interface speaker volume control interface: bt_interface_set_speaker_volume + - bts2_app_interface speaker volume control interface: + bt_interface_set_speaker_volume - bts2_app_hfp_hf speaker volume control interface: bt_hfp_hf_update_spk_vol - - bts2_app_hfp_hf microphone volume control interface: bt_hfp_hf_update_mic_vol - - Volume setting processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_VGS/HFP_HF_AT_VGM) + - bts2_app_hfp_hf microphone volume control interface: + bt_hfp_hf_update_mic_vol + - Volume setting processing result event: BT_NOTIFY_HF_AT_CMD_CFM with + cmd_id (HFP_HF_AT_VGS/HFP_HF_AT_VGM) - Peer device volume control event: BT_NOTIFY_HF_VOLUME_CHANGE ```c // When call audio exists, to control call audio volume, call bt_interface_set_speaker_volume with volume value @@ -285,29 +321,35 @@ enum HFP_AT_EXTERN_AT_CMD }; ``` - ### Voice Recognition Function -- AT cmd: +- AT command: - AT+BVRA: Voice Recognition Activation - Format: AT+BVRA=< status > - - status + - Status - 0 (Disable Voice recognition in the AG) - 1 (Enable voice recognition in the AG) - 2 (Enable voice recognition in the AG with esco exist) -- AT cmd: +- AT command: - +BVRA: Voice Recognition Activation - Format: +BVRA:< status > - - status + - Status - 0 (Voice recognition is disabled in the AG) - 1 (Voice recognition is enabled in the AG) -HF initiates voice recognition application activation by sending AT+BVRA command to AG. Voice recognition application is installed in AG. Apart from audio routing, voice recognition activation control and other functions that need Bluetooth functionality, everything else depends on the voice recognition application implementation. -- Peer device supports voice recognition function event: BT_NOTIFY_HF_VOICE_RECOG_CAP_UPDATE -- Peer device actively uses voice recognition function status sync event: BT_NOTIFY_HF_VOICE_RECOG_STATUS_CHANGE +HF initiates voice recognition application activation by sending AT+BVRA command +to AG. Voice recognition application is installed in AG. Apart from audio +routing, voice recognition activation control and other functions that need +Bluetooth functionality, everything else depends on the voice recognition +application implementation. +- Peer device supports voice recognition function event: + BT_NOTIFY_HF_VOICE_RECOG_CAP_UPDATE +- Peer device actively uses voice recognition function status sync event: + BT_NOTIFY_HF_VOICE_RECOG_STATUS_CHANGE - Active wake up/close voice function interface: - - bts2_app_interface voice recognition interface: bt_interface_voice_recog - - bts2_app_hfp_hf voice recognition interface: bt_hfp_hf_voice_recog_send - - Voice cmd processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_BVRA) + - bts2_app_interface voice recognition interface: bt_interface_voice_recog + - bts2_app_hfp_hf voice recognition interface: bt_hfp_hf_voice_recog_send + - Voice cmd processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id + (HFP_HF_AT_BVRA) ```c // step1: HF actively wakes up voice recognition by calling bt_interface_voice_recog(1); // step2: HF sends AT+BVRA=1 @@ -356,90 +398,116 @@ int bt_sifli_notify_hfp_hf_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` - ### Phone Control Related Functions #### Phone Status Update Related AT cmd -- AT cmd: - - AT+CIND: (Standard indicator update AT command) +- AT command: + - AT+CIND: Indicator Control - Format: - - AT+CIND=? Test command. HF obtains indicator index values and ranges supported by AG side. Must be requested at least once before sending indicator-related commands (AT+CIND? or AT_CMER). + - AT+CIND=? Test command. HF obtains indicator index values and ranges + supported by AG side. Must be requested at least once before sending + indicator-related commands (AT+CIND? or AT_CMER). - AT+CIND? Read command, HF reads current indicator values from AG side -- AT cmd: - - +CIEV: unsolicited result code (Standard indicator events reporting unsolicited result code) +- AT command: + - +CIEV: unsolicited result code (Standard indicator events reporting + unsolicited result code) - Format: +CIEV: < ind >,< value > - - When AG indicators change, AG needs to actively notify HF side using +ciev AT cmd + - When AG indicators change, AG needs to actively notify HF side using +ciev + AT cmd - Phone end active status update: - - HF connection successful, sync phone call status event (call/callsetup/callheld): BT_NOTIFY_HF_CALL_STATUS_UPDATE + - HF connection successful, sync phone call status event + (call/callsetup/callheld): BT_NOTIFY_HF_CALL_STATUS_UPDATE - During connection process, actively get phone status: - - bts2_app_interface get phone status interface: bt_interface_get_remote_call_status + - bts2_app_interface get phone status interface: + bt_interface_get_remote_call_status - Phone status sync event: BT_NOTIFY_HF_CALL_STATUS_UPDATE - - Phone status cmd processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_CIND_STATUS) - - During connection process, phone call status active update through event: BT_NOTIFY_HF_INDICATOR_UPDATE - + - Phone status cmd processing result event: BT_NOTIFY_HF_AT_CMD_CFM with + cmd_id (HFP_HF_AT_CIND_STATUS) + - During connection process, phone call status active update through event: + BT_NOTIFY_HF_INDICATOR_UPDATE #### Phone Control Related AT cmd -- AT cmd: - - AT+CNUM: Subscriber Number Information +- AT command: + - AT+CNUM: Subscriber Number - Format: AT+CNUM - This command is used to query local number - +CNUM: Subscriber Number Information - Format: +CNUM: ,< number >,< type >[,, < service >] - - After AG receives this request, it will reply the phone's local number to HF side through +CNUM. -- AT cmd: - - AT+CLIP: Calling Line Identification notification + - After AG receives this request, it will reply the phone's local number to + HF side through +CNUM. +- AT command: + - AT+CLIP: Calling Line Identification Presentation - Format: AT+CLIP=(0/1) - +CLIP: Calling Line Identification notification - Format: +CLIP: < number >,< type > - - Enable or disable caller ID notification. When enabled, AG side sends current incoming call number and type to HF through "+CLIP" command during incoming calls -- AT cmd: + - Enable or disable caller ID notification. When enabled, AG side sends + current incoming call number and type to HF through "+CLIP" command during + incoming calls +- AT command: - AT+CCWA: Three-Way Call Handling - Format: AT+CCWA=(0/1) - Enable or disable three-way call waiting reminder - +CCWA: Call Waiting Notification - Format: +CCWA: < number >,< type > - - When enabled, if there's already one connected call and another call comes in, AG will send +CCWA -- AT cmd: + - When enabled, if there's already one connected call and another call comes + in, AG will send +CCWA +- AT command: - ATD: Dial call req - Format: ATDdd…dd - HF actively requests to make a call - AT+BLDN: Bluetooth Last Dialed Number - Format: AT+BLDN - - Request AG side to redial the last call. After receiving this request, AG initiates a call based on the most recently dialed number. -- AT cmd: - - ATA: call answer + - Request AG side to redial the last call. After receiving this request, AG + initiates a call based on the most recently dialed number. +- AT command: + - ATA: Answer Call - Format: ATA - - Answer call. When connected, +CIEV:< call_ind >, < 1 > and +CIEV:< call_setup_ind >, < 0 > appear -- AT cmd: - - AT+CHUP: Reject an Incoming Call/Terminate a Call Process + - Answer call. When connected, +CIEV:< call_ind >, < 1 > and +CIEV:< + call_setup_ind >, < 0 > appear +- AT command: + - AT+CHUP: Hang up Call - Format: AT+CHUP - - Reject or hang up call, +CIEV:< call_setup_ind >, < 0 > / +CIEV:< call_ind >, < 0 > appears -- AT cmd: - - AT+CLCC: Standard list current calls command + - Reject or hang up call, +CIEV:< call_setup_ind >, < 0 > / +CIEV:< call_ind + >, < 0 > appears +- AT command: + - AT+CLCC: List Current Calls - Format: AT+CLCC - +CLCC: Standard list current calls command - - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< type > - - HF requests current call information list, AG side replies current call information list through "+CLCC". If there are currently no calls, AG side must also reply with OK command. - + - Format: +CLCC: < idx >,< dir >,< status >,< mode >,< mpty >,< number >,< + type > + - HF requests current call information list, AG side replies current call + information list through "+CLCC". If there are currently no calls, AG side + must also reply with OK command. #### Phone Control Function Usage - Phone control - Get phone local number (AT+CNUM): - - bts2_app_interface get local phone number interface: bt_interface_get_ph_num - - bts2_app_hfp_hf get local phone number interface: bt_hfp_hf_at_cnum_send + - bts2_app_interface get local phone number interface: + bt_interface_get_ph_num + - bts2_app_hfp_hf get local phone number interface: + bt_hfp_hf_at_cnum_send - Local number information event: BT_NOTIFY_HF_LOCAL_PHONE_NUMBER - - Get local number cmd processing result message event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_CNUM) + - Get local number cmd processing result message event: + BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_CNUM) - Make call - Redial call (AT+BLDN) - - bts2_app_interface redial call interface: bt_interface_start_last_num_dial_req_send - - bts2_app_hfp_hf redial call interface: bt_hfp_hf_last_num_dial_send - - Redial call processing result message event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_BLDN) + - bts2_app_interface redial call interface: + bt_interface_start_last_num_dial_req_send + - bts2_app_hfp_hf redial call interface: bt_hfp_hf_last_num_dial_send + - Redial call processing result message event: BT_NOTIFY_HF_AT_CMD_CFM + with cmd_id (HFP_HF_AT_BLDN) - Make call by phone number (ATD10086) - - bts2_app_interface make call by phone number interface: bt_interface_hf_out_going_call - - bts2_app_hfp_hf make call by phone number interface: bt_hfp_hf_make_call_by_number_send - - Make call by phone number processing result message event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_ATD) + - bts2_app_interface make call by phone number interface: + bt_interface_hf_out_going_call + - bts2_app_hfp_hf make call by phone number interface: + bt_hfp_hf_make_call_by_number_send + - Make call by phone number processing result message event: + BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_ATD) - Get all information of current active calls on phone end (AT+CLCC) - - bts2_app_interface get all call information interface: bt_interface_get_remote_ph_num + - bts2_app_interface get all call information interface: + bt_interface_get_remote_ph_num - bts2_app_hfp_hf get all call information interface: bt_hfp_hf_at_clcc_send - - Call status information event: BT_NOTIFY_HF_REMOTE_CALL_INFO_IND for notification - - Get current active call information cmd processing result event: BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_CLCC) + - Call status information event: BT_NOTIFY_HF_REMOTE_CALL_INFO_IND for + notification + - Get current active call information cmd processing result event: + BT_NOTIFY_HF_AT_CMD_CFM with cmd_id (HFP_HF_AT_CLCC) ```c // step1: After HF connects successfully with AG, can get AG end phone number through bt_interface_get_ph_num // step2: When AG sends local number to HF through +CNUM, and corresponding OK. @@ -504,15 +572,19 @@ int bt_sifli_notify_hfp_hf_event_hdl(uint16_t event_id, uint8_t *data, uint16_t return 0; } ``` -:::{note} -Note: HF part extensible interfaces are in bts2_app_hfp_hf, users can extend functionality according to requirements and encapsulate interfaces in interface according to needs. -Also, after each cmd is sent, need to wait for cmd_cfm message to avoid too many messages in protocol stack queue, triggering protection mechanism. -::: +:::{note} Note: HF part extensible interfaces are in bts2_app_hfp_hf, users can +extend functionality according to requirements and encapsulate interfaces in +interface according to needs. Also, after each cmd is sent, need to wait for +cmd_cfm message to avoid too many messages in protocol stack queue, triggering +protection mechanism. ::: ## HFP_HF Call Function Usage Demo -- First, during project initialization, register the processing function for receiving notify events -- Enter the MAC address of the phone to connect to, wait for connection success message -- After receiving connection success, enter the phone number and length for making a call +- First, during project initialization, register the processing function for + receiving notify events +- Enter the MAC address of the phone to connect to, wait for connection success + message +- After receiving connection success, enter the phone number and length for + making a call ```c //register notify event handle function start // HF side receives AG side AT cmd id processing result: 0 (success) 1 (failure) 2 (timeout, no reply from AG end) @@ -722,4 +794,4 @@ unsigned char mac[6] = {0x00,0x1b,0xdc,0xf4,0xb6,0xbd} bt_interface_conn_ext((unsigned char *)(mac), BT_PROFILE_HFP); // -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_pan_profile.md b/docs/source/en/middleware/bt_pan_profile.md index bebe76f57..fb1b20151 100644 --- a/docs/source/en/middleware/bt_pan_profile.md +++ b/docs/source/en/middleware/bt_pan_profile.md @@ -1,21 +1,36 @@ # BT_PAN -PAN (Personal Area Networking Profile) is a personal area networking protocol. It describes how two or more Bluetooth-enabled devices form an ad-hoc network and how to use the same mechanism to access remote networks through network access points. - -The main roles included in PAN Profile are: +PAN (Personal Area Networking Profile) is a personal area networking protocol. +It describes how two or more Bluetooth-enabled devices form an ad-hoc network +and how to use the same mechanism to access remote networks through network +access points. - Network Access Point NAP (Network Access Point) - - A Bluetooth device supporting Network Access Point (NAP) is a Bluetooth device that provides some functions of an Ethernet bridge to support network services. Devices with NAP service forward network packets between each connected Bluetooth device. NAP exchanges data with PANU using Bluetooth Network Encapsulation Protocol (BNEP). Devices supporting NAP service can allow one or more connected devices to access the network. + - A Bluetooth device supporting Network Access Point (NAP) is a Bluetooth + device that provides some functions of an Ethernet bridge to support + network services. Devices with NAP service forward network packets between + each connected Bluetooth device. NAP exchanges data with PANU using + Bluetooth Network Encapsulation Protocol (BNEP). Devices supporting NAP + service can allow one or more connected devices to access the network. - Group Ad-hoc Network GN (Group Ad-hoc Network) - - Group ad-hoc network allows mobile hosts to collaboratively create ad-hoc wireless networks without using additional network hardware. A group ad-hoc network consists of one Bluetooth device operating as a master node, communicating with 1 to 7 Bluetooth devices operating as slave nodes. GN exchanges data with PANU using Bluetooth Network Encapsulation Protocol (BNEP). Additionally, there may be more inactive group network members in park mode. Bluetooth enforces a limit of only 7 active slave devices in a group ad-hoc network. + - Group ad-hoc network allows mobile hosts to collaboratively create ad-hoc + wireless networks without using additional network hardware. A group + ad-hoc network consists of one Bluetooth device operating as a master + node, communicating with 1 to 7 Bluetooth devices operating as slave + nodes. GN exchanges data with PANU using Bluetooth Network Encapsulation + Protocol (BNEP). Additionally, there may be more inactive group network + members in park mode. Bluetooth enforces a limit of only 7 active slave + devices in a group ad-hoc network. - Personal Area Network User PANU (Personal Area Network User) - - PANU is a Bluetooth device that uses NAP or GN services. PANU supports client roles for both NAP and GN roles, or direct PANU to PANU communication. + - PANU is a Bluetooth device that uses NAP or GN services. PANU supports + client roles for both NAP and GN roles, or direct PANU to PANU + communication. -This document is mainly based on Sifli SDK, introducing how to use basic bt pan functions as a PANU role. -Related files include: +The main roles included in PAN Profile are: - bts2_app_interface - bts2_app_pan - + ## bt_pan Initialization -- PAN initialization function: bt_pan_init, assigns initial values to PAN-related states and flags +- PAN initialization function: bt_pan_init, assigns initial values to + PAN-related states and flags - PAN service enable function: bt_pan_reg, enables PAN profile ```c @@ -23,7 +38,7 @@ void bt_pan_init(bts2_app_stru *bts2_app_data) { U8 i; bts2_app_data->pan_inst_ptr = &bts2_app_data->pan_inst; - + //Assign initial state of PAN bts2_app_data->pan_inst.pan_st = PAN_REG_ST; //Each PAN connection will be allocated an ID @@ -76,11 +91,23 @@ typedef enum ``` ## PAN Device Connection -The following process describes how PANU discovers, connects to, and uses NAP and its network services. -1. The first step is to discover available NAP devices in the vicinity. For this, PANU can perform a search on nearby devices, then use SDP to retrieve NAP services from those devices that support NAP role. (Note: Devices supporting NAP must include the Networking bit in the service class field of class of device) -2. Select a NAP device to connect to. Choose the device to connect to and initiate ACL connection. If the NAP device connects to multiple PANU devices simultaneously, role switch may be required after ACL connection. -3. BNEP connection. Once ACL connection is established, PANU should initiate BNEP L2CAP connection. The BNEP connection process includes required BNEP control commands and optional packet filter setup. If NAP supports filtering, all accepted network packet type filters should be stored for each connection. -4. Network packet interaction. NAP should forward network packets to connected PANU devices. This behaves similarly to a network bridge. +The following process describes how PANU discovers, connects to, and uses NAP +and its network services. +1. The first step is to discover available NAP devices in the vicinity. For + this, PANU can perform a search on nearby devices, then use SDP to retrieve + NAP services from those devices that support NAP role. (Note: Devices + supporting NAP must include the Networking bit in the service class field of + class of device) +2. Select a NAP device to connect to. Choose the device to connect to and + initiate ACL connection. If the NAP device connects to multiple PANU devices + simultaneously, role switch may be required after ACL connection. +3. BNEP connection. Once ACL connection is established, PANU should initiate + BNEP L2CAP connection. The BNEP connection process includes required BNEP + control commands and optional packet filter setup. If NAP supports filtering, + all accepted network packet type filters should be stored for each + connection. +4. Network packet interaction. NAP should forward network packets to connected + PANU devices. This behaves similarly to a network bridge. 5. PANU or NAP can terminate the connection at any time. - PAN device connection interface: @@ -121,7 +148,7 @@ void bt_pan_conn(BTS2S_BD_ADDR *bd) ptr = bts2_app_data->pan_inst_ptr; USER_TRACE(" pan st %x\n", ptr->pan_st); - + //Check if state is PAN_IDLE_ST if (ptr->pan_st == PAN_IDLE_ST) { @@ -171,7 +198,7 @@ void bt_pan_conn(BTS2S_BD_ADDR *bd) } } ``` - + - PAN device disconnection interface: - bts2_app_interface disconnection interface: bt_interface_disc_ext - bts2_app_pan disconnection interface: bt_pan_disc @@ -191,7 +218,7 @@ void bt_pan_disc(BTS2S_BD_ADDR *bd) bts2_app_stru *bts2_app_data = getApp(); bts2_pan_inst_data *ptr = NULL; ptr = bts2_app_data->pan_inst_ptr; - + //State must be PAN_BUSY_ST to disconnect if (ptr->pan_st == PAN_BUSY_ST) { @@ -205,15 +232,14 @@ void bt_pan_disc(BTS2S_BD_ADDR *bd) } } ``` - + - PAN event handling: - PAN connection status callback events - PAN connection successful: BT_NOTIFY_PAN_PROFILE_CONNECTED - PAN connection failed: BT_NOTIFY_PAN_PROFILE_DISCONNECTED -:::{note} -Note: The address parameters passed by the two interfaces need to be converted accordingly. -::: +:::{note} Note: The address parameters passed by the two interfaces need to be +converted accordingly. ::: ```c // After calling the API to connect PAN, the PAN connection success message is sent to user through notify // Users need to implement hdl functions to receive notify events, such as: bt_notify_handle @@ -284,9 +310,13 @@ void bt_pan_scan_proc_net_dev(void); ``` #### bt_lwip Interface Layer -Sifli SDK's network implementation is based on lwip, and PAN does not directly call lwip interfaces, but indirectly calls through bt_lwip as an intermediate layer. -LwIP is Light Weight IP protocol, which can run with or without operating system support. -The focus of LwIP implementation is to reduce RAM usage while maintaining the main functions of TCP protocol. It only needs about ten KB of RAM and about 40K ROM to run, making LwIP protocol stack suitable for use in low-end embedded systems. +Sifli SDK's network implementation is based on lwip, and PAN does not directly +call lwip interfaces, but indirectly calls through bt_lwip as an intermediate +layer. LwIP is Light Weight IP protocol, which can run with or without operating +system support. The focus of LwIP implementation is to reduce RAM usage while +maintaining the main functions of TCP protocol. It only needs about ten KB of +RAM and about 40K ROM to run, making LwIP protocol stack suitable for use in +low-end embedded systems. ```c //1. bt_lwip initialization static struct rt_bt_prot_ops ops = @@ -492,9 +522,13 @@ rt_err_t rt_bt_instance_transfer_prot(struct rt_bt_pan_instance *bt_instance, vo ``` ## PAN Functionality Usage Demo -- First, during project initialization, register the processing function for receiving notify events -- Enter the MAC address of the phone to connect to, wait for connection success message -- To use PAN, you must enable Bluetooth network sharing on the phone. Different operating systems have different ways to enable Bluetooth network sharing, which can be searched online +- First, during project initialization, register the processing function for + receiving notify events +- Enter the MAC address of the phone to connect to, wait for connection success + message +- To use PAN, you must enable Bluetooth network sharing on the phone. Different + operating systems have different ways to enable Bluetooth network sharing, + which can be searched online ```c //register notify event handle function start int bt_sifli_notify_pan_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -552,7 +586,7 @@ int bt_sifli_notify_pan_event_hdl(uint16_t event_id, uint8_t *data, uint16_t dat bfree(msg->payload); break; } - + default: return -1; } @@ -632,4 +666,4 @@ INIT_ENV_EXPORT(app_bt_notify_init); unsigned char mac[6] = {0x00,0x1b,0xdc,0xf4,0xb6,0xbd} bt_interface_conn_ext((unsigned char *)(mac), BT_PROFILE_PAN); // -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_pbap.md b/docs/source/en/middleware/bt_pbap.md index 8376cf899..b7d867877 100644 --- a/docs/source/en/middleware/bt_pbap.md +++ b/docs/source/en/middleware/bt_pbap.md @@ -1,16 +1,14 @@ - # PBAP (Phone Book Access Profile) - -PBAP stands for Phone Book Access Profile, an upper-layer protocol based on OBEX. This protocol allows synchronization of contacts, call logs, and other information from devices with phone book functionality, such as mobile phones. +PBAP stands for Phone Book Access Profile, an upper-layer protocol based on +OBEX. This protocol allows synchronization of contacts, call logs, and other +information from devices with phone book functionality, such as mobile phones. +- **PSE (Phone Book Server Equipment)**: The device that holds the phone book + source data, acting as the server, such as a mobile phone. +- **PCE (Phone Book Client Equipment)**: The device that requests phone book + information from the PSE, acting as the client, such as a car infotainment + system. PBAP defines two roles: - -- **PSE (Phone Book Server Equipment)**: The device that holds the phone book source data, acting as the server, such as a mobile phone. -- **PCE (Phone Book Client Equipment)**: The device that requests phone book information from the PSE, acting as the client, such as a car infotainment system. - -The PSE can be a mobile phone or a device with a SIM card. The stored contact information may reside on the phone or the SIM card. The PCE must specify the path from which to retrieve the data during synchronization, i.e., whether to sync from the phone or the SIM card. - -The following objects are supported in PBAP: - Phone Book object (pb): `pb.vcf` - Incoming Calls History object (ich): `ich.vcf` - Outgoing Calls History object (och): `och.vcf` @@ -19,46 +17,47 @@ The following objects are supported in PBAP: - Speed-Dial object (spd): `spd.vcf` - Favorite Contacts object (fav): `fav.vcf` -**Contact paths:** +The PSE can be a mobile phone or a device with a SIM card. The stored contact +information may reside on the phone or the SIM card. The PCE must specify the +path from which to retrieve the data during synchronization, i.e., whether to +sync from the phone or the SIM card. - Phone path: `telecom/xxx.vcf` - SIM card path: `SIM1/telecom/xxx.vcf` -This document mainly describes the basic functionality support for PBAP in the PCE based on the Sifli SDK. The relevant files are: +The following objects are supported in PBAP: - `bts2_app_interface` - `bts2_app_pbap_c` - ## PBAP Initialization - -- The PBAP initialization function: `bt_pbap_clt_init`, which initializes PBAP-related states and flags. - +- The PBAP initialization function: `bt_pbap_clt_init`, which initializes + PBAP-related states and flags. ```c void bt_pbap_clt_init(bts2_app_stru *bts2_app_data) { local_inst = (bts2s_pbap_clt_inst_data *)bmalloc(sizeof(bts2s_pbap_clt_inst_data)); // Must allocate successful BT_ASSERT(local_inst); - local_inst->pbap_clt_st = BT_PBAPC_IDLE_ST; - local_inst->is_valid_vcard = FALSE; - local_inst->elem_index = BT_PBAP_ELEM_VCARD_IDLE; - local_inst->pbab_vcard = NULL; - local_inst->mfs = pbap_clt_get_max_mtu(); - local_inst->rmt_supp_repos = 0; - local_inst->curr_cmd = BT_PBAP_CLT_IDLE; + local_inst->pbap_clt_st = BT_PBAPC_IDLE_ST; + local_inst->is_valid_vcard = FALSE; + local_inst->elem_index = BT_PBAP_ELEM_VCARD_IDLE; + local_inst->pbab_vcard = NULL; + local_inst->mfs = pbap_clt_get_max_mtu(); + local_inst->rmt_supp_repos = 0; + local_inst->curr_cmd = BT_PBAP_CLT_IDLE; - local_inst->curr_repos = PBAP_LOCAL; - local_inst->curr_phonebook = PBAP_PB; + local_inst->curr_repos = PBAP_LOCAL; + local_inst->curr_phonebook = PBAP_PB; - local_inst->target_repos = PBAP_UNKNOWN_REPO; - local_inst->target_phonebook = PBAP_UNKNOWN_PHONEBOOK; + local_inst->target_repos = PBAP_UNKNOWN_REPO; + local_inst->target_phonebook = PBAP_UNKNOWN_PHONEBOOK; - local_inst->cur_file_hdl = NULL; + local_inst->cur_file_hdl = NULL; } ``` - ### PBAP Function for Getting Contact Names - -Since there are many phone books on the mobile phone and syncing all the data to a watch would result in too much data, this feature retrieves contact names by querying the phone using a number during a call. Note: This feature requires permission from the phone during pairing. - +Since there are many phone books on the mobile phone and syncing all the data to +a watch would result in too much data, this feature retrieves contact names by +querying the phone using a number during a call. Note: This feature requires +permission from the phone during pairing. - **PBAP connection device interfaces:** - `bts2_app_interface` connection interface: `bt_interface_conn_ext` - `bts2_app_pbap_c` connection interface: `bt_pbap_clt_conn_to_srv` @@ -67,14 +66,16 @@ Since there are many phone books on the mobile phone and syncing all the data to - `bts2_app_interface` disconnect interface: `bt_interface_disc_ext` - `bts2_app_pbap_c` disconnect interface: `bt_pbap_clt_disc_to_srv` -- **PBAP select and set contact repository (by default, it is set to phone storage):** - - `bts2_app_pbap_c` interface for setting contact repository: `bt_pbap_client_set_pb` - -- **PBAP retrieve contact name by number (this is called when there is a call):** - - `bts2_app_pbap_c` interface to get contact name by number: `bt_pbap_client_get_name_by_number` - - Contact name event: `BT_NOTIFY_PBAP_VCARD_LIST_ITEM_IND` - - Event indicating the end of contact name retrieval: `BT_NOTIFY_PBAP_VCARD_LIST_CMPL` - +- **PBAP select and set contact repository (by default, it is set to phone + storage):** + - `bts2_app_pbap_c` interface for setting contact repository: + `bt_pbap_client_set_pb` + - PBAP retrieves contact names by phone number (invoked during active + calls): + - bts2_app_pbap_c interface for setting the contact repository: + bt_pbap_client_get_name_by_number + - Contact name event: BT_NOTIFY_PBAP_VCARD_LIST_ITEM_IND + - Contact name retrieval completion event: BT_NOTIFY_PBAP_VCARD_LIST_CMPL ```c // Register notify event handle function start // step1: Successfully establish PBAP connection via interface @@ -180,5 +181,3 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); // Register notify event handle function end ``` - -This document provides an overview of PBAP functionality, implementation details, and the necessary SDK files. diff --git a/docs/source/en/middleware/bt_service.md b/docs/source/en/middleware/bt_service.md index 4cc3f374e..0d7874f75 100644 --- a/docs/source/en/middleware/bt_service.md +++ b/docs/source/en/middleware/bt_service.md @@ -2,36 +2,74 @@ ## Overview -Currently, Bluetooth is mainly divided into Classic Bluetooth BR (Basic Rate)/EDR (Enhanced Data Rate) and Low Energy (BLE) Bluetooth. Sifli Bluetooth is based on Bluetooth 5.3 and provides a comprehensive dual-mode Bluetooth solution. Sifli Bluetooth focuses on supporting Bluetooth audio and Bluetooth voice functions, providing convenient related development methods. Sifli Bluetooth has good readability, scalability, and portability. Sifli Bluetooth is module-oriented, providing rich interfaces with clear hierarchy and logic between modules, simple and easy to understand, providing a good foundation for users to learn and develop. The overall design goal of Sifli Bluetooth is to enable users to form high-quality products in a shorter time through configuration or secondary development of Sifli Bluetooth. This section mainly introduces Sifli's architecture and related specification configuration information for classic Bluetooth services. - -To transmit data via Bluetooth on Bluetooth-enabled devices, Sifli provides basic Bluetooth functionality APIs and common Bluetooth protocol specifications (A2DP/AVRCP/HFP/PBAP/HID/SPP, etc.). Users can perform the following operations through APIs: +Currently, Bluetooth is mainly divided into Classic Bluetooth BR (Basic +Rate)/EDR (Enhanced Data Rate) and Low Energy (BLE) Bluetooth. Sifli Bluetooth +is based on Bluetooth 5.3 and provides a comprehensive dual-mode Bluetooth +solution. Sifli Bluetooth focuses on supporting Bluetooth audio and Bluetooth +voice functions, providing convenient related development methods. Sifli +Bluetooth has good readability, scalability, and portability. Sifli Bluetooth is +module-oriented, providing rich interfaces with clear hierarchy and logic +between modules, simple and easy to understand, providing a good foundation for +users to learn and develop. The overall design goal of Sifli Bluetooth is to +enable users to form high-quality products in a shorter time through +configuration or secondary development of Sifli Bluetooth. This section mainly +introduces Sifli's architecture and related specification configuration +information for classic Bluetooth services. + +To transmit data via Bluetooth on Bluetooth-enabled devices, Sifli provides +basic Bluetooth functionality APIs and common Bluetooth protocol specifications +(A2DP/AVRCP/HFP/PBAP/HID/SPP, etc.). Users can perform the following operations +through APIs: - Scan other Bluetooth devices - Manage connected devices -- Implement call and audio functions wirelessly with other Bluetooth devices (such as phones, headphones, etc.) +- Implement call and audio functions wirelessly with other Bluetooth devices + (such as phones, headphones, etc.) - Transfer custom data with other devices -:::{note} -For more information about APIs, please refer to: [bluetooth_service](middleware-bluetooth_service) -::: +:::{note} For more information about APIs, please refer to: +[bluetooth_service](middleware-bluetooth_service) ::: ### Classic Bluetooth Architecture -The main purpose of Sifli Classic Bluetooth architecture is to build a convenient, stable, comfortable, and efficient solution for users, structurally encapsulating functions and logic that users care about, and minimizing users' secondary development workload as much as possible. Therefore, the design of Sifli Classic Bluetooth architecture always revolves around the hierarchical structure and functional modularization. -- From the overall Bluetooth architecture perspective, Bluetooth is divided into two major parts: controller and host. - - The controller includes PHY, Baseband, Link Controller, Link Manager, Device Manager, HCI and other modules, used for hardware interface management, link management, etc.; - - The host includes L2CAP, RFCOMM, SDP, GAP and various specifications, building the foundation for providing interfaces to the application layer, facilitating user access to the Bluetooth system. -- Sifli's controller runs on LCPU, while the host part and APIs that provide users access to Bluetooth-related functions run on HCPU. -- Sifli's host part is divided into three categories: protocol stack, service, and interface. - - The protocol stack mainly implements state machines and message processing related to Bluetooth protocols and specifications, which is the core of Bluetooth-related specifications, providing standardized interfaces for Bluetooth communication establishment and data interaction. Provided to users in lib format; - - Service mainly provides modules for processing specific Bluetooth function service-related information, designed for user-specific functions, released to users in source code format; - - Interface mainly provides specific functions for users to access the Bluetooth system, which are simple and efficient general-purpose interfaces, released to users in source code format. Users can use or customize related functions according to their needs. -![Figure 1: Sifli Bluetooth Architecture](../../assets/bluetooth_arch.png) +The main purpose of Sifli Classic Bluetooth architecture is to build a +convenient, stable, comfortable, and efficient solution for users, structurally +encapsulating functions and logic that users care about, and minimizing users' +secondary development workload as much as possible. Therefore, the design of +Sifli Classic Bluetooth architecture always revolves around the hierarchical +structure and functional modularization. +- From the overall Bluetooth architecture perspective, Bluetooth is divided into + two major parts: controller and host. + - The controller includes PHY, Baseband, Link Controller, Link Manager, + Device Manager, HCI and other modules, used for hardware interface + management, link management, etc.; + - The host includes L2CAP, RFCOMM, SDP, GAP and various specifications, + building the foundation for providing interfaces to the application layer, + facilitating user access to the Bluetooth system. +- Sifli's controller runs on LCPU, while the host part and APIs that provide + users access to Bluetooth-related functions run on HCPU. +- Sifli's host part is divided into three categories: protocol stack, service, + and interface. + - The protocol stack mainly implements state machines and message processing + related to Bluetooth protocols and specifications, which is the core of + Bluetooth-related specifications, providing standardized interfaces for + Bluetooth communication establishment and data interaction. Provided to + users in lib format; + - Service mainly provides modules for processing specific Bluetooth function + service-related information, designed for user-specific functions, + released to users in source code format; + - Interface mainly provides specific functions for users to access the + Bluetooth system, which are simple and efficient general-purpose + interfaces, released to users in source code format. Users can use or + customize related functions according to their needs. ![Figure 1: Sifli + Bluetooth Architecture](../../assets/bluetooth_arch.png) ### Bluetooth Specification Configuration Information -Currently, the classic Bluetooth specifications and protocols supported by the host protocol stack are as follows: +Currently, the classic Bluetooth specifications and protocols supported by the +host protocol stack are as follows: - Specifications: A2DP, AVRCP, GATT over BR, HFP, HID, PAN, PBAP, SPP - Protocols: L2CAP, SDP, AVDTP, AVCTP, RFCOMM -![Figure 1: Bluetooth Specifications Supported by Sifli Bluetooth](../../assets/bluetooth_profiles.png) +![Figure 1: Bluetooth Specifications Supported by Sifli +Bluetooth](../../assets/bluetooth_profiles.png) ## Bluetooth Service Configuration and Development Instructions ### Sifli SDK Project Introduction @@ -47,7 +85,8 @@ Currently, the classic Bluetooth specifications and protocols supported by the h ### Sifli Bluetooth Project Compilation Basic Process 1. Project environment: Run set_env.bat to build the compilation environment 2. Enter directory: siflisdk\example\bt\test_example\project\common -3. Compile the corresponding BT project in the above path, and the generated files are also in the common path +3. Compile the corresponding BT project in the above path, and the generated + files are also in the common path - Compilation result build__hcpu directory description: - board: Mainly contains board-level related executable files - bootloader: Mainly contains bootloader-related executable files @@ -55,18 +94,25 @@ Currently, the classic Bluetooth specifications and protocols supported by the h - lcpu: Mainly contains lcpu-related executable files - peripheral: Mainly contains peripheral driver-related executable files - sifli_sdk: Mainly contains SDK middleware-related executable files -4. Flash files: Run script uart_download.bat -![Sifli Classic Bluetooth Example](../../assets/BT_PROJECT.png) -![Sifli Classic Bluetooth Compilation](../../assets/complie_result.png) +4. Flash files: Run script uart_download.bat ![Sifli Classic Bluetooth + Example](../../assets/BT_PROJECT.png) ![Sifli Classic Bluetooth + Compilation](../../assets/complie_result.png) ### Sifli SDK Bluetooth-Related File Description -- Sifli SDK Bluetooth-related source code requires entering folder: siflisdk\middleware\bluetooth\service\bt +- Sifli SDK Bluetooth-related source code requires entering folder: + siflisdk\middleware\bluetooth\service\bt - bt_cm file contains Bluetooth connection_manager related content - - bt_finsh file contains Bluetooth service and configuration-related content, specific description as shown in the figure below: - ![Sifli SDK Bluetooth-Related Source Code Description](../../assets/service_profiles.png) - + - bt_finsh file contains Bluetooth service and configuration-related + content, specific description as shown in the figure below: ![Sifli SDK + Bluetooth-Related Source Code + Description](../../assets/service_profiles.png) #### Sifli_SDK Bluetooth Initialization and Profile Configuration Brief Description -1. Sifli SDK runs on the rt-thread system. In addition to the tasks that come with rt-thread, Sifli implements a special task mechanism specifically for handling Bluetooth-related events according to Bluetooth characteristics, running on bts_task. Bluetooth custom tasks have special sub-task_ids, and Bluetooth service-related functions all run on sub-task_id: bts2_task_get_app_task_id() +1. Sifli SDK runs on the rt-thread system. In addition to the tasks that come + with rt-thread, Sifli implements a special task mechanism specifically for + handling Bluetooth-related events according to Bluetooth characteristics, + running on bts_task. Bluetooth custom tasks have special sub-task_ids, and + Bluetooth service-related functions all run on sub-task_id: + bts2_task_get_app_task_id() ```c void bts2_main(void) { @@ -81,37 +127,40 @@ void bts2_main(void) bts_run_init(); } ``` -2. bts2_main registers the initialization function, release function, and event handling function of sub-task_id: bts2_task_get_app_task_id() by calling bts2_app_reg_cbk -3. When sub-task related content is initialized, the app_fn_init function is executed in sequence +2. bts2_main registers the initialization function, release function, and event + handling function of sub-task_id: bts2_task_get_app_task_id() by calling + bts2_app_reg_cbk +3. When sub-task related content is initialized, the app_fn_init function is + executed in sequence 4. Sub-task related events are distributed and processed through app_fn_hdl_ext ```c void app_fn_init(void **pp) { bts2_app_stru *bts2_app_data; - /*app */ + /* Application initialization */ *pp = (void *)bmalloc(sizeof(bts2_app_stru)); RT_ASSERT(*pp); memset(*pp, 0, sizeof(bts2_app_stru)); bts2_app_data = (bts2_app_stru *)*pp; bts2g_app_p = bts2_app_data; - bts2_app_data->menu_id = menu_start; + bts2_app_data->menu_id = menu_start; bt_disply_menu(bts2_app_data); - bts2_app_data->menu_id = menu_main; + bts2_app_data->menu_id = menu_main; bt_disply_menu(bts2_app_data); - bts2_app_data->input_str_len = 0; - bts2_app_data->pin_code_len = strlen(CFG_PIN_CODE); - strcpy((char *)bts2_app_data->pin_code, CFG_PIN_CODE); + bts2_app_data->input_str_len = 0; + bts2_app_data->pin_code_len = strlen(CFG_PIN_CODE); + strcpy((char *)bts2_app_data->pin_code, CFG_PIN_CODE); init_inst_data(bts2_app_data); init_bt_cm(); - gap_rd_local_bd_req(bts2_app_data->phdl); - /*Send read local BD request,if receive confirm message,then BTS2 initialization is OK*/ - gap_app_init_req(bts2_app_data->phdl); + gap_rd_local_bd_req(bts2_app_data->phdl); + /* Send a request to read the local Bluetooth device address. A subsequent confirmation message indicates that BTS2 initialization is successful. */ + gap_app_init_req(bts2_app_data->phdl); //bts2_timer_ev_add(KEYB_CHK_TIMEOUT, key_msg_svc, 0, NULL); @@ -122,7 +171,7 @@ void app_fn_hdl_ext(void **pp) U16 msg_cls; void *msg; - bts2_msg_get(bts2_task_get_app_task_id(), &msg_cls, &msg); + bts2_msg_get(bts2_task_get_app_task_id(), &msg_cls, &msg); bt_event_publish(msg_cls, *((U16 *)msg), msg); bfree(msg); } @@ -141,8 +190,8 @@ void app_fn_rel(void **pp) return; } - /*get a msg from the demo application task*/ - while (bts2_msg_get(bts2_task_get_app_task_id(), &msg_type, &msg_data)) + /*Retrieve and process messages from the demo application task queue*/ + while (bts2_msg_get(bts2_task_get_app_task_id(), &msg_type, &msg_data)) { switch (msg_type) { @@ -159,28 +208,28 @@ void app_fn_rel(void **pp) BTS2S_SPP_CLT_DATA_IND *msg; msg = (BTS2S_SPP_CLT_DATA_IND *)msg_data; - bfree(msg->payload); + bfree(msg->payload); break; } } bfree(msg_data); - /*SPP */ - for (i = 0; i < SPP_CLT_MAX_CONN_NUM; i++) + /*SPP Client connection cleanup*/ + for (i = 0; i < SPP_CLT_MAX_CONN_NUM; i++) { - if (bts2_app_data->spp_inst[i].timer_flag) + if (bts2_app_data->spp_inst[i].timer_flag) { - bts2_timer_ev_cancel(bts2_app_data->spp_inst[i].time_id, NULL, NULL); + bts2_timer_ev_cancel(bts2_app_data->spp_inst[i].time_id, NULL, NULL); } - if (bts2_app_data->spp_inst[i].cur_file_hdl != NULL) + if (bts2_app_data->spp_inst[i].cur_file_hdl != NULL) { - fclose(bts2_app_data->spp_inst[i].cur_file_hdl); + fclose(bts2_app_data->spp_inst[i].cur_file_hdl); } - if (bts2_app_data->spp_inst[i].wr_file_hdl != NULL) + if (bts2_app_data->spp_inst[i].wr_file_hdl != NULL) { - fclose(bts2_app_data->spp_inst[i].wr_file_hdl); + fclose(bts2_app_data->spp_inst[i].wr_file_hdl); } } break; @@ -199,41 +248,41 @@ void app_fn_rel(void **pp) BTS2S_SPP_SRV_DATA_IND *msg; msg = (BTS2S_SPP_SRV_DATA_IND *)msg_data; - bfree(msg->payload); + bfree(msg->payload); break; } } bfree(msg_data); - /*SPP */ - for (i = 0; i < CFG_MAX_ACL_CONN_NUM; i++) + /*SPP Server connection cleanup*/ + for (i = 0; i < CFG_MAX_ACL_CONN_NUM; i++) { bts2_spp_srv_inst_data *bts2_spp_srv_inst = NULL; bts2_spp_service_list *spp_service_list = NULL; - bts2_spp_srv_inst = &bts2_app_data->spp_srv_inst[i]; + bts2_spp_srv_inst = &bts2_app_data->spp_srv_inst[i]; - if (bts2_spp_srv_inst->service_list != 0) + if (bts2_spp_srv_inst->service_list != 0) { - bts2_spp_service_list *spp_service_list = bts2_spp_srv_inst->spp_service_list; + bts2_spp_service_list *spp_service_list = bts2_spp_srv_inst->spp_service_list; while (spp_service_list) { - if (spp_service_list->timer_flag) + if (spp_service_list->timer_flag) { - bts2_timer_ev_cancel(spp_service_list->time_id, NULL, NULL); + bts2_timer_ev_cancel(spp_service_list->time_id, NULL, NULL); } - if (spp_service_list->cur_file_hdl != NULL) + if (spp_service_list->cur_file_hdl != NULL) { - fclose(spp_service_list->cur_file_hdl); + fclose(spp_service_list->cur_file_hdl); } - if (spp_service_list->wr_file_hdl != NULL) + if (spp_service_list->wr_file_hdl != NULL) { - fclose(spp_service_list->wr_file_hdl); + fclose(spp_service_list->wr_file_hdl); } - spp_service_list = (bts2_spp_service_list *)spp_service_list->next_struct; + spp_service_list = (bts2_spp_service_list *)spp_service_list->next_struct; } } } @@ -256,78 +305,83 @@ void app_fn_rel(void **pp) bt_pbap_clt_free_inst(); bfree(bts2_app_data); } - ``` -5. When sub-task: bts2_task_get_app_task_id() initialization is completed and receives BTS2MU_GAP_APP_INIT_CFM, Bluetooth profile function initialization begins. +5. When sub-task: bts2_task_get_app_task_id() initialization is completed and + receives BTS2MU_GAP_APP_INIT_CFM, Bluetooth profile function initialization + begins. ```c - case BTS2MU_GAP_APP_INIT_CFM: +case BTS2MU_GAP_APP_INIT_CFM: { - if (bts2_app_data->state == BTS_APP_IDLE) + if (bts2_app_data->state == BTS_APP_IDLE) { bt_init_profile(bts2_app_data); bt_init_local_ctrller(bts2_app_data); - bts2_app_data->state = BTS_APP_READY; + bts2_app_data->state = BTS_APP_READY; } break; ``` - #### Bluetooth Basic Information Modification Interface -1. Change Bluetooth device COD (class of device): Re-implement the bt_get_class_of_device function +1. Change Bluetooth device COD (class of device): Re-implement the + bt_get_class_of_device function ```c __WEAK uint32_t bt_get_class_of_device(void) { return 0x240704; } ``` -2. Change Bluetooth device name: Call interface void bt_interface_set_local_name(int len, void *data); +2. Change Bluetooth device name: Call interface void + bt_interface_set_local_name(int len, void *data); 3. Bluetooth profile configuration: bt_init_profile ```c void bt_init_profile(bts2_app_stru *bts2_app_data) { - /*SPP */ + /*Initialize SPP*/ bt_spp_clt_init(bts2_app_data); - /*HFP_HF */ + /*Initialize HFP_HF*/ bt_hfp_hf_init(bts2_app_data); bt_hfp_hf_start_enb(bts2_app_data); - /*HFP_AG */ + /*Initialize HFP_AG*/ bt_hfp_ag_app_init(bts2_app_data); bt_hfp_start_profile_service(bts2_app_data); - /*PAN */ + /*Initialize PAN*/ bt_pan_init(bts2_app_data); bt_pan_reg(bts2_app_data); - /*A2DP SNK */ + /*Initialize A2DP SNK*/ bt_av_init(bts2_app_data); - /*AVRCP */ + /*Initialize AVRCP*/ bt_avrcp_int(bts2_app_data); - /*HID */ + /*Initialize HID*/ bt_hid_init(bts2_app_data); - /*PBAP_CLT */ + /*Initialize PBAP_CLT*/ bt_pbap_clt_init(bts2_app_data); - /*SPP_SRV */ + /*Initialize SPP_SRV */ bt_spp_srv_init(bts2_app_data); bt_spp_srv_start_enb(bts2_app_data); } ``` - ### Bluetooth Service Interface Invocation and Callback Usage Methods and Precautions -- Bluetooth interface integrates BT discovery, connection, and reconnection functions. Related function interfaces are mainly in: bts2_app_interface -- Bluetooth service callbacks include data transmitted by remote Bluetooth devices, results of calling Bluetooth service interface processing, and active updates of Bluetooth status information, etc. - - Sifli Bluetooth service callbacks require users to implement callback handling functions themselves and transfer data to user's own task to process related data +- Bluetooth interface integrates BT discovery, connection, and reconnection + functions. Related function interfaces are mainly in: bts2_app_interface +- Bluetooth service callbacks include data transmitted by remote Bluetooth + devices, results of calling Bluetooth service interface processing, and active + updates of Bluetooth status information, etc. + - Sifli Bluetooth service callbacks require users to implement callback + handling functions themselves and transfer data to user's own task to + process related data - Registration function: bt_interface_register_bt_event_notify_callback - Unregistration function: bt_interface_unregister_bt_event_notify_callback -:::{note} -The data processing task for callback functions is a user-defined implemented task. -::: + :::{note} The data processing task for callback functions is a + user-defined implemented task. ::: ```c int bt_notify_event_hdl(uint16_t type, uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -335,16 +389,18 @@ int bt_notify_event_hdl(uint16_t type, uint16_t event_id, uint8_t *data, uint16_ return 0; } ``` - #### Brief Description of Important Bluetooth Events Messages received by bt_notify_event_hdl include: - ACL connection successful message: BT_NOTIFY_COMMON_ACL_CONNECTED - ACL disconnection successful message: BT_NOTIFY_COMMON_ACL_DISCONNECTED -- Profile connection successful message: BT_NOTIFY_(profile_type)_PROFILE_CONNECTED -- Profile disconnection successful message: BT_NOTIFY_(profile_type)_PROFILE_DISCONNECTED +- Profile connection successful message: + BT_NOTIFY_(profile_type)_PROFILE_CONNECTED +- Profile disconnection successful message: + BT_NOTIFY_(profile_type)_PROFILE_DISCONNECTED - SCO connection successful message: BT_NOTIFY_COMMON_SCO_CONNECTED - SCO disconnection successful message: BT_NOTIFY_COMMON_SCO_DISCONNECTED -- HFP_HF sending AT cmd peer device processing result message: BT_NOTIFY_HF_AT_CMD_CFM +- HFP_HF sending AT cmd peer device processing result message: + BT_NOTIFY_HF_AT_CMD_CFM ```c // ACL start typedef struct @@ -420,7 +476,6 @@ typedef struct } bt_notify_at_cmd_cfm_t; // at cmd cfm end ``` - 1. Bluetooth on/off demo: - Turn on Bluetooth, corresponding interface: bt_interface_open_bt - Turn off Bluetooth, corresponding interface: bt_interface_close_bt @@ -432,12 +487,12 @@ static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, ui { case BT_NOTIFY_COMMON_BT_STACK_READY: { - // handle open bt + // Handle Bluetooth stack ready event break; } case BT_NOTIFY_COMMON_CLOSE_COMPLETE: { - //handle close bt + // Handle Bluetooth stack close completion break; } } @@ -467,10 +522,11 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); ``` - 2. Bluetooth device scanning demo: - - Start Bluetooth scanning, corresponding interface: bt_interface_start_inquiry - - Stop Bluetooth scanning, corresponding interface: bt_interface_stop_inquiry + - Start Bluetooth scanning, corresponding interface: + bt_interface_start_inquiry + - Stop Bluetooth scanning, corresponding interface: + bt_interface_stop_inquiry - Corresponding processing result message event handling as follows: ```c static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -479,12 +535,12 @@ static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, ui { case BT_NOTIFY_COMMON_DISCOVER_IND: { - //handle inquiry result device info + // Handle device information from inquiry results break; } case BT_NOTIFY_COMMON_INQUIRY_CMP: { - //handle inquiry complete result + // Handle inquiry completion status break; } } @@ -517,7 +573,8 @@ INIT_ENV_EXPORT(app_bt_notify_init); 3. Bluetooth device connection demo: - Connect Bluetooth device, corresponding interface: bt_interface_conn_ext - - Disconnect Bluetooth device, corresponding interface: bt_interface_disc_ext + - Disconnect Bluetooth device, corresponding interface: + bt_interface_disc_ext - Corresponding processing result message event handling as follows: ```c static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -526,12 +583,12 @@ static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, ui { case BT_NOTIFY_COMMON_BT_STACK_READY: { - // handle open bt + // Handle Bluetooth stack ready event break; } case BT_NOTIFY_COMMON_CLOSE_COMPLETE: { - //handle close bt + // Handle Bluetooth stack close completion break; } } @@ -561,10 +618,11 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); ``` - 4. Bluetooth device scanning demo: - - Start Bluetooth scanning, corresponding interface: bt_interface_start_inquiry - - Stop Bluetooth scanning, corresponding interface: bt_interface_stop_inquiry + - Start Bluetooth scanning, corresponding interface: + bt_interface_start_inquiry + - Stop Bluetooth scanning, corresponding interface: + bt_interface_stop_inquiry - Corresponding processing result message event handling as follows: ```c static int bt_sifli_notify_(profile)_event_hdl(uint16_t event_id, uint8_t *data, uint16_t data_len) @@ -573,12 +631,12 @@ static int bt_sifli_notify_(profile)_event_hdl(uint16_t event_id, uint8_t *data, { case BT_NOTIFY_(profile_type)_PROFILE_CONNECTED: { - //handle profile connected event + // Handle profile connected event break; } case BT_NOTIFY_(profile_type)_PROFILE_DISCONNECTED: { - //handle profile disconnected event + // Handle profile disconnected event break; } } @@ -589,12 +647,12 @@ static int bt_sifli_notify_common_event_hdl(uint16_t event_id, uint8_t *data, ui { case BT_NOTIFY_COMMON_ACL_CONNECTED: { - //handle acl connected event + // Handle ACL connection establishment break; } case BT_NOTIFY_COMMON_ACL_DISCONNECTED: { - //handle acl disconnected event + // Handle ACL disconnection break; } } @@ -629,7 +687,6 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); ``` - ## Bluetooth Protocols and Specifications ```{toctree} @@ -642,4 +699,4 @@ bt_gatt.md bt_pan_profile.md bt_pbap.md bt_spp.md -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/bt_spp.md b/docs/source/en/middleware/bt_spp.md index 57be542c2..6b5724d5a 100644 --- a/docs/source/en/middleware/bt_spp.md +++ b/docs/source/en/middleware/bt_spp.md @@ -1,32 +1,31 @@ - # SPP (Serial Port Profile) - -SPP stands for Serial Port Profile, which allows devices to wirelessly transfer data by simulating a serial port connection. Based on the RFCOMM communication layer, the SPP protocol is similar to the traditional RS-232 serial port standard, making it ideal for low-speed, short-range data transmission, such as communication between Android devices, sensors, and microcontrollers. - -SPP defines two roles: - -- **Device A (DevA)** – The device that initiates the connection to another device. +SPP stands for Serial Port Profile, which allows devices to wirelessly transfer +data by simulating a serial port connection. Based on the RFCOMM communication +layer, the SPP protocol is similar to the traditional RS-232 serial port +standard, making it ideal for low-speed, short-range data transmission, such as +communication between Android devices, sensors, and microcontrollers. +- **Device A (DevA)** – The device that initiates the connection to another + device. - Initiates requests through SDP to query DevB's RFCOMM channel. - Can perform security authentication with the other device. - - Can establish an L2CAP (RFCOMM) RFCOMM (DLC) channel with the other device through the queried RFCOMM channel. + - Can establish an L2CAP (RFCOMM) RFCOMM (DLC) channel with the other device + through the queried RFCOMM channel. - Can send and receive data. - Can disconnect the connection. - -- **Device B (DevB)** – The device that waits for another device to initiate the connection. +- **Device B (DevB)** – The device that waits for another device to initiate the + connection. - Registers the SPP-related UUID in the SDP database so DevA can query it. - Can perform security authentication with the other device. - Receives the connection request from the other device. - Can send and receive data. - Can disconnect the connection. -This document mainly describes the basic functionality support for DevB in SPP based on the Sifli SDK. The relevant files are: +SPP defines two roles: - `bts2_app_interface` - `bts2_app_spp_s` - ## SPP Initialization - -- The SPP initialization function: `bt_spp_srv_init`, which initializes SPP-related states, flags, and registers the SPP UUID. - +- The SPP initialization function: `bt_spp_srv_init`, which initializes + SPP-related states, flags, and registers the SPP UUID. ```c //step1: Users can override the bt_spp_srv_add_uuid_list function to register custom SPP UUIDs into the BR/EDR SDP database //step2: When enabling the SPP profile, the SPP will register data into the SDP @@ -87,13 +86,12 @@ void bt_spp_srv_start_enb(bts2_app_stru *bts2_app_data) "); } ``` - ## SPP Data Transmission and Reception - -SPP, as a DevB feature, can only receive connection requests initiated by the other device. - +SPP, as a DevB feature, can only receive connection requests initiated by the +other device. - **SPP disconnect device interface:** - - `bts2_app_interface` disconnect interface: `bt_interface_dis_spp_by_addr_and_chl` + - `bts2_app_interface` disconnect interface: + `bt_interface_dis_spp_by_addr_and_chl` - `bts2_app_spp_s` disconnect interface: `bt_spp_srv_disc_req` - **SPP connection status callback events:** @@ -105,13 +103,15 @@ SPP, as a DevB feature, can only receive connection requests initiated by the ot - **SPP data transmission and reception interfaces and events:** - **Data sending:** - `bts2_app_interface` data send interface: `bt_interface_spp_send_data` - - `bts2_app_spp_s` data send interface: `bt_spp_srv_sending_data_by_device_id_and_srv_chnl` + - `bts2_app_spp_s` data send interface: + `bt_spp_srv_sending_data_by_device_id_and_srv_chnl` - Data send success event: `BT_NOTIFY_SPP_DATA_CFM` - **Data reception:** - - `bts2_app_interface` data reception success response interface: `bt_interface_spp_srv_data_rsp` - - `bts2_app_spp_s` data reception success response interface: `spp_srv_data_rsp_ext` + - `bts2_app_interface` data reception success response interface: + `bt_interface_spp_srv_data_rsp` + - `bts2_app_spp_s` data reception success response interface: + `spp_srv_data_rsp_ext` - Data received event: `BT_NOTIFY_SPP_DATA_IND` - ```c // step1: When receiving a connection from the other device, if only a single channel is connected, handle the events: BT_NOTIFY_SPP_PROFILE_CONNECTED and BT_NOTIFY_SPP_PROFILE_DISCONNECTED // step2: When multiple channels are connected, handle the related connection events: BT_NOTIFY_SPP_CONN_IND and BT_NOTIFY_SPP_DISC_IND @@ -234,5 +234,3 @@ int app_bt_notify_init(void) INIT_ENV_EXPORT(app_bt_notify_init); // Register notify event handle function end ``` - -This document provides an overview of SPP functionality, implementation details, and the necessary SDK files. diff --git a/docs/source/en/middleware/button.md b/docs/source/en/middleware/button.md index 25cd0ce30..b7d8a3d99 100644 --- a/docs/source/en/middleware/button.md +++ b/docs/source/en/middleware/button.md @@ -1,36 +1,38 @@ - # Button Component - Source Path: `example\button\src` [Button Example](example-button) -The button library uses pin devices to detect various button actions. It utilizes one timer to handle debouncing and another timer to detect long press actions. - -It supports the following actions: +The button library uses pin devices to detect various button actions. It +utilizes one timer to handle debouncing and another timer to detect long press +actions. - **Press**: The button is pressed. - **Release**: The button is released. -- **Long Press**: The button is pressed and held for a duration specified by `BUTTON_ADV_ACTION_CHECK_DELAY`. -- **Click**: The button is pressed and released without triggering a long press action. +- **Long Press**: The button is pressed and held for a duration specified by + `BUTTON_ADV_ACTION_CHECK_DELAY`. +- **Click**: The button is pressed and released without triggering a long press + action. -Users can register handlers for each button to be notified when any action occurs. The button activity state is configurable. +It supports the following actions: ## Configuration -The maximum number of buttons supported and the threshold for detecting long press actions are configured by the following macros: - +The maximum number of buttons supported and the threshold for detecting long +press actions are configured by the following macros: ```c #define BUTTON_MAX_NUM 2 #define BUTTON_ADV_ACTION_CHECK_DELAY 3000 ``` -These can be configured under `SiFli Middleware -> Enable button library`. You can enter the compilation interface and type `menuconfig` to access it. - -![Figure 1: Button Library Configuration Menu](../../assets/button_menu.png) +These can be configured under `SiFli Middleware -> Enable button library`. You +can enter the compilation interface and type `menuconfig` to access it. ## Using the Button Library +In the example below, the button is first initialized by binding the button to a +pin device and registering a button action handler. Then, button detection is +enabled, which involves enabling the pin IRQ. + -In the example below, the button is first initialized by binding the button to a pin device and registering a button action handler. Then, button detection is enabled, which involves enabling the pin IRQ. -## Main Code Section +## Main Code Section ```c static void button_event_handler(int32_t pin, button_action_t action) { @@ -64,7 +66,6 @@ button_cfg_t cfg; RT_ASSERT(id >= 0); RT_ASSERT(SF_EOK == button_enable(id)); ``` - ## Button Pin Mode Configuration ```c diff --git a/docs/source/en/middleware/data_service.md b/docs/source/en/middleware/data_service.md index b7113f9b0..9c1e4433b 100644 --- a/docs/source/en/middleware/data_service.md +++ b/docs/source/en/middleware/data_service.md @@ -1,32 +1,60 @@ - # Data Service -Applications need to use data from various sensors or data transmitted via BLE, and this data may come from different hardware interfaces or cores. For example, sensors connected to the LCPU may provide data, and the graphical interface running on the HCPU may need to display the data collected by the sensor. To simplify dual-core designs and to make the application unaware of the data sources, regardless of which core generates the data or from which device, data consumers can obtain and process the data in the same way. The SDK provides a data service framework that allows applications to use the data without knowing the details of data generation. +Applications need to use data from various sensors or data transmitted via BLE, +and this data may come from different hardware interfaces or cores. For example, +sensors connected to the LCPU may provide data, and the graphical interface +running on the HCPU may need to display the data collected by the sensor. To +simplify dual-core designs and to make the application unaware of the data +sources, regardless of which core generates the data or from which device, data +consumers can obtain and process the data in the same way. The SDK provides a +data service framework that allows applications to use the data without knowing +the details of data generation. The main features include: -- Applications can subscribe to data services, where the application is called the subscriber or client, acting as the consumer of the data. -- Sensor or BLE data services act as the provider, implementing a specific data service and obtaining data from I2C, SPI, or different remote BLE devices. They are the producers of the data. -- The framework supports data service providers and subscribers running on different CPU cores. A data service can be implemented on one core and moved to another core without affecting the subscriber application. -- Provides data service simulation features to allow independent development of applications and data services. -- Thread-safe API interfaces, allowing the service to be used in multi-threaded environments. - -The SIFLI SDK includes test tools for testing data service providers or subscribers. Users can simulate sensor services, such as heart rate sensors, compass, motion sensors, etc. These functions are integrated with the SDK example – the watch emulator, which helps users develop watch applications that require sensor support. For a detailed introduction to the data service API, please refer to [data_service](middleware-data_service). - -Data is transferred between cores/threads via messages, which are divided into request (XXX_REQ) and response (XXX_RSP) types. A request message is sent from the client to the service, while a response message is sent from the service to the client. The message ID is 16 bits long, with the lower 15 bits representing the message number, and the highest bit (bit 15) indicating the message type: 0 for request messages and 1 for response messages. Request and response messages typically appear in pairs, with the lower 15 bits of their IDs being the same, and only the highest bit differing. For example, the following defines two messages, `SUBSCRIBE_REQ` and `SUBSCRIBE_RSP`: - +- Applications can subscribe to data services, where the application is called + the subscriber or client, acting as the consumer of the data. +- Sensor or BLE data services act as the provider, implementing a specific data + service and obtaining data from I2C, SPI, or different remote BLE devices. + They are the producers of the data. +- The framework supports data service providers and subscribers running on + different CPU cores. A data service can be implemented on one core and moved + to another core without affecting the subscriber application. +- Provides data service simulation features to allow independent development of + applications and data services. +- Thread-safe API interfaces, allowing the service to be used in multi-threaded + environments. + +The SIFLI SDK includes test tools for testing data service providers or +subscribers. Users can simulate sensor services, such as heart rate sensors, +compass, motion sensors, etc. These functions are integrated with the SDK +example – the watch emulator, which helps users develop watch applications that +require sensor support. For a detailed introduction to the data service API, +please refer to [data_service](middleware-data_service). + +Data is transferred between cores/threads via messages, which are divided into +request (XXX_REQ) and response (XXX_RSP) types. A request message is sent from +the client to the service, while a response message is sent from the service to +the client. The message ID is 16 bits long, with the lower 15 bits representing +the message number, and the highest bit (bit 15) indicating the message type: 0 +for request messages and 1 for response messages. Request and response messages +typically appear in pairs, with the lower 15 bits of their IDs being the same, +and only the highest bit differing. For example, the following defines two +messages, `SUBSCRIBE_REQ` and `SUBSCRIBE_RSP`: ```c MSG_SERVICE_SUBSCRIBE_REQ = 0x0, MSG_SERVICE_SUBSCRIBE_RSP = RSP_MSG_TYPE | MSG_SERVICE_SUBSCRIBE_REQ, ``` - -Sometimes, a service may actively send messages to the client without a corresponding request message. In such cases, independent response messages are defined, generally ending with `IND`, but they are also marked as response messages. For example: - +Sometimes, a service may actively send messages to the client without a +corresponding request message. In such cases, independent response messages are +defined, generally ending with `IND`, but they are also marked as response +messages. For example: ```c MSG_SERVICE_DATA_NTF_IND = RSP_MSG_TYPE | 0x09, ``` -The framework reserves 48 message IDs (0x0 ~ 0x2F) for internal use. Users can define their own messages starting from `MSG_SERVICE_CUSTOM_ID_BEGIN` to avoid conflicts with the reserved messages. For example: - +The framework reserves 48 message IDs (0x0 ~ 0x2F) for internal use. Users can +define their own messages starting from `MSG_SERVICE_CUSTOM_ID_BEGIN` to avoid +conflicts with the reserved messages. For example: ```c typedef enum { @@ -36,25 +64,34 @@ typedef enum } ble_dfu_service_message_t; ``` -## Data Service Configuration - -Run `menuconfig`, and under `SiFli Middleware`, select `Enable Data Service`. If cross-core services are required, you must also select the `Enable IPC Queue Library` in the Middleware. Once configured, the following two macros will appear in the project's `rtconfig.h`: -- `BSP_USING_DATA_SVC`: A macro for enabling the data service. -- `USING_IPC_QUEUE`: A macro for enabling IPC Queue to support cross-core operations. +## Data Service Configuration +Run `menuconfig`, and under `SiFli Middleware`, select `Enable Data Service`. If +cross-core services are required, you must also select the `Enable IPC Queue +Library` in the Middleware. Once configured, the following two macros will +appear in the project's `rtconfig.h`: ```c #define BSP_USING_DATA_SVC 1 #define USING_IPC_QUEUE 1 ``` ## System Resources Used - -If IPC Queue is enabled, the data service framework uses IPC Queue 1 as the communication channel between the two cores. The buffer address for sending from HCPU to LCPU is `HCPU2LCPU_MB_CH2_BUF_START_ADDR`, with a size of `HCPU2LCPU_MB_CH2_BUF_SIZE`. The buffer address for sending from LCPU to HCPU is `LCPU2HCPU_MB_CH2_BUF_START_ADDR`, with a size of `LCPU2HCPU_MB_CH2_BUF_SIZE`. The default size for these buffers is 512 bytes. If you need to change the buffer size, refer to (_/app_note/memory_usage.md_). +If IPC Queue is enabled, the data service framework uses IPC Queue 1 as the +communication channel between the two cores. The buffer address for sending from +HCPU to LCPU is `HCPU2LCPU_MB_CH2_BUF_START_ADDR`, with a size of +`HCPU2LCPU_MB_CH2_BUF_SIZE`. The buffer address for sending from LCPU to HCPU is +`LCPU2HCPU_MB_CH2_BUF_START_ADDR`, with a size of `LCPU2HCPU_MB_CH2_BUF_SIZE`. +The default size for these buffers is 512 bytes. If you need to change the +buffer size, refer to (_/app_note/memory_usage.md_). ## Registering Data Services - -The data service component is an open framework, and the implemented data services must be registered with the framework before they can be used by subscribers. The following example uses the function `#datas_register` to register a service named `test`. Note that service registration must be done during the `INIT_COMPONENT` stage to ensure all services are ready when the data service framework is started during the `INIT_ENV` phase. +The data service component is an open framework, and the implemented data +services must be registered with the framework before they can be used by +subscribers. The following example uses the function `#datas_register` to +register a service named `test`. Note that service registration must be done +during the `INIT_COMPONENT` stage to ensure all services are ready when the data +service framework is started during the `INIT_ENV` phase. ```c #include "data_service_provider.h" @@ -119,8 +156,10 @@ INIT_COMPONENT_EXPORT(test_service_register); ``` ## Using Data Services - -Applications use the service name to subscribe to services. The following example shows how to subscribe to a service named `test` and send a request message. Note that you can only send a message to the service after successfully subscribing. Otherwise, it will return a failure. +Applications use the service name to subscribe to services. The following +example shows how to subscribe to a service named `test` and send a request +message. Note that you can only send a message to the service after successfully +subscribing. Otherwise, it will return a failure. ```c #include "data_service_subscriber.h" @@ -183,30 +222,44 @@ int unsubscribe(void) ## Call Sequence -Users should follow the following call sequence to use data services. In the SDK, the data service framework is started during the `INIT_ENV` phase, so it requires the data service to be registered in the `INIT_COMPONENT` phase. Subscribers can only subscribe to services in the `INIT_APP` phase or later. +Users should follow the following call sequence to use data services. In the +SDK, the data service framework is started during the `INIT_ENV` phase, so it +requires the data service to be registered in the `INIT_COMPONENT` phase. +Subscribers can only subscribe to services in the `INIT_APP` phase or later. -1. `datas_register`: Called during the `INIT_COMPONENT` phase of RT-Thread to register the data service with the framework. -2. `datas_start`: Automatically executed during the `INIT_ENV` phase (no user code needed), starts the data service framework and accepts requests from subscribers. The HCPU will start the LCPU at this point. +1. `datas_register`: Called during the `INIT_COMPONENT` phase of RT-Thread to + register the data service with the framework. +2. `datas_start`: Automatically executed during the `INIT_ENV` phase (no user + code needed), starts the data service framework and accepts requests from + subscribers. The HCPU will start the LCPU at this point. 3. `datac_open`: Allocates a port for the subscriber. -4. `datac_subscribe`: The subscriber initiates a connection and subscribes to the data service. +4. `datac_subscribe`: The subscriber initiates a connection and subscribes to + the data service. ## Using Data Services in GUI -GUI systems like LVGL run in single-threaded mode and have their own LVGL task. To update data in the GUI thread, the data service defines specific interfaces that can be called from the GUI thread/task. +GUI systems like LVGL run in single-threaded mode and have their own LVGL task. +To update data in the GUI thread, the data service defines specific interfaces +that can be called from the GUI thread/task. ### Working Principle Implementation mechanism of GUI data service: 1. Register a message queue through `datac_subscribe_ex` -2. All messages from the data service first enter this queue instead of calling back directly +2. All messages from the data service first enter this queue instead of calling + back directly 3. Start an LVGL timer (lv_timer) to periodically check this queue -4. Retrieve messages from the queue and trigger callbacks in the LVGL task context +4. Retrieve messages from the queue and trigger callbacks in the LVGL task + context -This design meets the requirement that LVGL can only execute in a single thread, ensuring all GUI update operations are completed in the LVGL task, avoiding thread safety issues. +This design meets the requirement that LVGL can only execute in a single thread, +ensuring all GUI update operations are completed in the LVGL task, avoiding +thread safety issues. ### Usage Example -The following demonstrates the core steps for using data services in a GUI application: +The following demonstrates the core steps for using data services in a GUI +application: ```c #include "ui_datasrv_subscriber.h" @@ -232,7 +285,7 @@ static int sensor_data_callback(data_callback_arg_t *arg) { /* Received data notification, safely update LVGL widgets */ sensor_data_t *data = (sensor_data_t *)arg->data; - + // Update UI directly, no additional synchronization needed lv_label_set_text_fmt(label, "Value: %d", data->value); break; @@ -246,11 +299,11 @@ void app_start(void) { /* 1. Initialize GUI data service module (only once for the entire app) */ ui_datac_init(); - + /* 2. Allocate client handle */ sensor_handle = datac_open(); RT_ASSERT(DATA_CLIENT_INVALID_HANDLE != sensor_handle); - + /* 3. Subscribe to service - callback will execute in LVGL task */ ui_datac_subscribe(sensor_handle, "SENSOR", sensor_data_callback, 0); @@ -268,26 +321,35 @@ void app_stop(void) } ``` -**For a complete GUI application example**, please refer to the compass application in the [Graphical Application Framework](gui_app_framework.md#application-example) section, which demonstrates the full application lifecycle and data service integration. +**For a complete GUI application example**, please refer to the compass +application in the [Graphical Application Framework](gui_app_framework.md#应用示例) +section, which demonstrates the full application lifecycle and data service +integration. ### Key Interface Description -- **`ui_datac_init()`**: Initialize the GUI data service module, create message queue and start LVGL timer (15ms period). Should be called once during GUI initialization. +- **`ui_datac_init()`**: Initialize the GUI data service module, create message + queue and start LVGL timer (15ms period). Should be called once during GUI + initialization. -- **`ui_datac_subscribe(handle, name, callback, user_data)`**: Subscribe to data service in GUI thread context. Unlike regular `datac_subscribe`, it ensures callbacks execute in the LVGL task through a message queue. +- **`ui_datac_subscribe(handle, name, callback, user_data)`**: Subscribe to data + service in GUI thread context. Unlike regular `datac_subscribe`, it ensures + callbacks execute in the LVGL task through a message queue. -- **Callback Execution Environment**: All callback functions registered through `ui_datac_subscribe` execute in the LVGL task, allowing safe calls to any LVGL API for interface updates. +- **Callback Execution Environment**: All callback functions registered through + `ui_datac_subscribe` execute in the LVGL task, allowing safe calls to any LVGL + API for interface updates. ### Differences from Regular Subscription -| Feature | datac_subscribe | ui_datac_subscribe | -|---------|-----------------|-------------------| -| Callback Execution Thread | Data service task | LVGL task | -| Thread Safety | User handles synchronization | Framework automatically ensures | -| Application Scenario | Non-GUI applications | GUI applications | -| Can Update UI | No, requires additional sync | Yes, direct updates | +| Feature | datac_subscribe | ui_datac_subscribe | +| ------------------------- | ---------------------------- | ------------------------------- | +| Callback Execution Thread | Data service task | LVGL task | +| Thread Safety | User handles synchronization | Framework automatically ensures | +| Application Scenario | Non-GUI applications | GUI applications | +| Can Update UI | No, requires additional sync | Yes, direct updates | ## API Reference diff --git a/docs/source/en/middleware/dfu_service/dfu_pan_firmware_generation.md b/docs/source/en/middleware/dfu_service/dfu_pan_firmware_generation.md index 93e696115..da1977fa9 100644 --- a/docs/source/en/middleware/dfu_service/dfu_pan_firmware_generation.md +++ b/docs/source/en/middleware/dfu_service/dfu_pan_firmware_generation.md @@ -2,22 +2,27 @@ ## 1. Overview -DFU_PAN is an OTA firmware upgrade middleware based on Bluetooth PAN network, which allows devices to connect to OTA servers via Bluetooth network, download and update firmware. The entire process includes device registration, version checking, firmware downloading and updating steps. +DFU_PAN is an OTA firmware upgrade middleware based on Bluetooth PAN network, +which allows devices to connect to OTA servers via Bluetooth network, download +and update firmware. The entire process includes device registration, version +checking, firmware downloading and updating steps. -To use the DFU_PAN feature, add the examplele/dfu_pan sub-project and combine with middleware/dfu_pan middleware +To use the DFU_PAN feature, add the examplele/dfu_pan sub-project and combine +with middleware/dfu_pan middleware -1. Add to main program project/proj.conf file to enable DFU_PAN function +Location is usually below DoBuilding(TARGET, objs) ``` CONFIG_USING_DFU_PAN=y ``` -2. Need to add sub-project syntax under main project's project/SConstruct file: +Refer to example/bt/pan_ota example for using DFU_PAN ``` AddDFU_PAN(SIFLI_SDK) ``` -Location is usually below DoBuilding(TARGET, objs) +The typical placement is below DoBuilding(TARGET, objs). -Refer to example/bt/pan_ota example for using DFU_PAN +For more details, refer to the DFU_PAN implementation in the example/bt/pan_ota +project. ## 2. Workflow Overview ``` @@ -30,9 +35,11 @@ Refer to example/bt/pan_ota example for using DFU_PAN ### 3.1 Device Registration Process -When connecting for the first time, the device needs to register with the OTA server so the server can identify the device and record device information. +When connecting for the first time, the device needs to register with the OTA +server so the server can identify the device and record device information. -**Implementation**: dfu_pan provides a registration interface, applications need to prepare device information, optional parameters can be omitted +**Implementation**: dfu_pan provides a registration interface, applications need +to prepare device information, optional parameters can be omitted ```c // Device registration request parameters structure @@ -57,7 +64,7 @@ typedef struct { - Current version number - OTA version number - Chip ID (unique ID generated using SHA256) -- ota_server_url:https://xxx.xxx.com +- ota_server_url: https://xxx.xxx.com 2. Call `dfu_pan_register_device(ota_server_url, ®_params)` - dfu_pan_register_device internal POST request API:https://xxx.xxx.com/register @@ -89,14 +96,16 @@ json: "flash_type": "Optional", "chip_id": "Required" } - ``` -**Note**: The `solution`, `model` fields should preferably match the folder names, such as folder structure `"https://xxx.xxx.com/v2/xiaozhi/SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp?chip_id=%s&version=latest"` +**Note**: The `solution`, `model` fields should preferably match the folder +names, such as folder structure +`"https://xxx.xxx.com/v2/xiaozhi/SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp?chip_id=%s&version=latest"` ### 3.2 Version Check Process -After successful registration, the device can query the server for new firmware versions.  +After successful registration, the device can query the server for new firmware +versions. @@ -113,14 +122,17 @@ char* dynamic_ota_url = build_ota_query_url(chip_id); int result = dfu_pan_query_latest_version(dynamic_ota_url, VERSION, latest_version, sizeof(latest_version)); ``` -Where `build_ota_query_url` needs to be implemented by the application side for building the URL, -Example: +Where `build_ota_query_url` needs to be implemented by the application side for +building the URL, Example: ```c dynamic_ota_url :"https://xxx.xxx.com/v2/xiaozhi/SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp?chip_id=%s&version=latest" //where SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp is based on server file deployment hierarchy ``` -**Note**: dfu_pan_query_latest_version() retrieves JSON data returned from the server and writes the firmware structure to flash address for direct download later, JSON as follows, where v1.3.9.bin is a placeholder file that needs to be placed with firmware files and match the current folder name +**Note**: dfu_pan_query_latest_version() retrieves JSON data returned from the +server and writes the firmware structure to flash address for direct download +later, JSON as follows, where v1.3.9.bin is a placeholder file that needs to be +placed with firmware files and match the current folder name ```json { "result": 200, @@ -196,10 +208,12 @@ struct firmware_file_info { ``` ### 3.3 Setting Update Flag -When a new version is detected, the update flag needs to be set so that the device enters OTA mode on next boot. +When a new version is detected, the update flag needs to be set so that the +device enters OTA mode on next boot. **Process**: -1. User clicks "Update" button on UI, or at specific trigger update operation location +1. User clicks "Update" button on UI, or at specific trigger update operation + location 2. Call `dfu_pan_set_update_flags()` to set update flag 3. System reboots @@ -241,13 +255,13 @@ for (int i = 0; i < MAX_FIRMWARE_FILES; i++) { // Check magic number uint32_t magic_value = 0; g_flash_read(magic_addr, (const int8_t*)&magic_value, sizeof(uint32_t)); - + if (magic_value == FIRMWARE_MAGIC_DFU_PAN) { // Check update flag uint32_t needs_update_value = 0; g_flash_read(needs_update_addr, (const int8_t*)&needs_update_value, sizeof(uint32_t)); - + if (needs_update_value) { needs_update = 1; break; @@ -263,7 +277,8 @@ if (needs_update && is_ota_program_valid(DFU_PAN_LOADER_START_ADDR)) { ### 3.5 DFU_PAN Program Executes Firmware Download -After entering OTA mode, the DFU_PAN program automatically connects to the network and downloads firmware. +After entering OTA mode, the DFU_PAN program automatically connects to the +network and downloads firmware. **Process**: 1. Initialize Bluetooth and connect to PAN network @@ -308,19 +323,19 @@ if (ret == 0) { for (int i = 0; i < file_count; i++) { // Erase Flash rt_flash_erase(firmware_file_info[i].addr, aligned_size); - + // Create HTTP session session = webclient_session_create(PAN_OTA_HEADER_BUFSZ); - + // Send GET request int resp_status = webclient_get(session, firmware_file_info[i].url); - + // Download in chunks and write to Flash while (remaining_length > 0) { int bytes_read = webclient_read(session, buffer, chunk_size); rt_flash_write(addr, (uint8_t *)buffer, bytes_read); } - + // CRC verification uint32_t calculated_crc = calculate_crc32(verify_buffer, verify_chunk, calculated_crc); @@ -334,7 +349,9 @@ for (int i = 0; i < file_count; i++) { ## 4. CRC32 Check Algorithm Description -The DFU_PAN OTA upgrade process uses the CRC32 check algorithm to ensure firmware data integrity. The implementation is consistent with standard CRC32 (IEEE 802.3), with the specific logic as follows: +The DFU_PAN OTA upgrade process uses the CRC32 check algorithm to ensure +firmware data integrity. The implementation is consistent with standard CRC32 +(IEEE 802.3), with the specific logic as follows: ### 4.1 CRC32 Algorithm Parameters @@ -354,15 +371,15 @@ static uint32_t crc32_table[256]; static void init_crc32_table(void) { - for (int i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { uint32_t crc = i; - for (int j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) { - if (crc & 1) - crc = (crc >> 1) ^ CRC32_POLY; + if (crc & 1) + crc = (crc >> 1) ^ CRC32_POLY; else - crc >>= 1; + crc >>= 1; } crc32_table[i] = crc; } @@ -394,16 +411,19 @@ static uint32_t calculate_crc32(const uint8_t *data, size_t length, uint32_t crc ### 4.3 Algorithm Workflow -1. **Table Initialization**: Initialize 256-item CRC32 lookup table on first call +1. **Table Initialization**: Initialize 256-item CRC32 lookup table on first + call 2. **Initial Value Processing**: XOR initial CRC value with 0xFFFFFFFF 3. **Data Processing**: For each byte of input data: - Calculate index: `(current CRC value ^ byte value) & 0xFF` - Update CRC: `(current CRC value >> 8) ^ crc32_table[index]` -4. **Final Value Processing**: XOR result with 0xFFFFFFFF to get final CRC32 value +4. **Final Value Processing**: XOR result with 0xFFFFFFFF to get final CRC32 + value ### 4.4 Application in Firmware Verification -After firmware download completes, the system performs CRC32 verification to check firmware integrity: +After firmware download completes, the system performs CRC32 verification to +check firmware integrity: ```c // Read downloaded firmware data from Flash @@ -444,64 +464,83 @@ if (calculated_crc != firmware_file_info[i].crc32) ### 4.5 Notes -1. **Consistency Requirements**: Server-side generated CRC32 values must use the same algorithm and parameters -2. **Data Integrity**: Entire firmware file must be completely downloaded before performing CRC check -3. **Error Handling**: CRC verification failures should terminate update process and report error -4. **Performance Optimization**: Use lookup table method to improve calculation efficiency, avoiding bit operations on each calculation +1. **Consistency Requirements**: Server-side generated CRC32 values must use the + same algorithm and parameters +2. **Data Integrity**: Entire firmware file must be completely downloaded before + performing CRC check +3. **Error Handling**: CRC verification failures should terminate update process + and report error +4. **Performance Optimization**: Use lookup table method to improve calculation + efficiency, avoiding bit operations on each calculation -Through the above CRC32 verification mechanism, DFU_PAN can effectively ensure the integrity and correctness of firmware data during OTA upgrade processes, preventing firmware damage caused by transmission errors. +Through the above CRC32 verification mechanism, DFU_PAN can effectively ensure +the integrity and correctness of firmware data during OTA upgrade processes, +preventing firmware damage caused by transmission errors. ## 5. Firmware Package Deployment -Firmware package deployment refers to uploading firmware packages to the server for devices to download and install. +Firmware package deployment refers to uploading firmware packages to the server +for devices to download and install. Example 1: Deploying OTA upgrade packages for Xiaozhi as an example: -1. Create a directory and upload firmware packages to that directory: -**Note**: The server address below is for internal use only -https://ota.sifli.com/browser/ is the file deployment homepage, to create a directory just fill the address bar with the directory structure to be created, the last level directory name needs to be the version number such as v1.1 - +1. Create a directory and upload firmware packages to that directory: **Note**: + The server address below is for internal use only + https://ota.sifli.com/browser/ is the file deployment homepage, to create a + directory just fill the address bar with the directory structure to be + created, the last level directory name needs to be the version number such as + v1.1 ![](../../../assets/dfu_pan2.png) -2. Upload bin file firmware packages, make sure to upload a bin file with the same name as the version directory, such as v1.1.bin in the figure, this bin file serves as a placeholder reflecting the current version, generally projects have version number iterations, so the deployed placeholder bin file needs to be higher than the current project version, upload a maximum of 3 actual functional firmwares, firmware names can start with letters +![]{1} ![](../../../assets/dfu_pan4.png) -3. Fill in firmware information, after uploading files click extra information on the right side of each file to fill in, click save after completion, you can query firmware starting address and firmware size information according to the ptab.json used by your own program +![]{1} -Fill in firmware starting address -![](../../../assets/dfu_pan5.png) -Fill in firmware region allocation size -![](../../../assets/dfu_pan3.png) +You can also check whether data can be successfully responded to according to +the response address: +https://ota.sifli.com/v2/xiaozhi/SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp?chip_id=123&version=latest -4. After clicking save, click extra information again to check if the crc32 value was generated +**Note** The chip_id in the address should be filled with the device ID, this is +only for verifying whether the response is successful, you can fill in any +string of numbers, version is filled with latest to get the latest firmware +information ![](../../../assets/dfu_pan5.png) -You can also check whether data can be successfully responded to according to the response address: https://ota.sifli.com/v2/xiaozhi/SF32LB52_ULP_NOR_TFT_CO5300/sf32lb52-lchspi-ulp?chip_id=123&version=latest +Fill in firmware starting address ![]{1} -**Note** -The chip_id in the address should be filled with the device ID, this is only for verifying whether the response is successful, you can fill in any string of numbers, version is filled with latest to get the latest firmware information +Fill in firmware region allocation size ![]{1} -Example 2: example/pan_ota example -1. Create a directory (directory corresponds to specific code access address), fill the address bar with directory structure `https://ota.sifli.com/browser/example/pan_ota/SF32LB52_LCD_N16R8_TFT_CO5300/sf32lb52-lcd-n16r8/v1.1` and upload firmware packages to that directory: -![](../../../assets/pan_ota1.png) +You can also check whether data can be successfully responded to according to +the response address: +https://ota.sifli.com/v2/example/pan_ota/SF32LB52_LCD_N16R8_TFT_CO5300/sf32lb52-lcd-n16r8?chip_id=123&version=latest +1. Upload bin file firmware packages, make sure to upload a bin file with the + same name as the version directory, such as v1.1.bin in the figure, this bin + file serves as a placeholder reflecting the current version, generally + projects have version number iterations, so the deployed placeholder bin file + needs to be higher than the current project version, upload a maximum of 3 + actual functional firmwares, firmware names can start with letters -2. Fill in firmware information, after uploading files click extra information on the right side of each file to fill in, click save after completion, you can query firmware starting address and firmware size information according to the ptab.json used by your own program +2. Fill in firmware information, after uploading files click extra information + on the right side of each file to fill in, click save after completion, you + can query firmware starting address and firmware size information according + to the ptab.json used by your own program -Fill in firmware starting address ![](../../../assets/pan_ota2.png) -Fill in firmware region allocation size -![](../../../assets/pan_ota3.png) +Enter the firmware partition size ![](../../../assets/pan_ota3.png) + +3. After clicking save, click extra information again to check if the crc32 + value was generated -3. After clicking save, click extra information again to check if the crc32 value was generated -![](../../../assets/pan_ota4.png) +Alternatively, verify accessibility via the response URL: +https://ota.sifli.com/v2/example/pan_ota/SF32LB52_LCD_N16R8_TFT_CO5300/sf32lb52-lcd-n16r8?chip_id=123&version=latest -You can also check whether data can be successfully responded to according to the response address: https://ota.sifli.com/v2/example/pan_ota/SF32LB52_LCD_N16R8_TFT_CO5300/sf32lb52-lcd-n16r8?chip_id=123&version=latest +![](../../../assets/pan_ota5.png) -![](../../../assets/pan_ota5.png) \ No newline at end of file diff --git a/docs/source/en/middleware/dfu_service/firmware_flow.md b/docs/source/en/middleware/dfu_service/firmware_flow.md index e37494090..434829bea 100644 --- a/docs/source/en/middleware/dfu_service/firmware_flow.md +++ b/docs/source/en/middleware/dfu_service/firmware_flow.md @@ -2,48 +2,42 @@ ## Flash Layout -As shown in the figure below, by default, Bootrom will jump to 0x10020000 according to the flash config table (for details, refer to [](/bootloader.md)). The firmware upgrade service requires creating a separate OTA manager project, and the user project (User Code) needs to be placed after the OTA manager. +As shown in the figure below, by default, Bootrom will jump to 0x10020000 +according to the flash config table (for details, refer to []{1}). The firmware +upgrade service requires creating a separate OTA manager project, and the user +project (User Code) needs to be placed after the OTA manager. -After Bootrom jumps to OTA manager, it will act according to the current state: if no upgrade is needed, it jumps to the user project; if an upgrade is needed, it waits for the upgrade. +After Bootrom jumps to OTA manager, it will act according to the current state: +if no upgrade is needed, it jumps to the user project; if an upgrade is needed, +it waits for the upgrade. -The starting address of the user project and the Upgrade bin address where firmware upgrade packages are stored can be configured through the project's _memory_map.h_ and _custom_memory_map.h_. It is recommended to place the Upgrade bin at the end of Flash. - ![](../../../assets/ota_flash_layout.png) +The starting address of the user project and the Upgrade bin address where +firmware upgrade packages are stored can be configured through the project's +_memory_map.h_ and _custom_memory_map.h_. It is recommended to place the Upgrade +bin at the end of Flash. ## Process Overview -The diagram below illustrates the basic OTA process. A complete OTA upgrade file contains _ctrl_packet.bin_ with verification information, followed by firmware packages, resource packages, and font packages. +1. Step 1. The remote device sends _ctrl_packet.bin_ to user bin to confirm + whether OTA can proceed. If yes, continue to step 2 +2. Step 2. User bin needs to restart and enter ota manager bin, then + re-establish Bluetooth connection with the remote device. If no connection is + made within a certain time, it will return to user bin. +3. Step 3. After establishing Bluetooth connection, the remote device will + continuously transmit upgrade packages until all upgrade packages are + transmitted. +4. Step 4. Decompress the firmware upgrade package and complete installation. -![](../../../assets/ota_flow.png) - - -- Step 1. The remote device sends _ctrl_packet.bin_ to user bin to confirm whether OTA can proceed. If yes, continue to step 2 -- Step 2. User bin needs to restart and enter ota manager bin, then re-establish Bluetooth connection with the remote device. If no connection is made within a certain time, it will return to user bin. -- Step 3. After establishing Bluetooth connection, the remote device will continuously transmit upgrade packages until all upgrade packages are transmitted. - - If firmware upgrade package download fails, it will return to user bin. - - If resource and font downloads fail, it will forcibly remain in ota manager bin until the download succeeds. - - After download failure, OTA supports both resume and forced restart from beginning methods, determined by the remote device. -- Step 4. Decompress the firmware upgrade package and complete installation. -- Step 5. After installation is complete, jump to user bin to complete OTA. +The starting address of the user project and the Upgrade bin address where +firmware upgrade packages are stored can be configured through the project's +_memory_map.h_ and _custom_memory_map.h_. It is recommended to place the Upgrade +bin at the end of Flash. ## Important Notes -- OTA upgrade packages use encryption. Ensure using a flash config table with encryption information; if decryption exists in efuse, ensure efuse has correctly programmed relevant content. If verification fails, the remote device will receive error code 09 (DFU_ERR_CONTROL_PACKET_INVALID). -- If the OTA process fails due to BLE disconnection or other reasons, the remote device will receive error code 10 (DFU_ERR_OTA_ONGOING). The remote device can decide whether to resume or restart the upgrade from the beginning. - - -## Project Configuration - -User project configuration: -- Both cores need configuration: - ![](../../../assets/ota_hcpu_config1.png) - ![](../../../assets/ota_hcpu_config2.png) -- LCPU configuration: - If BLE service is on LCPU, LCPU port service needs to be configured so that OTA manager can obtain BLE data - ![](../../../assets/ota_lcpu_config1.png) -OTA Manager project configuration: -- In addition to the content that both cores need to configure in the user project, zlib also needs to be added - ![](../../../assets/ota_lcpu_config2.png) \ No newline at end of file +Refer to the `example/ble/peripheral_with_ota` project and its corresponding +README: {doc}`../../example/ble/peripheral_with_ota/README` diff --git a/docs/source/en/middleware/dfu_service/index.md b/docs/source/en/middleware/dfu_service/index.md index d7ffd92b8..6a3a34d7c 100644 --- a/docs/source/en/middleware/dfu_service/index.md +++ b/docs/source/en/middleware/dfu_service/index.md @@ -1,8 +1,11 @@ # Firmware Upgrade Service -Device Firmware Update (DFU) is the process of downloading target firmware to a device and replacing the currently running firmware, thereby completing the device's firmware version upgrade. Typically, devices can download upgrade firmware via serial port or Over-the-Air (OTA) methods. SiFli firmware upgrade service supports downloading upgrade firmware via BLE. +Device Firmware Update (DFU) is the process of downloading target firmware to a +device and replacing the currently running firmware, thereby completing the +device's firmware version upgrade. Typically, devices can download upgrade +firmware via serial port or Over-the-Air (OTA) methods. SiFli firmware upgrade +service supports downloading upgrade firmware via BLE. -SIFLI firmware upgrade service supports downloading three types of content by default: firmware, resources, and fonts. Among these, firmware is first downloaded as a compressed upgrade package to a reserved area, then installed and overwritten after download completion; resources and fonts are directly overwritten after download. ## DFU firmware upgrade service ```{toctree} @@ -18,4 +21,3 @@ firmware_generation.md dfu_pan_firmware_generation.md ``` -``` \ No newline at end of file diff --git a/docs/source/en/middleware/file_system.md b/docs/source/en/middleware/file_system.md index 69f3e621e..2a8df6248 100644 --- a/docs/source/en/middleware/file_system.md +++ b/docs/source/en/middleware/file_system.md @@ -1,18 +1,27 @@ +# File Systems -# File System +RT-Thread allows users to port and utilize various file systems. By default, +ELM-FAT and DevFs are enabled. DevFs is typically mounted to `/dev`, where all +registered devices are visible. As a FAT file system implementation, ELM-FAT +supports standard operations such as opening, closing, reading, writing files, +and creating directories (`mkdir`). To port ELM-FAT, users must implement disk +operations including `disk_read`, `disk_write`, and `disk_ioctrl`. -Users can port and use a file system on RT-Thread. By default, we enable ELM-FAT and DevFs. For DevFs, it is mounted by default at /dev, and all registered devices will be visible at this path. +ELM-FAT can utilize Nor Flash, Nand Flash, or SD cards as storage media. These +media must interface with disk operations via the `rt-device` interface; Nand +and Nor Flash are registered as MTD devices, while SD cards are registered as +block devices. Detailed information regarding the file system can be found in +the RT-Thread documentation. -ELM-FAT, as a FAT file system, supports common file operations such as open/close/read/write, mkdir, etc. To port ELM-FAT, users need to implement disk operations such as disk_read, disk_write, disk_ioctrl, and others. - -ELM-FAT can use Nor-Flash, Nand-Flash, and SDCARD as memory disks. These memory devices need to meet the rt-device interface. Nand and Nor Flash are registered to the MTD devices, while SDCARD is registered to block devices. Detailed information about the file system can be found in the RT-Thread documentation. ## File System Configuration -Users can enable the file system using the `menuconfig` tool. The configuration is usually saved in a C header file. By default, configurations are saved in `rtconfig.h`. - -The following example shows the flags defined in a project's header file, where the project uses the ELM-FAT file system and mounts it on NOR-FLASH1. It includes three parts: RT-Thread file system configuration: +Users can enable the file system using the `menuconfig` tool. Configurations are +typically stored in a C header file, which by default is saved as `rtconfig.h`. +The following example demonstrates macro definitions in a project header file +for an ELM-FAT file system mounted on `NOR-FLASH1`. The configuration consists +of three parts. For the RT-Thread file system configuration: ```c #define RT_DFS_ELM_CODE_PAGE 437 #define RT_DFS_ELM_WORD_ACCESS @@ -25,16 +34,14 @@ The following example shows the flags defined in a project's header file, where #define RT_USING_DFS_DEVFS ``` -MTD device configuration: - +For MTD device configuration: ```c #define RT_USING_MTD_NOR #define RT_USING_NOR_FS #define RT_NOR_FS_BASE_SEC 512 ``` -FLASH configuration: - +For FLASH configuration: ```c #define BSP_USING_FLASH #define BSP_USING_NOR_FLASH @@ -44,51 +51,54 @@ FLASH configuration: #define BSP_FLASH1_MTD_EN ``` -After completing the configuration, users need to include the header files in all source files that need to access the file system. +After configuration, the header file must be included in all source files that +require file system access. ## Creating and Mounting the File System -After configuration, the file system needs to be created (mkfs) and mounted. - +Once configured, the file system must be initialized, formatted (`mkfs`), and +mounted. ```c -// If ELM is enabled, initialize and mount it as soon as possible +// If ELM is enabled, initialize and mount it as early as possible elm_init(); -// Check if the file system exists +// Check if the file system was previously created int res = dfs_mount("flash1", "/", "elm", 0, 0); if(res != 0) // File system does not exist { // Create the file system - res = dfs_mkfs("elm", "flash1"); + res = dfs_mkfs("elm","flash1"); - // Mount the file system if creation is successful - if(res == 0) - dfs_mount("flash1", "/", "elm", 0, 0); + // Mount the file system if creation was successful + if(res == 0) + dfs_mount("flash1", "/", "elm", 0, 0); } + ...... ``` ## File Access Functions -File open/close/read/write operations. - +Standard file operations: open, close, read, and write. ```c -// File open -int res = dfs_file_open(&src_fd, src, O_RDONLY); -int res2 = dfs_file_open(&fd, dst, O_WRONLY | O_CREAT); +// Open files +int res = dfs_file_open(&src_fd, src, O_RDONLY); +int res2 = dfs_file_open(&fd, dst, O_WRONLY | O_CREAT); + +// Read from file +int read_bytes = dfs_file_read(&src_fd, block_ptr, BUF_SZ); -// Read file -int read_bytes = dfs_file_read(&src_fd, block_ptr, BUF_SZ); +// Write to file +int length = dfs_file_write(&fd, block_ptr, read_bytes); -// Write file -int length = dfs_file_write(&fd, block_ptr, read_bytes); ...... -// Close file -dfs_file_close(&src_fd); -dfs_file_close(&fd); +// Close files +dfs_file_close(&src_fd); +dfs_file_close(&fd); ``` -## Command Line File Operations +## Command-Line File Operations +Standard file system commands are available via the command line (FinSH), +including `ls`, `copy`, `mkdir`, and `cat`. -Some commands can be used on the command line as a normal file system: ls, copy, mkdir, cat, etc. diff --git a/docs/source/en/middleware/gauss.md b/docs/source/en/middleware/gauss.md index 3d9d2e0ff..37a3cdae8 100644 --- a/docs/source/en/middleware/gauss.md +++ b/docs/source/en/middleware/gauss.md @@ -1,7 +1,10 @@ - # Gaussian Blur +Our Gaussian blur uses a fast algorithm, which performs closer to standard +Gaussian blur when the blur degree is relatively high. Additionally, considering +memory usage and computational load, the current Gaussian blur calculation has a +minimum radius and step of 25 pixels. Further optimization will be carried out +in the future. -Our Gaussian blur uses a fast algorithm, which performs closer to standard Gaussian blur when the blur degree is relatively high. Additionally, considering memory usage and computational load, the current Gaussian blur calculation has a minimum radius and step of 25 pixels. Further optimization will be carried out in the future. ```{note} Gaussian blur utilizes NNACC and EPIC, so make sure to use them alternately. @@ -9,6 +12,7 @@ Gaussian blur utilizes NNACC and EPIC, so make sure to use them alternately. ## Usage Example + ```c static void gauss_done_cbk(void) { diff --git a/docs/source/en/middleware/gui_app_framework.md b/docs/source/en/middleware/gui_app_framework.md index 5a58bd012..08b2a1d4f 100644 --- a/docs/source/en/middleware/gui_app_framework.md +++ b/docs/source/en/middleware/gui_app_framework.md @@ -1,14 +1,26 @@ - # Graphical Application Framework ## Terminology -- **App**: Refers to the GUI part of an application, specifically the View in the MVC model. It is a collection of pages. Both built-in and dynamically installed Apps are supported. -- **Page**: Refers to a display page where users can create controls, register input device handlers, link data services, and display content (Note: This is not the same as `lv_page`). Each page has its own `lv_screen`, state handling callback functions, and transition animations. -- **lv_screen**: A virtual screen in LittleVGL (LVGL). Only one `lv_screen` can be displayed at a time on a physical LCD, and input devices can only interact with the currently displayed `lv_screen`. +App: Refers to the GUI component of an application, corresponding to the View in +the MVC model. It consists of a collection of pages and supports both built-in +and dynamically installed applications.\ +\ +Page: Refers to a single display page where users can create widgets, register +input device handlers, link data services, and display information (note: this +is distinct from `lv_page`). Each page possesses an independent `lv_screen`, +state handling callbacks, and transition animations.\ +\ +lv_screen: A virtual screen in LVGL. Only one `lv_screen` can be displayed on a +physical LCD at a time, and input devices can only interact with the currently +active `lv_screen`. + + ## Features -- Provides scheduling and transition animations for display interfaces between and within Apps. -- Keeps track of the order in which Apps are opened and the order in which Pages are opened within an App. +- Provides scheduling and transition animations for display interfaces between + and within Apps. +- Keeps track of the order in which Apps are opened and the order in which Pages + are opened within an App. - Supports background refreshing of Apps and Pages. ## Restrictions @@ -18,37 +30,45 @@ - Only one App can be active at a time. ## Scheduling Between Pages -For AppA and AppB, each having three pages, labeled A1~A3 and B1~B3 respectively, the diagram below shows the final state of each page in various scheduling scenarios (Note: the transition states are ignored here). +For AppA and AppB, each having three pages, labeled A1~A3 and B1~B3 +respectively, the diagram below shows the final state of each page in various +scheduling scenarios (Note: the transition states are ignored here). ![Figure 1: Scheduling Between Pages](../../assets/app_fsm.png) + ## Page State Machine and State Implementation Guidelines -- **entryfunction()**: The function that starts the page. If no parameters are needed, this step can be merged with `on_start`. - - Allocate memory - - Receive processing parameters +- **entryfunction()**: The function that starts the page. If no parameters are + needed, this step can be merged with `on_start`. + - Allocate memory + - Receive processing parameters -- **on_start()**: - - Create and layout `lv` controls within the current page. - - Subscribe to services. - - Request data from services. +- **on_start()**: + - Create and layout `lv` controls within the current page. + - Subscribe to services. + - Request data from services. -- **on_resume()**: - - Run internal `lv_task` or timers within the App. +- **on_resume()**: + - Run internal `lv_task` or timers within the App. -- **on_pause()**: - - Stop or delete internal `lv_task` in the App. +- **on_pause()**: + - Stop or delete internal `lv_task` in the App. -- **on_stop()**: - - Unsubscribe from services. - - Release memory. - - Created `lv` controls will be automatically deleted, no need for manual deletion. +- **on_stop()**: + - Unsubscribe from services. + - Release memory. + - Created `lv` controls will be automatically deleted, no need for manual + deletion. ![Figure 2: Page Internal State Machine](../../assets/app_page_fsm.png) -### Additional Handling Functions: -- **xxx_service_callback()**: The handler for services subscribed within the page. @see data_service -- **Page’s lv_task()**: Optional `lv_task` handling function within the page. -- **lv_obj_callback()**: Event handling function for LittleVGL objects. +Description of other handler functions in the illustrated example: +- xxx_service_callback(): A handler function for subscribing to services + within a Page. @see data_service + +- Page’s lv_task(): An optional `lv_task` handler function within the Page. + +- lv_obj_callback(): An event handler function for LVGL objects. ## Application Example @@ -162,7 +182,7 @@ static void on_start(void) /* Subscribe to service data */ p_compass->srv_handle = datac_open(); RT_ASSERT(DATA_CLIENT_INVALID_HANDLE != p_compass->srv_handle); - + ui_datac_subscribe(p_compass->srv_handle, "COMP", compass_data_callback, 0); } diff --git a/docs/source/en/middleware/index.md b/docs/source/en/middleware/index.md index e73d33b3f..878dda8fc 100644 --- a/docs/source/en/middleware/index.md +++ b/docs/source/en/middleware/index.md @@ -12,7 +12,7 @@ pm.md share_preference.md button.md gui_app_framework.md -watch_complication.md +watch_complications.md file_system.md logger.md dfu_service/index.md diff --git a/docs/source/en/middleware/ipc_queue.md b/docs/source/en/middleware/ipc_queue.md index 5aa301077..c5ffbc579 100644 --- a/docs/source/en/middleware/ipc_queue.md +++ b/docs/source/en/middleware/ipc_queue.md @@ -1,40 +1,83 @@ - # Inter-Core Communication Queue -The Inter-Core Communication Queue (IPC Queue library) implements bidirectional inter-core communication functionality. It combines the notification mechanism of [mailbox](/hal/mailbox.md) with a software circular buffer, making inter-core communication similar to serial communication between two chips. -The library supports up to 4 queues operating simultaneously. Each queue is bound to a pair of transmit and receive buffers (buffers are optional; if set to NULL, only interrupt notification functionality is provided). The queues are mapped to corresponding hardware channels according to user configuration. The platform-supported hardware channel numbers can be found in the corresponding _ipc_hw_port.h_. - -Taking the communication between HCPU and LCPU as an example, from _ipc_hw_port.h_ we know that channels 0~7 are hardware channels between HCPU and LCPU. By selecting channel 0, calling `ipc_queue_init()` configures the addresses of the transmit and receive buffers and the callback function for receiving. If successful, it returns a valid queue handle. Then, calling `ipc_queue_open()` opens the channel, and data can be transmitted and received normally. - -By calling `ipc_queue_write()`, data can be sent to the opposite end. The data will be written to the configured `tx_buffer`, and the receiver will receive an interrupt notification (the receiver has already opened the corresponding IPC queue). If the opposite end sends data, the receive callback registered in `ipc_queue_init()` will be triggered, and you can call `ipc_queue_read()` to read data from the `rx_buffer`. - -It is important to note that the `rx_buffer` address configured for HCPU should be the same as the `tx_buffer_alias` address configured for LCPU, i.e., pointing to `tx_buffer`. Similarly, the `tx_buffer_alias` configured for HCPU should be the same as the `rx_buffer` address for LCPU. `tx_buffer` must be the RAM address of the subsystem where the sender is located. In other words, HCPU needs to allocate a buffer in its own RAM space as the sending buffer, so data can still be written even if the opposite subsystem has not been woken up. `tx_buffer` is managed by the sender. Since the receiver may not be able to directly access the sender's address space, the `tx_buffer_alias` is used to specify the address space of the `tx_buffer` that is accessible to the receiver. The two addresses point to the same physical buffer. +The Inter-Core Communication Queue (IPC Queue library) implements bidirectional +inter-core communication functionality. It combines the notification mechanism +of [mailbox](/hal/mailbox.md) with a software circular buffer, making inter-core +communication similar to serial communication between two chips. The library +supports up to 4 queues operating simultaneously. Each queue is bound to a pair +of transmit and receive buffers (buffers are optional; if set to NULL, only +interrupt notification functionality is provided). The queues are mapped to +corresponding hardware channels according to user configuration. The +platform-supported hardware channel numbers can be found in the corresponding +_ipc_hw_port.h_. + +Taking the communication between HCPU and LCPU as an example, from +_ipc_hw_port.h_ we know that channels 0~7 are hardware channels between HCPU and +LCPU. By selecting channel 0, calling `ipc_queue_init()` configures the +addresses of the transmit and receive buffers and the callback function for +receiving. If successful, it returns a valid queue handle. Then, calling +`ipc_queue_open()` opens the channel, and data can be transmitted and received +normally. + +By calling `ipc_queue_write()`, data can be sent to the opposite end. The data +will be written to the configured `tx_buffer`, and the receiver will receive an +interrupt notification (the receiver has already opened the corresponding IPC +queue). If the opposite end sends data, the receive callback registered in +`ipc_queue_init()` will be triggered, and you can call `ipc_queue_read()` to +read data from the `rx_buffer`. + + +It is important to note that the `rx_buffer` address configured for HCPU should +be the same as the `tx_buffer_alias` address configured for LCPU, i.e., pointing +to `tx_buffer`. Similarly, the `tx_buffer_alias` configured for HCPU should be +the same as the `rx_buffer` address for LCPU. `tx_buffer` must be the RAM +address of the subsystem where the sender is located. In other words, HCPU needs +to allocate a buffer in its own RAM space as the sending buffer, so data can +still be written even if the opposite subsystem has not been woken up. +`tx_buffer` is managed by the sender. Since the receiver may not be able to +directly access the sender's address space, the `tx_buffer_alias` is used to +specify the address space of the `tx_buffer` that is accessible to the receiver. +The two addresses point to the same physical buffer. The relationship between `tx_buffer` and `rx_buffer` is shown in Figure 1. -![Figure 1: Relationship Between rx_buffer and tx_buffer](../../assets/ipc_queue_mem.png) - -The architecture of the library is shown in Figure 2. The API interfaces are defined in _ipc_queue.h_, with platform-independent implementation in _ipc_queue.c_. _ipc_hw.c_ encapsulates the ButterFli's [mailbox](../hal/mailbox.md) interface and provides interrupt services for _ipc_queue.c_. However, since different ButterFli chip series have different hardware channel configurations, each chip has its own _ipc_hw_port.c_, which defines the variable `ipc_hw_obj` to describe the hardware channel and implements the interrupt handling function. -The _ipc_queue.c_ provides the interface `ipc_queue_data_ind` for the interrupt handler to notify the upper layer of new data arrival. +![Figure 1: Relationship Between rx_buffer and tx_buffer](/hal/mailbox.md) -![Figure 2: IPC Queue Architecture](../../assets/ipc_queue_arch.png) +The architecture of the library is shown in Figure 2. The API interfaces are +defined in _ipc_queue.h_, with platform-independent implementation in +_ipc_queue.c_. _ipc_hw.c_ encapsulates the ButterFli's +[mailbox](../../assets/ipc_queue_arch.png) interface and provides interrupt +services for _ipc_queue.c_. However, since different ButterFli chip series have +different hardware channel configurations, each chip has its own +_ipc_hw_port.c_, which defines the variable `ipc_hw_obj` to describe the +hardware channel and implements the interrupt handling function. The +_ipc_queue.c_ provides the interface `ipc_queue_data_ind` for the interrupt +handler to notify the upper layer of new data arrival. -For the RT-Thread platform, you can use the API provided by [ipc_queue_device](#middleware-ipc_queue_device) to encapsulate IPC Queue into an RT Device. +![Figure 2: IPC Queue Architecture](#middleware-ipc_queue_device) ```{note} - #ipc_queue_read and #ipc_queue_write are not thread-safe. If `ipc_queue_read` or `ipc_queue_write` is called in a multi-threaded environment on the same queue, the caller must ensure mutual exclusion to avoid re-entry. +#ipc_queue_read and #ipc_queue_write are not thread-safe. If `ipc_queue_read` or `ipc_queue_write` is called in a multi-threaded environment on the same queue, the caller must ensure mutual exclusion to avoid re-entry. However, if accessing different queues, no mutual exclusion is needed. For example, thread_1 writes data to `queue_0` using `ipc_queue_write`, while thread_2 writes data to `queue_1` using `ipc_queue_write`. Since different queues are being operated, no mutual exclusion is required. However, if both threads are writing data to `queue_0`, mutual exclusion must be ensured before calling `ipc_queue_write`. ``` + ## Configuration -Enable the IPC Queue library by selecting `SiFli Middleware -> Enable IPC Queue Library` in the configuration menu. +Enable the IPC Queue library by selecting `SiFli Middleware -> Enable IPC Queue +Library` in the configuration menu. -![Figure 3: IPC Queue Library Configuration Menu](../../assets/ipc_queue_menu.png) +![Figure 3: IPC Queue Library Configuration +Menu](../../assets/ipc_queue_menu.png) ## Usage Example -The following test code demonstrates using hardware channel 0 as the bidirectional communication channel between HCPU and LCPU. The HCPU's address `0x20000000` is used as the send buffer, and the LCPU's address `0x20100000` is used as the LCPU's send buffer. `HCPU_ADDR_2_LCPU_ADDR` is used to convert the HCPU address to the LCPU address space, and `LCPU_ADDR_2_HCPU_ADDR` does the reverse. +The following test code demonstrates using hardware channel 0 as the +bidirectional communication channel between HCPU and LCPU. The HCPU's address +`0x20000000` is used as the send buffer, and the LCPU's address `0x20100000` is +used as the LCPU's send buffer. `HCPU_ADDR_2_LCPU_ADDR` is used to convert the +HCPU address to the LCPU address space, and `LCPU_ADDR_2_HCPU_ADDR` does the +reverse. -### HCPU Code Snippet: +## API Reference ```c static int32_t hcpu_rx_ind(ipc_queue_handle_t ipc_queue, size_t size) { @@ -54,15 +97,15 @@ void hcpu_queue_test(void) q_cfg.rx_ind = hcpu_rx_ind; q_cfg.user_data = 0; - q_handle = ipc_queue_init(&q_cfg); + q_handle = ipc_queue_init(&q_cfg); ipc_queue_open(q_handle); - /* Send data to LCPU */ + /* send data to LCPU */ ipc_queue_write(q_handle, buf, sizeof(buf), 10); } ``` -### LCPU Code Snippet: +## LCPU code snippet: ```c uint8_t lcpu_rx_data_size; static int32_t lcpu_rx_ind(ipc_queue_handle_t ipc_queue, size_t size) @@ -84,25 +127,27 @@ void lcpu_queue_test(void) q_cfg.rx_ind = lcpu_rx_ind; q_cfg.user_data = 0; - q_handle = ipc_queue_init(&q_cfg); + q_handle = ipc_queue_init(&q_cfg); ipc_queue_open(q_handle); while (0 == lcopu_rx_data_size) { - /* Wait for data */ + /* wait for incoming data */ } buffer = malloc(lcpu_rx_data_size); - /* Read data */ + /* read data */ ipc_queue_read(q_handle, buffer, lcpu_rx_data_size); - /* Handle data */ + /* handle data */ ... free(buffer) } ``` + + ## API Reference -[Middleware IPC Queue](middleware-ipc_queue) -[Middleware IPC Queue Device](middleware-ipc_queue_device) +[](middleware-ipc_queue)\ +[](middleware-ipc_queue_device) diff --git a/docs/source/en/middleware/logger.md b/docs/source/en/middleware/logger.md index d45c82e44..194a7888c 100644 --- a/docs/source/en/middleware/logger.md +++ b/docs/source/en/middleware/logger.md @@ -1,20 +1,18 @@ - # Logger -SIFLI SDK uses RT-Thread's `ulog` as the logging (log) output mechanism. As a concise and easy-to-use logging output component, `ulog` supports: -- Logs with different output levels. -- Output by module. -- Thread safety with options for synchronous or asynchronous log output. -- Configurable output format. -- Configurable output backends, which can be UART or flash. +SIFLI SDK uses RT-Thread's `ulog` as the logging (log) output mechanism. As a +concise and easy-to-use logging output component, `ulog` supports: -For specific design architecture and implementation methods, you can refer to the [ulog documentation](https://www.rt-thread.org/document/site/programming-manual/ulog/ulog). +For specific design architecture and implementation methods, you can refer to +the [ulog +documentation]. ## ulog Configuration -`ulog` can be configured through many options in `menuconfig`, including log output levels, synchronous or asynchronous output, and custom output formats. +`ulog` can be configured through many options in `menuconfig`, including log +output levels, synchronous or asynchronous output, and custom output formats. -![Logger Configuration]( ../../assets/logger_config.png) +![Logger Configuration](../../assets/logger_config.png) ## ulog Usage Example diff --git a/docs/source/en/middleware/multimedia.md b/docs/source/en/middleware/multimedia.md index f41e028f0..fd3caaec7 100644 --- a/docs/source/en/middleware/multimedia.md +++ b/docs/source/en/middleware/multimedia.md @@ -1,15 +1,23 @@ # Audio document ## Standard - When developing third-party libraries, avoid directly calling interfaces like audio_open() in the library, as header files and structures may change. Instead, encapsulate an adaptor to invoke multimedia interfaces. After the library is released, some structures in the header files may be modified. Only recompile the adaptor code without recompiling the released library. +When developing third-party libraries, avoid directly calling interfaces like +audio_open() in the library, as header files and structures may change. Instead, +encapsulate an adaptor to invoke multimedia interfaces. After the library is +released, some structures in the header files may be modified. Only recompile +the adaptor code without recompiling the released library. + ## 1 Audio -In the RT-Thread device driver documentation for audio drivers -[audprc device driver](/drivers/audprc_audcodec.md),In practical scenario, multi audio stream may work together, if not support audio mix, only one reqeust can use hardware according to priority, request may resume playback after being interrupted, or mix and play together. To meet these requirements, an audio server was implemented. ref[audio server](/extra/audio_server_en.pdf).use client/server design pattern. +In the RT-Thread device driver documentation for audio drivers [audprc device +driver](/drivers/audprc_audcodec.md),In practical scenario, multi audio stream +may work together, if not support audio mix, only one reqeust can use hardware +according to priority, request may resume playback after being interrupted, or +mix and play together. To meet these requirements, an audio server was +implemented. ref[audio server](/extra/audio_server.pdf).use client/server design +pattern. audio_server_init() will be run at kernel start up,. see API in $(sdk_root)/middleware/audio/include/audio_server.h - -**1.1 create a client** ```c #include audio_client_t audio_open(audio_type_t audio_type, @@ -33,7 +41,7 @@ parameters: callback_userdata - [in] use as input parameter for callback */ ``` -**1.2 Data structure** +**1.1 create a client** ```c typedef struct @@ -79,7 +87,7 @@ typedef struct uint8_t read_bits_per_sample; /** should be 16 now */ } audio_parameter_t; ``` -**1.3 another client create function** +**1.2 Data structure** ```c typedef enum { @@ -107,11 +115,10 @@ audio_client_t audio_open2(audio_type_t audio_type, this has fixed_device than audio_open() fixed_device means this client always use fixed_device for audio */ - ``` -**1.4 callback** +**1.3 another client create function** -audio tranfered by DMA. +**1.4 callback** ```c //reveived one frame data @@ -134,10 +141,10 @@ typedef enum /*should be processed,means cache is half empty, can call audio_write() to send more data to cache */ as_callback_cmd_cache_half_empty = 3, - + /*cache is full empty, should be processed, can call audio_write()*/ as_callback_cmd_cache_empty = 4, - + /* this client is interrupted by a higher priority audio client. this client will be suspended, write data to cache will be droped. */ @@ -164,7 +171,7 @@ typedef enum as_callback_cmd_play_resume = 11, /*avrcp, Pause button pressed on peer side*/ as_callback_cmd_play_pause = 12, - + /*User defined command, defined by the app itself for what purpose. *The MP3 player plugin uses this to notify the app of the time it has *been played*/ @@ -185,6 +192,8 @@ typedef int (*audio_server_callback_func)(audio_server_callback_cmt_t cmd, */ ``` ** ** +audio tranfered by DMA. + **exmaple for mp3 record** 在$(sdk_root)\middleware\audio\audio_local_music\audio_recorder.c ** ** @@ -273,7 +282,6 @@ MSH_CMD_EXPORT(speaker, pcm2speaker test); ``` **1.6 Example of collecting mic data and playing it back to the speaker** - ```c #include #include @@ -347,20 +355,21 @@ MSH_CMD_EXPORT(mic2speaker, mic2speaker test); **1.7 audio write** -if data_len is larger than the write cache size, it will not be written and will keep returning 0. +if data_len is larger than the write cache size, it will not be written and will +keep returning 0. ```c int audio_write(audio_client_t handle, uint8_t *data, uint32_t data_len); /* -input: - handle - [in] handle of audio client - data - [in] 16bit PCM little-end PCM data, if stereo, data layout as LRLRLR..... - data_len - [in] data lenght in bytes, should less than write cache size, - best is half of write cache size -return: - -2: invalid parameter - -1: clent is suppended or paused, drop audio data - > 0: is eq to data_len, data was putted in to write cache - 0: write cache is full, should sleep than try again +Input: + handle - [in] Audio client handle. + data - [in] 16-bit little-endian PCM data. For stereo, data layout is LRLRLR... + data_len - [in] Data length in bytes. Should be less than the write cache size; + ideally half of the write cache size. +Return: + -2: Invalid parameter. + -1: Client is suspended or paused; audio data discarded. + > 0: Equal to data_len; data successfully buffered in write cache. + 0: Write cache is full; sleep and retry. */ ``` **1.8 audio ioctl** @@ -384,13 +393,14 @@ cmd value and parameter: AUDIO_IOCTL_ENABLE_CPU_LOW_SPEED - parameter eq 1, allow cpu freq scale down. parameter eq 0,cpu freq scale up to normal. */ - ``` **1.9 audio close** ```c int audio_close(audio_client_t handle); ``` -Except for audio_write(), the functions above are synchronous and are best called within a single thread. Especially audio_close(), this function cannot be called in the callback function of audio_open(), as it will cause a deadlock. +Except for audio_write(), the functions above are synchronous and are best +called within a single thread. Especially audio_close(), this function cannot be +called in the callback function of audio_open(), as it will cause a deadlock. **1.10 hardware device** ```c @@ -410,7 +420,6 @@ int audio_server_select_public_audio_device(audio_device_e audio_device); Selecting the corresponding hardware devices for all music types, will definitely succeed if called after audio_server_init(). */ - ``` @@ -460,8 +469,11 @@ int audio_server_select_private_audio_device(audio_type_t audio_type, #endif } ``` -**1.11 register a hardware device in audio server** -This app does not require attention; it is already implemented within the system. It mainly registers some hardware or virtual hardware devices such as speakers and BT, for selecting devices during playback. If necessary, refer to the places in the system where it is invoked. +**1.11 register a hardware device in audio server** This app does not require +attention; it is already implemented within the system. It mainly registers some +hardware or virtual hardware devices such as speakers and BT, for selecting +devices during playback. If necessary, refer to the places in the system where +it is invoked. ```c int audio_server_register_audio_device(audio_device_e audio_device, const struct audio_device *p_audio_device); @@ -470,13 +482,25 @@ p_audio_device - [in] device config and callback ``` **1.12 audio volume** -1.12.1 **Get Max Volume** -Currently, the volume level ranges from 0 to 15, and the following function will return 15. +1.12.1 **Get Max Volume** Currently, the volume level ranges from 0 to 15, and +the following function will return 15. ```c //return Max voluem 15 uint8_t audio_server_get_max_volume(void); ``` -The volume level is divided into public and private settings. Each music type can have its own private volume, allowing different music types to have different volume settings during playback. Public is the volume shared by all music types, similar to C++ overloading, while private can override the public value. If a music type sets its own private volume, this private volume will be used when playing that type of music. If a music type has not set a private volume, the public volume will be used. On the hardware side, volume changes are checked each time a DMA data frame is sent. If a change is detected, the hardware is updated. Currently, volume changes are achieved by setting the codec gain; the software does not alter the volume. To change the volume via software, system-level modifications are required. The hardware codec gain remains unchanged, and the PCM amplitude is adjusted in audio_write(). +The volume level is divided into public and private settings. Each music type +can have its own private volume, allowing different music types to have +different volume settings during playback. Public is the volume shared by all +music types, similar to C++ overloading, while private can override the public +value. If a music type sets its own private volume, this private volume will be +used when playing that type of music. If a music type has not set a private +volume, the public volume will be used. On the hardware side, volume changes are +checked each time a DMA data frame is sent. If a change is detected, the +hardware is updated. Currently, volume changes are achieved by setting the codec +gain; the software does not alter the volume. To change the volume via software, +system-level modifications are required. The hardware codec gain remains +unchanged, and the PCM amplitude is adjusted in audio_write(). + ```c //volume from 0 ~ 15 @@ -505,13 +529,24 @@ int audio_server_set_public_speaker_mute(uint8_t is_mute); //return 1 if mutted, 0 umutted uint8_t audio_server_get_public_speaker_mute(void); ``` -**1.13 one DMA frame size** -The change in data length currently does not provide an interface for dynamically modifying the recording size; it is configured by macro definitions. +**1.13 one DMA frame size** The change in data length currently does not provide +an interface for dynamically modifying the recording size; it is configured by +macro definitions. + +The CFG_AUDIO_RECORD_PIPE_SIZE macro in audio.h represents the data size of a +single DMA interrupt during recording. If it is 320, then for a 16kHz mono +microphone, data is generated every 10ms, and the audio_open callback is +triggered.In audio_server.c, CODEC_DATA_UNIT_LEN should have the same value as +CFG_AUDIO_RECORD_PIPE_SIZE. Currently, there is no interface provided to modify +it dynamically. -The CFG_AUDIO_RECORD_PIPE_SIZE macro in audio.h represents the data size of a single DMA interrupt during recording. If it is 320, then for a 16kHz mono microphone, data is generated every 10ms, and the audio_open callback is triggered.In audio_server.c, CODEC_DATA_UNIT_LEN should have the same value as CFG_AUDIO_RECORD_PIPE_SIZE. Currently, there is no interface provided to modify it dynamically. +In audio_server.c, CODEC_DATA_UNIT_LEN must be identical to +CFG_AUDIO_RECORD_PIPE_SIZE. Currently, no interface is provided for dynamic +modification. ### Special Purpose Interface -**It can only be used in product scenarios where the mic bias pin is treated as a regular GPIO, rather than as the mic power supply of the codec.** +**It can only be used in product scenarios where the mic bias pin is treated as +a regular GPIO, rather than as the mic power supply of the codec.** ```c need config CONFIG_MICBIAS_USING_AS_PDM_POWER=y @@ -520,12 +555,17 @@ void micbias_power_on(); //open micbias void micbias_power_off(); //close micbias ``` ## Add music genre and change priority -If you want to add a music type, you must add the priority in this array in audio_server.c. A higher value indicates higher priority. Also, specify whether mixing is allowed. The mixing configuration is quite complex. Currently, BT voice is exclusive with the highest priority and does not participate in mixing, while others can be mixed. If you want to customize mixing rules, you need to check how is_can_mix() is implemented and determines this. +If you want to add a music type, you must add the priority in this array in +audio_server.c. A higher value indicates higher priority. Also, specify whether +mixing is allowed. The mixing configuration is quite complex. Currently, BT +voice is exclusive with the highest priority and does not participate in mixing, +while others can be mixed. If you want to customize mixing rules, you need to +check how is_can_mix() is implemented and determines this. ```c static const audio_mix_policy_t mix_policy[AUDIO_TYPE_NUMBER] = ``` ## config -```c +``` #audio CONFIG_AUDIO=y #audio server @@ -548,8 +588,6 @@ CONFIG_AUDIO_RX_USING_I2S=y # from PDM CONFIG_AUDIO_RX_USING_PDM=y ``` -If outputting to I2S, first configure I2S according to the [I2S driver interface](/drivers/i2s.md), then in the audio server, refer to that configuration to set up the i2s_config(my, 1); check its internal implementation, and track whether speaker_tx_done is triggered. - ```c static void config_tx(audio_device_speaker_t *my, audio_client_t client) { @@ -560,8 +598,12 @@ static void config_tx(audio_device_speaker_t *my, audio_client_t client) .... #endif ``` +If outputting to I2S, first configure I2S according to the [I2S driver +interface](/drivers/i2s.md), then in the audio server, refer to that +configuration to set up the i2s_config(my, 1); check its internal +implementation, and track whether speaker_tx_done is triggered. -```python +```c Choose one of the two options below to indicate which hardware the speaker device uses for audio output. If it's I2S, you also need to enable the corresponding driver in RT-Thread. @@ -571,6 +613,7 @@ AUDIO_SPEAKER_USING_CODEC=y # output to I2S CONFIG_AUDIO_TX_USING_I2S=y ``` + ```python # If you want multiple clients to work together, for example, # playing music while recording, you need to configure this @@ -580,63 +623,102 @@ CONFIG_MULTI_CLIENTS_AT_WORKING=y # If both clients are AUDIO_TX and rely on the audio server to mix, # then you need to enable this CONFIG_SOFTWARE_TX_MIX_ENABLE=y - ``` - ## MP3 playback API -The audio playback interface is in audio_mp3ctlr.h. -MP3 playback baseon audio server. -There are quite a few examples, and you can search for example code in the SDK. Currently, it automatically recognizes mp3 and wav files, but wav files only support 16-bit PCM format.At the end of the audio_mp3ctrl.c file, there is an mp3 playback command. The code is commented out by default. -Change -#define MP3_TEST_CMD 0 to -#define MP3_TEST_CMD 1 -and you can use the mp3 command to play files. -mp3 command help in comment at end of audio_mp3ctlr.c - +The audio playback interface is in audio_mp3ctlr.h. MP3 playback baseon audio +server. There are quite a few examples, and you can search for example code in +the SDK. Currently, it automatically recognizes mp3 and wav files, but wav files +only support 16-bit PCM format.At the end of the audio_mp3ctrl.c file, there is +an mp3 playback command. The code is commented out by default. Change #define +MP3_TEST_CMD 0 to #define MP3_TEST_CMD 1 and you can use the mp3 command to play +files. mp3 command help in comment at end of audio_mp3ctlr.c + +An MP3 playback command is available at the end of the audio_mp3ctrl.c file, but +it is commented out by default. Change #define MP3_TEST_CMD 0 to #define +MP3_TEST_CMD 1 to enable the mp3 command for file playback. Usage help for the +mp3 command can be found at its implementation site in audio_mp3ctrl.c. ## resample - Implemented a simple resampling, mainly for internal use, especially during mixing. + /* + create a resampel handle + parameter: + channels - [in]channels of source data,1 - mono, 2, stereo + if stereo, data layout is LRLRLR..... + src_samplerate - [in] samplerate before resampling + dst_samplerate - [in] samplerate after resampling + return: hanle of resample + */ + sifli_resample_t *sifli_resample_open(uint8_t channels, + uint32_t src_samplerate, + uint32_t dst_samplerate); + + /* + process resample + parameter: + p - [in] hanle of resample + src - [in] source data address + src_bytes - [in] source data size in bytes + is_last_packet - [in] should always be zero if has more data to + process later + */ + uint32_t sifli_resample_process(sifli_resample_t *p, + int16_t *src, uint32_t src_bytes, + uint8_t is_last_packet); + + /* + return data process result after call sifli_resample_process(), + */ + int16_t *sifli_resample_get_output(sifli_resample_t *p); + + /* + close handle to release resource + */ + void sifli_resample_close(sifli_resample_t *p); ```c - /* - create a resampel handle -parameter: - channels - [in]channels of source data,1 - mono, 2, stereo - if stereo, data layout is LRLRLR..... - src_samplerate - [in] samplerate before resampling - dst_samplerate - [in] samplerate after resampling -return: hanle of resample +/* + Creates a resampling handle. +Parameters: + channels - [in] Number of channels for the source data (1 for mono, 2 for stereo). + For stereo, the data layout is LRLRLR... + src_samplerate - [in] Sample rate of the source data. + dst_samplerate - [in] Target sample rate after resampling. +Return: Resampling handle. */ sifli_resample_t *sifli_resample_open(uint8_t channels, uint32_t src_samplerate, uint32_t dst_samplerate); /* - process resample -parameter: - p - [in] hanle of resample - src - [in] source data address - src_bytes - [in] source data size in bytes - is_last_packet - [in] should always be zero if has more data to - process later + Executes the resampling process. +Parameters: + p - [in] Resampling handle. + src - [in] Source data address. + src_bytes - [in] Size of the source data in bytes. + is_last_packet - [in] Should be zero if more data follows. */ uint32_t sifli_resample_process(sifli_resample_t *p, - int16_t *src, uint32_t src_bytes, - uint8_t is_last_packet); + int16_t *src, + uint32_t src_bytes, + uint8_t is_last_packet); /* - return data process result after call sifli_resample_process(), + Returns the processed output data after calling sifli_resample_process(). */ int16_t *sifli_resample_get_output(sifli_resample_t *p); /* - close handle to release resource + Closes the handle and releases resources. */ void sifli_resample_close(sifli_resample_t *p); ``` + ## Integration of data processing algorithms -Currently, the supported voice processing algorithm is WebRTC. If you want to integrate a third-party algorithm, you need to implement the following functions yourself, refer to audio_3a.c. Or you can delete audio_3a.c to see what is missing. You can also choose not to use WebRTC and configure the following to use the Anyka speech algorithm: -CONFIG_PKG_USING_ANYKA=y -You can also refer to this algorithm to replace audio_3a.c, -source code at $(sdk_root)/middleware/audio/anyka +Currently, the supported voice processing algorithm is WebRTC. If you want to +integrate a third-party algorithm, you need to implement the following functions +yourself, refer to audio_3a.c. Or you can delete audio_3a.c to see what is +missing. You can also choose not to use WebRTC and configure the following to +use the Anyka speech algorithm: CONFIG_PKG_USING_ANYKA=y You can also refer to +this algorithm to replace audio_3a.c, source code at +$(sdk_root)/middleware/audio/anyka ```c /* @@ -662,10 +744,11 @@ void audio_3a_open(uint32_t samplerate, uint8_t is_bt_voice, uint8_t disable_uplink_agc); void audio_3a_close(); - ``` ## Hardware Amplifier Adaptation -The amplifier before the speaker may require different hardware amplifiers on different platforms. The following three functions need to be implemented in $(sdk_root)/middleware/audio/audio_port/audio_pa_api.c +The amplifier before the speaker may require different hardware amplifiers on +different platforms. The following three functions need to be implemented in +$(sdk_root)/middleware/audio/audio_port/audio_pa_api.c ```c RT_WEAK void audio_hardware_pa_init() { @@ -681,11 +764,15 @@ RT_WEAK void audio_hardware_pa_stop(void) // Turn off PA } ``` - ## EQ Switch Settings -If using the chip's codec, there is a hardware EQ on the chip. Currently, the software settings only support 44.1k and 16k.You can modify this file to decide whether to turn the EQ on or off for a certain music type. -Located at $(sdk_root)/middleware/audio/audio_port/audio_eq_config.c -Specifically, during factory test frequency response mode, the EQ should be turned off. You can add a check in the get_eq_config() function to return 0 to disable the EQ if it is factory mode. +If using the chip's codec, there is a hardware EQ on the chip. Currently, the +software settings only support 44.1k and 16k.You can modify this file to decide +whether to turn the EQ on or off for a certain music type. Located at +$(sdk_root)/middleware/audio/audio_port/audio_eq_config.c Specifically, during +factory test frequency response mode, the EQ should be turned off. You can add a +check in the get_eq_config() function to return 0 to disable the EQ if it is +factory mode. + ```c /* return: @@ -696,11 +783,30 @@ RT_WEAK uint8_t get_eq_config(audio_type_t type); ``` ## EQ Parameter Settings -The EQ tool [Sifli_EQ](https://wiki.sifli.com/tools/index.html) -The EQ parameters are in drv_audprc.c. They should ideally be generated using the tool, but sometimes it is convenient to directly modify the code for debugging.The following commands can be used to adjust the mic gain. You can also refer to the code implementation: -mic_gain -pdm_gain (if PDM is configured) -Sometimes, volume is manually adjusted. Volume testing must meet hardware requirements; the maximum volume should not exceed the speaker's power to avoid damaging it. The maximum volume should be determined through hardware testing to meet power requirements. + +The EQ tool [Sifli_EQ](https://wiki.sifli.com/tools/index.html) The EQ +parameters are in drv_audprc.c. They should ideally be generated using the tool, +but sometimes it is convenient to directly modify the code for debugging.The +following commands can be used to adjust the mic gain. You can also refer to the +code implementation: mic_gain pdm_gain (if PDM is configured) Sometimes, volume +is manually adjusted. Volume testing must meet hardware requirements; the +maximum volume should not exceed the speaker's power to avoid damaging it. The +maximum volume should be determined through hardware testing to meet power +requirements. + +EQ parameters are located in drv_audprc.c. While these should ideally be +generated using specialized tools, they can be manually modified in the code for +debugging convenience. + +The following commands can be used to debug microphone gain. Once optimized, +update the compile-time initial values. Refer to the implementation of mic_gain +and pdm_gain (if PDM is configured) in the source code. + +Volume can also be adjusted manually. Volume testing must adhere to hardware +specifications; the maximum volume must not exceed the speaker's rated power to +prevent hardware damage. Maximum volume settings require hardware validation to +ensure power compliance. + ```c int8_t g_adc_volume = 0; // mic gain /*Maximum volume protection for phone calls, unit: 0.5db. @@ -713,4 +819,4 @@ If the values in g_music_vol_level[] multiplied by 2 exceed this value, this val */ int8_t g_music_max_vol = 0; int8_t g_music_vol_level[16] = {-55, -34, -32, -30, -28, -26, -24, -22, -20, -17, -14, -11, -10, -8, -6, -4}; -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/partition_table.md b/docs/source/en/middleware/partition_table.md index 1498655e7..0d710962f 100644 --- a/docs/source/en/middleware/partition_table.md +++ b/docs/source/en/middleware/partition_table.md @@ -1,27 +1,33 @@ # Partition Table - -The `partition_table` module is a build script tool that parses the partition table description file `ptab.json` and generates the header file `ptab.h`. This header file contains a series of macro definitions related to partition information, which can be included in projects to obtain partition details. - -The partition table can describe the address mapping for all memory types, including NOR Flash, NAND Flash, eMMC, TF cards, PSRAM, and on-chip SRAM. Each board has its own `ptab.json` that describes the partition information for that board. Any project compiled for that board must follow the address mapping defined by the partition table. Projects can also use a custom `ptab.json` to override the board’s default configuration. +The `partition_table` module is a build script tool that parses the partition +table description file `ptab.json` and generates the header file `ptab.h`. This +header file contains a series of macro definitions related to partition +information, which can be included in projects to obtain partition details. ## Enabling the Partition Table - -Select `Use partition table to manage all memory layout` in the middleware to enable the partition table feature: +Select `Use partition table to manage all memory layout` in the middleware to +enable the partition table feature: ![](../../assets/partition_table/ptab_menuconfig.png) -You also need to define the following switch in your project’s `Kconfig.proj`. This snippet is already included in all example projects. - +You also need to define the following switch in your project’s `Kconfig.proj`. +This snippet is already included in all example projects. ```kconfig -#APP specific configuration. +# Application-specific configuration. config CUSTOM_MEM_MAP bool select custom_mem_map default y if !SOC_SIMULATOR ``` + ## Partition Table Syntax +The partition table description file `ptab.json` is a text file in JSON format. +It follows standard JSON syntax and can be edited with any text editor. There +are two versions of the partition table syntax: 1.0 and 2.0. The 2.0 version +simplifies the syntax compared to 1.0, making it easier to understand and +maintain. It is recommended that new projects adopt the 2.0 syntax. For detailed +syntax, refer to [](partition_table_v1.md) and [](partition_table_v2.md). -The partition table description file `ptab.json` is a text file in JSON format. It follows standard JSON syntax and can be edited with any text editor. There are two versions of the partition table syntax: 1.0 and 2.0. The 2.0 version simplifies the syntax compared to 1.0, making it easier to understand and maintain. It is recommended that new projects adopt the 2.0 syntax. For detailed syntax, refer to [](partition_table_v1.md) and [](partition_table_v2.md). ```{toctree} :hidden: diff --git a/docs/source/en/middleware/partition_table_v1.md b/docs/source/en/middleware/partition_table_v1.md index ae4f17d52..f46850d2b 100644 --- a/docs/source/en/middleware/partition_table_v1.md +++ b/docs/source/en/middleware/partition_table_v1.md @@ -1,8 +1,12 @@ # Partition Table Syntax Version 1.0 -The partition table description file `ptab.json` is a text file in JSON format. It follows standard JSON syntax and can be edited with any text editor. -The partition table uses a list to define all memory devices used in the system, such as `flash2`, `psram1`, etc. -In version 1.0 of the partition table, there is no dedicated property to specify the version number. Alternatively, a special list element (referred to as the header element) may be used with a `version` property set to `1`, as shown below: +The partition table description file `ptab.json` is a text file in JSON format. +It follows standard JSON syntax and can be edited with any text editor. The +partition table uses a list to define all memory devices used in the system, +such as `flash2`, `psram1`, etc. In version 1.0 of the partition table, there is +no dedicated property to specify the version number. Alternatively, a special +list element (referred to as the header element) may be used with a `version` +property set to `1`, as shown below: ```json [ @@ -17,27 +21,33 @@ In version 1.0 of the partition table, there is no dedicated property to specify "base": "0x60000000", "regions": [] } -] +] ``` -Each element in the list (excluding the header) corresponds to a memory block. For example, in the following example, there are memories such as `flash5`, `psram1`, `flash4`, and `hpsys_ram`. Each memory has the following properties: - -* `mem`: The name of the memory. -* `base`: The base address of the memory, in hexadecimal. Must be correct. -* `regions`: The list of partitions within the memory. - -`regions` defines the partitions within the memory. Each partition has the following properties: - -* `offset`: The offset in bytes (hexadecimal). -* `max_size`: The size in bytes (hexadecimal). -* `tags`: A list of tags. Each tag is used to generate corresponding macros representing the partition’s size and starting address. For example, a tag `FLASH_BOOT_LOADER` generates `FLASH_BOOT_LOADER_START_ADDR`, `FLASH_BOOT_LOADER_OFFSET`, and `FLASH_BOOT_LOADER_SIZE` macros. `START_ADDR` is `base + offset`, `OFFSET` equals the `offset` value, and `SIZE` equals the `max_size` value. -* `ftab`: Flash table entry information (optional). -* `img`: The name of the image file stored in this partition, used to generate flashing scripts (optional). -* `exec`: The name of the program that runs on this partition (optional). -* `custom`: A custom macro dictionary (optional). - - -````{dropdown} ptab.json Example +Each element in the list (excluding the header) corresponds to a memory block. +For example, in the following example, there are memories such as `flash5`, +`psram1`, `flash4`, and `hpsys_ram`. Each memory has the following properties: +- `mem`: The name of the memory. +- `base`: The base address of the memory, in hexadecimal. Must be correct. +- `regions`: The list of partitions within the memory. + +`regions` defines the partitions within the memory. Each partition has the +following properties: +- `offset`: The offset in bytes (hexadecimal). +- `max_size`: The size in bytes (hexadecimal). +- `tags`: A list of tags. Each tag is used to generate corresponding macros + representing the partition’s size and starting address. For example, a tag + `FLASH_BOOT_LOADER` generates `FLASH_BOOT_LOADER_START_ADDR`, + `FLASH_BOOT_LOADER_OFFSET`, and `FLASH_BOOT_LOADER_SIZE` macros. `START_ADDR` + is `base + offset`, `OFFSET` equals the `offset` value, and `SIZE` equals the + `max_size` value. +- `ftab`: Flash table entry information (optional). +- `img`: The name of the image file stored in this partition, used to generate + flashing scripts (optional). +- `exec`: The name of the program that runs on this partition (optional). +- `custom`: A custom macro dictionary (optional). + +````{dropdown} ptab.json示例 ```json [ { @@ -154,12 +164,22 @@ Each element in the list (excluding the header) corresponds to a memory block. F ## Property Details ### ftab - -The `ftab` property defines parameters for a flash table entry, generating the flash table description file `ftab.c` for compilation. The flash table affects program startup, so `ftab` must be filled correctly. `ftab` includes the following properties: -- `name`: Program name. `bootloader` means the secondary bootloader, `main` means the main program, and `dfu` means the DFU program. These are reserved system names and should not be used arbitrarily. Other names can be defined freely by the user, e.g., `acpu_region1` can represent an ACPU code partition. -- `address`: A list of address types. If the partition stores a program image, use `"base"`. If the program runs directly from the memory region, use `"xip"`. If both (i.e., the program executes in place, XIP), specify both `"base"` and `"xip"`. - -Below is an example describing `bootloader` stored in flash5, with the address range `0x1C020000`~`0x1C03FFFF`. The secondary bootloader code also runs directly from flash5 (XIP). +The `ftab` property defines parameters for a flash table entry, generating the +flash table description file `ftab.c` for compilation. The flash table affects +program startup, so `ftab` must be filled correctly. `ftab` includes the +following properties: +- `name`: Program name. `bootloader` means the secondary bootloader, `main` + means the main program, and `dfu` means the DFU program. These are reserved + system names and should not be used arbitrarily. Other names can be defined + freely by the user, e.g., `acpu_region1` can represent an ACPU code partition. +- `address`: A list of address types. If the partition stores a program image, + use `"base"`. If the program runs directly from the memory region, use + `"xip"`. If both (i.e., the program executes in place, XIP), specify both + `"base"` and `"xip"`. + +Below is an example describing `bootloader` stored in flash5, with the address +range `0x1C020000`~`0x1C03FFFF`. The secondary bootloader code also runs +directly from flash5 (XIP). ```json { @@ -183,17 +203,24 @@ Below is an example describing `bootloader` stored in flash5, with the address r "exec": "bootloader" } ] -}, +}, ``` -Programs that are not reserved system programs (`name` is not `main`, `bootloader`, or `dfu`) use the following flash table entries to describe stored image info in sequence: +Programs that are not reserved system programs (`name` is not `main`, +`bootloader`, or `dfu`) use the following flash table entries to describe stored +image info in sequence: - DFU_FLASH_HCPU_EXT2: 11 - DFU_FLASH_LCPU_EXT1: 12 - DFU_FLASH_LCPU_EXT2: 13 -For example, the following `ptab.json` snippet defines `acpu_region1` using flash4 offset `0x00300000` as the ACPU program’s base address and hpsys_ram offset `0x00200000` as the XIP address. The generated `ftab.c` file uses `DFU_FLASH_HCPU_EXT2` to describe the image storage and execution addresses, with `length` determined by the program image file (example: 0x7d4 bytes) that is specified by `img` property (see [](#img) for details) +For example, the following `ptab.json` snippet defines `acpu_region1` using +flash4 offset `0x00300000` as the ACPU program’s base address and hpsys_ram +offset `0x00200000` as the XIP address. The generated `ftab.c` file uses +`DFU_FLASH_HCPU_EXT2` to describe the image storage and execution addresses, +with `length` determined by the program image file (example: 0x7d4 bytes) that +is specified by `img` property (see [](#img) for details) -````{dropdown} acpu_region1 Example +````{dropdown} acpu_region1示例代码 ```json { "mem": "flash4", @@ -268,22 +295,28 @@ RT_USED const struct sec_configuration sec_config = .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_LCPU_EXT2)] = {.length = 0xFFFFFFFF}, .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_RESERVED)] = {.length = 0xFFFFFFFF}, .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_SINGLE)] = {.length = 0xFFFFFFFF}, - .running_imgs[CORE_HCPU] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_HCPU)], + .running_imgs[CORE_HCPU] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_HCPU)], .running_imgs[CORE_LCPU] = (struct image_header_enc *)0xFFFFFFFF, - .running_imgs[CORE_BL] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_BL)], + .running_imgs[CORE_BL] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_BL)], .running_imgs[CORE_BOOT] = (struct image_header_enc *)0xFFFFFFFF, }; ``` -The following diagram shows how the storage and execution addresses for the ACPU program in `ftab.c` are extracted from `ptab.json`. + +The following diagram shows how the storage and execution addresses for the ACPU +program in `ftab.c` are extracted from `ptab.json`. + ![](../../assets/partition_table/ptab_ftab.png) + ### img -The `img` property specifies the program image file stored in a partition. The flashing script uses this to determine the flash address. If the `ftab` `base` and `xip` addresses are the same, `img` is unnecessary because the hex file already contains the address info for flashing. +The `img` property specifies the program image file stored in a partition. The +flashing script uses this to determine the flash address. If the `ftab` `base` +and `xip` addresses are the same, `img` is unnecessary because the hex file +already contains the address info for flashing. -Example: ```json { @@ -336,16 +369,14 @@ Example: "exec": "main" } ] -}, +}, ``` -The specified image name must match the binary generated by the project. If only one binary is generated, you can omit the `.bin` extension and name it simply `main`, `bootloader`, or `lcpu`. If there are multiple files, use the format `proj_name:binary_name`. For example, if `acpu` is added as a sub-project, its binaries `ER_IROM1.bin` and `ER_IROM2.bin` can be specified as `acpu:ER_IROM1.bin` and `acpu:ER_IROM2.bin`. - ### exec - -The `exec` property specifies the name of the executable program stored in a partition. It allows the same linker script to be reused for building the main and sub-programs like bootloader, DFU, and main. For example, `CODE_START_ADDR` is specified by `ptab.h` based on the partition. - -When building the bootloader: +The `exec` property specifies the name of the executable program stored in a +partition. It allows the same linker script to be reused for building the main +and sub-programs like bootloader, DFU, and main. For example, `CODE_START_ADDR` +is specified by `ptab.h` based on the partition. ```c #undef FLASH_BOOT_LOADER_START_ADDR @@ -358,7 +389,7 @@ When building the bootloader: #define CODE_SIZE (FLASH_BOOT_LOADER_SIZE) ``` -When building the main program: +When building the bootloader: ```c #undef HCPU_FLASH_CODE_START_ADDR @@ -376,8 +407,8 @@ Note: For PSRAM partitions, CBUS and SBUS are two address spaces. For example, C ``` ### custom - -The `custom` property allows adding custom macros to `ptab.h`. The value must be a dictionary. For example: +The `custom` property allows adding custom macros to `ptab.h`. The value must be +a dictionary. For example: ```json "custom": { @@ -387,8 +418,6 @@ The `custom` property allows adding custom macros to `ptab.h`. The value must be } ``` -Generates: - ```c #define PSRAM_BL_MODE (3) #define PSRAM_BL_SIZE (8) @@ -404,14 +433,15 @@ Note: Dictionary values must be integers. ### CODE, Resource binary separation -Taking 'example\multimedia\lvgl\watch\project\sf32lb52-lcd_n16r8_ccpu' as an example, under this project configuration, will generate 3 binary files: -+ ER_IROM1.bin:CODE -+ ER_IROM2.bin:Image Resources -+ ER_IROM3.bin:Font Resources +Taking 'example\multimedia\lvgl\watch\project\sf32lb52-lcd_n16r8_ccpu' as an +example, under this project configuration, will generate 3 binary files: ++ ER_IROM1.bin:CODE ++ ER_IROM2.bin:Image Resources ++ ER_IROM3.bin:Font Resources Key configurations: 1. partition configuration(ptab.json) - ![ptab_config](../../assets/partition_table/ptab_config.png) + ![ptab_config](../../assets/partition_table/ptab_config.png) 2. link script configuration(.sct or .lds) + link.sct @@ -454,23 +484,24 @@ Key configurations: *(.ROM1_IMG) *(.ROM3_IMG*.*) *(.ROM3_IMG*) - } > ROM2 + } > ROM2 /* Font/ER_IROM3 */ .rom3 : { *lvsf_font_*(.rodata*) *(.SECTION_TTF*.*) - } > ROM3 + } > ROM3 ``` ### Add custom binary -For example, it is necessary to add a binary to store the `RO data` of 'xxx.c' and download it independently. -Refer to [ CODE, Resource binary separation](#code-resource-binary-separation), complete step by step: -1. Add a new partition(ptab.json): +For example, it is necessary to add a binary to store the `RO data` of 'xxx.c' +and download it independently. Refer to [ CODE, Resource binary +separation](#code资源binary分离), complete step by step: +1. Add a new partition(ptab.json): ```c - { + { "offset": "0x00420000", "max_size": "0x00200000", "tags": [ @@ -495,9 +526,10 @@ Refer to [ CODE, Resource binary separation](#code-resource-binary-separation), "img": "main:ER_IROM4.bin" }, ``` -2. link script configuration(.sct or.lds): - Add a new region to store `xxx.o (+RO)` data.(rules can be modified as needed): - + link.sct +2. link script configuration(.sct or.lds):\ + Add a new region to store `xxx.o (+RO)` data.(rules can be modified as + needed): + + link.sct ```c LR_IROM3 HCPU_FLASH2_FONT_START_ADDR HCPU_FLASH2_FONT_SIZE { ; load region size_region @@ -507,13 +539,13 @@ Refer to [ CODE, Resource binary separation](#code-resource-binary-separation), } } - ; IROM4, specify which part data will store here + ; IROM4: Specify storage location for specific data partitions LR_IROM4 HCPU_FUNC_START_ADDR HCPU_FUNC_SIZE { ; load region size_region ER_IROM4 HCPU_FUNC_START_ADDR HCPU_FUNC_SIZE { ; RW data xxx.o (+RO) } } - ``` + ``` + link.lds ```c ... ... @@ -525,7 +557,7 @@ Refer to [ CODE, Resource binary separation](#code-resource-binary-separation), __ROM4_SIZE = HCPU_FUNC_SIZE; /* - *-------------------- <<< end of configuration section >>> ------------------- + *-------------------- <<< end of configuration section >>> ------------------- */ MEMORY { @@ -539,30 +571,31 @@ Refer to [ CODE, Resource binary separation](#code-resource-binary-separation), { *lvsf_font_*(.rodata*) *(.SECTION_TTF*.*) - } > ROM3 + } > ROM3 - /* ROM4 , specify which part data will store here */ + /* ROM4; specify the data to be stored in this section */ .rom4 : { *xxx.o(.rodata*) - } > ROM4 + } > ROM4 ``` ### Add custom img -For example, adding a partition for downloading pre packaged binary files (such as third-party or other pre packaged ones): +For example, adding a partition for downloading pre packaged binary files (such +as third-party or other pre packaged ones): 1. partition configuration(ptab.json) ```c - { + { "offset": "0x00640000", "max_size": "0x00400000", "img": "ext_bin", "tags": [ "EXT_BIN" ] - }, + }, ``` -2. `AddCustomImg`(Sconstruct of this project) +2. `AddCustomImg`(Sconstruct of this project) ```c # Add custom image bin. `bin` specifies the path of the target binary. @@ -571,4 +604,5 @@ For example, adding a partition for downloading pre packaged binary files (such # Generate download .bat script GenDownloadScript(env) ``` -Compile and you can see that it already includes the newly added custom img binary in download script. \ No newline at end of file + Compile and you can see that it already includes the newly added custom img + binary in download script. diff --git a/docs/source/en/middleware/partition_table_v2.md b/docs/source/en/middleware/partition_table_v2.md index 43ee69ae2..83b0bab82 100644 --- a/docs/source/en/middleware/partition_table_v2.md +++ b/docs/source/en/middleware/partition_table_v2.md @@ -1,7 +1,10 @@ # Partition Table Syntax Version 2.0 - -The partition table description file `ptab.json` is a text file in JSON format. It follows standard JSON syntax and can be edited with any text editor. -The partition table uses a list to define all memory devices used in the system, such as `flash2`, `psram1`, etc. In version 2.0 of the partition table, a special list element (referred to as the header element) is used to specify the version number with the `version` property set to `2`, as shown below: +The partition table description file `ptab.json` is a text file in JSON format. +It follows standard JSON syntax and can be edited with any text editor. The +partition table uses a list to define all memory devices used in the system, +such as `flash2`, `psram1`, etc. In version 2.0 of the partition table, a +special list element (referred to as the header element) is used to specify the +version number with the `version` property set to `2`, as shown below: ```json [ {"version": "2"}, @@ -15,26 +18,34 @@ The partition table uses a list to define all memory devices used in the system, "base": "0x60000000", "regions": [] } -] +] ``` -Each element in the list (excluding the header) corresponds to a memory block. For example, in the following example, there are memories such as `flash5`, `psram1`, `flash4`, and `hpsys_ram`. Each memory has the following properties: - -* `mem`: The name of the memory. -* `base`: The base address of the memory, in hexadecimal. Must be correct. -* `regions`: The list of partitions within the memory. - -`regions` defines the partitions within the memory. Each partition has the following properties: -* `offset`: The offset in bytes (hexadecimal). -* `max_size`: The size in bytes (hexadecimal). -* `tags`: Optional. A list of tags. Each tag is used to generate corresponding macros representing the partition’s size and starting address. For example, a tag `FLASH_BOOT_LOADER` generates `FLASH_BOOT_LOADER_START_ADDR`, `FLASH_BOOT_LOADER_OFFSET`, and `FLASH_BOOT_LOADER_SIZE` macros. `START_ADDR` is `base + offset`, `OFFSET` equals the `offset` value, and `SIZE` equals the `max_size` value. -* `name`: Partition name -* `type`: Optional. Partition type -* `core`: Optional. When the partition type is `app_exec`, it indicates the core that runs the code in this partition. The available names are `hcpu`, `lcpu`, and `acpu`. -* `custom`: Optional. A custom macro dictionary - - -````{dropdown} ptab.json Example +Each element in the list (excluding the header) corresponds to a memory block. +For example, in the following example, there are memories such as `flash5`, +`psram1`, `flash4`, and `hpsys_ram`. Each memory has the following properties: +- `mem`: The name of the memory. +- `base`: The base address of the memory, in hexadecimal. Must be correct. +- `regions`: The list of partitions within the memory. + +`regions` defines the partitions within the memory. Each partition has the +following properties: +- `offset`: The offset in bytes (hexadecimal). +- `max_size`: The size in bytes (hexadecimal). +- `tags`: Optional. A list of tags. Each tag is used to generate corresponding + macros representing the partition’s size and starting address. For example, a + tag `FLASH_BOOT_LOADER` generates `FLASH_BOOT_LOADER_START_ADDR`, + `FLASH_BOOT_LOADER_OFFSET`, and `FLASH_BOOT_LOADER_SIZE` macros. `START_ADDR` + is `base + offset`, `OFFSET` equals the `offset` value, and `SIZE` equals the + `max_size` value. +- `name`: Partition name +- `type`: Optional. Partition type +- `core`: Optional. When the partition type is `app_exec`, it indicates the core + that runs the code in this partition. The available names are `hcpu`, `lcpu`, + and `acpu`. +- `custom`: Optional. A custom macro dictionary + +````{dropdown} ptab.json示例 ```json [ { @@ -106,29 +117,38 @@ Each element in the list (excluding the header) corresponds to a memory block. F ```` ## Property Details - ### name - -The `name` property defines the name of the partition. For partitions of type `app_img` or `app_exec` (see [](#type) for details), it indicates which program the partition is associated with. The value `bootloader` refers to the secondary bootloader, `main` refers to the main application, `dfu` refers to the DFU (Device Firmware Upgrade) program, and `ftab` stands for the flash table. These are reserved names and should not be used arbitrarily. Other names can be freely defined by the user. For example, `acpu` can be used to represent a code partition for ACPU. - -It’s important to note that for program image partitions, the partition name must match the program name. For instance, if the ACPU and LCPU programs are added to the main project as sub-projects using the `AddChildProj` function, and are named `acpu` and `lcpu` respectively, then their corresponding partition names must also be `acpu` and `lcpu`. - -Another case is when a partition stores a precompiled binary file, which is added using the `AddCustomImg` function. In this case, the `name` parameter specified in `AddCustomImg` must match the partition’s `name` property. - -Additionally, a program might consist of multiple files. For example, the main program `main` might include two binary files: one for code (`ER_IROM1.bin`) and one for resources (`ER_IROM2.bin`). In this case, the `name` property of the corresponding partitions can be set to `main:1` and `main:2` respectively, where `main:1` corresponds to `ER_IROM1.bin`, and `main:2` to `ER_IROM2.bin`. - -In summary, the value of `name` should follow the format `proj_name:num`, where `proj_name` is the program name and `num` is an index starting from 1. If the program consists of only one file, the `num` part can be omitted. +The `name` property defines the name of the partition. For partitions of type +`app_img` or `app_exec` (see [](#type) for details), it indicates which program +the partition is associated with. The value `bootloader` refers to the secondary +bootloader, `main` refers to the main application, `dfu` refers to the DFU +(Device Firmware Upgrade) program, and `ftab` stands for the flash table. These +are reserved names and should not be used arbitrarily. Other names can be freely +defined by the user. For example, `acpu` can be used to represent a code +partition for ACPU. + +It’s important to note that for program image partitions, the partition name +must match the program name. For instance, if the ACPU and LCPU programs are +added to the main project as sub-projects using the `AddChildProj` function, and +are named `acpu` and `lcpu` respectively, then their corresponding partition +names must also be `acpu` and `lcpu`. ### type - -The `type` property defines the type of the partition. It is a list of strings, and the supported types include: - -* `app_img`: The partition is used to store the program image (primary partition). The flashing tool will download the program to this address. -* `app_img2`: The partition is used to store a backup of the program image (backup partition), typically used for upgrades where it acts as a backup to the primary partition. -* `app_exec`: The partition is used to execute program code, meaning the code runs in the address space of this partition. - -Below is a description snippet for `flash5`. From the code, we can see that the `bootloader` (i.e., the secondary bootloader) is stored in `flash5`, with the address range from `0x1C020000` to `0x1C03FFFF`. At the same time, the bootloader also executes from `flash5`, meaning the storage address and execution address are the same. The program executes in-place (XIP) on `flash5`. - +The `type` property defines the type of the partition. It is a list of strings, +and the supported types include: +- `app_img`: The partition is used to store the program image (primary + partition). The flashing tool will download the program to this address. +- `app_img2`: The partition is used to store a backup of the program image + (backup partition), typically used for upgrades where it acts as a backup to + the primary partition. +- `app_exec`: The partition is used to execute program code, meaning the code + runs in the address space of this partition. + +Below is a description snippet for `flash5`. From the code, we can see that the +`bootloader` (i.e., the secondary bootloader) is stored in `flash5`, with the +address range from `0x1C020000` to `0x1C03FFFF`. At the same time, the +bootloader also executes from `flash5`, meaning the storage address and +execution address are the same. The program executes in-place (XIP) on `flash5`. ```json { "mem": "flash5", @@ -142,20 +162,26 @@ Below is a description snippet for `flash5`. From the code, we can see that the "type": ["app_img", "app_exec"] } ] -}, +}, ``` -Program partition name that are not system-reserved (i.e., `name` is not `main`, `bootloader`, `ftab`, or `dfu`) will use the following entries in the flash table to describe the image information stored in flash: - -* `DFU_FLASH_HCPU_EXT2`: 11 -* `DFU_FLASH_LCPU_EXT1`: 12 -* `DFU_FLASH_LCPU_EXT2`: 13 - -For example, in the `ptab.json` snippet below, the partition `acpu` is defined to use an offset of `0x00300000` in `flash4` as the storage address for the ACPU program, and an offset of `0x00200000` in `hpsys_ram` as the execution address. -The generated `ftab.c` file will use the `DFU_FLASH_HCPU_EXT2` entry to describe the storage and execution addresses of the ACPU image. -The `length` (i.e., the amount of data to be relocated) is determined based on the actual file size of the program specified by the `name` property (see [](#name) for details). In this example, the actual length is 0x7d4 bytes. - -````{dropdown} ACPU Program Partition Example +Program partition name that are not system-reserved (i.e., `name` is not `main`, +`bootloader`, `ftab`, or `dfu`) will use the following entries in the flash +table to describe the image information stored in flash: +- `DFU_FLASH_HCPU_EXT2`: 11 +- `DFU_FLASH_LCPU_EXT1`: 12 +- `DFU_FLASH_LCPU_EXT2`: 13 + +For example, in the `ptab.json` snippet below, the partition `acpu` is defined +to use an offset of `0x00300000` in `flash4` as the storage address for the ACPU +program, and an offset of `0x00200000` in `hpsys_ram` as the execution address. +The generated `ftab.c` file will use the `DFU_FLASH_HCPU_EXT2` entry to describe +the storage and execution addresses of the ACPU image. The `length` (i.e., the +amount of data to be relocated) is determined based on the actual file size of +the program specified by the `name` property (see [](#name) for details). In +this example, the actual length is 0x7d4 bytes. + +````{dropdown} ACPU程序分区示例 ```json { "mem": "flash4", @@ -215,16 +241,16 @@ RT_USED const struct sec_configuration sec_config = .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_LCPU_EXT2)] = {.length = 0xFFFFFFFF}, .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_RESERVED)] = {.length = 0xFFFFFFFF}, .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_SINGLE)] = {.length = 0xFFFFFFFF}, - .running_imgs[CORE_HCPU] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_HCPU)], + .running_imgs[CORE_HCPU] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_HCPU)], .running_imgs[CORE_LCPU] = (struct image_header_enc *)0xFFFFFFFF, - .running_imgs[CORE_BL] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_BL)], + .running_imgs[CORE_BL] = (struct image_header_enc *) &sec_config.imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_IMG_BL)], .running_imgs[CORE_BOOT] = (struct image_header_enc *)0xFFFFFFFF, }; ``` ### custom - -The `custom` property allows adding custom macros to `ptab.h`. The value must be a dictionary. For example: +The `custom` property allows adding custom macros to `ptab.h`. The value must be +a dictionary. For example: ```json "custom": { @@ -234,8 +260,6 @@ The `custom` property allows adding custom macros to `ptab.h`. The value must be } ``` -Generates: - ```c #define PSRAM_BL_MODE (3) #define PSRAM_BL_SIZE (8) @@ -246,19 +270,27 @@ Generates: Note: Dictionary values must be integers. ``` -Here is the English translation: - ---- - ## Default Partition Configuration +If the partition table does not define the `ftab` and `bootloader` partition +configurations, the tool will generate `ptab.h` using default settings. Users +can check the generated file to understand these defaults. In general, the +default configuration is sufficient for most application development needs. +However, users can also add `ftab` and `bootloader` configurations to the +partition table to override the default parameters. Note that `ftab` must be +placed in the correct location to ensure it can be read by the chip's Boot ROM. +The specific requirements are as follows: +- **SF32LB55X series**: Must be placed at the base address of flash1 (i.e., the + NOR Flash embedded in the high-performance core, connected to the QSPI1 + interface). +- **SF32LB58X series**: Must be placed at the base address of flash5 (i.e., the + NOR Flash embedded in the low-power core, connected to the MPI5 interface). +- **SF32LB56X series**: Must be placed at the base address of flash5 (i.e., the + NOR Flash embedded in the low-power core, connected to the MPI5 interface). +- **SF32LB52X series**: + - For chips with internal Flash, `ftab` must be placed at the base address + of the internal Flash (i.e., flash1, connected to the MPI1 interface). + - Otherwise, it should be placed at the base address of the external SPI NOR + or SPI NAND Flash. + - For eMMC, SD-NAND, and SD cards, `ftab` must be placed starting at an + offset of 0x1000. -If the partition table does not define the `ftab` and `bootloader` partition configurations, the tool will generate `ptab.h` using default settings. Users can check the generated file to understand these defaults. In general, the default configuration is sufficient for most application development needs. However, users can also add `ftab` and `bootloader` configurations to the partition table to override the default parameters. Note that `ftab` must be placed in the correct location to ensure it can be read by the chip's Boot ROM. The specific requirements are as follows: - -* **SF32LB55X series**: Must be placed at the base address of flash1 (i.e., the NOR Flash embedded in the high-performance core, connected to the QSPI1 interface). -* **SF32LB58X series**: Must be placed at the base address of flash5 (i.e., the NOR Flash embedded in the low-power core, connected to the MPI5 interface). -* **SF32LB56X series**: Must be placed at the base address of flash5 (i.e., the NOR Flash embedded in the low-power core, connected to the MPI5 interface). -* **SF32LB52X series**: - - * For chips with internal Flash, `ftab` must be placed at the base address of the internal Flash (i.e., flash1, connected to the MPI1 interface). - * Otherwise, it should be placed at the base address of the external SPI NOR or SPI NAND Flash. - * For eMMC, SD-NAND, and SD cards, `ftab` must be placed starting at an offset of 0x1000. diff --git a/docs/source/en/middleware/pm.md b/docs/source/en/middleware/pm.md index 627129a4d..536c272d8 100644 --- a/docs/source/en/middleware/pm.md +++ b/docs/source/en/middleware/pm.md @@ -1,27 +1,39 @@ - # Power Management -The Power Management module is developed based on the RT-Thread power management framework. It helps minimize the effort required for users to implement low-power functionality. -In addition to the RT-Thread power management API, users can also use this module to implement their own low-power designs. -Butterfli includes three subsystems (power domains): HPSYS (HCPU internal), LPSYS (LCPU internal), and BLESYS (BCPU internal). Each subsystem can independently enter its own low-power mode. - -Currently, four low-power modes are supported. IDLE is the lowest power mode, while STANDBY is the highest low-power mode. Starting from the LIGHT mode, subsystems are inaccessible in low-power mode. -- `PM_SLEEP_MODE_IDLE`: CPU executes the WFE instruction, waiting for events or IRQ. +The Power Management module is developed based on the RT-Thread power management +framework. It helps minimize the effort required for users to implement +low-power functionality. In addition to the RT-Thread power management API, +users can also use this module to implement their own low-power designs. +Butterfli includes three subsystems (power domains): HPSYS (HCPU internal), +LPSYS (LCPU internal), and BLESYS (BCPU internal). Each subsystem can +independently enter its own low-power mode. + +Currently, four low-power modes are supported. IDLE is the lowest power mode, +while STANDBY is the highest low-power mode. Starting from the LIGHT mode, +subsystems are inaccessible in low-power mode. +- `PM_SLEEP_MODE_IDLE`: CPU executes the WFE instruction, waiting for events or + IRQ. - `PM_SLEEP_MODE_LIGHT`: Subsystem enters light sleep mode. - `PM_SLEEP_MODE_DEEP`: Subsystem enters deep sleep mode. - `PM_SLEEP_MODE_STANDBY`: Subsystem enters standby mode. -When entering the idle loop, the RT-Thread power management framework selects the appropriate low-power mode based on how long the CPU has been idle. -The default power mode selection method uses the pm policy table to decide the low-power mode. The default pm policy table can be overridden. Additionally, the default power mode selection method can be replaced by a user-defined algorithm. -Users can block the system from entering low-power modes higher than `PM_SLEEP_MODE_IDLE` by calling `rt_pm_request`, even if the CPU has been idle for a long time, such as when DMA transfer is ongoing or a thread is suspended waiting for a completion signal. -If `PM_SLEEP_MODE_IDLE` or `PM_SLEEP_MODE_NONE` is requested, the system will stay in `PM_SLEEP_MODE_IDLE` after entering the idle loop. If `PM_SLEEP_MODE_LIGHT`, `PM_SLEEP_MODE_DEEP`, or `PM_SLEEP_MODE_STANDBY` is requested, it will not affect the low-power mode selection result. -Below is the timing diagram of the idle loop. - -![Figure 1: Idle Loop](../../assets/idle_loop.png) +When entering the idle loop, the RT-Thread power management framework selects +the appropriate low-power mode based on how long the CPU has been idle. The +default power mode selection method uses the pm policy table to decide the +low-power mode. The default pm policy table can be overridden. Additionally, the +default power mode selection method can be replaced by a user-defined algorithm. +Users can block the system from entering low-power modes higher than +`PM_SLEEP_MODE_IDLE` by calling `rt_pm_request`, even if the CPU has been idle +for a long time, such as when DMA transfer is ongoing or a thread is suspended +waiting for a completion signal. If `PM_SLEEP_MODE_IDLE` or `PM_SLEEP_MODE_NONE` +is requested, the system will stay in `PM_SLEEP_MODE_IDLE` after entering the +idle loop. If `PM_SLEEP_MODE_LIGHT`, `PM_SLEEP_MODE_DEEP`, or +`PM_SLEEP_MODE_STANDBY` is requested, it will not affect the low-power mode +selection result. Below is the timing diagram of the idle loop. ## pm_request Example -The following example demonstrates how to prevent the system from entering higher low-power modes, even when sleep time conditions are met. - +The following example demonstrates how to prevent the system from entering +higher low-power modes, even when sleep time conditions are met. ```c rt_device_t uart_device; rt_err_t tx_done(rt_device_t dev, void *buffer) @@ -51,10 +63,16 @@ void start_tx(void) ``` ## Default PM Policy Table -Following is default PM Policy Table. The threshold for sleep time is used to determine the highest power mode for low-power selection. The sleep time is calculated based on the operating system timer, i.e., the most recent timer timeout tick is compared with the current tick (using `rt_timer_next_timeout_tick()` and `rt_tick_get()`). -For example, if the sleep time is 20ms, which is greater than 15ms (threshold for `PM_SLEEP_MODE_LIGHT`) but less than 25ms (threshold for `PM_SLEEP_MODE_DEEP`), `PM_SLEEP_MODE_LIGHT` is selected as the low-power mode. -If the sleep time is 50ms, exceeding both 15ms and 25ms, the system enters `PM_SLEEP_MODE_DEEP`. +Following is default PM Policy Table. The threshold for sleep time is used to +determine the highest power mode for low-power selection. The sleep time is +calculated based on the operating system timer, i.e., the most recent timer +timeout tick is compared with the current tick (using +`rt_timer_next_timeout_tick()` and `rt_tick_get()`). For example, if the sleep +time is 20ms, which is greater than 15ms (threshold for `PM_SLEEP_MODE_LIGHT`) +but less than 25ms (threshold for `PM_SLEEP_MODE_DEEP`), `PM_SLEEP_MODE_LIGHT` +is selected as the low-power mode. If the sleep time is 50ms, exceeding both +15ms and 25ms, the system enters `PM_SLEEP_MODE_DEEP`. ```c const static pm_policy_t default_pm_policy[] = { @@ -71,35 +89,61 @@ typedef struct } pm_policy_t; ``` -## Custom RT-Thread Power Management API -- `rt_pm_policy_register`: Register user-defined policies to override default values. -- `rt_pm_override_mode_select`: Register a user-defined power mode selection method to override the default. -- `rt_pm_request/rt_pm_release`: Prevent entry into LIGHT/DEEP/STANDBY modes. -- `rt_application_get_power_on_mode`: Get the system's power-on mode, e.g., if the code was started from standby mode or woken up. - -### PM Module API -- `pm_enable_pin_wakeup/pm_disable_pin_wakeup`: Specify a pin to wake up the subsystem. -- `pm_get_power_mode`: Get the last low-power mode. -- `pm_get_wakeup_src`: Get the last wake-up source. -- `aon_irq_handler_hook`: AON IRQ handler hook function. Users can re-implement this hook to execute custom operations. -- `pm_shutdown`: Shut down the system. -## Inter-Subsystem Access -If a subsystem is in LIGHT, DEEP, or STANDBY low-power mode, other subsystems cannot access it. If an illegal access occurs, a hard fault exception is triggered. -To access resources from another subsystem in a low-power mode, the target subsystem must be awakened first. -The hardware mailbox can automatically wake up the target subsystem. Its driver implementation takes low-power features into account. -When using the hardware mailbox driver for inter-processor communication, the driver ensures memory access when the accessed subsystem is in ACTIVE or IDLE mode. -The sending driver writes data to its buffer and notifies the receiver. The sending subsystem will not enter any low-power mode other than idle until the receiving subsystem consumes the data, i.e., the sender’s ring buffer is empty. +RT-Thread Power Management APIs for Customization +- `rt_pm_policy_register`: Registers a user-defined policy to override the + default implementation. +- `rt_pm_override_mode_select`: Registers a user-defined power mode selection + method to override the default mechanism. +- `rt_pm_request/rt_pm_release`: Prevents the system from entering LIGHT, DEEP, + or STANDBY modes. +- `rt_application_get_power_on_mode`: Retrieves the system boot mode (e.g., + determining whether the code started from a cold boot or woke up from + standby). + +PM Module APIs +- `pm_enable_pin_wakeup/pm_disable_pin_wakeup`: Designates a specific pin to + wake up the subsystem. +- `pm_get_power_mode`: Retrieves the previous low-power mode. +- `pm_get_wakeup_src`: Retrieves the previous wakeup source. +- `aon_irq_handler_hook`: A hook for the AON_IRQHandler. Users can implement + this hook to perform custom operations. +- pm_shutdown: Shuts down the system. -## Configuration -This module can be enabled in the SiFli Middleware menu, which automatically enables RT_USING_PM. +## Custom RT-Thread Power Management API +If a subsystem is in LIGHT, DEEP, or STANDBY low-power mode, it becomes +inaccessible to other subsystems. Any illegal access will trigger a HardFault +exception.
To access resources belonging to another subsystem in low-power +mode, that subsystem must be awakened first. The hardware Mailbox can +automatically wake up the target subsystem, and its driver implementation is +designed with low-power characteristics in mind. When using the hardware Mailbox +driver for inter-processor communication, the driver ensures that memory +accesses only occur when the accessed subsystem is in ACTIVE or IDLE mode. The +sender driver writes data to its own buffer and notifies the receiver. The +sending subsystem will not enter any low-power mode (except IDLE) until the +receiver consumes the data and the sender's ring buffer is empty. +## Inter-Subsystem Access +If a subsystem is in LIGHT, DEEP, or STANDBY low-power mode, other subsystems +cannot access it. If an illegal access occurs, a hard fault exception is +triggered. To access resources from another subsystem in a low-power mode, the +target subsystem must be awakened first. The hardware mailbox can automatically +wake up the target subsystem. Its driver implementation takes low-power features +into account. When using the hardware mailbox driver for inter-processor +communication, the driver ensures memory access when the accessed subsystem is +in ACTIVE or IDLE mode. The sending driver writes data to its buffer and +notifies the receiver. The sending subsystem will not enter any low-power mode +other than idle until the receiving subsystem consumes the data, i.e., the +sender’s ring buffer is empty. ```c #define BSP_USING_PM #define RT_USING_PM ``` -![Figure 2: Enabling Low Power Support in Middleware](../../assets/pm_menu2.png) +![Figure 2: Enabling low-power support in middleware](../../assets/pm_menu2.png) -## API Reference -[bf0_pm.h](middleware-bf0_pm) + + +## Configuration +This module can be enabled in the SiFli Middleware menu, which automatically +enables RT_USING_PM. diff --git a/docs/source/en/middleware/security.md b/docs/source/en/middleware/security.md index ecbf4e5b9..a5fed1dbd 100644 --- a/docs/source/en/middleware/security.md +++ b/docs/source/en/middleware/security.md @@ -1,48 +1,83 @@ # 52x Platform Security Solution -The security solution based on the 52x platform mainly includes four components: secure boot, security isolation, secure storage, and secure upgrade. The following provides detailed explanations of secure boot and security isolation. +The security solution based on the 52x platform mainly includes four components: +secure boot, security isolation, secure storage, and secure upgrade. The +following provides detailed explanations of secure boot and security isolation. ## Secure Boot -Secure boot protects certain system components of the product from both software and hardware perspectives, preventing attackers from reading or writing to critical system parts, thereby achieving commercial confidentiality and intellectual property protection purposes. -The 52x secure boot task executes in the bootloader. When the bootloader starts, it reads the rootkey and uid from efuse, decrypts and verifies the digital signature of the image. If verification passes, it jumps to execute the image program. If verification fails, it prints failure information and enters exception handling. +Secure boot protects certain system components of the product from both software +and hardware perspectives, preventing attackers from reading or writing to +critical system parts, thereby achieving commercial confidentiality and +intellectual property protection purposes. The 52x secure boot task executes in +the bootloader. When the bootloader starts, it reads the rootkey and uid from +efuse, decrypts and verifies the digital signature of the image. If verification +passes, it jumps to execute the image program. If verification fails, it prints +failure information and enters exception handling. ### Secure Boot Requirements - Should start execution from immutable code. -- Should have signature verification mechanisms for trusted system components, trusted application components, or other security subsystems. -- Should have integrity verification mechanisms for trusted system components, trusted application components, or other security subsystems to prevent illegal tampering. +- Should have signature verification mechanisms for trusted system components, + trusted application components, or other security subsystems. +- Should have integrity verification mechanisms for trusted system components, + trusted application components, or other security subsystems to prevent + illegal tampering. - Should have exception handling mechanisms for the secure boot process. ### Secure Boot Keys The keys and data used in secure boot include: -- rootkey: Stored in the unreadable area BANK3 of efuse, used to encrypt the image key. -- uid: Chip ID, stored in the readable area BANK0 of efuse, used as nonce for image key decryption. -- image key: Randomly generated 32-byte data, encrypted with rootkey and stored in ftab, used for image decryption. -- RSA digital signature public key: Stored in ftab, used to verify image identity and integrity. -- RSA public key hash value: Hash value of the RSA digital signature public key, with the first 8 bytes stored in efuse readable area BANK0, used as nonce for image decryption and RSA digital signature public key integrity verification. -- image hash value digital signature: Digital signature obtained by calculating the hash of the image plaintext and signing the hash value with RSA private key, stored in ftab, used to verify image identity and integrity. - +- rootkey: Stored in the unreadable area BANK3 of efuse, used to encrypt the + image key. +- uid: Chip ID, stored in the readable area BANK0 of efuse, used as nonce for + image key decryption. +- image key: Randomly generated 32-byte data, encrypted with rootkey and stored + in ftab, used for image decryption. +- RSA digital signature public key: Stored in ftab, used to verify image + identity and integrity. +- RSA public key hash value: Hash value of the RSA digital signature public key, + with the first 8 bytes stored in efuse readable area BANK0, used as nonce for + image decryption and RSA digital signature public key integrity verification. +- image hash value digital signature: Digital signature obtained by calculating + the hash of the image plaintext and signing the hash value with RSA private + key, stored in ftab, used to verify image identity and integrity. + ### Secure Boot Loading Process 1. Get image header, determine if it's an encrypted image through flag. -2. RSA public key hash verification: Read RSA public key from ftab, calculate hash to get hash value, read sig_hash from efuse, compare the two for verification. If verification succeeds, continue; if fails, enter exception handling. +2. RSA public key hash verification: Read RSA public key from ftab, calculate + hash to get hash value, read sig_hash from efuse, compare the two for + verification. If verification succeeds, continue; if fails, enter exception + handling. 3. Determine whether to execute image program in flash. -4. If running in flash, first read encrypted image key from ftab, read rootkey and uid from efuse, decrypt image key, then configure the decrypted imagekey to flash xip. -5. If executing in RAM, first read encrypted image key from ftab, read rootkey and uid from efuse, decrypt image key, then copy encrypted image to RAM and decrypt the encrypted image using image key. -6. Verify the digital signature and integrity of the image. If verification succeeds, jump to execute image program; if fails, enter exception handling. The digital signature is generated by calculating the hash of the plaintext image and digitally signing the calculated hash value with RSA private key, then writing the signed value to ftab. - +4. If running in flash, first read encrypted image key from ftab, read rootkey + and uid from efuse, decrypt image key, then configure the decrypted imagekey + to flash xip. +5. If executing in RAM, first read encrypted image key from ftab, read rootkey + and uid from efuse, decrypt image key, then copy encrypted image to RAM and + decrypt the encrypted image using image key. +6. Verify the digital signature and integrity of the image. If verification + succeeds, jump to execute image program; if fails, enter exception handling. + The digital signature is generated by calculating the hash of the plaintext + image and digitally signing the calculated hash value with RSA private key, + then writing the signed value to ftab. #### Digital signature and integrity verification consists of the following steps: - Calculate hash of the decrypted image to get image hash value. -- Read digital signature data value and RSA digital signature public key from ftab. -- Call the verify interface provided by mbedtls library, pass in image hash value, digital signature data value, and digital signature public key for verification. Non-zero return value indicates verification failure, zero return value indicates verification success. +- Read digital signature data value and RSA digital signature public key from + ftab. +- Call the verify interface provided by mbedtls library, pass in image hash + value, digital signature data value, and digital signature public key for + verification. Non-zero return value indicates verification failure, zero + return value indicates verification success. ### Secure Boot Flowcharts ![Figure 1: Secure Boot Process](../../assets/sf52x_seboot_launch_image.png) -![Figure 2: RSA Public Key Hash Verification](../../assets/sf52x_seboot_sigkey_hash.png) -![Figure 3: Image Decryption](../../assets/sf52x_dec_image.png) -![Figure 4: Image Digital Signature Integrity Verification](../../assets/sf52x_image_dig_sig_ver.png) +![Figure 2: RSA Public Key Hash +Verification](../../assets/sf52x_seboot_sigkey_hash.png) ![Figure 3: Image +Decryption](../../assets/sf52x_dec_image.png) ![Figure 4: Image Digital +Signature Integrity Verification](../../assets/sf52x_image_dig_sig_ver.png) ### Secure Boot Code Code path: _$SDK_ROOT\example\boot_loader\project\butterflmicro\board_ \ -secboot.c: Image digital signature integrity verification, secboot exception handling.\ +secboot.c: Image digital signature integrity verification, secboot exception +handling.\ efuse.c: Efuse reading, encrypted imagekey and encrypted image decryption.\ main.c: Image copy loading. @@ -52,23 +87,23 @@ int sifli_hash_calculate(uint8_t *in, uint32_t in_size, uint8_t *out, uint8_t al { int last, i; - if (!in || !in_size || !out || algo > 3) + if (!in || !in_size || !out || algo > 3) return -1; HAL_HASH_reset(); HAL_HASH_init(NULL, algo, 0); - if (in_size > SPLIT_THRESHOLD) + if (in_size > SPLIT_THRESHOLD) { - for (i = 0; i < in_size; i += SPLIT_THRESHOLD) + for (i = 0; i < in_size; i += SPLIT_THRESHOLD) { - last = (i + SPLIT_THRESHOLD >= in_size) ? 1 : 0; - if (i > 0) + last = (i + SPLIT_THRESHOLD >= in_size) ? 1 : 0; + if (i > 0) { HAL_HASH_reset(); HAL_HASH_init((uint32_t *)out, algo, last ? i : 0); } - HAL_HASH_run(&in[i], last ? in_size - i : SPLIT_THRESHOLD, last); + HAL_HASH_run(&in[i], last ? in_size - i : SPLIT_THRESHOLD, last); HAL_HASH_result(out); } HAL_HASH_result(out); @@ -118,7 +153,7 @@ int sifli_hw_dec_key(uint8_t *in_data, uint8_t *out_data, int size) uint8_t *uid; uint8_t *key = NULL; - uid = &g_uid[0]; + uid = &g_uid[0]; sifli_hw_efuse_read(EFUSE_UID, uid, DFU_UID_SIZE); HAL_AES_init((uint32_t *)key, DFU_KEY_SIZE, (uint32_t *)uid, AES_MODE_CBC); HAL_AES_run(AES_DEC, in_data, out_data, DFU_KEY_SIZE); @@ -135,9 +170,9 @@ int sifli_hw_dec(uint8_t *key, uint8_t *in_data, uint8_t *out_data, int size, ui static uint8_t temp[AES_BLOCK_SIZE]; memset(temp, 0, AES_BLOCK_SIZE); - while (offset < size) + while (offset < size) { - int len = (size - offset) < AES_BLOCK_SIZE ? (size - offset) : AES_BLOCK_SIZE; + int len = (size - offset) < AES_BLOCK_SIZE ? (size - offset) : AES_BLOCK_SIZE; memcpy(temp, in_data + offset, len); HAL_AES_init((uint32_t *)key, DFU_KEY_SIZE, (uint32_t *)dfu_get_counter(init_offset + offset), AES_MODE_CTR); HAL_AES_run(AES_DEC, temp, out_data + offset, len); @@ -147,6 +182,7 @@ int sifli_hw_dec(uint8_t *key, uint8_t *in_data, uint8_t *out_data, int size, ui } ``` + Image hash digital signature integrity verification code: ```c int sifli_img_sig_hash_verify(uint8_t *img_hash_sig, uint8_t *sig_pub_key, uint8_t *image, uint32_t img_size) @@ -154,16 +190,16 @@ int sifli_img_sig_hash_verify(uint8_t *img_hash_sig, uint8_t *sig_pub_key, uint8 uint8_t img_hash[32] = {0}; mbedtls_pk_context pk; - /*1.calculate image hash*/ + /*1. Calculate image hash*/ if (sifli_hash_calculate(image, img_size, img_hash, HASH_ALGO_SHA256)) return -1; - - /*2.verify image hash digital signature*/ - mbedtls_pk_init(&pk); - if (mbedtls_pk_parse_public_key(&pk, sig_pub_key, DFU_SIG_KEY_SIZE)) + + /*2. Verify image hash digital signature*/ + mbedtls_pk_init(&pk); + if (mbedtls_pk_parse_public_key(&pk, sig_pub_key, DFU_SIG_KEY_SIZE)) return -1; mbedtls_rsa_set_padding((mbedtls_rsa_context *)pk.pk_ctx, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256); - if (mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, img_hash, DFU_IMG_HASH_SIZE, img_hash_sig, DFU_SIG_SIZE)) + if (mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, img_hash, DFU_IMG_HASH_SIZE, img_hash_sig, DFU_SIG_SIZE)) return -1; return 0; @@ -197,16 +233,22 @@ void sifli_secboot_exception(uint8_t excpt) ``` ### Secure Encrypted Image Generation -Script path for generating encrypted images: _$SDK_ROOT\\example\\security\\hcpu\\project\\eh-lb525\\secboot_ +Script path for generating encrypted images: +_$SDK_ROOT\\example\\security\\hcpu\\project\\eh-lb525\\secboot_ -The encryption script uses keys from the default directory secboot/sifli01. -Keys and data used for generating encrypted images include: +The encryption script uses keys from the default directory secboot/sifli01. Keys +and data used for generating encrypted images include: - rootkey: 32-byte key provided by customer, used to encrypt image key. -- uid: Chip ID, burned to efuse BANK0 during chip factory production. Before running encryption script, uid must be read from efuse and saved as uid.bin file, used as nonce for image key encryption. -- image key: Randomly generated 32-byte data, used for image encryption before encryption, stored in ftab after encryption. -- RSA digital signature private key: Provided by customer, used to digitally sign image hash values. +- uid: Chip ID, burned to efuse BANK0 during chip factory production. Before + running encryption script, uid must be read from efuse and saved as uid.bin + file, used as nonce for image key encryption. +- image key: Randomly generated 32-byte data, used for image encryption before + encryption, stored in ftab after encryption. +- RSA digital signature private key: Provided by customer, used to digitally + sign image hash values. - RSA digital signature public key: Provided by customer, stored in ftab. -- RSA digital signature public key hash value: Hash calculated from RSA digital signature public key, with first 8 bytes used as nonce for image encryption. +- RSA digital signature public key hash value: Hash calculated from RSA digital + signature public key, with first 8 bytes used as nonce for image encryption. Files needed for generating encrypted images: - _build/bf0_ap.bin_ Plaintext unencrypted image generated by compilation. @@ -216,50 +258,117 @@ Run encryption script in project directory: ```bat ./secboot/gen_sec_img.bat ``` -After successful script execution, an image_sec directory will be created in the secboot directory, containing the encrypted image (image_sec.bin) and newly generated ftab (ftab_sec.bin). +After successful script execution, an image_sec directory will be created in the +secboot directory, containing the encrypted image (image_sec.bin) and newly +generated ftab (ftab_sec.bin). Execute download script in project directory: ```bat ./secboot/uart_download.bat ``` -Press the reset button on the development board, execute the script `uart_download.bat`. After successful execution, _bootloader.bin_, _image_sec.bin_, _ftab_sec.bin_ will be downloaded to flash. +Press the reset button on the development board, execute the script +`uart_download.bat`. After successful execution, _bootloader.bin_, +_image_sec.bin_, _ftab_sec.bin_ will be downloaded to flash. + ## Security Isolation ### sf52x Security Isolation Solution Introduction -The sf52x security solution is designed based on the secu management module. sf52x contains two secu modules, secu1 and secu2, located in the big core system and small core system respectively. By configuring the secu modules, the security attributes of various master and slave peripherals can be managed. Here, master refers to devices that actively initiate access requests, such as CPU, DMA, etc., while slave refers to devices that receive access requests, such as PTC, DMA, efuse, etc. - -The sf52x security solution uses the small core as the security core, always running in secure state, while the big core runs in both secure and non-secure states. The NMI interrupt serves as the entry point for big core security. When security tasks need to be executed, the big core sends a request to the small core (to enter secure state). After inspection and verification by the small core, it sets the big core to secure state and triggers the big core's NMI interrupt. The big core enters the NMI interrupt function, accesses the secure code area, and after the security task completes, the big core sets itself to non-secure state and exits the secure code area. When the big core is in non-secure state, it cannot access code in the secure area, nor can it access the secure code area in the small core system. +The sf52x security solution is designed based on the secu management module. +sf52x contains two secu modules, secu1 and secu2, located in the big core system +and small core system respectively. By configuring the secu modules, the +security attributes of various master and slave peripherals can be managed. +Here, master refers to devices that actively initiate access requests, such as +CPU, DMA, etc., while slave refers to devices that receive access requests, such +as PTC, DMA, efuse, etc. + +The sf52x security solution uses the small core as the security core, always +running in secure state, while the big core runs in both secure and non-secure +states. The NMI interrupt serves as the entry point for big core security. When +security tasks need to be executed, the big core sends a request to the small +core (to enter secure state). After inspection and verification by the small +core, it sets the big core to secure state and triggers the big core's NMI +interrupt. The big core enters the NMI interrupt function, accesses the secure +code area, and after the security task completes, the big core sets itself to +non-secure state and exits the secure code area. When the big core is in +non-secure state, it cannot access code in the secure area, nor can it access +the secure code area in the small core system. The sf52x security isolation process can be referenced in the following diagram: ![Figure 5: sf52x Security Isolation](../../assets/sf52x_security.png) ### sf52x Security Solution Software Introduction -The sf52x security solution code is developed based on sdk2.1.4, with code path in _$SDK_ROOT\middleware\\security\\sf52x_ directory, divided into hcpu and lcpu parts. hcpu mainly implements the configuration of big and small core security environments, management of big core security code, and security code trigger interfaces; lcpu is mainly responsible for auditing whether the big core enters secure state and triggering NMI interrupts. - -_security.c_ in the hcpu directory implements the establishment of big and small core security environments, including configuration of big core secure code area, configuration of small core system entering secure mode, big core exiting secure mode interfaces, and writing of big and small core security shared data. The big core secure code area contains two parts: the first part is the secure code area, storing code and data; the other part is the shared area for big and small core security data, which the small core can access at any time, and the big core can only access when in secure state. The size of the big core secure code area can be configured, currently defaulting to 100kb of RAM space located on sram2, with the security data shared area fixed at 128 bytes, no need to modify the size. - -_sec_entry.c_ implements the interrupt entry point for security code. All security code runs in NMI interrupts, and security code interfaces are also added to this file. All security code including code in this file will be linked to the secure code area. -_sec_task.c_ implements the security task trigger interface `sec_task_enter()`. When hcpu in non-secure mode wants to switch to secure mode to run security code, it needs to call this interface. This interface is mutually exclusive in multithreaded calls, with the thread that first obtains the mutex running security area code first. This interface is a blocking call, only exiting after security code execution completes. - -_security.c_ in the Lcpu directory implements arbitration for hcpu entering secure mode. When receiving a request for hcpu to enter secure mode, it first checks whether the hcpu vector register and NMI interrupt function entry value in the interrupt vector table have been tampered with. If tampered, it will reject the hcpu's request to enter secure mode; if not tampered, it will set hcpu to secure mode and trigger hcpu's NMI interrupt. - -The encrypt_demo directory contains security code samples, simply implementing several security interfaces such as random number generation, AES encryption, and hash calculation. +The sf52x security solution code is developed based on sdk2.1.4, with code path +in _$SDK_ROOT\middleware\\security\\sf52x_ directory, divided into hcpu and lcpu +parts. hcpu mainly implements the configuration of big and small core security +environments, management of big core security code, and security code trigger +interfaces; lcpu is mainly responsible for auditing whether the big core enters +secure state and triggering NMI interrupts. + +_security.c_ in the hcpu directory implements the establishment of big and small +core security environments, including configuration of big core secure code +area, configuration of small core system entering secure mode, big core exiting +secure mode interfaces, and writing of big and small core security shared data. +The big core secure code area contains two parts: the first part is the secure +code area, storing code and data; the other part is the shared area for big and +small core security data, which the small core can access at any time, and the +big core can only access when in secure state. The size of the big core secure +code area can be configured, currently defaulting to 100kb of RAM space located +on sram2, with the security data shared area fixed at 128 bytes, no need to +modify the size. + +_sec_entry.c_ implements the interrupt entry point for security code. All +security code runs in NMI interrupts, and security code interfaces are also +added to this file. All security code including code in this file will be linked +to the secure code area. _sec_task.c_ implements the security task trigger +interface `sec_task_enter()`. When hcpu in non-secure mode wants to switch to +secure mode to run security code, it needs to call this interface. This +interface is mutually exclusive in multithreaded calls, with the thread that +first obtains the mutex running security area code first. This interface is a +blocking call, only exiting after security code execution completes. + +_security.c_ in the Lcpu directory implements arbitration for hcpu entering +secure mode. When receiving a request for hcpu to enter secure mode, it first +checks whether the hcpu vector register and NMI interrupt function entry value +in the interrupt vector table have been tampered with. If tampered, it will +reject the hcpu's request to enter secure mode; if not tampered, it will set +hcpu to secure mode and trigger hcpu's NMI interrupt. + +The encrypt_demo directory contains security code samples, simply implementing +several security interfaces such as random number generation, AES encryption, +and hash calculation. ### sf52x Security Isolation Software Interface Usage #### 1. How to Add Security Code to Security Protection Area -Adding security code can refer to lines 55 to 57 in _$SDK_ROOT\\security\\sf52x\\hcpu\\sec_entry.c_. First, define SEC_ENTRY_IDX_XX for each interface according to the security code interface functionality. The ID number is an enumeration type, defined in sec_entry.h. +Adding security code can refer to lines 55 to 57 in +_$SDK_ROOT\\security\\sf52x\\hcpu\\sec_entry.c_. First, define SEC_ENTRY_IDX_XX +for each interface according to the security code interface functionality. The +ID number is an enumeration type, defined in sec_entry.h. ![](../../assets/sf52x_sec_entry.png) -Second, write security entry functions, such as int sec_entry_xxx(void *arg). This function parses passed parameters and calls corresponding security code interfaces. -![](../../assets/sf52x_sec_entry1.png) +Second, write security entry functions, such as int sec_entry_xxx(void *arg). +This function parses passed parameters and calls corresponding security code +interfaces. ![](../../assets/sf52x_sec_entry1.png) -Third, modify the linker file to link added security code to the security protection area. The linker file is in directory _$SDK_ROOT\\example\\security\\hcpu\\project\\eh-lb525\\linker_scripts_. Open _link_flash.sct_, find NMI_SEC_AREA, and add security code to the section. +Third, modify the linker file to link added security code to the security +protection area. The linker file is in directory +_$SDK_ROOT\\example\\security\\hcpu\\project\\eh-lb525\\linker_scripts_. Open +_link_flash.sct_, find NMI_SEC_AREA, and add security code to the section. ![](../../assets/sf52x_sec_entry2.png) #### 2. How hcpu Enters Secure State to Run Security Code -The interface for hcpu to enter secure state and run security code is in _sec_task.c_: `int sec_task_enter(sec_task_list_t * sec_tls)`. Interface usage can refer to `sec_demo1` in _security_demo.c_. First, prepare parameters required for security interface execution, fill the security interface ID and corresponding parameters into `sec_task_list`, note to fill in the total number of interfaces to run `task_cnt`. `sec_task_list` can fill up to 32 interfaces, which can be extended. Finally, call `sec_task_enter()`, and security interfaces in `sec_task_list` will execute sequentially according to the filled order. - -Note that security code execution occurs in NMI interrupts. NMI interrupts have relatively high priority and will not be interrupted by other interrupts, so NMI interrupt execution time should not be too long. It's best not to add printing in interrupts, and not to call sleep or long-delay functions. +The interface for hcpu to enter secure state and run security code is in +_sec_task.c_: `int sec_task_enter(sec_task_list_t * sec_tls)`. Interface usage +can refer to `sec_demo1` in _security_demo.c_. First, prepare parameters +required for security interface execution, fill the security interface ID and +corresponding parameters into `sec_task_list`, note to fill in the total number +of interfaces to run `task_cnt`. `sec_task_list` can fill up to 32 interfaces, +which can be extended. Finally, call `sec_task_enter()`, and security interfaces +in `sec_task_list` will execute sequentially according to the filled order. + +Note that security code execution occurs in NMI interrupts. NMI interrupts have +relatively high priority and will not be interrupted by other interrupts, so NMI +interrupt execution time should not be too long. It's best not to add printing +in interrupts, and not to call sleep or long-delay functions. Example of triggering entry into secure mode to run security code: ```c @@ -267,108 +376,108 @@ static struct trng_gen_arg trng; static struct hash_encrypt_arg hash; static struct aes_encrypt_arg aes; static sec_task_list_t sec_tls; -/*exe sec task, contain SEC_ENTRY_ID1_T/SEC_ENTRY_ID2_T/SEC_ENTRY_ID3_T*/ +/*Execute security tasks, including SEC_ENTRY_ID1_T/SEC_ENTRY_ID2_T/SEC_ENTRY_ID3_T*/ static void sec_demo1(uint8_t argc, char **argv) { - /*1.generate 1kb random num*/ - rt_memset(&trng, 0, sizeof(struct trng_gen_arg)); + /*1. Generate 1KB random number*/ + rt_memset(&trng, 0, sizeof(struct trng_gen_arg)); trng.random = rt_calloc(1, 1024); trng.random_num = 1024 / 4; - /*prepare sec task list*/ + /*Prepare security task list*/ sec_tls.task[0].id = SEC_ENTRY_ID1_RTNG_GEN; - sec_tls.task[0].arg = &trng; + sec_tls.task[0].arg = &trng; sec_tls.task_cnt = 1; - /*exe sec task, it will block in this function until sec task exe done*/ - sec_task_enter(&sec_tls); + /*Execute security task; blocks until the task completion*/ + sec_task_enter(&sec_tls); if (trng.complete) { LOG_I("trng generate complete"); - for (int i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { LOG_I("0x%x ", trng.random[i]); } } - /*2.aes encrypt 1kb random number*/ - rt_memset(&aes, 0, sizeof(struct aes_encrypt_arg)); + /*2. Encrypt 1KB random number using AES*/ + rt_memset(&aes, 0, sizeof(struct aes_encrypt_arg)); aes.aes_mode = AES_MODE_CTR; aes.input = (uint8_t *)trng.random; aes.size = 1024; aes.output = rt_calloc(1, aes.size); sec_tls.task[0].id = SEC_ENTRY_ID3_AES_ENC; - sec_tls.task[0].arg = &aes; + sec_tls.task[0].arg = &aes; sec_tls.task_cnt = 1; - sec_task_enter(&sec_tls); + sec_task_enter(&sec_tls); if (aes.complete) { LOG_I("aes encrypt complete"); - for (int i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { LOG_I("0x%x ", ((uint32_t *)aes.output)[i]); } } - /*3.hash 1kb aes encrypt data*/ - rt_memset(&hash, 0, sizeof(struct hash_encrypt_arg)); + /*3. Hash 1KB AES-encrypted data*/ + rt_memset(&hash, 0, sizeof(struct hash_encrypt_arg)); hash.input = (uint8_t *)aes.output; hash.in_size = 1024; hash.output = rt_calloc(1, HASH_SHA256_SIZE); hash.algo = HASH_ALGO_SHA256; sec_tls.task[0].id = SEC_ENTRY_ID2_HASH_ENC; - sec_tls.task[0].arg = &hash; + sec_tls.task[0].arg = &hash; sec_tls.task_cnt = 1; - sec_task_enter(&sec_tls); + sec_task_enter(&sec_tls); if (hash.complete) { LOG_I("hash encrypt complete"); - for (int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { LOG_I("0x%x ", ((uint32_t *)hash.output)[i]); } } - /*4.write data to nand flash, Write 2kb at most at one time*/ + /*4. Write data to NAND flash (max 2KB per operation)*/ rt_nand_erase(FLASH_SEC_DATA_START_ADDR, 1024 * 128); rt_nand_write_page(FLASH_SEC_DATA_START_ADDR, (uint8_t *)trng.random, 1024, NULL, 0); rt_nand_write_page(FLASH_SEC_DATA_START_ADDR + SPI_NAND_PAGE_SIZE, aes.output, 1024, NULL, 0); rt_nand_write_page(FLASH_SEC_DATA_START_ADDR + SPI_NAND_PAGE_SIZE * 2, hash.output, 32, NULL, 0); - /*5.read data from nand flash and check*/ + /*5. Read and verify data from NAND flash*/ uint8_t *random_data = rt_calloc(1, 1024); rt_nand_read_page(FLASH_SEC_DATA_START_ADDR, random_data, 1024, NULL, 0); if (rt_memcmp((void *)trng.random, (void *)random_data, 1024)) { - LOG_E("read random_data compare err"); + LOG_E("random_data verification failed"); } else { - LOG_E("read random_data compare succ"); + LOG_E("random_data verification successful"); } uint8_t *aes_data = rt_calloc(1, 1024); rt_nand_read_page(FLASH_SEC_DATA_START_ADDR + SPI_NAND_PAGE_SIZE, aes_data, 1024, NULL, 0); if (rt_memcmp((void *)aes.output, (void *)aes_data, 1024)) { - LOG_E("read aes_data compare err"); + LOG_E("aes_data verification failed"); } else { - LOG_E("read aes_data compare succ"); + LOG_E("aes_data verification successful"); } uint8_t *hash_data = rt_calloc(1, 32); rt_nand_read_page(FLASH_SEC_DATA_START_ADDR + SPI_NAND_PAGE_SIZE * 2, hash_data, 32, NULL, 0); if (rt_memcmp((void *)hash.output, (void *)hash_data, 32)) { - LOG_E("read hash_data compare err"); + LOG_E("hash_data verification failed"); } else { - LOG_E("read hash_data compare succ"); + LOG_E("hash_data verification successful"); } - /*6.free buffer*/ + /*6. Release buffers*/ rt_free((void *)trng.random); rt_free((void *)aes.output); rt_free((void *)hash.output); @@ -376,4 +485,4 @@ static void sec_demo1(uint8_t argc, char **argv) rt_free(aes_data); rt_free(hash_data); } -``` \ No newline at end of file +``` diff --git a/docs/source/en/middleware/share_preference.md b/docs/source/en/middleware/share_preference.md index 96046ffc4..fe43bf6c0 100644 --- a/docs/source/en/middleware/share_preference.md +++ b/docs/source/en/middleware/share_preference.md @@ -1,9 +1,11 @@ - # Configuration Storage ## Introduction -Configuration Storage (`Shared Preferences`) is a lightweight storage interface on the Android platform. It is a key-value style database suitable for storing small amounts of application data (such as configuration information) and shared configuration information between applications. +Configuration Storage (`Shared Preferences`) is a lightweight storage interface +on the Android platform. It is a key-value style database suitable for storing +small amounts of application data (such as configuration information) and shared +configuration information between applications. - Built-in semaphore, thread-safe - Does not support interrupt calls @@ -11,10 +13,12 @@ Configuration Storage (`Shared Preferences`) is a lightweight storage interface ## Enable the Module -The configuration menu path in `menuconfig` is: `SiFli Middleware -> Enable share preference` +The configuration menu path in `menuconfig` is: `SiFli Middleware -> Enable +share preference` ## Usage -Below is an example of the alarm application obtaining and storing the alarm list: +Below is an example of the alarm application obtaining and storing the alarm +list: ```c typedef struct{ @@ -58,5 +62,7 @@ void app_alarm_main(int argc, char **argv) } ``` + + ## API Reference [share_prefs.h](middleware-share_prefs) diff --git a/docs/source/en/middleware/video.md b/docs/source/en/middleware/video.md index a35a2f75b..153ca4aed 100644 --- a/docs/source/en/middleware/video.md +++ b/docs/source/en/middleware/video.md @@ -1,38 +1,60 @@ # Video Document -video use ffmpeg,see exernal/ffmpeg/Kconfig,use software decode only, no harware accelerator,video should convert codec to h264 or mjpeg, and should use baseline profile。 and support ezip encoder for this chip,Use hardware decoding for ezip. Ezip does not support inter-frame compression, meaning each image is compressed with ezip individually. Combined with audio, it still uses MP4 packaging, and the external interface remains unchanged. +video use ffmpeg,see exernal/ffmpeg/Kconfig,use software decode only, no harware +accelerator,video should convert codec to h264 or mjpeg, and should use baseline +profile。 and support ezip encoder for this chip,Use hardware decoding for ezip. +Ezip does not support inter-frame compression, meaning each image is compressed +with ezip individually. Combined with audio, it still uses MP4 packaging, and +the external interface remains unchanged. ## memory footprint -code size: 310K bytes -global var size: 1K bytes -malloc: 3.3M byte 240 * 320 (3 frame cache). +code size: 310K bytes global var size: 1K bytes malloc: 3.3M byte 240 * 320 (3 +frame cache). ## performance -- The maximum playback size around 240 * 320 can reach 30fps. If it’s larger, the frame rate needs to be reduced. It also depends on the complexity of the image details; if the details are too complex, the compression rate is low and decoding slowly. -- The previous software required the width of the converted video to be a multiple of 16. (Otherwise, there will be display artifacts, because after decoding with ffmpeg, each line is padded to align to a multiple of 16, which reduces performance as data has to be copied line by line from ffmpeg to display correctly) +- The maximum playback size around 240 * 320 can reach 30fps. If it’s larger, + the frame rate needs to be reduced. It also depends on the complexity of the + image details; if the details are too complex, the compression rate is low and + decoding slowly. +- The previous software required the width of the converted video to be a + multiple of 16. (Otherwise, there will be display artifacts, because after + decoding with ffmpeg, each line is padded to align to a multiple of 16, which + reduces performance as data has to be copied line by line from ffmpeg to + display correctly) ## suupored codec - - h264 - - h263 - - mp3 - - aac - - mjpeg + - H.264 + - H.263 + - MP3 + - AAC + - MJPEG - ezip - - opus - - vorbis + - Opus + - Vorbis ## Supported audio and video container formats - - ogg - - mp4 + - OGG + - MP4 ## menuconfig -You need to enable PKG_USING_FFMPEG in menuconfig to support ffmpeg. To support audio in mp4 files, you also need to enable PKG_USING_FFMPEG_AUDIO. To support online videos, you need to enable PKG_USING_FFMPEG_HTTP. To support mjpeg, enable PKG_USING_FFMPEG_MJPEG (hardware decoding is only available on the 58x chip platform; software decoding is not recommended). +You need to enable PKG_USING_FFMPEG in menuconfig to support ffmpeg. To support +audio in mp4 files, you also need to enable PKG_USING_FFMPEG_AUDIO. To support +online videos, you need to enable PKG_USING_FFMPEG_HTTP. To support mjpeg, +enable PKG_USING_FFMPEG_MJPEG (hardware decoding is only available on the 58x +chip platform; software decoding is not recommended). ![](./png/menuconfig_ffmpeg.png) + ## toolchain -Video files are usually large and the formats can be quite complex, so they need to be converted before they can be played. +Video files are usually large and the formats can be quite complex, so they need +to be converted before they can be played. ### ffmpeg toolchain - https://ffmpeg.org +https://ffmpeg.org * Video conversion, trimming, and scaling tool ffmpeg.exe * probe tool ffprobe.exe - * player tools ffplay.exe -This is generally used for local debugging, an example -![](./png/ffprobe.png) -high means High-quality encoding format, this software cannot support decoding it and needs to be converted to baseline. -example: + * player tools ffplay.exe\ + This is generally used for local debugging, an example ![]{1} high means + High-quality encoding format, this software cannot support decoding it and + needs to be converted to baseline. example: + +use ffprobe.exe to probe,use ffplay.exe to play + +The "high" profile indicates a high-quality encoding format that is not +supported; it must be converted to the "baseline" profile. Use the following +local conversion command: ```python # ffmpeg -i input.mp4 -profile:v baseline -level 1.0 -r 30 -acodec mp3 -ar 44100 -ac 2 output.mp4 @@ -47,24 +69,36 @@ ffmpeg -i input.mp4 -profile:v baseline -level 1.0 -r 30 -acodec mp3 -ar 44100 - # to mjpeg ffmpeg -i input.mp4 -c:v mjpeg -c:a copy -vf "colorspace=bt709:iall=bt470bg:range=pc" video_example.mp4 ``` -use ffprobe.exe to probe,use ffplay.exe to play + +After conversion, use ffprobe.exe to verify the file format or ffplay.exe to +test playback. + ### Sifli toolchain - An image conversion tool built on the official FFmpeg toolchain. Instructions for use are provided in the documentation under the tool. - GraphicsTool https://wiki.sifli.com/tools/index.html - If you want to convert to the ezip image encoding format, you can only use this tool. - EZIP format cannot be played with ffplay.exe; it can only be played on the board. +An image conversion tool built on the official FFmpeg toolchain. Instructions +for use are provided in the documentation under the tool. GraphicsTool +https://wiki.sifli.com/tools/index.html If you want to convert to the ezip image +encoding format, you can only use this tool. EZIP format cannot be played with +ffplay.exe; it can only be played on the board. + ## Viedo convert -- Video conversion can use the official ffmpeg tool mentioned above (does not support ezip) or the Sifli toolchain. For using the official tool, you can check the help with ffmpeg -h or ffmpeg -h full, or you can search online for commonly used ffmpeg commands. -- The required converted width is a multiple of 16, and the encoding format is baseline. -## example -- local file player: -It turns out that the disk directory contains an empty file, which needs to be replaced with the converted baseline format MP4 file. -https://gitee.com/SiFli/sifli-sdk/tree/main/example/multimedia/lvgl/lvgl_v8_media -- network URL example: -You need to turn on your phone's BT PAN and share the network and hotspot. -https://gitee.com/SiFli/sifli-sdk/tree/main/example/multimedia/lvgl/streaming_media +- Video conversion can use the official ffmpeg tool mentioned above (does not + support ezip) or the Sifli toolchain. For using the official tool, you can + check the help with ffmpeg -h or ffmpeg -h full, or you can search online for + commonly used ffmpeg commands. +- The required converted width is a multiple of 16, and the encoding format is + baseline. + +## Example +- local file player: It turns out that the disk directory contains an empty + file, which needs to be replaced with the converted baseline format MP4 file.\ + https://gitee.com/SiFli/sifli-sdk/tree/main/example/multimedia/lvgl/lvgl_v8_media + +- network URL example: You need to turn on your phone's BT PAN and share the + network and hotspot. + https://gitee.com/SiFli/sifli-sdk/tree/main/example/multimedia/lvgl/streaming_media + ## API -API refrence media_dec.h + ```c /** * @brief open a media URL to play @@ -197,3 +231,166 @@ bool ffmpeg_is_video_available(ffmpeg_handle hanlde); */ ffmpeg_handle ffmpeg_player_status_get(void); ``` + +## Interface Description +API Reference: media_dec.h + +1. int ffmpeg_open(ffmpeg_handle *return_hanlde, ffmpeg_config_t *cfg, uint32_t + user_data); +``` +Description: + Opens a file or network URL for playback. +Parameters: + return_hanlde: Returns a handle to the media session. + cfg: Media configuration information; see ffmpeg_config_t. + user_data: User-defined data passed to the notify() callback specified in the cfg. +Return Value: + Returns 0 on success; otherwise, returns a non-zero error code. +``` +2. void ffmpeg_close(ffmpeg_handle hanlde); + +``` +Description: + Stops playback. This function must not be called from within the notify() callback. +Parameters: + hanlde: The handle obtained via ffmpeg_open(). +``` +3. void ffmpeg_pause(ffmpeg_handle hanlde); +``` +Description: + Pauses playback. This function must not be called from within the notify() callback. +Parameters: + handle: Handle obtained via ffmpeg_open(). +``` +4. void ffmpeg_resume(ffmpeg_handle hanlde); +``` +Description: + Resumes playback. This function must not be called from within the notify() callback. +Parameters: + handle: Handle obtained via ffmpeg_open(). +``` +5. void ffmpeg_seek(ffmpeg_handle hanlde, uint32_t second); +``` +Description: + Seeks to a specific timestamp for playback. This function must not be called from within the notify() callback. +Parameters: + handle: Handle obtained via ffmpeg_open(). + second: Offset in seconds from the start of the video. +``` +6. void ffmpeg_audio_mute(ffmpeg_handle hanlde, bool is_mute); +``` +Description: + Mutes or unmutes the audio. This function must not be called from within the notify() callback. +Parameters: + handle: Handle obtained via ffmpeg_open(). + is_mute: 1 to mute, 0 to unmute. +``` +7. uint8_t *ffmpeg_get_first_ezip(const char *filename, uint32_t *w, uint32_t + *h, uint32_t *psize); +``` +Description: + Retrieves the first frame of a video if the video is EZIP-encoded and stored as a local file. The allocated memory must be released using ffmpeg_eizp_release() after use. +Parameters: + filename: Path to the file. + w: Returns the width. + h: Returns the height. + psize: Returns the memory size. +Return Value: + Pointer to the image memory. The memory must be released using ffmpeg_eizp_release() after use. +``` +8. uint8_t *ffmpeg_get_first_ezip_in_nand(const char *nand_address, uint32_t + nand_size, uint32_t *w, uint32_t *h, uint32_t *psize); +``` +Description: + Retrieves the first frame of a video if the video is EZIP-encoded and stored directly in NAND flash. +Parameters: + nand_address: Starting address of the video in NAND. + nand_size: Size of the video. + w: Returns the width. + h: Returns the height. + psize: Returns the memory size. +Return Value: + Pointer to the image memory. The memory must be released using ffmpeg_eizp_release() after use. +``` +9. void ffmpeg_eizp_release(uint8_t *ezip); +``` +Description: + Releases the memory allocated when retrieving the first frame. +Parameters: + ezip: Memory pointer returned by ffmpeg_get_first_ezip() or ffmpeg_get_first_ezip_in_nand(). +``` +10. int ffmpeg_get_video_info(ffmpeg_handle hanlde, uint32_t *video_width, + uint32_t *video_height, video_info_t *info); + +``` +Description: + Retrieves video metadata. +Parameters: + handle: Handle obtained via ffmpeg_open(). + video_width: Returns the width. + video_height: Returns the height. + info: Detailed image format information required for display. If gpu_pic_fmt within info is EZIP, the application should record this and use the EZIP data directly for display. +Return Value: + 0 for success; non-zero value for failure. +``` + +11. bool ffmpeg_is_video_available(ffmpeg_handle hanlde); +``` +Description: + Checks if a new frame is available in the decoding buffer. This should be called before attempting to retrieve a frame. +Parameters: + handle: Handle obtained via ffmpeg_open(). +Return Value: + true if a frame is available; false otherwise. +``` + +12. int ffmpeg_next_video_frame(ffmpeg_handle hanlde, uint8_t *data); +``` +Description: + Retrieves the next frame from the decoding buffer. +Parameters: + handle: Handle obtained via ffmpeg_open(). + data: Pointer used to return image information. Although defined as uint8_t *data, it is treated as uint8_t **data to return three pointers. The assignments for these pointers vary by format (refer to info in ffmpeg_get_video_info()): + A. format is e_sifli_fmt_ezip: + data[0] -- data address + data[1] -- data size + data[2] -- IMG_DESC_FMT_EZIP + C. format is e_sifli_fmt_yuv420p (YUV can be used directly for 52x/56x/57x chips): + data[0] -- Y plane address + data[1] -- U plane address + data[2] -- V plane address + D. others: + data[0] -- data address + data[1] -- unused + data[2] -- unused + +Return Value: + 0 for success (frame ready for display); non-zero value for failure. +``` +13. ffmpeg_handle ffmpeg_player_status_get(void); + +``` +Description: + Checks whether a video is currently playing. Note that this function is not thread-safe; the playback state may change immediately after the function returns. +Parameters: + void +Return Value: + Returns the handle of the video currently being played, or NULL if no video is playing. +``` +## Image Display +The `fmt` field in `ffmpeg_config_t` specifies the display format for the UI. If +the video is H.264/H.263 encoded, the internal decoder outputs YUV format. The +internal `media_video_convert()` function then converts this YUV data into the +format specified by `fmt`. If the video is EZIP encoded, the internal decoder +simply extracts the EZIP data, which the UI displays directly. If the video is +MJPEG encoded, the internal decoder outputs in `IMG_DESC_FMT_ARGB8888`. + +When creating an image control, the application must use the macros defined in +`media_dec.h`. Since supported formats vary across platforms, refer to the +provided examples for configuration. + +IMG_DESC_FMT IMG_PIXEL_SIZE IMG_LV_FMT + +## Debugging +The decoder currently buffers only three frames, prioritizing audio playback. If +"drop" appears in the logs, it indicates that frame dropping has occurred. diff --git a/docs/source/en/middleware/watch_complication.md b/docs/source/en/middleware/watch_complication.md index fa99259b4..d4b643166 100644 --- a/docs/source/en/middleware/watch_complication.md +++ b/docs/source/en/middleware/watch_complication.md @@ -1,36 +1,42 @@ - # Watch Application Components -The SiFli Software Development Kit provides UI components for watch applications, helping users develop features similar to the Apple Watch complications. It includes APIs for creating the following components: +The SiFli Software Development Kit provides UI components for watch +applications, helping users develop features similar to the Apple Watch +complications. It includes APIs for creating the following components: + + +- **Circular Small** The circular small template displays a small image or + several text characters. It appears in the corner of the watch face (for + example, on a colored dial). ![Figure 1: Circular Small](../../assets/cir.png) -- **Circular Small** - The circular small template displays a small image or several text characters. It appears in the corner of the watch face (for example, on a colored dial). - ![Figure 1: Circular Small](../../assets/cir.png) +- **Modular Small** The modular small template displays two stacked lines, + composed of an icon and content, a circular image, or a larger item (for + example, the bottom complication on a modular dial). ![Figure 2: Modular + Small](../../assets/mos.png) -- **Modular Small** - The modular small template displays two stacked lines, composed of an icon and content, a circular image, or a larger item (for example, the bottom complication on a modular dial). - ![Figure 2: Modular Small](../../assets/mos.png) +- **Modular Large** The modular large template provides a large canvas, capable + of displaying up to three lines of content (for example, in the center of a + modular dial). ![Figure 3: Modular Large](../../assets/mol.png) -- **Modular Large** - The modular large template provides a large canvas, capable of displaying up to three lines of content (for example, in the center of a modular dial). - ![Figure 3: Modular Large](../../assets/mol.png) +- **Utility Small** The utility small template occupies a rectangular area in + the corner of the dial (for example, in Chronograph or Simple dials). Content + can include glyphs or icons, or a circular image. ![Figure 4: Utility + Small](../../assets/utils.png) -- **Utility Small** - The utility small template occupies a rectangular area in the corner of the dial (for example, in Chronograph or Simple dials). Content can include glyphs or icons, or a circular image. - ![Figure 4: Utility Small](../../assets/utils.png) +- **Extra Large** The extra large template displays larger text and images (for + example, on an X-Large dial). ![Figure 5: Extra Large](../../assets/exl.png) -- **Extra Large** - The extra large template displays larger text and images (for example, on an X-Large dial). - ![Figure 5: Extra Large](../../assets/exl.png) +- **Graphic Bezel** The graphic bezel template displays a graphic circular + template with optional text around the bezel on an Infograph dial. The text + can fill nearly 180 degrees of the bezel before being truncated. ![Figure 6: + Graphic Bezel](../../assets/bezel.png) -- **Graphic Bezel** - The graphic bezel template displays a graphic circular template with optional text around the bezel on an Infograph dial. The text can fill nearly 180 degrees of the bezel before being truncated. - ![Figure 6: Graphic Bezel](../../assets/bezel.png) +- **Graphic Corner** The graphic corner template displays full-color images, + text, and gauges in the corners of the Infograph dial. Some templates also + support multi-color text. ![Figure 7: Graphic Corner](../../assets/corner.png) -- **Graphic Corner** - The graphic corner template displays full-color images, text, and gauges in the corners of the Infograph dial. Some templates also support multi-color text. - ![Figure 7: Graphic Corner](../../assets/corner.png) +- **Graphic Circle** The graphic circle template displays text, gauges, and + full-color images in small circular regions on the Infograph and Infograph + Modular dials. Some templates also support multi-color text. ![Figure 8: + Graphic Circle](../../assets/gcr.png) -- **Graphic Circle** - The graphic circle template displays text, gauges, and full-color images in small circular regions on the Infograph and Infograph Modular dials. Some templates also support multi-color text. - ![Figure 8: Graphic Circle](../../assets/gcr.png) diff --git a/docs/source/en/quickstart/arch.md b/docs/source/en/quickstart/arch.md index 778dba2a3..b1d491df4 100644 --- a/docs/source/en/quickstart/arch.md +++ b/docs/source/en/quickstart/arch.md @@ -1,14 +1,24 @@ - # Software Architecture -SiFli SDK is an officially provided software development framework customized based on RT-Thread. Using it, you can quickly develop applications running on SiFli Technology chip platforms. +SiFli SDK is an officially provided software development framework customized +based on RT-Thread. Using it, you can quickly develop applications running on +SiFli Technology chip platforms. The software framework is shown in the following diagram: ![](../../assets/sdk_arch_diagram.png) -- HAL is the Hardware Abstraction Layer, providing driver functionality independent of operating system services -- RT-Thread Device Driver is implemented based on HAL, providing higher-level encapsulation. Users do not need to implement interrupt service routines, making it easier to use. For a more detailed comparison between HAL and RT-Thread device drivers, please refer to [drivers.md](/app_development/drivers.md). -- Middleware (components) includes RT-Thread's built-in software components (such as finsh, ulog), third-party components (located in the `external` directory), and self-developed components (located in the `middleware` directory). Applications can use all service interfaces including HAL to develop applications. +- HAL is the Hardware Abstraction Layer, providing driver functionality + independent of operating system services +- RT-Thread Device Driver is implemented based on HAL, providing higher-level + encapsulation. Users do not need to implement interrupt service routines, + making it easier to use. For a more detailed comparison between HAL and + RT-Thread device drivers, please refer to + [drivers.md](../app_development/drivers.md). +- Middleware (components) includes RT-Thread's built-in software components + (such as finsh, ulog), third-party components (located in the `external` + directory), and self-developed components (located in the `middleware` + directory). Applications can use all service interfaces including HAL to + develop applications. SDK Directory Structure ``` @@ -52,4 +62,7 @@ SDK Directory Structure | | | -\---tools // Tools \ No newline at end of file +\---tools // Tools +``` + + diff --git a/docs/source/en/quickstart/build.md b/docs/source/en/quickstart/build.md index fc5b8469c..0f59f4e39 100644 --- a/docs/source/en/quickstart/build.md +++ b/docs/source/en/quickstart/build.md @@ -2,9 +2,17 @@ ## Building Project -First, install the dependency packages according to the environment installation requirements and configure the environment variables. - -Execute the command `cd example\get-started\hello_world\rtt\project` to enter the project directory of the RT-Thread version hello_world example, run the command `scons --board=sf32lb52-lcd_n16r8 -j8` to compile the hello_world program that can run on the SF32LB52x-DevKit-LCD development board, where `sf32lb52-lcd_n16r8` is the name of the development board. Available board names can be found in [index.md](/supported_boards/index.md), you can replace sf32lb52-lcd_n16r8 with other development board names. The compiled files are stored in the `build_sf32lb52-lcd_n16r8_hcpu` directory. +First, install the dependency packages according to the environment installation +requirements and configure the environment variables. + +Execute the command `cd example\get-started\hello_world\rtt\project` to enter +the project directory of the RT-Thread version hello_world example, run the +command `scons --board=sf32lb52-lcd_n16r8 -j8` to compile the hello_world +program that can run on the SF32LB52x-DevKit-LCD development board, where +`sf32lb52-lcd_n16r8` is the name of the development board. Available board names +can be found in [index.md](/supported_boards/index.md), you can replace +sf32lb52-lcd_n16r8 with other development board names. The compiled files are +stored in the `build_sf32lb52-lcd_n16r8_hcpu` directory. ```{note} Build command format: `scons --board= -jN`, where `` is the board name. Available board names can be found in [index.md](/supported_boards/index.md). If board_name does not specify a core, the HCPU configuration is used by default for compilation, and will be expanded to _hcpu. `-jN` is the multi-threaded compilation parameter, where `N` is the number of threads. For example, in the above example, `-j8` means starting 8 threads for compilation. @@ -14,9 +22,14 @@ The compiled files are stored in the `build_` directory, which conta ## Configuration Options -Different projects may have different customized configuration options. We use the menuconfig tool to configure projects. The method to open menuconfig is as follows: +Different projects may have different customized configuration options. We use +the menuconfig tool to configure projects. The method to open menuconfig is as +follows: -Run the command `scons --board= --menuconfig` in the project directory, a configuration interface will pop up, and you can modify configuration options as needed. After modification, press the `ESC` key twice, select save configuration and exit. +Run the command `scons --board= --menuconfig` in the project +directory, a configuration interface will pop up, and you can modify +configuration options as needed. After modification, press the `ESC` key twice, +select save configuration and exit. ```{note} `--board` is a required parameter that specifies the board name to be compiled. Available board names can be found in [](/supported_boards/index.md). If not specified, configuration cannot be performed normally. @@ -24,12 +37,22 @@ Run the command `scons --board= --menuconfig` in the project directo ## Download Program -Keep the USB connection between the development board and the computer, run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` to download the program to the development board. When prompted `please input serial port number`, enter the actual serial port number of the development board, for example, if it's COM19, enter 19. After entering, press Enter to start downloading the program (it's recommended to restart the development board before pressing Enter to start downloading, and press Enter within 2 seconds after restarting the development board to start downloading). After completion, press any key as prompted to return to the command line prompt. - +Keep the USB connection between the development board and the computer, run +`build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` to download the program to the +development board. When prompted `please input serial port number`, enter the +actual serial port number of the development board, for example, if it's COM19, +enter 19. After entering, press Enter to start downloading the program (it's +recommended to restart the development board before pressing Enter to start +downloading, and press Enter within 2 seconds after restarting the development +board to start downloading). After completion, press any key as prompted to +return to the command line prompt. ```{note} Linux and macOS users use the script file `build_sf32lb52-lcd_n16r8_hcpu/uart_download.sh`, and the usage is the same as the Windows script. Note that macOS users should use device names starting with `/dev/cu.` for serial port numbers, such as `/dev/cu.usbserial-12345678`, rather than device names starting with `/dev/tty.`. ``` ## Running Program -After the download is complete, a software reset will be automatically executed, or you can also press the RESET button on the development board. The program will run automatically, and the serial assistant will print hello world prompt information. +After the download is complete, a software reset will be automatically executed, +or you can also press the RESET button on the development board. The program +will run automatically, and the serial assistant will print hello world prompt +information. diff --git a/docs/source/en/quickstart/get-started.md b/docs/source/en/quickstart/get-started.md index 3b4ff00ec..6825e25e6 100644 --- a/docs/source/en/quickstart/get-started.md +++ b/docs/source/en/quickstart/get-started.md @@ -1,36 +1,47 @@ # Getting Started Guide -[SDK]: https://github.com/OpenSiFli/SiFli-SDK -[Trace]: https://webfile.lovemcu.cn/file/sdk/SifliTrace_v2.2.6.7z -[52DevKit]: https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html -[52Module]: https://wiki.sifli.com/silicon/%E6%A8%A1%E7%BB%84%E5%9E%8B%E5%8F%B7%E6%8C%87%E5%8D%97.html +[52Module]: https://github.com/OpenSiFli/SiFli-SDK +[52Module]: https://webfile.lovemcu.cn/file/sdk/SifliTrace_v2.2.6.7z +[52Module]: https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html +[52Module]: +https://wiki.sifli.com/silicon/%E6%A8%A1%E7%BB%84%E5%9E%8B%E5%8F%B7%E6%8C%87%E5%8D%97.html ## Preparation ### Hardware -- A development board, such as [SF32LB52-DevKit-LCD Development Board][52DevKit] -- A USB Type-C data cable to connect the development board to the computer. Note that it cannot be a Type-C cable with only charging function. Insert it into the USB-to-UART interface of the development board (do not insert it into the dedicated USB function interface) +- A development board, such as [SF32LB52-DevKit-LCD Development Board][52Module] +- A USB Type-C data cable to connect the development board to the computer. Note + that it cannot be a Type-C cable with only charging function. Insert it into + the USB-to-UART interface of the development board (do not insert it into the + dedicated USB function interface) - Computer (Windows, Linux, or macOS) ### Software To use SiFli-SDK on SF32, please install the following software: - Set up toolchain for compiling SF32 code; -- Build tool — SDK2.x uses Scons as the build tool for compiling SF32 applications; -- Obtain SiFli-SDK software development framework. This framework basically includes SF32 APIs (software libraries and source code) and scripts for running the **toolchain**; +- Build tool — SDK2.x uses Scons as the build tool for compiling SF32 + applications; +- Obtain SiFli-SDK software development framework. This framework basically + includes SF32 APIs (software libraries and source code) and scripts for + running the **toolchain**; ### Installation -To install the required software, SiFli provides the following methods, you can choose one of them as needed. +To install the required software, SiFli provides the following methods, you can +choose one of them as needed. #### Install via VSCode Plugin (Recommended) -Refer to the installation documentation: [CodeKit-Doc](https://docs.sifli.com/projects/codekit/get-started/) +Refer to the installation documentation: +[CodeKit-Doc](https://docs.sifli.com/projects/codekit/get-started/) -Plugin download: Click to jump to [SiFli-SDK-CodeKit](https://marketplace.visualstudio.com/items?itemName=SiFli.SiFli-SDK-CodeKit) +Plugin download: Click to jump to +[SiFli-SDK-CodeKit](https://marketplace.visualstudio.com/items?itemName=SiFli.SiFli-SDK-CodeKit) -Alternatively, search for the "SiFli-SDK-CodeKit" plugin in VSCode and install it. +Alternatively, search for the "SiFli-SDK-CodeKit" plugin in VSCode and install +it. #### Manual Installation diff --git a/docs/source/en/quickstart/index.md b/docs/source/en/quickstart/index.md index 5f656a10f..0149d5166 100644 --- a/docs/source/en/quickstart/index.md +++ b/docs/source/en/quickstart/index.md @@ -4,9 +4,8 @@ :maxdepth: 2 :titlesonly: -get-started -install/index -build -arch - +Getting Started +Installation Guide +Build System +Architecture Overview ``` diff --git a/docs/source/en/quickstart/install/index.md b/docs/source/en/quickstart/install/index.md index 1b59e3e7e..e707a6a77 100644 --- a/docs/source/en/quickstart/install/index.md +++ b/docs/source/en/quickstart/install/index.md @@ -1,9 +1,12 @@ # Installation Environment -This section introduces the installation methods for the SiFli-SDK development environment. We provide two installation approaches: +This section introduces the installation methods for the SiFli-SDK development +environment. We provide two installation approaches: -- **Script Installation**: Use automated scripts to quickly install the development environment -- **ENV Tool Installation**: Use the ENV tool for environment configuration and management +- **Script Installation**: Use automated scripts to quickly install the + development environment +- **ENV Tool Installation**: Use the ENV tool for environment configuration and + management Please select the appropriate installation method based on your requirements: @@ -12,4 +15,4 @@ Please select the appropriate installation method based on your requirements: script/index ./lacey_install -``` \ No newline at end of file +``` diff --git a/docs/source/en/quickstart/install/lacey_install.md b/docs/source/en/quickstart/install/lacey_install.md index d8d2d5fb8..0bb9999ce 100644 --- a/docs/source/en/quickstart/install/lacey_install.md +++ b/docs/source/en/quickstart/install/lacey_install.md @@ -1,20 +1,29 @@ # Installing Environment Using ENV Tool -Compared to full script-based environment installation, you might prefer or be more familiar with using the previous SiFli-ENV tool to install and manage the SiFli-SDK development environment. While we recommend using script installation, SiFli-ENV can still be used for compatibility. However, please note that SiFli-ENV may be deprecated in future versions. +Compared to full script-based environment installation, you might prefer or be +more familiar with using the previous SiFli-ENV tool to install and manage the +SiFli-SDK development environment. While we recommend using script installation, +SiFli-ENV can still be used for compatibility. However, please note that +SiFli-ENV may be deprecated in future versions. ## Download SiFli-ENV Tool -The current latest download link for the SiFli-ENV tool is: . +The current latest download link for the SiFli-ENV tool is: +. -If you encounter the prompt `Please upgrade env to v1.1.2 or greater`, it indicates that your ENV version is outdated. Please use the above link to download the latest version of the SiFli-ENV tool. +If you encounter the prompt `Please upgrade env to v1.1.2 or greater`, it +indicates that your ENV version is outdated. Please use the above link to +download the latest version of the SiFli-ENV tool. -After downloading, extract the files to the directory where you wish to store SiFli-ENV. Double-click the `env.bat` file to open the command line window. +After downloading, extract the files to the directory where you wish to store +SiFli-ENV. Double-click the `env.bat` file to open the command line window. ![](image/2025-05-26-13-55-36.png) -According to the prompt, we need to enter the environment setup command in the SDK root directory. +According to the prompt, we need to enter the environment setup command in the +SDK root directory. ![](image/2025-05-26-13-56-01.png) ```{note} For SDK download instructions, please refer to [Getting SiFli-SDK](./script/windows.md#sifli-sdk). -``` \ No newline at end of file +``` diff --git a/docs/source/en/quickstart/install/script/index.md b/docs/source/en/quickstart/install/script/index.md index 6804764ed..5051cb05e 100644 --- a/docs/source/en/quickstart/install/script/index.md +++ b/docs/source/en/quickstart/install/script/index.md @@ -1,10 +1,11 @@ # Script Installation -This section describes how to install the SiFli-SDK development environment using scripts, with slight differences between operating systems. +This section describes how to install the SiFli-SDK development environment +using scripts, with slight differences between operating systems. ```{toctree} :maxdepth: 1 -windows -unix -``` \ No newline at end of file +Windows +Unix +``` diff --git a/docs/source/en/quickstart/install/script/unix.md b/docs/source/en/quickstart/install/script/unix.md index 59143b2b7..40f9a7b69 100644 --- a/docs/source/en/quickstart/install/script/unix.md +++ b/docs/source/en/quickstart/install/script/unix.md @@ -2,16 +2,15 @@ ## Installation Prerequisites -To install SiFli-SDK, you need to install some software packages according to your operating system. You can refer to the following installation guide to install all required software packages on Linux and macOS systems. +To install SiFli-SDK, you need to install some software packages according to +your operating system. You can refer to the following installation guide to +install all required software packages on Linux and macOS systems. -::::::{tab-set} -:sync-group: os +::::::{tab-set} :sync-group: os -:::::{tab-item} Linux -:sync: Linux +:::::{tab-item} Linux :sync: Linux -::::{tab-set} -:sync-group: linux +::::{tab-set} :sync-group: linux :::{tab-item} Ubuntu and Debian @@ -24,7 +23,7 @@ sudo apt-get install git wget flex bison gperf python3 python3-pip python3-venv :::{tab-item} CentOS 7 & 8 ```bash -sudo yum -y update && sudo yum install git wget flex bison gperf python3 python3-setuptools cmake ninja-build ccache dfu-util libusbx +sudo yum -y update && sudo yum install git wget flex bison gperf python3 python3-setuptools cmake ninja-build ccache dfu-util libusbx ``` ::: @@ -41,8 +40,7 @@ sudo pacman -S --needed gcc git make flex bison gperf python cmake ninja ccache ::::: -:::::{tab-item} macOS -:sync: macOS +:::::{tab-item} macOS :sync: macOS SiFli-SDK will use the Python version installed by default on macOS. @@ -59,18 +57,18 @@ SiFli-SDK will use the Python version installed by default on macOS. sudo port install cmake ninja ``` - - Neither of the above - If neither of the above applies, please visit the CMake and Ninja homepages to find download and installation information for the macOS platform. + - Neither of the above If neither of the above applies, please visit the CMake + and Ninja homepages to find download and installation information for the + macOS platform. -:::{note} -If you encounter the following error in any of the above steps: +:::{note} If you encounter the following error in any of the above steps: ``` xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun ``` -You must install XCode command line tools by running the `xcode-select --install` command. -::: +You must install XCode command line tools by running the `xcode-select +--install` command. ::: ::::: @@ -78,14 +76,17 @@ You must install XCode command line tools by running the `xcode-select --install ## Get SiFli-SDK -Before building applications around SF32, please first obtain the software library files provided by SiFli from the [SiFli-SDK repository](https://github.com/OpenSiFli/SiFli-SDK). +Before building applications around SF32, please first obtain the software +library files provided by SiFli from the [SiFli-SDK +repository](https://github.com/OpenSiFli/SiFli-SDK). -Get a local copy of SiFli-SDK: Open terminal, switch to the working directory where you want to save SiFli-SDK, and use the `git clone` command to clone the remote repository. Generally, we recommend using code from the release branch to get the latest stable version. +Get a local copy of SiFli-SDK: Open terminal, switch to the working directory +where you want to save SiFli-SDK, and use the `git clone` command to clone the +remote repository. Generally, we recommend using code from the release branch to +get the latest stable version. ```{warning} - Since SiFli-SDK contains submodules, you cannot obtain the complete code by downloading the zip package. - ``` Open PowerShell terminal and run the following commands: @@ -118,7 +119,6 @@ or ```powershell git checkout release/v2.3 ``` - ```` ````{note} @@ -131,7 +131,9 @@ git submodule update --init --recursive ## Install Tools -In addition to SiFli-SDK itself, you also need to install various tools used by SiFli-SDK for projects supporting SF32, such as compilers, debuggers, Python packages, etc. +In addition to SiFli-SDK itself, you also need to install various tools used by +SiFli-SDK for projects supporting SF32, such as compilers, debuggers, Python +packages, etc. ```bash cd ~/OpenSiFli/SiFli-SDK @@ -142,7 +144,8 @@ cd ~/OpenSiFli/SiFli-SDK It should be noted that the pyenv tool should not be used to manage the Python environment of the system. Otherwise, errors may occur during the subsequent process. ``` -For domestic users in China, you can use the following commands to add domestic mirror sources: +For domestic users in China, you can use the following commands to add domestic +mirror sources: ```bash cd ~/OpenSiFli/SiFli-SDK @@ -153,7 +156,13 @@ export PIP_INDEX_URL="https://mirrors.ustc.edu.cn/pypi/simple" ### Custom Tool Installation Path (Optional) -The script described in this step installs the compilation tools required by SiFli-SDK in the user's home directory by default, which is the `$HOME/.sifli` directory in *nix systems, or `C:\Users\\.sifli` in Windows. We can choose to install tools to other directories, but please export the environment variable `SIFLI_SDK_TOOLS_PATH` before running the installation script. Note that please ensure the user account has read and write permissions for that path. +The script described in this step installs the compilation tools required by +SiFli-SDK in the user's home directory by default, which is the `$HOME/.sifli` +directory in *nix systems, or `C:\Users\\.sifli` in Windows. We can choose +to install tools to other directories, but please export the environment +variable `SIFLI_SDK_TOOLS_PATH` before running the installation script. Note +that please ensure the user account has read and write permissions for that +path. ```powershell export SIFLI_SDK_TOOLS_PATH="$HOME/required_sdk_tools_path" @@ -162,7 +171,8 @@ export SIFLI_SDK_TOOLS_PATH="$HOME/required_sdk_tools_path" . ./export.sh ``` -If you modified the `SIFLI_SDK_TOOLS_PATH` variable, please export this variable to the environment variables before running any SiFli-SDK tools or scripts. +If you modified the `SIFLI_SDK_TOOLS_PATH` variable, please export this variable +to the environment variables before running any SiFli-SDK tools or scripts. ```{note} If environment variables are not exported, most shells will not support using `SIFLI_SDK_TOOLS_PATH` in variable assignments, such as `SIFLI_SDK_TOOLS_PATH="$HOME/required_sdk_tools_path" ./install.sh`. Because even if the variable is exported or modified in the source script, the current execution environment is not affected by variable assignment. @@ -170,9 +180,13 @@ If environment variables are not exported, most shells will not support using `S ## Set Environment Variables -After the above steps, the SDK and related tools are installed, but their paths are not in the environment variables, so they cannot be used in any directory. Therefore, some environment variables must be set. This can be done through another script provided by SiFli-SDK. +After the above steps, the SDK and related tools are installed, but their paths +are not in the environment variables, so they cannot be used in any directory. +Therefore, some environment variables must be set. This can be done through +another script provided by SiFli-SDK. -Please run the following command in terminal windows where you need to use compilation or download commands: +Please run the following command in terminal windows where you need to use +compilation or download commands: ```bash . export.sh @@ -191,16 +205,24 @@ export SIFLI_SDK_TOOLS_PATH="$HOME/required_sdk_tools_path" The current script may have some occasional bugs. If you get prompts like "command not found `arm-none-eabi-gcc`" during compilation, you can try running `. export.sh` twice to resolve it. ``` -If you need to run SiFli-SDK frequently, you can create an alias for executing export.sh by following these steps: +If you need to run SiFli-SDK frequently, you can create an alias for executing +export.sh by following these steps: -1. Copy and paste the following command into your shell configuration file (.profile, .bashrc, .zprofile, etc.) +1. Copy and paste the following command into your shell configuration file + (.profile, .bashrc, .zprofile, etc.) ```bash alias sf32sdk='. $HOME/OpenSiFli/SiFli-SDK/export.sh' ``` -2. Refresh the configuration file by restarting the terminal window or running `source [path to profile]`, such as `source ~/.bashrc` +2. Refresh the configuration file by restarting the terminal window or running + `source [path to profile]`, such as `source ~/.bashrc` -Now you can run `sf32sdk` in any terminal window to set or refresh the SiFli-SDK environment. +Now you can run `sf32sdk` in any terminal window to set or refresh the SiFli-SDK +environment. -It is not recommended to add export.sh directly to the shell's configuration file. This will cause the SDK virtual environment to be activated in every terminal session (including sessions that don't need to use SiFli-SDK). This goes against the purpose of using virtual environments and may affect the use of other software. \ No newline at end of file +It is not recommended to add export.sh directly to the shell's configuration +file. This will cause the SDK virtual environment to be activated in every +terminal session (including sessions that don't need to use SiFli-SDK). This +goes against the purpose of using virtual environments and may affect the use of +other software. diff --git a/docs/source/en/quickstart/install/script/windows.md b/docs/source/en/quickstart/install/script/windows.md index ab1a8962f..491401cd2 100644 --- a/docs/source/en/quickstart/install/script/windows.md +++ b/docs/source/en/quickstart/install/script/windows.md @@ -4,9 +4,13 @@ ### Python Environment -For Windows users, you need to ensure that the `Python` environment variable exists in the environment variables. +For Windows users, you need to ensure that the `Python` environment variable +exists in the environment variables. -If Python is not installed, please refer to the [Python official website](https://www.python.org/downloads/) to download and install Python version 3.9 or above, below 3.14. After installation, make sure to add Python to the system's environment variables. +If Python is not installed, please refer to the [Python official +website](https://www.python.org/downloads/) to download and install Python +version 3.9 or above, below 3.14. After installation, make sure to add Python to +the system's environment variables. ![](image/2025-05-26-13-39-17.png) @@ -14,7 +18,9 @@ If Python is not installed, please refer to the [Python official website](https: For domestic users in China, you can use the following domestic mirror link to download Python installer: ``` -After installation, you can run the `python --version` command in the terminal to check if Python is installed successfully. Normally, it should output Python version information, such as: +After installation, you can run the `python --version` command in the terminal +to check if Python is installed successfully. Normally, it should output Python +version information, such as: ```powershell Python 3.12.0 @@ -22,13 +28,17 @@ Python 3.12.0 ### Git Environment -If Git is not installed, please refer to the [Git official website](https://git-scm.com/download/win) to download and install Git. After installation, make sure to add Git to the system's environment variables. +If Git is not installed, please refer to the [Git official +website](https://git-scm.com/download/win) to download and install Git. After +installation, make sure to add Git to the system's environment variables. ```{note} For domestic users in China, you can use the following domestic mirror link to download Git installer: . Keep the default installation options each time. ``` -After installation, you can run the `git --version` command in the terminal to check if Git is installed successfully. Normally, it should output Git version information, such as: +After installation, you can run the `git --version` command in the terminal to +check if Git is installed successfully. Normally, it should output Git version +information, such as: ```powershell git version 2.47.0.windows.1 @@ -38,17 +48,29 @@ git version 2.47.0.windows.1 SiFli-SDK script installation only supports `powershell`. -For terminal choice, we recommend using [Windows Terminal](https://aka.ms/terminal). Users can also choose other terminals, such as the integrated terminal that comes with VSCode. However, Windows Terminal is more recommended. Note that in some newer Windows 10/11 versions, Windows Terminal is already pre-installed. +For terminal choice, we recommend using [Windows +Terminal](https://aka.ms/terminal). Users can also choose other terminals, such +as the integrated terminal that comes with VSCode. However, Windows Terminal is +more recommended. Note that in some newer Windows 10/11 versions, Windows +Terminal is already pre-installed. To open `PowerShell`, you can use the following methods: -- Press the Win key or click the Windows icon in the lower left corner, type `powershell`, then click to open PowerShell terminal. -- Press Win + R key combination to open the Run window, type `powershell`, then click OK. +- Press the Win key or click the Windows icon in the lower left corner, type + `powershell`, then click to open PowerShell terminal. +- Press Win + R key combination to open the Run window, type `powershell`, then + click OK. -If you are using Windows Terminal, you can directly open PowerShell in the terminal. To open the terminal, you can press the Win key or click the Windows icon in the lower left corner, type `terminal`, then click to open Windows Terminal. +If you are using Windows Terminal, you can directly open PowerShell in the +terminal. To open the terminal, you can press the Win key or click the Windows +icon in the lower left corner, type `terminal`, then click to open Windows +Terminal. -If you encounter the error message -`Cannot load file C:\OpenSiFli\SiFli-SDK\export.ps1 because running scripts is disabled on this system.` in the subsequent script running steps, or if you have never heard of or run `.ps1` scripts before, please open PowerShell terminal in **administrator mode** and run the following command: +If you encounter the error message `Cannot load file +C:\OpenSiFli\SiFli-SDK\export.ps1 because running scripts is disabled on this +system.` in the subsequent script running steps, or if you have never heard of +or run `.ps1` scripts before, please open PowerShell terminal in **administrator +mode** and run the following command: ```powershell Set-ExecutionPolicy RemoteSigned @@ -58,14 +80,17 @@ Then type `Y` and press Enter to gain permission to run scripts. ## Get SiFli-SDK -Before building applications around SF32, please first obtain the software library files provided by SiFli from the [SiFli-SDK repository](https://github.com/OpenSiFli/SiFli-SDK). +Before building applications around SF32, please first obtain the software +library files provided by SiFli from the [SiFli-SDK +repository](https://github.com/OpenSiFli/SiFli-SDK). -Get a local copy of SiFli-SDK: Open terminal, switch to the working directory where you want to save SiFli-SDK, and use the `git clone` command to clone the remote repository. Generally, we recommend using code from the release branch to get the latest stable version. +Get a local copy of SiFli-SDK: Open terminal, switch to the working directory +where you want to save SiFli-SDK, and use the `git clone` command to clone the +remote repository. Generally, we recommend using code from the release branch to +get the latest stable version. ```{warning} - Since SiFli-SDK contains submodules, you cannot obtain the complete code by downloading the zip package. - ``` Open PowerShell terminal and run the following commands: @@ -98,7 +123,6 @@ or ```powershell git checkout release/v2.3 ``` - ```` ````{note} @@ -111,7 +135,9 @@ git submodule update --init --recursive ## Install Tools -In addition to SiFli-SDK itself, you also need to install various tools used by SiFli-SDK for projects supporting SF32, such as compilers, debuggers, Python packages, etc. +In addition to SiFli-SDK itself, you also need to install various tools used by +SiFli-SDK for projects supporting SF32, such as compilers, debuggers, Python +packages, etc. ```powershell cd C:\OpenSiFli\SiFli-SDK @@ -131,12 +157,17 @@ $env:SIFLI_SDK_GITHUB_ASSETS="downloads.sifli.com/github_assets" $env:PIP_INDEX_URL="https://mirrors.ustc.edu.cn/pypi/simple" .\install.ps1 ``` - ```` ### Custom Tool Installation Path (Optional) -The script described in this step installs the compilation tools required by SiFli-SDK in the user's home directory by default, which is the `$HOME/.sifli` directory in *nix systems, or `C:\Users\\.sifli` in Windows. We can choose to install tools to other directories, but please export the environment variable `SIFLI_SDK_TOOLS_PATH` before running the installation script. Note that please ensure the user account has read and write permissions for that path. +The script described in this step installs the compilation tools required by +SiFli-SDK in the user's home directory by default, which is the `$HOME/.sifli` +directory in *nix systems, or `C:\Users\\.sifli` in Windows. We can choose +to install tools to other directories, but please export the environment +variable `SIFLI_SDK_TOOLS_PATH` before running the installation script. Note +that please ensure the user account has read and write permissions for that +path. ```powershell $env:SIFLI_SDK_TOOLS_PATH="D:\SIFLI\tools" @@ -145,7 +176,8 @@ $env:SIFLI_SDK_TOOLS_PATH="D:\SIFLI\tools" .\export.ps1 ``` -If you modified the `SIFLI_SDK_TOOLS_PATH` variable, please export this variable to the environment variables before running any SiFli-SDK tools or scripts. +If you modified the `SIFLI_SDK_TOOLS_PATH` variable, please export this variable +to the environment variables before running any SiFli-SDK tools or scripts. ```{note} For Windows users, if your username contains spaces, Chinese characters, or other non-English characters, it is strongly recommended to set `SIFLI_SDK_TOOLS_PATH` to specify the tool installation path, otherwise it may cause installation failure or compilation errors. It is recommended to set this path to a pure English path, such as `D:\SIFLI\tools`. @@ -157,9 +189,13 @@ If environment variables are not exported, most shells will not support using `S ## Set Environment Variables -After the above steps, the SDK and related tools are installed, but their paths are not in the environment variables, so they cannot be used in any directory. Therefore, some environment variables must be set. This can be done through another script provided by SiFli-SDK. +After the above steps, the SDK and related tools are installed, but their paths +are not in the environment variables, so they cannot be used in any directory. +Therefore, some environment variables must be set. This can be done through +another script provided by SiFli-SDK. -Please run the following command in terminal windows where you need to use compilation or download commands: +Please run the following command in terminal windows where you need to use +compilation or download commands: ```powershell cd C:\OpenSiFli\SiFli-SDK @@ -185,12 +221,16 @@ The current script may have some occasional bugs. If you get prompts like "comma ### Windows Terminal Quick Configuration -If you need to run SiFli-SDK frequently and want to automatically set environment variables each time you open the terminal, you can create a new Windows Terminal profile by following these steps: +If you need to run SiFli-SDK frequently and want to automatically set +environment variables each time you open the terminal, you can create a new +Windows Terminal profile by following these steps: -Press `Ctrl+,` in Windows Terminal to open settings, click to add a new profile, select duplicate profile `Windows PowerShell`, then follow these steps: +Press `Ctrl+,` in Windows Terminal to open settings, click to add a new profile, +select duplicate profile `Windows PowerShell`, then follow these steps: ![](image/Windows-T1.png) 1. Change the name to SiFli-SDK -2. Change the command line configuration to the following, change the final export.ps1 file location to your SDK path +2. Change the command line configuration to the following, change the final + export.ps1 file location to your SDK path ```powershell %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -File D:\SIFIL\SiFli-SDK\export.ps1 ``` @@ -203,8 +243,11 @@ Press `Ctrl+,` in Windows Terminal to open settings, click to add a new profile, 4. Other configurations can remain unchanged 5. Click Save -Subsequently, you only need to open Windows Terminal in any code directory, click the dropdown menu in the upper right corner, select SiFli-SDK, and the environment variables will be set automatically. In the newly opened window, you can use the SDK's compilation and download commands. -![](image/Windows-T4.png) +Subsequently, you only need to open Windows Terminal in any code directory, +click the dropdown menu in the upper right corner, select SiFli-SDK, and the +environment variables will be set automatically. In the newly opened window, you +can use the SDK's compilation and download commands. ![](image/Windows-T4.png) ### Check if Environment Setup is Successful -You can try compiling and downloading to see if it's successful. For compilation and downloading, please refer to [](../../build.md) +You can try compiling and downloading to see if it's successful. For compilation +and downloading, please refer to [](../../build.md) diff --git a/docs/source/en/sf_pkg/create.md b/docs/source/en/sf_pkg/create.md index f35e47eee..54c85e7a1 100644 --- a/docs/source/en/sf_pkg/create.md +++ b/docs/source/en/sf_pkg/create.md @@ -1,6 +1,7 @@ # Creating and Uploading SiFli Package Registry Packages -This section describes how to log in, create, build, and upload your own SiFli Package Registry packages. +This section describes how to log in, create, build, and upload your own SiFli +Package Registry packages. ```{note} Some screenshots on this page were captured with the old CLI format. If a screenshot differs from the text, follow the current `sdk.py sf-pkg ...` commands in the document. @@ -8,13 +9,14 @@ Some screenshots on this page were captured with the old CLI format. If a screen ## Obtaining an Access Token -1. Open and log in using your GitHub account. Your username will be your GitHub username (all lowercase). +1. Open and log in using your GitHub account. + Your username will be your GitHub username (all lowercase). 2. After logging in, navigate to **Profile**. -3. In your profile center, apply for an access token (Token) and save it securely. This token will be used for the `sdk.py sf-pkg login` command. +3. In your profile center, apply for an access token (Token) and save it + securely. This token will be used for the `sdk.py sf-pkg login` command. -![Log in to the website](./assert/log_in_to_the_website.png) -![Navigate to Profile](./assert/enter_profile.png) -![Create Token](./assert/create_token.png) +![Log in to the website](./assert/log_in_to_the_website.png) ![Navigate to +Profile](./assert/enter_profile.png) ![Create Token](./assert/create_token.png) ![Obtain Token](./assert/get_token.png) ```{note} @@ -44,7 +46,7 @@ sdk.py sf-pkg users Switch active user: ```bash -sdk.py sf-pkg use --name +sdk.py sf-pkg use --name ``` Show current active user: @@ -55,10 +57,15 @@ sdk.py sf-pkg current-user Notes: -- The selected user is mapped to a Conan remote with the same name, and remote operations use `-r=`. -- If no user is selected, remote commands will ask you to login or switch user first. -- If the same-name remote is missing, has a mismatched URL, or is authenticated as another user, local credentials for that user are cleared and you will be asked to login again. -- `sf-pkg logout --name ` also clears the same-name Conan remote for that user. +- The selected user is mapped to a Conan remote with the same name, and remote + operations use `-r=`. +- If no user is selected, remote commands will ask you to login or switch user + first. +- If the same-name remote is missing, has a mismatched URL, or is authenticated + as another user, local credentials for that user are cleared and you will be + asked to login again. +- `sf-pkg logout --name ` also clears the same-name Conan remote for + that user. To override user for a single command, use the `sf-pkg` group `--user` option: @@ -68,16 +75,17 @@ sdk.py sf-pkg --user upload --name /@ +sdk.py sf-pkg new --name ``` By default, this uses the active user. To temporarily select another user: ```bash -sdk.py sf-pkg --user new --name +sdk.py sf-pkg --user new --name ``` Optional parameters: @@ -90,10 +98,12 @@ Optional parameters: Example (with version and author information): ```bash -sdk.py sf-pkg new --name --version 1.0.0 --author yourname +sdk.py sf-pkg new --name --version 1.0.0 --author yourname ``` -Upon successful execution, a `conanfile.py` file will be generated. For detailed information, refer to the [Conan Official Documentation](https://docs.conan.io/en/latest/reference/conanfile.html). +Upon successful execution, a `conanfile.py` file will be generated. For detailed +information, refer to the [Conan Official +Documentation](https://docs.conan.io/en/latest/reference/conanfile.html). Generally, the default content of the `conanfile.py` file is as follows: @@ -128,18 +138,24 @@ class Example_AddRecipe(ConanFile): ``` Pay close attention to the following parameters: - -- `name`: Package name, required. Used as a unique identifier on `https://packages.sifli.com`. -- `version`: Package version number. It is recommended to use semantic versioning, such as `0.0.1`, `1.0.0`, etc. -- `user`: Your username (also called `namespace`) on `https://packages.sifli.com`, required. -- `license`: Open-source license. Common options include `Apache-2.0`, `MIT`, `GPL-3.0`, `BSD-3-Clause`, etc. The default is `Apache-2.0`. +- `name`: Package name, required. Used as a unique identifier on + `https://packages.sifli.com`. +- `version`: Package version number. It is recommended to use semantic + versioning, such as `0.0.1`, `1.0.0`, etc. +- `user`: Your username (also called `namespace`) on + `https://packages.sifli.com`, required. +- `license`: Open-source license. Common options include `Apache-2.0`, `MIT`, + `GPL-3.0`, `BSD-3-Clause`, etc. The default is `Apache-2.0`. - `author`: Package author/maintainer name, optional. - `url`: Package repository URL (GitHub/GitLab, etc.), optional. - `description`: Detailed description of the package, optional. -- `topics`: Package tags/topics for easier searching and categorization. Use tuple format, optional. -- `support_sdk_version`: Supported SiFli-SDK version, required. Format follows [Semantic Versioning range](https://semver.org/). +- `topics`: Package tags/topics for easier searching and categorization. Use + tuple format, optional. +- `support_sdk_version`: Supported SiFli-SDK version, required. Format follows + [Semantic Versioning range](https://semver.org/). -The combination of `user` and `name` serves as the unique identifier for the package. +The combination of `user` and `name` serves as the unique identifier for the +package. The `requirements` method is used to add package dependencies: @@ -150,14 +166,16 @@ def requirements(self): pass ``` -This indicates that no dependencies have been added. You can add required packages in the `requirements` method. For example: +This indicates that no dependencies have been added. You can add required +packages in the `requirements` method. For example: ```python def requirements(self): self.requires("sht30/0.0.4@caisong123") ``` -`self.requires` is used to specify dependencies in the format `package_name/version@username`. +`self.requires` is used to specify dependencies in the format +`package_name/version@username`. ## Build Package (sf-pkg build) @@ -169,7 +187,8 @@ sdk.py sf-pkg build --version ![Build Package](./assert/sf-pkg-build.png) -> It is recommended to use semantic versioning for the version number, such as `0.0.1`, `1.0.0`, etc. +> It is recommended to use semantic versioning for the version number, such as +> `0.0.1`, `1.0.0`, etc. ## Upload Package (sf-pkg upload) @@ -201,7 +220,8 @@ Command format explanation: ```bash sdk.py sf-pkg remove --name /@ --remote ``` - Note: `--remote` removes the package from the selected user's same-name remote (`-r=`). Please login first and ensure user state is valid. + Note: `--remote` removes the package from the selected user's same-name + remote (`-r=`). Please login first and ensure user state is valid. 3. Rebuild: ```bash sdk.py sf-pkg build --version @@ -213,6 +233,54 @@ Command format explanation: ### Verify Upload Result -After a successful upload, you can view the uploaded package on the server website: +After a successful upload, you can view the uploaded package on the server +website: ![Package on Server](./assert/pkg_in_website.png) + + +## Using as an Organization + +Organizations are designed for centralized management of component packages +maintained by multiple users. This is a core feature for team and +enterprise-level use cases. + +An organization can include multiple members, allowing them to share access to +component packages and release workflows within that organization. + +Usage workflows for organizations and individuals are largely identical, +differing only in the method of token acquisition and the workspace namespace. + +### Creating an Organization Token + +1. Open and sign in with your GitHub account. +2. After logging in, navigate to Organization Management. +3. Locate the target organization and click Manage. +4. Request an access token in the Organization Management section. Securely + store this token for use with the `sdk.py sf-pkg login` command. + +![Access Organization Management](./assert/enter_org.png) ![Manage +Organization](./assert/check_org.png) ![Create +Token](./assert/create_org_token.png) ![Acquire +Token](./assert/get_org_token.png) + +```{note} +Organization and personal tokens can coexist locally. You can switch between namespaces using `sf-pkg use` or the `sf-pkg --user` flag. +``` + +### Namespace Description + +1. When logging in as an organization, the namespace corresponds to the + organization name. Therefore, use the following command to log in via the + terminal: + + ```bash + sdk.py sf-pkg login -u -t + ``` + + where `org_name` represents the name of the organization. + +2. When creating a package configuration, the `author` field is independent of + the `namespace` and represents the specific author within the organization. + Ensure that the `user` field matches the organization name; **otherwise, the + component package cannot be uploaded successfully**. diff --git a/docs/source/en/sf_pkg/faq.md b/docs/source/en/sf_pkg/faq.md index b7a37efb9..543798f97 100644 --- a/docs/source/en/sf_pkg/faq.md +++ b/docs/source/en/sf_pkg/faq.md @@ -8,9 +8,11 @@ ## What should I do if dependency installation fails? -1. Check if the package name, version number, and username format in `conanfile.py` are correct +1. Check if the package name, version number, and username format in + `conanfile.py` are correct 2. Use `sdk.py sf-pkg search ` to confirm the package exists -3. Ensure you have executed `.\export.ps1` (or `./export.sh`) to initialize the environment +3. Ensure you have executed `.\export.ps1` (or `./export.sh`) to initialize the + environment ## How do I update installed dependencies? diff --git a/docs/source/en/sf_pkg/index.md b/docs/source/en/sf_pkg/index.md index c6c1b9e7d..adc0138bc 100644 --- a/docs/source/en/sf_pkg/index.md +++ b/docs/source/en/sf_pkg/index.md @@ -1,33 +1,38 @@ # SiFli Package Registry -Similar to [RT-PKG](../app_note/rt-pkg.md), SiFli Package Registry is also a package manager. However, SiFli Package Registry uses [Conan](https://conan.io/) as its underlying package management tool, supporting a rich set of package management features. It facilitates the creation, upload, and download of driver packages, and supports semantic versioning. +Similar to [RT-PKG](../app_note/rt-pkg.md), SiFli Package Registry is also a +package manager. However, SiFli Package Registry uses [Conan](https://conan.io/) +as its underlying package management tool, supporting a rich set of package +management features. It facilitates the creation, upload, and download of driver +packages, and supports semantic versioning. - Click here to access the [SiFli Package Registry](https://packages.sifli.com/) ## Prerequisites - Navigate to a valid SDK project directory -- Execute `.\export.ps1` (Windows) or `./export.sh` (Linux/macOS) to initialize the environment +- Execute `.\export.ps1` (Windows) or `./export.sh` (Linux/macOS) to initialize + the environment ## Quick Reference Command Table -| Command | Description | -| --------------------------------------------------------- | -------------------------- | -| `sdk.py sf-pkg login -u -t ` | Log in and store local credentials | -| `sdk.py sf-pkg users` | List locally logged-in users | -| `sdk.py sf-pkg use --name ` | Switch active user | -| `sdk.py sf-pkg current-user` | Show active user | -| `sdk.py sf-pkg new --name ` | Create a new package configuration | -| `sdk.py sf-pkg build --version ` | Build a package | -| `sdk.py sf-pkg upload --name /@` | Upload a package to the server | -| `sdk.py sf-pkg --user upload --name ...` | Temporarily override user for this command | -| `sdk.py sf-pkg remove --name ` | Clear local cache | -| `sdk.py sf-pkg init` | Initialize dependency configuration | -| `sdk.py sf-pkg install` | Install dependency packages | -| `sdk.py sf-pkg search ` | Search for available packages | +| Command | Description | +| ----------------------------------------------------------------- | ------------------------------------------ | +| `sdk.py sf-pkg login -u -t ` | Log in and store local credentials | +| `sdk.py sf-pkg users` | List locally logged-in users | +| `sdk.py sf-pkg use --name ` | Switch active user | +| `sdk.py sf-pkg current-user` | Show active user | +| `sdk.py sf-pkg new --name ` | Create a new package configuration | +| `sdk.py sf-pkg build --version ` | Build a package | +| `sdk.py sf-pkg upload --name /@` | Upload a package to the server | +| `sdk.py sf-pkg --user upload --name ...` | Temporarily override user for this command | +| `sdk.py sf-pkg remove --name ` | Clear local cache | +| `sdk.py sf-pkg init` | Initialize dependency configuration | +| `sdk.py sf-pkg install` | Install dependency packages | +| `sdk.py sf-pkg search ` | Search for available packages | ```{toctree} :titlesonly: -use -create -faq +Usage +Creation +FAQ ``` diff --git a/docs/source/en/sf_pkg/use.md b/docs/source/en/sf_pkg/use.md index 7754b3290..7fc22545c 100644 --- a/docs/source/en/sf_pkg/use.md +++ b/docs/source/en/sf_pkg/use.md @@ -1,6 +1,7 @@ # Using SiFli Package Registry in Your Project -The following steps explain how to install and use SiFli Package Registry dependencies in an existing project. +The following steps explain how to install and use SiFli Package Registry +dependencies in an existing project. ```{note} Some screenshots on this page were captured with the old CLI format. If a screenshot differs from the text, follow the current `sdk.py sf-pkg ...` commands in the document. @@ -12,19 +13,24 @@ Some screenshots on this page were captured with the old CLI format. If a screen sdk.py sf-pkg init ``` -Upon successful execution, a `conanfile.py` file will be generated in the `project` directory. +Upon successful execution, a `conanfile.py` file will be generated in the +`project` directory. -`conanfile.py` is the Conan configuration file used to define the dependencies required by the project. For detailed information, refer to the [Conan Official Documentation](https://docs.conan.io/en/latest/reference/conanfile.html). For now, you can ignore most of the content and focus only on the `requires` field. - -Generally, the auto-generated `conanfile.py` file contains a `requires` field similar to the following: +`conanfile.py` is the Conan configuration file used to define the dependencies +required by the project. For detailed information, refer to the [Conan Official +Documentation](https://docs.conan.io/en/latest/reference/conanfile.html). For +now, you can ignore most of the content and focus only on the `requires` field. +Generally, the auto-generated `conanfile.py` file contains a `requires` field +similar to the following: ```python requires = ( # "core-lib/1.0.0", ) ``` -This indicates that no dependencies have been added. You can manually add the required packages. For example, to add an SHT30 sensor driver package: +This indicates that no dependencies have been added. You can manually add the +required packages. For example, to add an SHT30 sensor driver package: ```python requires = ( @@ -39,7 +45,7 @@ The format for each dependency is `/@`. If you are unsure about the package name or version, you can search for it: ```bash -sdk.py sf-pkg search +sdk.py sf-pkg search ``` Example: @@ -47,7 +53,9 @@ Example: ```bash sdk.py sf-pkg search sht30 ``` -You can also search directly on the official website of the SiFli Package Registry: Click here to visit [SiFli Package Registry](https://packages.sifli.com/) +You can also search directly on the official website of the SiFli Package +Registry: Click here to visit [SiFli Package +Registry](https://packages.sifli.com/) ## Install Dependencies (sf-pkg install) @@ -60,16 +68,20 @@ sdk.py sf-pkg install ![Install Dependencies](./assert/sf-pkg-install.png) -After successful installation, an `sf-pkgs` folder will be generated in the `project` directory, containing the installed packages. +After successful installation, an `sf-pkgs` folder will be generated in the +`project` directory, containing the installed packages. ## Using the Driver Once installation is complete, you can use the driver directly: - You can compile immediately -- When including header files, there is no need to specify absolute paths—Conan will automatically handle path configuration +- When including header files, there is no need to specify absolute paths—Conan + will automatically handle path configuration ### Kconfig Configuration Notes -- `menuconfig` will automatically integrate all `Kconfig` files under the `sf-pkgs` folder -- These configuration options will appear in the **SiFli External Components** menu within `menuconfig` +- `menuconfig` will automatically integrate all `Kconfig` files under the + `sf-pkgs` folder +- These configuration options will appear in the **SiFli External Components** + menu within `menuconfig` diff --git a/docs/source/en/supported_boards/index.md b/docs/source/en/supported_boards/index.md index 938446eae..886e2d6b9 100644 --- a/docs/source/en/supported_boards/index.md +++ b/docs/source/en/supported_boards/index.md @@ -2,31 +2,52 @@ Development board source code root directory: `customer/boards` -The source code path for each board is shown in the **Board Directory** column in the table. For example, the code for development board 551-HDK is in the `eh-lb551` directory. This directory name is also used as the board name when compiling. - -For boards with multi-core chips, each board directory contains subdirectories organized by core. As shown in the figure below, the eh-lb551 directory has two subdirectories: `hcpu` and `lcpu`, which store the configuration code for the HCPU and LCPU of the SF32LB551 chip respectively. When using `scons --board=` to compile a program for a specific board, if no core is specified, the HCPU configuration is used by default. To specify the LCPU configuration, add the `_lcpu` suffix. For example, both `scons --board=eh-lb551` and `scons --board=eh-lb551_hcpu` compile with the 551-HDK's HCPU configuration, and the generated image files are saved in the `build_eh-lb551_hcpu` directory, while `scons --board=eh-lb551_lcpu` compiles with the 551-HDK's LCPU configuration, and the generated image files are saved in the `build_eh-lb551_lcpu` directory. - -For currently available development boards, we have created a naming convention, generally following the pattern `model-type_memory-type_display-interface`. Note that memory type and display interface may be omitted. - -Memory type naming rules: - -- A: Indicates the board uses SPI NAND memory, followed by the memory capacity in MB -- N: Indicates the board uses SPI NOR memory, followed by the memory capacity in MB -- R: Indicates the board uses SPI PSRAM memory, followed by the memory capacity in MB +The source code path for each board is shown in the **Board Directory** column +in the table. For example, the code for development board 551-HDK is in the +`eh-lb551` directory. This directory name is also used as the board name when +compiling. + +For boards with multi-core chips, each board directory contains subdirectories +organized by core. As shown in the figure below, the eh-lb551 directory has two +subdirectories: `hcpu` and `lcpu`, which store the configuration code for the +HCPU and LCPU of the SF32LB551 chip respectively. When using `scons +--board=` to compile a program for a specific board, if no core is +specified, the HCPU configuration is used by default. To specify the LCPU +configuration, add the `_lcpu` suffix. For example, both `scons +--board=eh-lb551` and `scons --board=eh-lb551_hcpu` compile with the 551-HDK's +HCPU configuration, and the generated image files are saved in the +`build_eh-lb551_hcpu` directory, while `scons --board=eh-lb551_lcpu` compiles +with the 551-HDK's LCPU configuration, and the generated image files are saved +in the `build_eh-lb551_lcpu` directory. + +For currently available development boards, we have created a naming convention, +generally following the pattern `model-type_memory-type_display-interface`. Note +that memory type and display interface may be omitted. + +- A: Indicates the board uses SPI NAND memory, followed by the memory capacity + in MB +- N: Indicates the board uses SPI NOR memory, followed by the memory capacity in + MB +- R: Indicates the board uses SPI PSRAM memory, followed by the memory capacity + in MB - E: Indicates the board uses eMMC memory, followed by the memory capacity in GB -For example, `a128r32n1` indicates 128MB SPI NAND memory, 32MB SPI PSRAM memory, and 1MB SPI NOR memory. +Memory type naming rules: -Some typical examples: +For example, `a128r32n1` indicates 128MB SPI NAND memory, 32MB SPI PSRAM memory, +and 1MB SPI NOR memory. -- `sf32lb52-nano_n4`: Indicates the Nano version development board of model SF32LB52, using 4MB SPI NOR memory. -- `sf32lb56-lcd_a128r12n1`: Indicates the LCD version development board of model SF32LB56, using 128MB SPI NAND memory, 12MB SPI PSRAM memory, and 1MB SPI NOR memory. +- `sf32lb52-nano_n4`: Indicates the Nano version development board of model + SF32LB52, using 4MB SPI NOR memory. +- `sf32lb56-lcd_a128r12n1`: Indicates the LCD version development board of model + SF32LB56, using 128MB SPI NAND memory, 12MB SPI PSRAM memory, and 1MB SPI NOR + memory. ```{image} ../../assets/folder.png :scale: 70% ``` -Please refer to [](../app_development/create_board.md) to create a custom board if your board is not listed here. +Some typical examples: + All platforms ## Overview - -This example demonstrates how to trigger Apple AMS (Apple Media Service) protocol subscription and simple handling of corresponding events. -AMS is an audio control protocol provided by Apple that allows access to the current iOS device's audio playback status and control of music play, pause, etc. + +This example demonstrates how to trigger Apple AMS (Apple Media Service) +protocol subscription and simple handling of corresponding events. AMS is an +audio control protocol provided by Apple that allows access to the current iOS +device's audio playback status and control of music play, pause, etc. ## Usage Instructions - -1. The example starts advertising upon boot with the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the device. This can be obtained using the finsh command "nvds get_mac". -2. Use BLE software (LightBlue, nRF Connect, etc.) on iOS devices (iPhone or iPad) to connect to this device. Note that AMS requires pairing to complete, so you must accept when the pairing dialog appears on the iOS device. -3. Play music on the iOS device. This example has registered AMS Player/queue/track, and you can see related content in the logs. - 1) Related protocol reference: [AMS Official Documentation](https://developer.apple.com/library/archive/documentation/CoreBluetooth/Reference/AppleMediaService_Reference/Specification/Specification.html) - + +1. The example starts advertising upon boot with the name + SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the + device. This can be obtained using the finsh command "nvds get_mac". +2. Use BLE software (LightBlue, nRF Connect, etc.) on iOS devices (iPhone or + iPad) to connect to this device. Note that AMS requires pairing to complete, + so you must accept when the pairing dialog appears on the iOS device. +3. Play music on the iOS device. This example has registered AMS + Player/queue/track, and you can see related content in the logs. + 1) Related protocol reference: [AMS Official + Documentation](https://developer.apple.com/library/archive/documentation/CoreBluetooth/Reference/AppleMediaService_Reference/Specification/Specification.html) ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_ams)). ++ One development board supported by this example ([Supported + Platforms](#Platform_ams)). + iOS device. ### menuconfig Configuration @@ -37,57 +45,71 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, can actively search for and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, can actively search + for and discover services, read/write data, and receive notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. - Enable: Enable BLE AMS - Macro switch: `CONFIG_BSP_BLE_AMS` - - Description: Apple Media Service. After registering AMS, provides iOS device playback control, playback synchronization, volume control, etc. + - Description: Apple Media Service. After registering AMS, provides iOS + device playback control, playback synchronization, volume control, + etc. 3. Enable AMS in Data service: - Path: Sifli middleware → Enable Data service - Enable: Enable AMS Service - Macro switch: `CONFIG_BSP_USING_AMS_SVC` - - Description: When using Data Service to register AMS, this option needs to be enabled + - Description: When using Data Service to register AMS, this option + needs to be enabled 4. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can be connected and successfully paired by BLE software on iOS (such as LightBlue, nRF Connect). -2. When the iOS device plays music, the device displays related information through logs. +1. It can be connected and successfully paired by BLE software on iOS (such as + LightBlue, nRF Connect). +2. When the iOS device plays music, the device displays related information + through logs. ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/ancs_dualcore/README_EN.md b/example/ble/ancs_dualcore/README_EN.md index 033888c67..3f679956a 100644 --- a/example/ble/ancs_dualcore/README_EN.md +++ b/example/ble/ancs_dualcore/README_EN.md @@ -4,79 +4,110 @@ Source code path: example/ble/ancs_dualcore (Platform_ancs)= ## Supported Platforms - + + eh-lb55x ## Overview - -This example demonstrates how to trigger Apple ANCS (Apple Notification Center Service) protocol subscription and simple handling of corresponding events. -ANCS is a messaging protocol provided by Apple that allows access to all messages received in the iOS device's notification bar and control of some special messages. + +This example demonstrates how to trigger Apple ANCS (Apple Notification Center +Service) protocol subscription and simple handling of corresponding events. ANCS +is a messaging protocol provided by Apple that allows access to all messages +received in the iOS device's notification bar and control of some special +messages. ## Usage Instructions - -1. The example starts advertising upon boot with the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the device. This can be obtained using the finsh command "nvds get_mac". -2. Use BLE software (LightBlue, nRF Connect, etc.) on iOS devices (iPhone or iPad) to connect to this device. Note that ANCS requires pairing to complete, so you must accept when the pairing dialog appears on the iOS device. - 2) Higher iOS versions may also show a system notification sharing confirmation dialog in addition to the pairing dialog, which can also be toggled in the iOS Bluetooth settings for the corresponding device. + +1. The example starts advertising upon boot with the name + SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the + device. This can be obtained using the finsh command "nvds get_mac". +2. Use BLE software (LightBlue, nRF Connect, etc.) on iOS devices (iPhone or + iPad) to connect to this device. Note that ANCS requires pairing to complete, + so you must accept when the pairing dialog appears on the iOS device. 2) + Higher iOS versions may also show a system notification sharing confirmation + dialog in addition to the pairing dialog, which can also be toggled in the + iOS Bluetooth settings for the corresponding device. 3. When messages are received, this example will print them through HCPU logs. - 1) Related protocol reference: [ANCS Official Documentation](https://developer.apple.com/library/archive/documentation/CoreBluetooth/Reference/AppleNotificationCenterServiceSpecification/Specification/Specification.html) - + 1) Related protocol reference: [ANCS Official + Documentation](https://developer.apple.com/library/archive/documentation/CoreBluetooth/Reference/AppleNotificationCenterServiceSpecification/Specification/Specification.html) ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_ancs)). ++ One development board supported by this example ([Supported + Platforms](#Platform_ancs)). + iOS device. ### menuconfig Configuration - Platform - - Select board peripherials->Select board: Select the running platform, please choose LB55XXX series according to the actual board. This option needs to be selected in both CPU corresponding options and ensure they are the same platform. + - Select board peripherials->Select board: Select the running platform, + please choose LB55XXX series according to the actual board. This option + needs to be selected in both CPU corresponding options and ensure they are + the same platform. - HCPU - - RTOS->On-chip Peripherial Drivers->Enable LCPU Patch[*]: - - RTOS->On-chip Peripherial Drivers->Enable LCPU image[*]: Enable LCPU Patch and image for LCPU to run normally. - - Sifli Middleware->Enable Data service[*]: Enable Data service, which provides a data interaction mechanism between data providers and data subscribers. - - Enable ble nvds service[*]: Enable NVDS data service in Data service. This service provides asynchronous NVDS operations for BLE stack/service running on LCPU to store data to HCPU flash. - - Third party packages->FlashDB[*]: Enable FlashDB to provide flash access interface, NVDS requires this service to be enabled. + - RTOS -> On-chip Peripheral Drivers -> Enable LCPU Patch[*]: + - RTOS->On-chip Peripherial Drivers->Enable LCPU image[*]: Enable LCPU Patch + and image for LCPU to run normally. + - Sifli Middleware->Enable Data service[*]: Enable Data service, which + provides a data interaction mechanism between data providers and data + subscribers. + - Enable ble nvds service[*]: Enable NVDS data service in Data service. + This service provides asynchronous NVDS operations for BLE + stack/service running on LCPU to store data to HCPU flash. + - Third party packages->FlashDB[*]: Enable FlashDB to provide flash access + interface, NVDS requires this service to be enabled. - LCPU - - Sifli Middleware->Enable BLE service[*]: Enable BLE service, which provides BLE GAP/GATT/COMMON services. - - Enable BLE ANCS[*]: Enable BLE ANCS service, which provides access to iOS ANCS service, obtains notifications and provides them to users. + - Sifli Middleware->Enable BLE service[*]: Enable BLE service, which + provides BLE GAP/GATT/COMMON services. + - Enable BLE ANCS[*]: Enable BLE ANCS service, which provides access to + iOS ANCS service, obtains notifications and provides them to users. - Sifli Middleware->Enable BLE stack[*]: Enable BLE protocol stack. - - Sifli Middleware->Enable Data service[*]: Enable Data service, which provides a data interaction mechanism between data providers and data subscribers. ANCS uses this mechanism mainly to separate data and UI. - - Enable ANCS service[*]: Enable ANCS data service in Data service. This service configures and enables BLE ANCS service and processes received notifications, providing processed data to subscribers of this service. - + - Sifli Middleware->Enable Data service[*]: Enable Data service, which + provides a data interaction mechanism between data providers and data + subscribers. ANCS uses this mechanism mainly to separate data and UI. + - Enable ANCS service[*]: Enable ANCS data service in Data service. This + service configures and enables BLE ANCS service and processes received + notifications, providing processed data to subscribers of this + service. ### Compilation and Flashing -Switch to the example project/lcpu/xx directory and run the scons command to compile: +Switch to the example project/lcpu/xx directory and run the scons command to +compile: ```c -> scons -j8 +> scons -j8 ``` -Switch to the example project/hcpu/xx directory and run the scons command to compile: +Switch to the example project/hcpu/xx directory and run the scons command to +compile: ```c -> scons -j8 +> scons -j8 ``` -Switch to the example `project/hcpu/xx/build_xx` directory and use JLink software commands to download the corresponding software: +Switch to the example `project/hcpu/xx/build_xx` directory and use JLink +software commands to download the corresponding software: ```c loadbin project/hcpu/xx/build_xx/xx.bin addr loadfile project/hcpu/xx/build_xx/xx.hex ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can be connected and successfully paired by BLE software on iOS (such as LightBlue, nRF Connect). -2. When iOS receives messages, the device displays related information through logs. +1. It can be connected and successfully paired by BLE software on iOS (such as + LightBlue, nRF Connect). +2. When iOS receives messages, the device displays related information through + logs. ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/basc/README_EN.md b/example/ble/basc/README_EN.md index 94b6a2cfe..9d3dd8ac4 100644 --- a/example/ble/basc/README_EN.md +++ b/example/ble/basc/README_EN.md @@ -9,52 +9,80 @@ The example can run on the following development boards: * sf32lb58-lcd series ## Overview -* This is an application example based on the Sifli BLE protocol stack that can read the microcontroller's battery level value. It includes the following functions: creation and registration of custom GATT services, BLE advertising (for Bluetooth connection), data read/write and notification mechanisms, and BASC functionality. +* This is an application example based on the Sifli BLE protocol stack that can + read the microcontroller's battery level value. It includes the following + functions: creation and registration of custom GATT services, BLE advertising + (for Bluetooth connection), data read/write and notification mechanisms, and + BASC functionality. ## GATT Protocol -GATT (Generic Attribute Profile, Generic Attribute Configuration File) is the core specification for low-power Bluetooth (BLE) communication, defining a unified framework and rules for data interaction between devices. It organizes data based on the attribute concept and is the foundation for BLE devices to implement service discovery, data read/write, real-time notifications, and other functions. GATT is essentially a data interaction protocol. -The GATT protocol includes the following types of data: - -* Service: A collection of related characteristics, representing a complete function of the device. -* Characteristic: The most common interaction unit in GATT, essentially a combination of related attributes. For example: "Heart Rate Characteristic" contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement Range (descriptor)". +GATT (Generic Attribute Profile, Generic Attribute Configuration File) is the +core specification for low-power Bluetooth (BLE) communication, defining a +unified framework and rules for data interaction between devices. It organizes +data based on the attribute concept and is the foundation for BLE devices to +implement service discovery, data read/write, real-time notifications, and other +functions. GATT is essentially a data interaction protocol. The GATT protocol +includes the following types of data: + +* Service: A collection of related characteristics, representing a complete + function of the device. +* Characteristic: The most common interaction unit in GATT, essentially a + combination of related attributes. For example: "Heart Rate Characteristic" + contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement + Range (descriptor)". * Attribute: The smallest data unit in GATT. Each attribute contains 3 parts: - 1. UUID: Used to uniquely identify the attribute. Differentiates different types of data (e.g., the UUID for "Heart Rate Value" is 0x2A37, and for "Battery Level" is 0x2A19) - 2. Value: The actual stored data (e.g., heart rate value "65", battery level "80%") - 3. Permissions: Access permissions for the attribute value, such as: read-only, write-only, read-write, notification, etc. -* Profile: A combination of multiple services, defined for specific application scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate monitoring must include "Heart Rate Service" and "Battery Service" (for users to check device battery level) + 1. UUID: Used to uniquely identify the attribute. Differentiates different + types of data (e.g., the UUID for "Heart Rate Value" is 0x2A37, and for + "Battery Level" is 0x2A19) + 2. Value: The actual stored data (e.g., heart rate value "65", battery level + "80%") + 3. Permissions: Access permissions for the attribute value, such as: + read-only, write-only, read-write, notification, etc. +* Profile: A combination of multiple services, defined for specific application + scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate + monitoring must include "Heart Rate Service" and "Battery Service" (for users + to check device battery level) ### Core Functions of GATT Service and Characteristic Discovery -* After the client connects to the server, it first needs to "traverse" the services and characteristics in the server to understand what data the other party can provide (similar to "querying a directory"). -* Process: Client sends "service discovery request" → Server returns all service UUIDs and ranges → Client then discovers the characteristics contained in each service. +* After the client connects to the server, it first needs to "traverse" the + services and characteristics in the server to understand what data the other + party can provide (similar to "querying a directory"). +* Process: Client sends "service discovery request" → Server returns all service + UUIDs and ranges → Client then discovers the characteristics contained in each + service. ## Using the Example ### Preparation Before Configuration -* Mobile phone recommendation: For iPhone, it is recommended to use third-party software LightBlue, and for Android, use nRF Connect for BLE testing. - +* Mobile phone recommendation: For iPhone, it is recommended to use third-party + software LightBlue, and for Android, use nRF Connect for BLE testing. ### menuconfig Configuration * The required configuration is already enabled by default ```c menuconfig --board=board_nane ``` 1. Enable Bluetooth +- Enable Bluetooth + - To enable: Enable bluetooth + - Macro: `CONFIG_BLUETOOTH` + - Description: Enables Bluetooth functionality. + +2. Enable Bluetooth-related FinSH commands (BT_FLASH) - Path: Sifli middleware → Bluetooth - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Function: Enable Bluetooth functionality -2. Enable Bluetooth-related finsh (BT_FLASH) -- Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT finsh - - Macro switch: `CONFIG_BT_FINSH` - - Function: Enable Bluetooth-related Finsh shell command support for convenient debugging - -3. Used to activate the Bluetooth battery service client (BLE battery service client) -- Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service +3. Enable Bluetooth Battery Service Client (BLE battery service client) +- Enable Bluetooth-related finsh (BT_FLASH) - Enable: BLE battery service client - - Macro switch: `CONFIG_BSP_BLE_BASC` - - Function: Enable Bluetooth Battery Service Client (BASC) profile implementation, allowing the device to act as a client to read battery level information from remote Bluetooth devices + - Macro: `CONFIG_BSP_BLE_BASC` + - Description: Enables the implementation of the Bluetooth Battery + Service Client (BASC) profile, allowing the device to function as a + client to read battery level information from remote Bluetooth + devices. + ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: @@ -62,34 +90,38 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### Running Result Display -If you can see the following log information printed in the boot log, it indicates that the example is running successfully: -* Bluetooth protocol initialization successful -![alt text](assets/ble_power.png) -* Advertising started successfully -![alt text](assets/adv_seccess.png) +If you can see the following log information printed in the boot log, it +indicates that the example is running successfully: +* Bluetooth protocol initialization successful ![alt text](assets/ble_power.png) +* Advertising started successfully ![alt text](assets/adv_seccess.png) -* Open the corresponding software downloaded above on your mobile phone and connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in the figure -![alt text](assets/connect.png) +* Open the corresponding software downloaded above on your mobile phone and + connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in + the figure ![alt text](assets/connect.png) -* After successful connection, you can see the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx connected in the mobile phone interface, as shown in the figure -![alt text](assets/mac.png) -![alt text](assets/connect_success.jpg) +* After successful connection, you can see the Bluetooth device named + SIFLI_APP-xx-xx-xx-xx-xx-xx connected in the mobile phone interface, as shown + in the figure ![alt text](assets/mac.png) ![alt + text](assets/connect_success.jpg) -* You can read the microcontroller's battery level and write values through the mobile app -![alt text](assets/read_write_cccd.png) -![alt text](assets/write_data.jpg) +* You can read the microcontroller's battery level and write values through the + mobile app ![alt text](assets/read_write_cccd.png) ![alt + text](assets/write_data.jpg) ### Troubleshooting -* If you cannot achieve the steps shown above, please check if Bluetooth is turned on on the mobile phone and whether the phone has connected to the microcontroller. -* Whether the correct menu option has been selected. \ No newline at end of file +* If you cannot achieve the steps shown above, please check if Bluetooth is + turned on on the mobile phone and whether the phone has connected to the + microcontroller. +* Whether the correct menu option has been selected. diff --git a/example/ble/central_and_peripheral/README_EN.md b/example/ble/central_and_peripheral/README_EN.md index 07096a8e0..e6363027c 100644 --- a/example/ble/central_and_peripheral/README_EN.md +++ b/example/ble/central_and_peripheral/README_EN.md @@ -4,27 +4,45 @@ Source code path: example/ble/central_and_peripheral (Platform_cen_peri)= ## Supported Platforms - + All platforms ## Overview - -This example demonstrates how to simultaneously implement GAP central and peripheral roles as well as GATT client and server on this platform. + +This example demonstrates how to simultaneously implement GAP central and +peripheral roles as well as GATT client and server on this platform. ## Usage Instructions - -1. The finsh commands for this example can be printed by entering "diss help" to show commands and usage methods. -2. When operating as a slave device, the board starts advertising upon boot with the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the device. It can be connected via BLE apps on mobile phones. -3. When operating as a master device, you can search for other slave devices and initiate connections through finsh commands. -4. When operating as a GATT server, write and read operations can be performed from the mobile client, or by enabling CCCD, the device will update the characteristic value every second. -5. When operating as a GATT client, you can search and display the server's database through finsh commands, and perform read or write operations on characteristic values. - + +1. The finsh commands for this example can be printed by entering "diss help" to + show commands and usage methods. +2. When operating as a slave device, the board starts advertising upon boot with + the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth + address of the device. It can be connected via BLE apps on mobile phones. +3. When operating as a master device, you can search for other slave devices and + initiate connections through finsh commands. +4. When operating as a GATT server, write and read operations can be performed + from the mobile client, or by enabling CCCD, the device will update the + characteristic value every second. +5. When operating as a GATT client, you can search and display the server's + database through finsh commands, and perform read or write operations on + characteristic values. +6. When acting as a central device, other peripheral devices can be discovered + and connected to via finsh commands. +7. When operating as a GATT server, the device supports read and write + operations from a mobile client. Additionally, if the Client Characteristic + Configuration Descriptor (CCCD) is enabled, the device updates characteristic + values at one-second intervals. +8. When operating as a GATT client, finsh commands can be used to discover and + display the server database, as well as perform read or write operations on + characteristic values. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_cen_peri)). ++ One development board supported by this example ([Supported + Platforms](#Platform_cen_peri)). + Mobile device. ### menuconfig Configuration @@ -37,49 +55,61 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, allows active service discovery, data reading/writing, and notification reception. + - Description: Switch for GATT CLIENT. When enabled, allows active + service discovery, data reading/writing, and notification reception. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, and link connection parameter updates. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, and link connection + parameter updates. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing -Switch to the example project/common directory and run the scons command to compile: +Switch to the example project/common directory and run the scons command to +compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/common/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/common/build_xx` directory and run +`uart_download.bat`, then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can be discovered and connected by mobile BLE apps, allowing corresponding GATT characteristic value read/write operations. -2. It can search for other BLE devices, connect to them and search the connected device's GATT database, while performing GATT read/write operations. +1. It can be discovered and connected by mobile BLE apps, allowing corresponding + GATT characteristic value read/write operations. +2. It can search for other BLE devices, connect to them and search the connected + device's GATT database, while performing GATT read/write operations. ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | ------------------------------------------- | +| 0.0.1 | 01/2025 | Initial version | +| 0.0.2 | 12/2025 | Extended advertising is enabled by default. | +| | | | diff --git a/example/ble/central_and_peripheral_with_pingpong_ota/README_EN.md b/example/ble/central_and_peripheral_with_pingpong_ota/README_EN.md index 394353a1f..a13e64ab4 100644 --- a/example/ble/central_and_peripheral_with_pingpong_ota/README_EN.md +++ b/example/ble/central_and_peripheral_with_pingpong_ota/README_EN.md @@ -1,26 +1,45 @@ # BLE Central and Peripheral with Pingpong OTA Example + Source Code Path: example/ble/central_and_peripheral_with_pingpong_ota +(Platform_cen_peri)= + (Platform_cen_peri)= ## Supported Platforms - + Projects with flash table programmed in mpi5 + ## Overview - -This example demonstrates how the platform can function as both GAP central and peripheral, as well as GATT client and server simultaneously. -It also shows how to upgrade the project using the pingpong method + +This example demonstrates how the platform can function as both GAP central and +peripheral, as well as GATT client and server simultaneously. It also shows how +to upgrade the project using the pingpong method + + ## Example Usage - -1. The Finsh commands for this example can be printed by entering 'diss help' to show command usage. -2. When acting as a peripheral device, it will start advertising on boot with a name formatted as SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the device's Bluetooth address. You can connect using a mobile BLE APP. -3. When acting as a central device, you can search for other peripheral devices through finsh commands and initiate connections. -4. When acting as a GATT server, you can perform write and read operations on the mobile terminal, or enable CCCD, and the device will update the characteristic value every second. -5. When acting as a GATT client, you can search and display the server's database through finsh commands, and perform read or write operations on characteristic values. -6. Connect the board through the SIFLE BLE APP, select a file, and perform the upgrade + +1. The Finsh commands for this example can be printed by entering 'diss help' to + show command usage. +2. When acting as a peripheral device, it will start advertising on boot with a + name formatted as SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the + device's Bluetooth address. You can connect using a mobile BLE APP. +3. When acting as a central device, you can search for other peripheral devices + through finsh commands and initiate connections. +4. When acting as a GATT server, you can perform write and read operations on + the mobile terminal, or enable CCCD, and the device will update the + characteristic value every second. +5. When acting as a GATT client, you can search and display the server's + database through finsh commands, and perform read or write operations on + characteristic values. +6. Connect the board through the SIFLE BLE APP, select a file, and perform the + upgrade + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](#Platform_cen_peri)). ++ A development board supported by this example ([Supported + Platforms](#Platform_cen_peri)). + A mobile device. + ### menuconfig Configuration 1. Enable Bluetooth(`BLUETOOTH`): - Path: Sifli middleware → Bluetooth @@ -31,18 +50,25 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, allows active service discovery, data reading/writing, and notification reception. + - Description: Switch for GATT CLIENT. When enabled, allows active + service discovery, data reading/writing, and notification reception. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, and link connection parameter updates. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, and link connection + parameter updates. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. 4. Enable pingpong OTA related features: - Path: Sifli middleware → Device firmware update support functions - Enable: Device firmware using compress @@ -50,7 +76,8 @@ Before running this example, you need to prepare: - Description: Enable DFU compression functionality - Enable: NAND flash OTA - Macro switch: `CONFIG_OTA_56X_NAND` - - Description: Enable pingpong OTA architecture. Although the macro name includes 56X, it is not limited to specific chipset types. + - Description: Enable pingpong OTA architecture. Although the macro name + includes 56X, it is not limited to specific chipset types. 5. Enable solution OTA macro: - Path: Home page - Enable: using solution dfu protocol @@ -58,52 +85,74 @@ Before running this example, you need to prepare: - Description: Enable solution dfu protocol. ### Other Access Related Notes -1. SConstruct -FTAB needs to be added via addchildproj: -![Sconstruct](./assets/SConstruct.png) -2. ptab.json -Need to allocate a main and base2 region with the same size as HCPU_FLASH_CODE_LOAD_REGION as the pong region: -![PTAB](./assets/ptab.png) -3. Boot loader -Need to add jump logic, please refer to the implementation of this example for details: -![BOOT](./assets/bootloader.png) +1. SConstruct FTAB needs to be added via addchildproj: + ![Sconstruct](./assets/SConstruct.png) + +2. ptab.json Need to allocate a main and base2 region with the same size as + HCPU_FLASH_CODE_LOAD_REGION as the pong region: ![PTAB](./assets/ptab.png) + +3. Boot loader Need to add jump logic, please refer to the implementation of + this example for details: ![BOOT](./assets/bootloader.png) + 4. Generation Command ```shell .\imgtoolv37.exe gen_dfu --img_para main 0 0 --key=s01 --sigkey=sig --dfu_id=1 --hw_ver=51 --sdk_ver=7001 --fw_ver=1001001 --com_type=0 --bksize=2048 --align=0 ``` main is the name of the bin to be upgraded. If it's hcpu.bin, just fill in hcpu. -The first parameter after the bin name is for compression, 16 means using compression, 0 means no compression. Only no compression can be selected. -The second parameter after the bin name represents the image id, hcpu is 0, and multiple bins can be generated simultaneously. -Then you need to implement whether the subsequent bins are stored in the backup area and installed finally, or directly overwrite the target address. -5. Mobile Operation -The operation is shown in the following figure: search for the board's BLE broadcast, click on the corresponding device, then select nand dfu, first select the ctrl file, then select hcpu as the outmain.bin generated刚才制作的outmain.bin, and finally click the start button. -![app1](./assets/app.jpg)![app2](./assets/app2.jpg) -![app3](./assets/app3.jpg)![app2](./assets/app4.jpg) +The first parameter after the bin name is for compression, 16 means using +compression, 0 means no compression. Only no compression can be selected. The +second parameter after the bin name represents the image id, hcpu is 0, and +multiple bins can be generated simultaneously. Then you need to implement +whether the subsequent bins are stored in the backup area and installed finally, +or directly overwrite the target address. 5. Mobile Operation The operation is +shown in the following figure: search for the board's BLE broadcast, click on +the corresponding device, then select nand dfu, first select the ctrl file, then +select hcpu as the outmain.bin generated刚才制作的outmain.bin, and finally click the +start button. ![app1]{1}![app2]{2} ![app3]{3}![app2]{4} + +5. **Smartphone Operation** \ + \ + Follow the steps illustrated below: Scan for the board's BLE broadcast and + select the corresponding device. Navigate to **nand dfu**, select the + **ctrl** file, and then designate the previously generated `outmain.bin` as + the **hcpu**. Finally, tap **start**.\ + \ + ![app1](./assets/app.jpg)![app2](./assets/app2.jpg) + ![app3](./assets/app3.jpg)![app2](./assets/app4.jpg) + ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=sf32lb58-lcd_n16r64n4 -j8 +> scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -Switch to the example `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Switch to the example `project/build_xx` directory, run `uart_download.bat`, and +select the port as prompted to download: ```c $ ./uart_download.bat Uart Download please input the serial port num:5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). + ## Expected Results - + After the example starts: -1. It can be discovered and connected by the mobile BLE APP, allowing corresponding GATT characteristic read/write operations. -2. It can search for other BLE devices, connect and search the connected device's GATT database, and perform GATT read/write operations. +1. It can be discovered and connected by the mobile BLE APP, allowing + corresponding GATT characteristic read/write operations. +2. It can search for other BLE devices, connect and search the connected + device's GATT database, and perform GATT read/write operations. 3. It can be upgraded using the APP + ## Troubleshooting + + ## Reference Documentation - + + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |07/2025 |Initial version | -| | | | -| | | | -No newline at end of right file. \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 07/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/cppc/README_EN.md b/example/ble/cppc/README_EN.md index a58992530..d73f7e96a 100644 --- a/example/ble/cppc/README_EN.md +++ b/example/ble/cppc/README_EN.md @@ -9,31 +9,55 @@ The example can run on the following development boards: * sf32lb58-lcd series ## Overview -* This is an application example based on the Sifli BLE protocol stack that creates a custom GATT service, performs BLE advertising and connection, and enables basic GATT data interaction after connection. It can send CCPC sensor data to a mobile phone via Bluetooth, and the phone can also write data. +* This is an application example based on the Sifli BLE protocol stack that + creates a custom GATT service, performs BLE advertising and connection, and + enables basic GATT data interaction after connection. It can send CCPC sensor + data to a mobile phone via Bluetooth, and the phone can also write data. ## GATT Protocol -GATT (Generic Attribute Profile, Generic Attribute Configuration File) is the core specification for low-power Bluetooth (BLE) communication, defining a unified framework and rules for data interaction between devices. It organizes data based on the attribute concept and is the foundation for BLE devices to implement service discovery, data read/write, real-time notifications, and other functions. GATT is essentially a data interaction protocol. -The GATT protocol includes the following types of data: - -* Service: A collection of related characteristics, representing a complete function of the device. - -* Characteristic: The most common interaction unit in GATT, essentially a combination of related attributes. For example: "Heart Rate Characteristic" contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement Range (descriptor)". +GATT (Generic Attribute Profile, Generic Attribute Configuration File) is the +core specification for low-power Bluetooth (BLE) communication, defining a +unified framework and rules for data interaction between devices. It organizes +data based on the attribute concept and is the foundation for BLE devices to +implement service discovery, data read/write, real-time notifications, and other +functions. GATT is essentially a data interaction protocol. The GATT protocol +includes the following types of data: + +* Service: A collection of related characteristics, representing a complete + function of the device. + +* Characteristic: The most common interaction unit in GATT, essentially a + combination of related attributes. For example: "Heart Rate Characteristic" + contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement + Range (descriptor)". * Attribute: The smallest data unit in GATT. Each attribute contains 3 parts: - 1. UUID: Used to uniquely identify the attribute. Differentiates different types of data (e.g., the UUID for "Heart Rate Value" is 0x2A37, and for "Battery Level" is 0x2A19) - 2. Value: The actual stored data (e.g., heart rate value "65", battery level "80%") - 3. Permissions: Access permissions for the attribute value, such as: read-only, write-only, read-write, notification, etc. -* Profile: A combination of multiple services, defined for specific application scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate monitoring must include "Heart Rate Service" and "Battery Service" (for users to check device battery level) + 1. UUID: Used to uniquely identify the attribute. Differentiates different + types of data (e.g., the UUID for "Heart Rate Value" is 0x2A37, and for + "Battery Level" is 0x2A19) + 2. Value: The actual stored data (e.g., heart rate value "65", battery level + "80%") + 3. Permissions: Access permissions for the attribute value, such as: + read-only, write-only, read-write, notification, etc. +* Profile: A combination of multiple services, defined for specific application + scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate + monitoring must include "Heart Rate Service" and "Battery Service" (for users + to check device battery level) ### Core Functions of GATT Service and Characteristic Discovery -* After the client connects to the server, it first needs to "traverse" the services and characteristics in the server to understand what data the other party can provide (similar to "querying a directory"). -* Process: Client sends "service discovery request" → Server returns all service UUIDs and ranges → Client then discovers the characteristics contained in each service. +* After the client connects to the server, it first needs to "traverse" the + services and characteristics in the server to understand what data the other + party can provide (similar to "querying a directory"). +* Process: Client sends "service discovery request" → Server returns all service + UUIDs and ranges → Client then discovers the characteristics contained in each + service. ## Using the Example ### Preparation Before Configuration -* Mobile phone recommendation: For iPhone, it is recommended to use third-party software LightBlue, and for Android, use nRF Connect for BLE testing. +* Mobile phone recommendation: For iPhone, it is recommended to use third-party + software LightBlue, and for Android, use nRF Connect for BLE testing. ### menuconfig Configuration * The required configuration is already enabled by default @@ -42,23 +66,24 @@ Service and Characteristic Discovery menuconfig --board=board_name ``` 1. Enable Bluetooth +- Enable Bluetooth + - To enable: Enable bluetooth + - Macro: `CONFIG_BLUETOOTH` + - Description: Enables Bluetooth functionality. + +2. Enable Bluetooth-related FinSH commands (BT_FINSH) - Path: Sifli middleware → Bluetooth - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Function: Enable Bluetooth functionality -2. Enable Bluetooth-related finsh (BT_FLASH) -- Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT finsh - - Macro switch: `CONFIG_BT_FINSH` - - Function: Enable Bluetooth-related Finsh shell command support for convenient debugging - -3. Used to enable Bluetooth Cycling Power Profile Client functionality (Enable BLE cycling power collector) -- Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service +3. Enables the Bluetooth Low Energy (BLE) Cycling Power Profile (CPP) Collector +role. +- Enable Bluetooth-related finsh (BT_FLASH) - Enable: Enable BLE cycling power collector - - Macro switch: `CONFIG_BSP_BLE_CPPC` - - Function: Used to enable Bluetooth cycling power, specifically for handling cycling power-related data transmission - + - Macro: `CONFIG_BSP_BLE_CPPC` + - Function: Enables the BLE Cycling Power Profile for handling data + transmission related to cycling power metrics. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: @@ -66,29 +91,33 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### Running Result Display -If you can see log information printed in the boot log, it indicates that the example is running successfully: -* Bluetooth protocol initialization successful -![alt text](assets/ble_power.png) -* Advertising started successfully -![alt text](assets/adv_seccess.png) +If you can see log information printed in the boot log, it indicates that the +example is running successfully: +* Bluetooth protocol initialization successful ![alt text](assets/ble_power.png) +* Advertising started successfully ![alt text](assets/adv_seccess.png) -* Open the corresponding software downloaded above on your mobile phone and connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in the figure -![alt text](assets/connect.png) +* Open the corresponding software downloaded above on your mobile phone and + connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in + the figure ![alt text](assets/connect.png) -* After successful connection, you can see the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx connected in the mobile phone interface, as shown in the figure -![alt text](assets/mac.png) -![alt text](assets/connect_success.jpg) +* After successful connection, you can see the Bluetooth device named + SIFLI_APP-xx-xx-xx-xx-xx-xx connected in the mobile phone interface, as shown + in the figure ![alt text](assets/mac.png) ![alt + text](assets/connect_success.jpg) ### Troubleshooting -* If you cannot achieve the steps shown above, please check if Bluetooth is turned on on the mobile phone and whether the phone has connected to the microcontroller. -* Whether the correct menu option has been selected. \ No newline at end of file +* If you cannot achieve the steps shown above, please check if Bluetooth is + turned on on the mobile phone and whether the phone has connected to the + microcontroller. +* Whether the correct menu option has been selected. diff --git a/example/ble/cscpc/README_EN.md b/example/ble/cscpc/README_EN.md index b72e2a922..6755ace87 100644 --- a/example/ble/cscpc/README_EN.md +++ b/example/ble/cscpc/README_EN.md @@ -9,32 +9,60 @@ The example can run on the following development boards: * sf32lb58-lcd series ## Overview -* This is an application example based on the Sifli BLE protocol stack. It creates a custom GATT service, performs BLE advertising and connection, and enables basic GATT data interaction after connection. CSCPC sensor data can be sent to the mobile phone via Bluetooth, and the mobile phone can also write data. +* This is an application example based on the Sifli BLE protocol stack. It + creates a custom GATT service, performs BLE advertising and connection, and + enables basic GATT data interaction after connection. CSCPC sensor data can be + sent to the mobile phone via Bluetooth, and the mobile phone can also write + data. ## CSCPC Basic Concepts -* CSCPC is one of the Bluetooth standard profiles, used for receiving and processing data from cycling sensors (such as speedometers, cadence meters). This profile allows the device to connect to cycling sensors (server side) as a client and obtain relevant data. +* CSCPC is one of the Bluetooth standard profiles, used for receiving and + processing data from cycling sensors (such as speedometers, cadence meters). + This profile allows the device to connect to cycling sensors (server side) as + a client and obtain relevant data. ## GATT Protocol -GATT (Generic Attribute Profile) is the core specification for low-energy Bluetooth (BLE) communication, defining a unified framework and rules for data interaction between devices. It organizes data based on the concept of attributes and is the foundation for BLE devices to implement service discovery, data read/write, real-time notifications, and other functions. GATT is essentially a data interaction protocol. -The GATT protocol includes the following types of data: - -* Service: A collection of related characteristics, representing a complete function of the device. -* Characteristic: The most common interaction unit in GATT, essentially a combination of related attributes. For example: "Heart Rate Characteristic" contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement Range (descriptor)". +GATT (Generic Attribute Profile) is the core specification for low-energy +Bluetooth (BLE) communication, defining a unified framework and rules for data +interaction between devices. It organizes data based on the concept of +attributes and is the foundation for BLE devices to implement service discovery, +data read/write, real-time notifications, and other functions. GATT is +essentially a data interaction protocol. The GATT protocol includes the +following types of data: + +* Service: A collection of related characteristics, representing a complete + function of the device. +* Characteristic: The most common interaction unit in GATT, essentially a + combination of related attributes. For example: "Heart Rate Characteristic" + contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement + Range (descriptor)". * Attribute: The smallest data unit in GATT. Each attribute consists of 3 parts: - 1. UUID: Uniquely identifies the attribute. Distinguishes different types of data (e.g., the UUID for "Heart Rate Value" is 0x2A37, "Battery Level" is 0x2A19) - 2. Value: The actual stored data (e.g., heart rate value "65", battery level "80%") - 3. Permissions: Access permissions for the attribute value, such as: read-only, write-only, read-write, notification, etc. -* Profile: A combination of multiple services, defined for specific application scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate monitoring must include "Heart Rate Service" and "Battery Service" (for user convenience to check device battery level) + 1. UUID: Uniquely identifies the attribute. Distinguishes different types of + data (e.g., the UUID for "Heart Rate Value" is 0x2A37, "Battery Level" is + 0x2A19) + 2. Value: The actual stored data (e.g., heart rate value "65", battery level + "80%") + 3. Permissions: Access permissions for the attribute value, such as: + read-only, write-only, read-write, notification, etc. +* Profile: A combination of multiple services, defined for specific application + scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate + monitoring must include "Heart Rate Service" and "Battery Service" (for user + convenience to check device battery level) ### Core Functions of GATT Service and Characteristic Discovery -* After the client connects to the server, it first needs to "traverse" the services and characteristics in the server to understand what data the other party can provide (similar to "querying a directory"). -* Process: Client sends "service discovery request" → Server returns all service UUIDs and ranges → Client then discovers the characteristics contained in each service. +* After the client connects to the server, it first needs to "traverse" the + services and characteristics in the server to understand what data the other + party can provide (similar to "querying a directory"). +* Process: Client sends "service discovery request" → Server returns all service + UUIDs and ranges → Client then discovers the characteristics contained in each + service. ## Example Usage ### Preparation Before Configuration -* Mobile phone recommendation: For iPhone, use third-party software LightBlue; for Android, use nRF Connect for BLE testing. +* Mobile phone recommendation: For iPhone, use third-party software LightBlue; + for Android, use nRF Connect for BLE testing. ### Menuconfig Configuration * "The required configuration is enabled by default @@ -42,24 +70,25 @@ Service and Characteristic Discovery ```c menuconfig --board=board_name ``` - 1. Enable Bluetooth +- Enable Bluetooth + - To enable: Enable bluetooth + - Macro: `CONFIG_BLUETOOTH` + - Description: Enables Bluetooth functionality. + +2. Enable Bluetooth-related FinSH commands (BT_FINSH) - Path: Sifli middleware → Bluetooth - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Function: Enable Bluetooth functionality -2. Enable Bluetooth-related finsh (BT_FLASH) -- Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT finsh - - Macro switch: `CONFIG_BT_FINSH` - - Function: Enable Bluetooth-related Finsh shell command support for convenient debugging - -3. Used to activate the Bluetooth cycling speed and cadence profile (Enable BLE cycling speed and cadence collector) -- Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - - Enable: Enable BLE cycling speed and cadence collector - - Macro switch: `CONFIG_BSP_BLE_CSCPC` - - Function: Enable Bluetooth CSCPC profile implementation, allowing the device to act as a speed and cadence data receiver (client) +3. Enable BLE Cycling Speed and Cadence Profile (CSCP) Collector +- Enable Bluetooth-related finsh (BT_FLASH) + - Standard: Enable BLE cycling speed and cadence collector + - Macro: `CONFIG_BSP_BLE_CSCPC` + - Description: Enables the implementation of the BLE CSCP profile, + allowing the device to function as a collector (client) for speed and + cadence data. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: @@ -68,34 +97,37 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and follow the prompts to select the port for downloading: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and follow the prompts to +select the port for downloading: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### Running Result Display -If you can see log information printed in the boot log, it indicates that the example is running successfully: -* Bluetooth protocol initialization successful -![alt text](assets/ble_power.png) -* Advertising started successfully -![alt text](assets/adv_seccess.png) +If you can see log information printed in the boot log, it indicates that the +example is running successfully: +* Bluetooth protocol initialization successful ![alt text](assets/ble_power.png) +* Advertising started successfully ![alt text](assets/adv_seccess.png) -* Open the corresponding software downloaded above on the mobile phone and connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in the figure -![alt text](assets/connect.png) +* Open the corresponding software downloaded above on the mobile phone and + connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in + the figure ![alt text](assets/connect.png) -* After successful connection, you can see in the mobile phone interface that the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx is connected, as shown in the figure -![alt text](assets/mac.png) -![alt text](assets/connect_success.jpg) - -* Data can be read and written through the mobile app -![alt text](assets/read_write_cccd.png) -![alt text](assets/write_data.jpg) +* After successful connection, you can see in the mobile phone interface that + the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx is connected, as shown + in the figure ![alt text](assets/mac.png) ![alt + text](assets/connect_success.jpg) +* Data can be read and written through the mobile app ![alt + text](assets/read_write_cccd.png) ![alt text](assets/write_data.jpg) ### Troubleshooting -* If you cannot achieve the steps shown above, please check if Bluetooth is turned on on the mobile phone and if the mobile phone has connected to the microcontroller. -* Check if the correct menu option has been selected \ No newline at end of file +* If you cannot achieve the steps shown above, please check if Bluetooth is + turned on on the mobile phone and if the mobile phone has connected to the + microcontroller. +* Check if the correct menu option has been selected + diff --git a/example/ble/file_transfer/README_EN.md b/example/ble/file_transfer/README_EN.md index f713aa218..0380475c5 100644 --- a/example/ble/file_transfer/README_EN.md +++ b/example/ble/file_transfer/README_EN.md @@ -1,22 +1,35 @@ # BLE File Transfer Example -Source code path: example/ble/file_transfer + +Source code path: example/ble/file_transfer (Platform_file_rec)= + (Platform_file_rec)= ## Supported Platforms - + All platforms + ## Overview - -This example demonstrates how to implement a GAP peripheral role on this platform to receive files sent from a mobile device. + +This example demonstrates how to implement a GAP peripheral role on this +platform to receive files sent from a mobile device. + ## Example Usage - -1. The Finsh commands for this example can be displayed by entering `diss help` to show command usage. -2. When operating as a peripheral device, it will start advertising on boot with the name format: SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the device's Bluetooth address. You can connect using a mobile BLE app. -3. The sifli ble serial transport protocol can be used to send files from the mobile device to the target device, supporting one or multiple files in a single transfer. + +1. The Finsh commands for this example can be displayed by entering `diss help` + to show command usage. +2. When operating as a peripheral device, it will start advertising on boot with + the name format: SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the + device's Bluetooth address. You can connect using a mobile BLE app. +3. The sifli ble serial transport protocol can be used to send files from the + mobile device to the target device, supporting one or multiple files in a + single transfer. + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](#Platform_file_rec)). ++ A development board supported by this example ([Supported + Platforms](#Platform_file_rec)). + A mobile device. + ### menuconfig Configuration 1. Enable Bluetooth(`BLUETOOTH`): - Path: Sifli middleware → Bluetooth @@ -27,68 +40,88 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled 4. Enable transmission related macros: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE serial transmission - Macro switch: `CONFIG_BSP_BLE_SERIAL_TRANSMISSION` - - Description: Serial transmission protocol. When enabled, it provides a simple serial transmission protocol that allows users to transmit content to the development board via BLE. + - Description: Serial transmission protocol. When enabled, it provides a + simple serial transmission protocol that allows users to transmit + content to the development board via BLE. - Enable: Enable watch face downloaded via BLE - Macro switch: `CONFIG_BSP_BLE_WATCH_FACE` - - Description: Watch face transmission protocol. Depends on serial transmission. When enabled, files can be transferred to the development board via BLE using the encapsulated mobile SDK. - + - Description: Watch face transmission protocol. Depends on serial + transmission. When enabled, files can be transferred to the + development board via BLE using the encapsulated mobile SDK. + ### Compilation and Flashing -Navigate to the example's project/common directory and run the scons command to compile: +Navigate to the example's project/common directory and run the scons command to +compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Navigate to the example's `project/common/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Navigate to the example's `project/common/build_xx` directory and run +`uart_download.bat`, then select the port as prompted to download: ```c $ ./uart_download.bat Uart Download please input the serial port num:5 ``` -For detailed compilation and downloading steps, please refer to the relevant sections in [Quick Start](/quickstart/get-started.md). +For detailed compilation and downloading steps, please refer to the relevant +sections in [Quick Start](/quickstart/get-started.md). + ## Expected Results - + After the example starts: 1. It can be discovered and connected by a mobile BLE app. -2. Compress the files to be transferred into a single .zip file and transfer this file to your mobile device. -3. Use the SIFLI BLE APP to search, connect the device, then go to the watchface interface, select the custom file, and then choose this file. This file can then be transferred to the file system of the development board. +2. Compress the files to be transferred into a single .zip file and transfer + this file to your mobile device. +3. Use the SIFLI BLE APP to search, connect the device, then go to the watchface + interface, select the custom file, and then choose this file. This file can + then be transferred to the file system of the development board. 4. Mobile app operation steps: -- Enable location permission for opening the feature -![APP1](./assets/app0.png) -- Click the query button at the bottom right corner to enter the Bluetooth scanning interface. -![APP1](./assets/app1.png) -- Click on "SCAN" to start the scan. -![APP2](./assets/app2.png) -- After finding the device, click on "SORT", and the broadcast named "SIFLI_APP-xx-xx-xx-xx-xx-xx" will be placed at the top. -![APP3](./assets/app3.png) -- Click on the broadcast name "SIFLI_APP-xx-xx-xx-xx-xx-xx" to enter the device interface. -![APP4](./assets/app4.png) +- Enable location permission for opening the feature ![APP1](./assets/app0.png) +- Click the query button at the bottom right corner to enter the Bluetooth + scanning interface. ![APP1](./assets/app1.png) +- Click on "SCAN" to start the scan. ![APP2](./assets/app2.png) +- After finding the device, click on "SORT", and the broadcast named + "SIFLI_APP-xx-xx-xx-xx-xx-xx" will be placed at the top. + ![APP3](./assets/app3.png) +- Click on the broadcast name "SIFLI_APP-xx-xx-xx-xx-xx-xx" to enter the device + interface. ![APP4](./assets/app4.png) - Click on the upper right corner to enter the operation interface. -![APP4](./assets/app5.png) + ![APP4](./assets/app5.png) - Click "CONNECT" to ensure that the State is "CONNECT" -![APP4](./assets/app6.png) -- Swipe up the last box, find File transfer WFPUSH2 and click to enter the file transfer interface -![APP4](./assets/app7.png) -- Click on "SELECT FILE" to select the pre-prepared zip file from your phone, and set the "File Type" to 3. Then, check the "With Byte Align" option, and finally click "START". -![APP4](./assets/app8.png) - -- After the transmission is completed, execute the command in the console window to enter the "file_recv" folder, and then execute the "ls" command to view the list of files. Among them, the content of the zip file will be displayed. -![APP4](./assets/app9.png) + ![APP4](./assets/app6.png) +- Swipe up the last box, find File transfer WFPUSH2 and click to enter the file + transfer interface ![APP4](./assets/app7.png) +- Click on "SELECT FILE" to select the pre-prepared zip file from your phone, + and set the "File Type" to 3. Then, check the "With Byte Align" option, and + finally click "START". ![APP4](./assets/app8.png) +- After the transmission is completed, execute the command in the console window + to enter the "file_recv" folder, and then execute the "ls" command to view the + list of files. Among them, the content of the zip file will be displayed. + ![APP4](./assets/app9.png) ## Access to the mobile APP and DEMO project for use ### Download address of Android's free software application @@ -98,19 +131,20 @@ https://www.pgyer.com/gurSBc https://github.com/OpenSiFli/SiFli_OTA_APP\ The corresponding part is "3. SiFli-SDK OTA" -### iOS demo工程 +### iOS Demo Project https://github.com/OpenSiFli/SiFli_OTA_APP_IOS\ -The corresponding part is "SiFli-SDK OTA (Nor Offline)" -SiFli-SDK file transfer +The corresponding part is "SiFli-SDK OTA (Nor Offline)" SiFli-SDK file transfer ## Troubleshooting -When the development board returns an error, check the ble_watchface_status_id_t enumeration in bf0_sibles_watchface.h +When the development board returns an error, check the ble_watchface_status_id_t +enumeration in bf0_sibles_watchface.h + ## Reference Documentation - + + ## Update History -| Version | Date | Release Notes | -|:--------|:--------|:--------------| +| Version | Date | Release Notes | +| ------- | ------- | --------------- | | 0.0.1 | 07/2025 | Initial version | -| | | | -| | | | -No newline at end of right file. \ No newline at end of file +| | | | +| | | | diff --git a/example/ble/hid/README_EN.md b/example/ble/hid/README_EN.md index 5abcad25c..93754d4cc 100644 --- a/example/ble/hid/README_EN.md +++ b/example/ble/hid/README_EN.md @@ -4,30 +4,41 @@ Source Code Path: example/ble/hid (Platform_hid)= ## Supported Platforms - + All platforms ## Overview - + 1. This example demonstrates how to implement BLE HID on this platform. 2. The example implements two types of HID: HID_KEYBOARD and HID_CONSUMER. - 1) By default, main.c defines HID_KEYBOARD. You can switch the supported type by undefining HID_KEYBOARD and defining HID_CONSUMER. - ![HID_TYPE_CHOOSE](./assets/hid_type_choose.png) + 1) By default, main.c defines HID_KEYBOARD. You can switch the supported + type by undefining HID_KEYBOARD and defining HID_CONSUMER. + ![HID_TYPE_CHOOSE](./assets/hid_type_choose.png) ## Usage Instructions - -1. This example starts broadcasting on boot with the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the device's Bluetooth address. It can be directly connected via Windows or Mac Bluetooth. -2. After compiling and flashing, it can be found and connected on the PC. Once connected successfully, you can input via the development board's buttons, and the PC will show the corresponding output: pressing briefly outputs 'a', and long pressing continuously outputs 'aaaaaa...' -* If the PC has a serial tool, you can send the Finsh command "test_hids 4 p" to output 'a' on the PC, and "test_hids 4 r" to stop output. -* You can change the keyboard function, for example, changing 'a' to 'b' by modifying 0x04 to 0x05 in the code (you can find the relevant HID key mapping table online). -Note: After modifying the code, recompiling, and flashing, you need to delete the previously connected device on the PC and reconnect. + +1. This example starts broadcasting on boot with the name + SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the device's Bluetooth + address. It can be directly connected via Windows or Mac Bluetooth. +2. After compiling and flashing, it can be found and connected on the PC. Once + connected successfully, you can input via the development board's buttons, + and the PC will show the corresponding output: pressing briefly outputs 'a', + and long pressing continuously outputs 'aaaaaa...' +* If the PC has a serial tool, you can send the Finsh command "test_hids 4 p" to + output 'a' on the PC, and "test_hids 4 r" to stop output. +* You can change the keyboard function, for example, changing 'a' to 'b' by + modifying 0x04 to 0x05 in the code (you can find the relevant HID key mapping + table online). Note: After modifying the code, recompiling, and flashing, you + need to delete the previously connected device on the PC and reconnect. ```c static key_mapping_t key_mapping_table[1] = { {0x01, 0x04} // HID keycode for 'a' }; ``` -* You can increase the number of buttons, each corresponding to different functions. Add a mapping table and modify the button initialization function as shown below. +* You can increase the number of buttons, each corresponding to different + functions. Add a mapping table and modify the button initialization function + as shown below. ```c static key_mapping_t key_mapping_table[2] = { {0x01, 0x04}, // HID keycode for 'a' @@ -39,7 +50,7 @@ static void key_button_handler(int pin, button_action_t action) { uint8_t hid_code = 0; uint8_t key_idx = 0; - + if (pin == BSP_KEY1_PIN) { key_idx = 0; } else if (pin == BSP_KEY2_PIN) { @@ -71,8 +82,8 @@ static void key_button_init(void) .active_state = BUTTON_ACTIVE_HIGH, .button_handler = key_button_handler, }; - int key1_id = button_init(&key1_cfg); - if (key1_id >= 0)button_enable(key1_id); + int key1_id = button_init(&key1_cfg); + if (key1_id >= 0)button_enable(key1_id); button_cfg_t key2_cfg = { .pin = BSP_KEY2_PIN, @@ -80,21 +91,24 @@ static void key_button_init(void) .active_state = BUTTON_ACTIVE_HIGH, .button_handler = key_button_handler, }; - int key2_id = button_init(&key2_cfg); - if (key2_id >= 0)button_enable(key2_id); + int key2_id = button_init(&key2_cfg); + if (key2_id >= 0)button_enable(key2_id); } ``` -3. After connecting to the PC device, send the finsh command "test_hids [key] [p|r]" via the serial assistant to initiate control commands to the PC. Here, p|r represents press|release and need to be used in pairs; the key value varies depending on whether the HID type is keyboard or consumer: +3. After connecting to the PC device, send the finsh command "test_hids [key] + [p|r]" via the serial assistant to initiate control commands to the PC. Here, + p|r represents press|release and need to be used in pairs; the key value + varies depending on whether the HID type is keyboard or consumer: 1) Keyboard type key value range: - ![keyboard_value](./assets/keyboard_value.png) + ![keyboard_value](./assets/keyboard_value.png) 2) Consumer type key value range: - ![consumer_value](./assets/consumer_value.png) - 3) For example, in consumer type, entering "test_hids 0 p" represents the press operation for the key value corresponding to PLAY. - - + ![consumer_value](./assets/consumer_value.png) + 3) For example, in consumer type, entering "test_hids 0 p" represents the + press operation for the key value corresponding to PLAY. ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](#Platform_hid)). ++ A development board supported by this example ([Supported + Platforms](#Platform_hid)). + A mobile phone device. ### menuconfig Configuration @@ -107,18 +121,26 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. 4. Enable buttons: - Path: Sifli middleware - Enable: Enable button library @@ -128,20 +150,22 @@ Before running this example, you need to prepare: ### Compilation and Programming Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - + After starting the example: 1. It can be discovered and connected by the phone's BLE APP. 2. The phone can be controlled via finsh commands. @@ -150,11 +174,11 @@ After starting the example: ## Reference Documents - + ## Update History -| Version | Date | Release Notes | -|:---|:---|:---| -| 0.0.1 | 01/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/hrpc/README_EN.md b/example/ble/hrpc/README_EN.md index 7537feee7..5760769f2 100644 --- a/example/ble/hrpc/README_EN.md +++ b/example/ble/hrpc/README_EN.md @@ -9,34 +9,61 @@ The example can run on the following development boards: * sf32lb58-lcd series ## Overview -* This is an application example based on the Sifli BLE protocol stack that creates a custom GATT service for BLE advertising, connection, and basic GATT data interaction after connection. It can send hrpc sensor data via Bluetooth to a mobile phone, and the phone can also write data. +* This is an application example based on the Sifli BLE protocol stack that + creates a custom GATT service for BLE advertising, connection, and basic GATT + data interaction after connection. It can send hrpc sensor data via Bluetooth + to a mobile phone, and the phone can also write data. ## hrpc Basic Concepts -* hrpc is one of the Bluetooth standard profiles, used to receive and process data from heart rate sensors (heart rate sensors are sensor devices, HRP is the heart rate sensor protocol). -* Role in the example: This example is an application based on the Sifli BLE protocol stack that creates a custom GATT service for BLE advertising, connection, and basic GATT data interaction after connection. It can send hrpc sensor data via Bluetooth to a mobile phone, and the phone can also write data. +* hrpc is one of the Bluetooth standard profiles, used to receive and process + data from heart rate sensors (heart rate sensors are sensor devices, HRP is + the heart rate sensor protocol). -## GATT Protocol -GATT (Generic Attribute Profile) is the core specification for Bluetooth Low Energy (BLE) communication, defining a unified framework and rules for data exchange between devices. Based on the concept of attributes, it is the foundation for BLE devices to implement service discovery, data read/write, and real-time notifications. GATT is essentially a data exchange protocol. - -GATT protocol includes the following data types: +* Role in the example: This example is an application based on the Sifli BLE + protocol stack that creates a custom GATT service for BLE advertising, + connection, and basic GATT data interaction after connection. It can send hrpc + sensor data via Bluetooth to a mobile phone, and the phone can also write + data. -* Service: A collection of related characteristics representing a complete device function. -* Characteristic: The most common interaction unit in GATT, essentially a combination of related attributes. For example: "Heart Rate Characteristic" contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement Range (descriptor)". +## GATT Protocol +GATT (Generic Attribute Profile) is the core specification for Bluetooth Low +Energy (BLE) communication, defining a unified framework and rules for data +exchange between devices. Based on the concept of attributes, it is the +foundation for BLE devices to implement service discovery, data read/write, and +real-time notifications. GATT is essentially a data exchange protocol. + +* Service: A collection of related characteristics representing a complete + device function. +* Characteristic: The most common interaction unit in GATT, essentially a + combination of related attributes. For example: "Heart Rate Characteristic" + contains "Heart Rate Value (characteristic value)" and "Heart Rate Measurement + Range (descriptor)". * Attribute: The smallest data unit in GATT. Each attribute consists of 3 parts: - 1. UUID: Uniquely identifies the attribute, distinguishing different types of data (e.g., Heart Rate Value UUID is 0x2A37, Battery Level is 0x2A19) - 2. Value: The actual stored data (e.g., heart rate value "65", battery level "80%") - 3. Permissions: Access permissions for attribute values, such as: read-only, write-only, read-write, notification, etc. -* Profile: A combination of multiple services defined for specific application scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate monitoring must include "Heart Rate Service" and "Battery Service" (for users to check device battery level) + 1. UUID: Uniquely identifies the attribute, distinguishing different types + of data (e.g., Heart Rate Value UUID is 0x2A37, Battery Level is 0x2A19) + 2. Value: The actual stored data (e.g., heart rate value "65", battery level + "80%") + 3. Permissions: Access permissions for attribute values, such as: read-only, + write-only, read-write, notification, etc. +* Profile: A combination of multiple services defined for specific application + scenarios. For example: "Heart Rate Profile (HRP)" specifies that heart rate + monitoring must include "Heart Rate Service" and "Battery Service" (for users + to check device battery level) ### Core Functions of GATT Service and Characteristic Discovery -* After the client connects to the server, it first needs to "traverse" the services and characteristics in the server to understand what data it can provide (similar to "querying a directory"). -* Process: Client sends "service discovery request" → Server returns all service UUIDs and ranges → Client then discovers characteristics contained in each service. +* After the client connects to the server, it first needs to "traverse" the + services and characteristics in the server to understand what data it can + provide (similar to "querying a directory"). +* Process: Client sends "service discovery request" → Server returns all service + UUIDs and ranges → Client then discovers characteristics contained in each + service. ## Using the Example ### Preparation Before Configuration -* Mobile recommendation: For iPhone, use third-party software LightBlue; for Android, use nRF Connect for BLE testing. +* Mobile recommendation: For iPhone, use third-party software LightBlue; for + Android, use nRF Connect for BLE testing. ### menuconfig Configuration * The required configuration is enabled by default @@ -45,22 +72,25 @@ Service and Characteristic Discovery menuconfig --board=board_name ``` 1. Enable Bluetooth +- Enable Bluetooth + - To enable: Enable bluetooth + - Macro: `CONFIG_BLUETOOTH` + - Description: Enables Bluetooth functionality. + +2. Enable Bluetooth-related FinSH commands (BT_FINSH) - Path: Sifli middleware → Bluetooth - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Function: Enable Bluetooth functionality -2. Enable Bluetooth-related finsh (BT_FLASH) -- Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT finsh - - Macro switch: `CONFIG_BT_FINSH` - - Function: Enable Bluetooth-related Finsh shell command support for convenient debugging - -3. Enable Bluetooth Heart Rate Profile (Enable BLE heart rate collector) -- Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - - Enable: Enable BLE heart rate collector - - Macro switch: `CONFIG_BSP_BLE_BASC` - - Function: Enable Bluetooth Heart Rate Profile Client (HRPC) implementation, allowing the device to act as a client connecting to heart rate sensor devices and receiving heart rate data +3. Enable BLE Heart Rate Collector +- Enable Bluetooth-related finsh (BT_FLASH) + - Option: Enable BLE heart rate collector + - Macro: `CONFIG_BSP_BLE_BASC` + - Description: Enables the Heart Rate Profile Collector (HRPC) + implementation, allowing the device to function as a client that + connects to heart rate sensors and receives heart rate data. + ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: @@ -68,34 +98,36 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, and select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` - ### Running Result Display -If log information can be seen in the boot log, the example is running successfully: -* Bluetooth protocol initialization successful -![alt text](assets/ble_power.png) -* Advertising started successfully -![alt text](assets/adv_seccess.png) +If log information can be seen in the boot log, the example is running +successfully: +* Bluetooth protocol initialization successful ![alt text](assets/ble_power.png) +* Advertising started successfully ![alt text](assets/adv_seccess.png) -* Open the corresponding software downloaded above on the mobile phone and connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in the figure -![alt text](assets/connect.png) +* Open the corresponding software downloaded above on the mobile phone and + connect to the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx, as shown in + the figure ![alt text](assets/connect.png) -* After successful connection, you can see that the Bluetooth device named SIFLI_APP-xx-xx-xx-xx-xx-xx is connected in the mobile interface, as shown in the figure -![alt text](assets/mac.png) -![alt text](assets/connect_success.jpg) +* After successful connection, you can see that the Bluetooth device named + SIFLI_APP-xx-xx-xx-xx-xx-xx is connected in the mobile interface, as shown in + the figure ![alt text](assets/mac.png) ![alt text](assets/connect_success.jpg) -* Data can be read and written through the mobile app -![alt text](assets/read_write_cccd.png) -![alt text](assets/write_data.jpg) +* Data can be read and written through the mobile app ![alt + text](assets/read_write_cccd.png) ![alt text](assets/write_data.jpg) ### Troubleshooting -* If you cannot achieve the steps shown above, please check if Bluetooth is enabled on the mobile phone and if the mobile phone is connected to the microcontroller. -* Check if the correct menu options were selected \ No newline at end of file +* If you cannot achieve the steps shown above, please check if Bluetooth is + enabled on the mobile phone and if the mobile phone is connected to the + microcontroller. +* Check if the correct menu options were selected + diff --git a/example/ble/iBeacon/README_EN.md b/example/ble/iBeacon/README_EN.md index d7985b035..90ab073e7 100644 --- a/example/ble/iBeacon/README_EN.md +++ b/example/ble/iBeacon/README_EN.md @@ -4,27 +4,34 @@ Source code path: example/ble/iBeacon ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x ## Overview - + This example demonstrates the usage of iBeacon advertisement. ## Usage Instructions - -1. After booting, the iBeacon broadcast will be enabled. You can refer to the implementation of ble_app_ibeacon_advertising_start(). The default iBeacon broadcast content is UUID: 95d0b422-a4bd-45d4-9920-576bc6632372, Major: 256, Minor: 258, RSSI at 1m: -50 dBm. -2. Use the finsh command "cmd_diss adv_update [UUID] [Major] [Minor] [RSSI_at_1m]" to modify the broadcast content. The UUID format should be like "12345678-1234-1234-1234-123456789abc"; Major value range is 0–65535; Minor value range is 0–65535; RSSI_at_1m value range is -128 to 127. -3. Use the finsh commands "cmd_diss adv_start" and "cmd_diss adv_stop" to enable and stop the iBeacon broadcast, respectively. - + +1. After booting, the iBeacon broadcast will be enabled. You can refer to the + implementation of ble_app_ibeacon_advertising_start(). The default iBeacon + broadcast content is UUID: 95d0b422-a4bd-45d4-9920-576bc6632372, Major: 256, + Minor: 258, RSSI at 1m: -50 dBm. +2. Use the finsh command "cmd_diss adv_update [UUID] [Major] [Minor] + [RSSI_at_1m]" to modify the broadcast content. The UUID format should be like + "12345678-1234-1234-1234-123456789abc"; Major value range is 0–65535; Minor + value range is 0–65535; RSSI_at_1m value range is -128 to 127. +3. Use the finsh commands "cmd_diss adv_start" and "cmd_diss adv_stop" to enable + and stop the iBeacon broadcast, respectively. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_iBeacon_adv)). ++ One development board supported by this example ([Supported + Platforms](#Platform_iBeacon_adv)). + Mobile device. ### menuconfig Configuration @@ -37,38 +44,42 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/build.html). ## Expected Results - + After the example starts: 1. It can perform iBeacon advertisement and modify advertisement content. - ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |09/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/index_EN.md b/example/ble/index_EN.md index 2905e512d..5a4733138 100644 --- a/example/ble/index_EN.md +++ b/example/ble/index_EN.md @@ -7,6 +7,4 @@ :glob: */* - - ``` diff --git a/example/ble/multi_connection/README_EN.md b/example/ble/multi_connection/README_EN.md index e9d838b4b..e860f0555 100644 --- a/example/ble/multi_connection/README_EN.md +++ b/example/ble/multi_connection/README_EN.md @@ -3,20 +3,25 @@ Source code path: example/ble/multi_connection ## Supported Platforms - + All platforms ## Overview -This example demonstrates BLE multi-connection functionality based on GAP central and peripheral roles and GATT server on this platform. +This example demonstrates BLE multi-connection functionality based on GAP +central and peripheral roles and GATT server on this platform. ## Usage Instructions -1. When operating as a slave device, the board automatically starts advertising upon boot and can be connected via BLE apps on mobile phones. -2. After connection, the board automatically restarts advertising and can accept connections from other mobile devices. -3. It can also operate as a master device, searching for and connecting to other slave devices through finsh commands. +1. When operating as a slave device, the board automatically starts advertising + upon boot and can be connected via BLE apps on mobile phones. +2. After connection, the board automatically restarts advertising and can accept + connections from other mobile devices. +3. It can also operate as a master device, searching for and connecting to other + slave devices through finsh commands. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_peri)). ++ One development board supported by this example ([Supported + Platforms](#Platform_peri)). + Mobile device. ### menuconfig Configuration @@ -29,49 +34,62 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing -Switch to the example project/common directory and run the scons command to compile: +Switch to the example project/common directory and run the scons command to +compile: ```c -> scons --board=eh-lb525 -j8 +> scons --board=eh-lb525 -j8 ``` -Switch to the example `project/common/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/common/build_xx` directory and run +`uart_download.bat`, then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can be discovered and connected by multiple different mobile phones via BLE apps, allowing corresponding GATT characteristic value read/write operations. +1. It can be discovered and connected by multiple different mobile phones via + BLE apps, allowing corresponding GATT characteristic value read/write + operations. 2. It can actively connect to other devices ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |02/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------------- | --------------- | +| 0.0.1 | February 2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/pair/README_EN.md b/example/ble/pair/README_EN.md index 6f34111cd..3baad6a44 100644 --- a/example/ble/pair/README_EN.md +++ b/example/ble/pair/README_EN.md @@ -4,35 +4,48 @@ Source path: example/ble/peripheral (Platform_peri)= ## Supported Platforms - + All platforms ## Overview - -This example demonstrates how this platform implements GAP peripheral and GATT server functionalities. + +This example demonstrates how this platform implements GAP peripheral and GATT +server functionalities. + ## Usage - -1. As a slave device, advertising will be enabled at startup with the advertising name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of this device. Connection can be established through a mobile BLE APP. -2. As a GATT server, write and read operations can be performed from the mobile device, or CCCD can be enabled, and the device will update the characteristic value every second. -3. In the initialization stage, bond_ack is set to BOND.Pending by default. You need to pay attention to CONNECTION_MANAGER_BOND_AUTH_INFOR and call connectionManager_bond_ack_reply in time. + +1. As a slave device, advertising will be enabled at startup with the + advertising name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the + Bluetooth address of this device. Connection can be established through a + mobile BLE APP. +2. As a GATT server, write and read operations can be performed from the mobile + device, or CCCD can be enabled, and the device will update the characteristic + value every second. +3. In the initialization stage, bond_ack is set to BOND.Pending by default. You + need to pay attention to CONNECTION_MANAGER_BOND_AUTH_INFOR and call + connectionManager_bond_ack_reply in time. ```c connection_manager_set_bond_ack(BOND_PENDING); ``` -4.You can reset the IO by setting IO cap to GAP_IO.cap_DISPLAY_ONLY by default, or you can also reset the IO by using the finsh command cmd_diss set_io iocap. + +4. When INPUT_ONLY is set, the key must be entered by the finsh command cmd_diss + set_key conn_IDX key ```c connection_manager_set_bond_cnf_iocap(GAP_IO_CAP_DISPLAY_ONLY); ``` -5. When INPUT_ONLY is set, the key must be entered by the finsh command cmd_diss set_key conn_IDX key - -6. The finsh command cmd_diss set_key conn_idx sec_level can be used to request the central to initiate a pairing +5. The finsh command cmd_diss set_key conn_idx sec_level can be used to request + the central to initiate a pairing +6. The central can be requested to initiate pairing using the finsh command: + cmd_diss set_key conn_idx sec_level. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_peri)) ++ One development board supported by this example ([Supported + Platforms](#Platform_peri)) + Mobile device ### Menuconfig Configuration @@ -45,49 +58,64 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Navigate to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Navigate to the example's `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Navigate to the example's `project/build_xx` directory, run `uart_download.bat`, +and select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant section in the [Quick Start Guide](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +section in the [Quick Start Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. The device can be discovered and connected by mobile BLE APP, and corresponding GATT characteristic value read/write operations can be performed. -2. By modifying io and then initiating pairing on the mobile terminal, different pairing authentication methods can be implemented. -3. You can also initiate an encryption request from the periphery development board side and then pair it through the finsh command. +1. The device can be discovered and connected by mobile BLE APP, and + corresponding GATT characteristic value read/write operations can be + performed. +2. By modifying io and then initiating pairing on the mobile terminal, different + pairing authentication methods can be implemented. +3. You can also initiate an encryption request from the periphery development + board side and then pair it through the finsh command. ## Troubleshooting + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/periodic_adv/README_EN.md b/example/ble/periodic_adv/README_EN.md index ae9ee5a28..666d2b73e 100644 --- a/example/ble/periodic_adv/README_EN.md +++ b/example/ble/periodic_adv/README_EN.md @@ -4,27 +4,38 @@ Source code path: example/ble/periodic_adv (Platform_peri_adv)= ## Supported Platforms - + All platforms + ## Overview - + This example demonstrates the usage of periodic advertisement. ## Usage Instructions - -1. Periodic advertisement starts after boot, refer to the implementation of ble_app_peri_advertising_start(). The default periodic advertisement content is 80 bytes of all-zero data. -2. Use finsh command "cmd_diss keep_per start [change_period] [len]" to change the periodic advertisement content. The change_period value range is 20-255 in milliseconds; len value range is 0-100 in bytes. - 1) After starting, the periodic advertisement will update content according to the set change period. The content consists of repeated digits of the specified length, and this digit increments with each periodic update, cycling between 0-255. - 2) Use finsh command "cmd_diss keep_per stop" to stop updating the periodic advertisement content. Note that this command only stops updating the content but does not stop the periodic advertisement. -3. Use finsh commands "cmd_diss adv_start" and "cmd_diss adv_stop" to enable and stop periodic advertisement. - + +1. Periodic advertisement starts after boot, refer to the implementation of + ble_app_peri_advertising_start(). The default periodic advertisement content + is 80 bytes of all-zero data. +2. Use finsh command "cmd_diss keep_per start [change_period] [len]" to change + the periodic advertisement content. The change_period value range is 20-255 + in milliseconds; len value range is 0-100 in bytes. + 1) After starting, the periodic advertisement will update content according + to the set change period. The content consists of repeated digits of the + specified length, and this digit increments with each periodic update, + cycling between 0-255. + 2) Use finsh command "cmd_diss keep_per stop" to stop updating the periodic + advertisement content. Note that this command only stops updating the + content but does not stop the periodic advertisement. +3. Use finsh commands "cmd_diss adv_start" and "cmd_diss adv_stop" to enable and + stop periodic advertisement. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_peri_adv)). ++ One development board supported by this example ([Supported + Platforms](#Platform_peri_adv)). + Mobile device. ### menuconfig Configuration @@ -37,38 +48,42 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: 1. It can perform periodic advertisement and modify advertisement content. - ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/periodic_adv_sync/README_EN.md b/example/ble/periodic_adv_sync/README_EN.md index 67f1fc9b7..2623308ec 100644 --- a/example/ble/periodic_adv_sync/README_EN.md +++ b/example/ble/periodic_adv_sync/README_EN.md @@ -4,32 +4,45 @@ Source code path: example/ble/periodic_adv_sync (Platform_peri_adv_sync)= ## Supported Platforms - + All platforms + ## Overview - + This example demonstrates the usage of periodic advertisement synchronization. ## Usage Instructions - -1. After boot, use finsh command "diss sync create" to create periodic advertisement sync. If created successfully, you can see "PER_ADV_SYNC created [idx]" in the log, where idx is the allocated handle. -2. Use finsh command "diss scan start [is_dup] [scan_interval] [scan_window] [duration]" to start scan to search for periodic advertisements. - 1) Command example: "diss scan start 1 60 30 30000". This command will scan continuously for 30 seconds. - 2) If a periodic advertisement is found, it will print "Periodic adv found addr_type [type], addr:0xXX:XX:XX:XX:XX:XX, adv_sid:[adv_sid]". -3. To establish periodic advertisement synchronization, use finsh command "diss sync start [addr] [addr_type] [adv_sid] [sync_to]", where addr, addr_type and adv_sid are the address, address type and advertisement SID printed after finding the periodic advertisement; - sync_to represents the sync timeout in units of 10ms + +1. After boot, use finsh command "diss sync create" to create periodic + advertisement sync. If created successfully, you can see "PER_ADV_SYNC + created [idx]" in the log, where idx is the allocated handle. +2. Use finsh command "diss scan start [is_dup] [scan_interval] [scan_window] + [duration]" to start scan to search for periodic advertisements. + 1) Command example: "diss scan start 1 60 30 30000". This command will scan + continuously for 30 seconds. + 2) If a periodic advertisement is found, it will print "Periodic adv found + addr_type [type], addr:0xXX:XX:XX:XX:XX:XX, adv_sid:[adv_sid]". +3. To establish periodic advertisement synchronization, use finsh command "diss + sync start [addr] [addr_type] [adv_sid] [sync_to]", where addr, addr_type and + adv_sid are the address, address type and advertisement SID printed after + finding the periodic advertisement; sync_to represents the sync timeout in + units of 10ms 1) Example: "diss sync start be:56:44:33:22:c2 0 0 80" - 2) Since establishing periodic advertisement sync requires scan to be enabled, the 30-second scan set by the previous command may have stopped when establishing periodic advertisement sync. If scan has stopped, you can see "Scan stopped" in the log. When scan is stopped, you need to restart scan. - 3) After periodic advertisement sync is established, it will print "PER_ADV_SYNC established(addr)" and "per_adv_data:" - - + 2) Since establishing periodic advertisement sync requires scan to be + enabled, the 30-second scan set by the previous command may have stopped + when establishing periodic advertisement sync. If scan has stopped, you + can see "Scan stopped" in the log. When scan is stopped, you need to + restart scan. + 3) After periodic advertisement sync is established, it will print + "PER_ADV_SYNC established(addr)" and "per_adv_data:" ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_peri_adv_sync)). ++ One development board supported by this example ([Supported + Platforms](#Platform_peri_adv_sync)). + Mobile device. ### menuconfig Configuration @@ -38,47 +51,50 @@ Before running this example, prepare: - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Description: Enables Bluetooth functionality -2. Enable GAP Central: -- Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - - Enable: Enable BLE GAP central role - - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. +2. Enable GAP Central: + - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service + - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can search for periodic advertisements and establish periodic advertisement synchronization. - +1. It can search for periodic advertisements and establish periodic + advertisement synchronization. ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/peripheral/README_EN.md b/example/ble/peripheral/README_EN.md index 7b5f307c9..0d084b1e7 100644 --- a/example/ble/peripheral/README_EN.md +++ b/example/ble/peripheral/README_EN.md @@ -4,24 +4,29 @@ Source code path: example/ble/peripheral (Platform_peri)= ## Supported Platforms - + All platforms ## Overview - -This example demonstrates how to implement GAP peripheral and GATT server functionality on this platform. + +This example demonstrates how to implement GAP peripheral and GATT server +functionality on this platform. ## Usage Instructions - -1. When operating as a slave device, the board starts advertising upon boot with the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth address of the device. It can be connected via BLE apps on mobile phones. -2. When operating as a GATT server, write and read operations can be performed from the mobile client, or by enabling CCCD, the device will update the characteristic value every second. - + +1. When operating as a slave device, the board starts advertising upon boot with + the name SIFLI_APP-xx-xx-xx-xx-xx-xx, where xx represents the Bluetooth + address of the device. It can be connected via BLE apps on mobile phones. +2. When operating as a GATT server, write and read operations can be performed + from the mobile client, or by enabling CCCD, the device will update the + characteristic value every second. ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_peri)). ++ One development board supported by this example ([Supported + Platforms](#Platform_peri)). + Mobile device. ### menuconfig Configuration @@ -34,49 +39,59 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the [Quick Start +Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. It can be discovered and connected by mobile BLE apps, allowing corresponding GATT characteristic value read/write operations. - +1. It can be discovered and connected by mobile BLE apps, allowing corresponding + GATT characteristic value read/write operations. ## Troubleshooting ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/ble/peripheral_with_ota/README_EN.md b/example/ble/peripheral_with_ota/README_EN.md index 6c7253f7e..a1b5a769b 100644 --- a/example/ble/peripheral_with_ota/README_EN.md +++ b/example/ble/peripheral_with_ota/README_EN.md @@ -1,22 +1,42 @@ # peripheral_with_ota Example Description and SDK DFU Integration +Source path: example/ble/peripheral_with_ota ## Supported Platforms All platforms ## Overview - -This example demonstrates adding DFU functionality based on a BLE peripheral project as the main project. -1. The minimum upgrade unit is the .bin file generated by project compilation. The files to be upgraded can be one or multiple files, which are compressed and packaged into an upgrade package through specific scripts. -2. You can use the mobile APP provided by Sifli or integrate the mobile SDK to download in the system's main project (also referred to as hcpu.bin), transfer the upgrade package to the system's upgrade backup area, or choose to transfer it yourself and then call the installation interface. -3. After calling the installation interface, the system will first check if the upgrade package contains dfu.bin. If it does, dfu.bin will be updated first. -4. After updating dfu.bin or if dfu.bin is not included, the system will restart and run the content of dfu.bin. -5. In dfu.bin, all bins except dfu.bin in the upgrade package will be extracted and installed to the corresponding areas. After installation is complete, it will restart again, enter hcpu.bin after restart, and the upgrade is complete. + +This example demonstrates adding DFU functionality based on a BLE peripheral +project as the main project. +1. The minimum upgrade unit is the .bin file generated by project compilation. + The files to be upgraded can be one or multiple files, which are compressed + and packaged into an upgrade package through specific scripts. +2. You can use the mobile APP provided by Sifli or integrate the mobile SDK to + download in the system's main project (also referred to as hcpu.bin), + transfer the upgrade package to the system's upgrade backup area, or choose + to transfer it yourself and then call the installation interface. +3. After calling the installation interface, the system will first check if the + upgrade package contains dfu.bin. If it does, dfu.bin will be updated first. +4. After updating dfu.bin or if dfu.bin is not included, the system will + restart and run the content of dfu.bin. +5. In dfu.bin, all bins except dfu.bin in the upgrade package will be extracted + and installed to the corresponding areas. After installation is complete, it + will restart again, enter hcpu.bin after restart, and the upgrade is + complete. ## Example Usage -1. The main project of this example is the same as BLE peripheral. For usage of this project, please refer to the example/ble/peripheral project. -2. The tools for creating upgrade packages (ezip.exe, img_toolv37.exe) are in the tool/secureboot directory, and key-related content is in the tool/secureboot/sifli02 directory. Put the above files in the same directory and create the upgrade package according to the package creation section below. -3. Download the upgrade package through BLE APP, or download to the DFU_DOWNLOAD_REGION area via uart/jlink. -4. If using Sifli BLE app for download, it will automatically install and restart. If downloading manually, you need to call dfu_offline_install_set_v2, then call HAL_PMU_ReBoot to restart. +1. The main project of this example is the same as BLE peripheral. For usage of + this project, please refer to the example/ble/peripheral project. +2. The tools for creating upgrade packages (ezip.exe, img_toolv37.exe) are in + the tool/secureboot directory, and key-related content is in the + tool/secureboot/sifli02 directory. Put the above files in the same directory + and create the upgrade package according to the package creation section + below. +3. Download the upgrade package through BLE APP, or download to the + DFU_DOWNLOAD_REGION area via uart/jlink. +4. If using Sifli BLE app for download, it will automatically install and + restart. If downloading manually, you need to call + dfu_offline_install_set_v2, then call HAL_PMU_ReBoot to restart. 5. After restart, the main program in the upgrade package will run. ### menuconfig Configuration @@ -25,121 +45,217 @@ See Integration Method - Main Project ### Compilation and Flashing Navigate to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb561 -j8 +> scons --board=eh-lb561 -j8 ``` -Navigate to the example's `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Navigate to the example's `project/build_xx` directory, run `uart_download.bat`, +and select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant section in the [Quick Start Guide](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +section in the [Quick Start Guide](/quickstart/get-started.md). ## Integration Method -This project has already been configured with the following content. If you need to integrate DFU sub project into your own project, you need to check as follows: - +This project has already been configured with the following content. If you need +to integrate DFU sub project into your own project, you need to check as +follows: ### ptab.json -Need to configure DFU_FLASH_CODE and DFU_DOWNLOAD_REGION areas. -DFU_FLASH_CODE is the area for dfu.bin, recommended size is 384KB -DFU_DOWNLOAD_REGION is the space for storing downloaded files, need to reserve space of all files' size * 0.7 for one upgrade -![ptab](./assets/ptab_561.png) +Need to configure DFU_FLASH_CODE and DFU_DOWNLOAD_REGION areas. DFU_FLASH_CODE +is the area for dfu.bin, recommended size is 384KB DFU_DOWNLOAD_REGION is the +space for storing downloaded files, need to reserve space of all files' size * +0.7 for one upgrade ![ptab](./assets/ptab_561.png) -For NAND projects, the following additional modifications are needed when modifying ptab: +For NAND projects, the following additional modifications are needed when +modifying ptab: 1. Move the HCPU_FLASH_CODE macro to the hcpu tags in flash2 2. Add DFU_DOWNLOAD_REGION -3. Additionally add a DFU_INFO_REGION, 128KB -![ptab](./assets/ptab_525.png) +3. Additionally add a DFU_INFO_REGION, 128KB ![ptab](./assets/ptab_525.png) 4. Add xip information for dfu partition 5. In psram1_cbus HCPU area, change HCPU_FLASH_CODE in tags to HCPU_PSRAM_CODE 6. Add DFU area to psram1_cbus, fill in DFU_PSRAM_CODE for tags -![ptab](./assets/ptab_525_2.png) + ![ptab](./assets/ptab_525_2.png) +### Bootloader +Check if the corresponding boot loader's main.c has the logic for selecting +running_imgs[CORE_HCPU]. If not, add it manually ![boot1]{1} + +Also, in the void dfu_boot_img_in_flash(int flashid) function in main.c, both +places that check core id need to be OR'd with CORE_LCPU +![boot2](./assets/bootloader1.png) -### Boot loader -Check if the corresponding boot loader's main.c has the logic for selecting running_imgs[CORE_HCPU]. If not, add it manually -![boot1](./assets/bootloader1.png) -Also, in the void dfu_boot_img_in_flash(int flashid) function in main.c, both places that check core id need to be OR'd with CORE_LCPU -![boot2](./assets/bootloader2.png) +In addition, both instances of the core ID check within the `void +dfu_boot_img_in_flash(int flashid)` function in `main.c` must be bitwise ORed +with `CORE_LCPU`. ![boot2](./assets/bootloader2.png) + ### Main Project -Kconfig.proj -Add DFU switch -![main1](./assets/mainproject1.png) +Kconfig.proj Add DFU switch ![main1](./assets/mainproject1.png) + -proj.conf -Enable DFU-related code and DFU switch +proj.conf Enable DFU-related code and DFU switch ![main2](./assets/mainproject2.png) -Sconstruct -Add DFU sub-project -Note: Need to add before AddFTAB + +Sconstruct Add DFU sub-project Note: Need to add before AddFTAB ![main3](./assets/mainproject3.png) ### DFU Project Usually no modification needed ## Transmission -If transmitting manually, you need to download the packaged file to DFU_DOWNLOAD_REGION +If transmitting manually, you need to download the packaged file to +DFU_DOWNLOAD_REGION -If using the mobile transmission lib provided by Sifli to transmit this upgrade package, you need to enable the following options in the main project +If using the mobile transmission lib provided by Sifli to transmit this upgrade +package, you need to enable the following options in the main project ![transport1](./assets/serialtransport1.png) Add the following content in the code ![transport2](./assets/serialtransport2.png) ![transport3](./assets/serialtransport3.png) + ## Creating Upgrade Package +```c .\imgtoolv37.exe gen_dfu --img_para hcpu 16 0 dfu 16 6 --com_type=0 --offline_img=2 +``` + +.\imgtoolv37.exe gen_dfu --img_para hcpu 16 0 dfu 16 6 --com_type=0 +--offline_img=2 +```c +.\imgtoolv37.exe gen_dfu --img_para hcpu 16 0 dfu 16 6 --com_type=0 --offline_img=2 --ezip_path=ezip.exe +``` + +Put all files and the upgrade files to be created in the same directory The +command above creates both hcpu and dfu simultaneously, where hcpu represents +creating hcpu.bin, dfu represents creating dfu.bin The first parameter after the +bin name is for compression, 16 means use compression, 0 means no compression +The second parameter after the bin name represents image id, hcpu is 0, dfu is +6. -Put all files and the upgrade files to be created in the same directory -The command above creates both hcpu and dfu simultaneously, where hcpu represents creating hcpu.bin, dfu represents creating dfu.bin -The first parameter after the bin name is for compression, 16 means use compression, 0 means no compression -The second parameter after the bin name represents image id, hcpu is 0, dfu is 6. -The number of files to be created can be adjusted arbitrarily. You can upgrade only HCPU, or create multiple bins simultaneously. If dfu.bin is created, the DFU installer will be updated before upgrading. +The number of files to be created can be adjusted arbitrarily. You can upgrade +only HCPU, or create multiple bins simultaneously. If dfu.bin is created, the +DFU installer will be updated before upgrading. After creation, only offline_install.bin needs to be transmitted -If you need to upgrade bins other than HCPU and DFU, you need to specify the flash address corresponding to the image id. In dfu_get_download_addr_by_id in dfu_flash.c, add the new ID, then return the address defined in ptab.c. The address under the flag&DFU_FLAG_COMPRESS condition does not need to be implemented. -![package](./assets/package.png) +If you need to upgrade bins other than HCPU and DFU, you need to specify the +flash address corresponding to the image id. In dfu_get_download_addr_by_id in +dfu_flash.c, add the new ID, then return the address defined in ptab.c. The +address under the flag&DFU_FLAG_COMPRESS condition does not need to be +implemented. ![package](./assets/package.png) ## Mobile App and Demo Project Access +| OFFSET | LENGTH | CONTENT | +| ------ | ------ | --------------------------------------------------------------------------------- | +| 0 | 4 | DFU Magic (0x46, 0x43, 0x45, 0x53) | +| 4 | 1 | Protocol version of the installation package | +| 5 | 1 | Installation flag, 0xFF | +| 6 | 2 | Image count | +| 8 | 4 | The CRC32MPEG2 result calculated across all image content (image1 + image2 + ...) | +| 12 | 1 | First image ID | +| 13 | 1 | First image flags | +| 14 | 4 | First image length | +| 18 | 1 | Second image ID | +| 19 | 1 | Second image flags | +| 20 | 4 | Second image length | +| | | ... | +| | | ImageX | +| | | ImageY | +| | | ... | + ### Android SiFli BLE App Download Link https://www.pgyer.com/gurSBc +1. Verify the MAGIC field and calculate the CRC (refer to the installation + package structure) to validate the integrity and authenticity of the + installation package. +2. Install the OTA manager if it is present in the installation package. +3. Erase the original OTA Manager. +4. For uncompressed binaries, directly copy the contents of the image in the DFU + installation package to the target region. +5. For compressed binaries, decompress the data before writing it to the + corresponding region. +6. Update DFU non-volatile (NV) parameters. +7. Update the RTC registers and reboot. ### Android Demo Project https://github.com/OpenSiFli/SiFli_OTA_APP\ Relevant sections are under "3. SiFli-SDK OTA" +1. Verify the MAGIC field and calculate the CRC (based on the package structure) + to validate the integrity and legitimacy of the installation package. +2. Install all binaries except for the OTA Manager, following the same + installation procedure as used in the HCPU. +3. Update DFU non-volatile (NV) parameters. +4. Update the RTC registers and reboot. ### iOS Demo Project https://github.com/OpenSiFli/SiFli_OTA_APP_IOS\ Relevant sections are under "SiFli-SDK OTA (Nor Offline)" +When generating a compressed binary, an 8-byte header is prepended, consisting +of a 4-byte original length and a 4-byte chunk length (typically 10240 bytes). + +The original data is then divided into chunks based on the specified chunk +length. Each chunk is compressed using either EZIP hardware GZIP or software +ZLIB (the former is currently the standard). The compressed data for each chunk +is prefixed with its compressed length, and all compressed chunks are then +concatenated. Finally, this payload is combined with the previously mentioned +header to form a complete compressed binary. + + + ## Mobile App Usage -The operation is shown in the following figures. Search for the board's BLE broadcast, click on the corresponding device, then select nor dfu, and finally select offline. No need to click the start button below -![app1](./assets/app.jpg)![app2](./assets/app2.jpg) -![app3](./assets/app3.jpg)![app2](./assets/app4.jpg) +### Download link for Android SiFli BLE App. +https://www.pgyer.com/gurSBc + +### Android demo project. +https://github.com/OpenSiFli/SiFli_OTA_APP\ +Refer to section "3. SiFli-SDK OTA". + +### iOS Demo Project +https://github.com/OpenSiFli/SiFli_OTA_APP_IOS\ +Refer to section "SiFli-SDK OTA (Nor Offline)". ## Troubleshooting -1. DFU project shows insufficient space during compilation -Content enabled in board.conf will also be compiled in the dfu project, causing the dfu project to compile unnecessary things, and the size may exceed the DFU_FLASH_CODE size in ptab.json. -For content defined in board.conf that doesn't need to be compiled into the dfu project, modify proj.conf under the dfu project to define the corresponding items as n -![more](./assets/more.png) +Operation procedure as illustrated: Search for the board's BLE broadcast, select +the corresponding device, choose "nor dfu," and finally select "offline." There +is no need to click the "start" button at the bottom.\ +![app1](./assets/app.jpg)![app2](./assets/app2.jpg) +![app3](./assets/app3.jpg)![app2](./assets/app4.jpg) -2. DFU_DOWNLOAD_REGION size related -Note: Image resources are already compressed, so the DFU script can hardly compress them further, so calculate with * 1.0 -For example, if the maximum upgrade design is to simultaneously upgrade hcpu.bin + res.bin + dfu.bin, where res.bin is image resources -Then you need to reserve space of maximum hcpu.bin size * 0.7 + res.bin size + dfu.bin size * 0.7 ## Reference Documentation - +1. Insufficient space warnings during DFU project compilation: The DFU project + compiles features enabled in `board.conf`, which may include unnecessary + modules and cause the binary size to exceed `DFU_FLASH_CODE` in `ptab.json`. + To exclude components defined in `board.conf` from the DFU build, modify the + `proj.conf` within the DFU project directory and set the corresponding items + to `n`. ![more](./assets/more.png) + + +2. Notes on DFU_DOWNLOAD_REGION sizing: Since image resources are already + compressed, the DFU script cannot significantly reduce their size; + therefore, they should be calculated with a * 1.0 factor. For example, if + the maximum upgrade scenario involves simultaneously updating `hcpu.bin`, + `res.bin` (image resources), and `dfu.bin`, the reserved space must be: + (size of `hcpu.bin` * 0.7) + size of `res.bin` + (size of `dfu.bin` * 0.7). ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version| -|0.0.2 |03/2025 |Added support for NAND chip DFU, updated creation commands and scripts, removed invalid parameters| -|0.0.3 |03/2025 |Added support for 58x | -|0.0.4 |04/2025 |Added HTTP download example, adjusted directory structure and macro switches | \ No newline at end of file + + +## Revision History +| Version | Date | Release Notes | +| ------- | ------- | ------------------------------------------------------------------------------------------------------ | +| 0.0.1 | 01/2025 | Initial release | +| 0.0.2 | 03/2025 | Added support for NAND flash DFU, updated build commands and scripts, and removed obsolete parameters. | +| 0.0.3 | 03/2025 | Added support for 58x series. | +| 0.0.4 | 04/2025 | Added HTTP download examples and adjusted directory structure and macro switches. | +| 0.0.5 | 11/2025 | Added update adaptation for 55x series. | +| 0.0.6 | 11/2025 | Updated deprecated content. | +| 0.0.7 | 01/2026 | Updated build tools and resolved path issues in the ezip utility. | +| 0.0.8 | 01/2026 | Added installation instructions. | diff --git a/example/ble/throughput/README_EN.md b/example/ble/throughput/README_EN.md index d1c1a6a25..40d9515c8 100644 --- a/example/ble/throughput/README_EN.md +++ b/example/ble/throughput/README_EN.md @@ -4,34 +4,29 @@ Source path: example/ble/throughput (Platform_peri)= ## Supported Platforms - + All platforms ## Overview - -This example demonstrates how this platform implements GAP central and peripheral roles, as well as GATT server and client functionalities, including connection establishment, service discovery, service registration, GATT write operations as a client, receiving notifications, receiving GATT writes as a server, and sending notifications. + +This example demonstrates how this platform implements GAP central and +peripheral roles, as well as GATT server and client functionalities, including +connection establishment, service discovery, service registration, GATT write +operations as a client, receiving notifications, receiving GATT writes as a +server, and sending notifications. + ## Usage - + 1. Flash this program to two development boards. -2. After flashing and running, enter the following finsh command on one of the development boards: -``` -diss speed_test 99227214AC03 512 0 100 65535 0 -``` -This will start the BLE throughput speed test, and the results will be printed in the log later. - -Command parameters: -- First parameter: Reversed address of the target board to connect (in this case, the address is 03:AC:14:72:22:99) -- Second parameter: Negotiated MTU -- Third parameter: Connection parameters (0 is the default short interval connection parameter; you can add custom connection parameters for testing as needed) -- Fourth parameter: Number of packets to send in one test -- Fifth parameter: Length of each packet (0 to 65535; if exceeding MTU limit, it will be filled according to the maximum length, i.e., MTU-3) -- Sixth parameter: Frequency of peer replies during transmission (e.g., setting to 10 means reply once every 10 packets; 0 means no reply) +2. After flashing and running, enter the following finsh command on one of the + development boards: ### Hardware Requirements Before running this example, prepare: -+ Two development boards supported by this example ([Supported Platforms](#Platform_peri)) ++ Two development boards supported by this example ([Supported + Platforms](#Platform_peri)) ### Menuconfig Configuration 1. Enable Bluetooth (`BLUETOOTH`): @@ -43,49 +38,64 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → BLE service - Enable: Enable BLE GAP central role - Macro switch: `CONFIG_BLE_GAP_CENTRAL` - - Description: Switch for BLE CENTRAL (central device). When enabled, it provides scanning and active connection initiation with peripherals. + - Description: Switch for BLE CENTRAL (central device). When enabled, it + provides scanning and active connection initiation with peripherals. - Enable: Enable BLE GATT client - Macro switch: `CONFIG_BLE_GATT_CLIENT` - - Description: Switch for GATT CLIENT. When enabled, it can actively search and discover services, read/write data, and receive notifications. + - Description: Switch for GATT CLIENT. When enabled, it can actively + search and discover services, read/write data, and receive + notifications. - Enable: Enable BLE connection manager - Macro switch: `CONFIG_BSP_BLE_CONNECTION_MANAGER` - - Description: Provides BLE connection control management, including multi-connection management, BLE pairing, link connection parameter updates, etc. + - Description: Provides BLE connection control management, including + multi-connection management, BLE pairing, link connection parameter + updates, etc. 3. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, so enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled. + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, so enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled. ### Compilation and Flashing -Navigate to the example's project/common directory and run the scons command to compile: +Navigate to the example's project/common directory and run the scons command to +compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Navigate to the example's `project/common/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Navigate to the example's `project/common/build_xx` directory, run +`uart_download.bat`, and select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant section in the [Quick Start Guide](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +section in the [Quick Start Guide](/quickstart/get-started.md). ## Expected Results - + After the example starts: -1. After executing the finsh command, it will connect to another development board and send data. After transmission is complete, it will print information such as transfer speed. +1. After executing the finsh command, it will connect to another development + board and send data. After transmission is complete, it will print + information such as transfer speed. ## Troubleshooting -1. After executing the finsh command and connecting to another development board, the connection immediately disconnects with reason code 62. -When a disconnection with code 0x3e occurs immediately after connection, simply retry the test. +1. After executing the finsh command and connecting to another development + board, the connection immediately disconnects with reason code 62. When a + disconnection with code 0x3e occurs immediately after connection, simply + retry the test. ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |02/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------------- | --------------- | +| 0.0.1 | February 2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/HCI_over_uart/README_EN.md b/example/bt/HCI_over_uart/README_EN.md index df1ddb0a0..04869207a 100644 --- a/example/bt/HCI_over_uart/README_EN.md +++ b/example/bt/HCI_over_uart/README_EN.md @@ -2,29 +2,35 @@ Source code path: example/bt/HCI_over_uart/src + ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x ## Overview - -This example demonstrates HCI communication with BT/BLE controller through uart1. + +This example demonstrates HCI communication with BT/BLE controller through +uart1. -## Example Usage - -After the example starts, HCI commands can be sent to the controller through uart1, and HCI events will also be sent back to uart1. +## Example Usage + +After the example starts, HCI commands can be sent to the controller through +uart1, and HCI events will also be sent back to uart1. The default console log port for 52x is uart3 (see project/sf32lb52x/proj.conf) -The default console log port for 56x/58x is uart4 (see project/sf32lb56x/proj.conf) (see project/sf32lb58x/proj.conf) +The default console log port for 56x/58x is uart4 (see +project/sf32lb56x/proj.conf) (see project/sf32lb58x/proj.conf) + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_music_sink)). ++ One development board supported by this example ([Supported + Platforms](#Platform_music_sink)). ### menuconfig Configuration @@ -33,33 +39,37 @@ Before running this example, you need to prepare: ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - -After the example starts: -HCI commands can be sent to the controller through uart1, and HCI events will also be sent back to uart1. + +After the example starts: HCI commands can be sent to the controller through +uart1, and HCI events will also be sent back to uart1. -For example: Send hexadecimal 01 03 0C 00 (need to add carriage return and line feed) through uart1, uart1 will receive hexadecimal 04 0E 04 06 03 0C 00 +For example: Send hexadecimal 01 03 0C 00 (need to add carriage return and line +feed) through uart1, uart1 will receive hexadecimal 04 0E 04 06 03 0C 00 ## Exception Diagnosis + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/hfp/README_EN.md b/example/bt/hfp/README_EN.md index 5d8481af0..c78e73cfc 100644 --- a/example/bt/hfp/README_EN.md +++ b/example/bt/hfp/README_EN.md @@ -4,7 +4,7 @@ Source code path: example/bt/hfp {#Platform_bt_hfp} ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x @@ -13,60 +13,69 @@ Source code path: example/bt/hfp + sf32lb58-lcd series ## Overview - + HFP_HF call status information acquisition demo: + Hands-free profile related AT command usage ## Example Usage - - -The example enables Bluetooth by default on startup and is controlled through FINSH commands: - -1. Search for Bluetooth devices -Use the command hfp_cmd start_inquiry to search for mobile phone Bluetooth devices. -Discovered devices will be printed in the form of logs "device [%s] searched" and "device COD is [%d], addr is xx:xx:xx:xx:xx:xx". - -2. Stop searching for Bluetooth devices -Use the command hfp_cmd stop_inquiry to stop searching for mobile phone Bluetooth devices. - -3. Connect to Bluetooth devices -Use the command hfp_cmd hfp_connect [addr] to connect, where addr should be copied from the device address (xx:xx:xx:xx:xx:xx) found above. -If you already know the mobile phone Bluetooth device address, you can connect directly without searching for Bluetooth devices. -Connection result print: "HFP HF connected" - -4. Disconnect from Bluetooth devices -Use the command hfp_cmd hfp_disconnect [addr] to disconnect, where addr should be copied from the device address (xx:xx:xx:xx:xx:xx) found above. -Disconnection result print: "HFP HF disconnected" - -5. Query local phone number -Use the command hfp_cmd local_phone_number to query the local phone number. When the local number is received, there will be a print "the remote phone local number + phone number". -Number acquisition completion print: "get remote local phone number complete" - -6. Make a call -Use the command hfp_cmd make_call [phone_number] to make a call. Call result print: "make a call complete " + result - -7. Call status notification -After a successful call, call status changes will be received, with corresponding prints: "the remote phone call status type " + type (callsetup) + status (2/3) outgoing call - -8. Hang up call -Use the command hfp_cmd handup_call to hang up a call. Hang up result print: "hangup a call complete " + result, followed by call status notification - -9. Answer call -Use the command hfp_cmd answer_call to answer a call. Answer result print: "answer a call complete " + result, followed by call status notification - -10. Connect call audio -Use the command hfp_cmd audio_connect to connect call audio. Successful call audio establishment print: "HFP HF audio_connected" - -11. Disconnect call audio -Use the command hfp_cmd audio_disconnect to disconnect call audio. Successful call audio disconnection print: "HFP HF audio_disconnected" - -12. Adjust remote Bluetooth device volume -Use the command hfp_cmd volume_control [val] to implement this, where val is valid between 0-15. Call volume adjustment completion print: "change volume value complete" + +The example enables Bluetooth by default on startup and is controlled through +FINSH commands: +1. Search for Bluetooth devices Use the command hfp_cmd start_inquiry to search + for mobile phone Bluetooth devices. Discovered devices will be printed in the + form of logs "device [%s] searched" and "device COD is [%d], addr is + xx:xx:xx:xx:xx:xx". + +2. Stop searching for Bluetooth devices Use the command hfp_cmd stop_inquiry to + stop searching for mobile phone Bluetooth devices. + +3. Connect to Bluetooth devices Use the command hfp_cmd hfp_connect [addr] to + connect, where addr should be copied from the device address + (xx:xx:xx:xx:xx:xx) found above. If you already know the mobile phone + Bluetooth device address, you can connect directly without searching for + Bluetooth devices. Connection result print: "HFP HF connected" + +4. Disconnect from Bluetooth devices Use the command hfp_cmd hfp_disconnect + [addr] to disconnect, where addr should be copied from the device address + (xx:xx:xx:xx:xx:xx) found above. Disconnection result print: "HFP HF + disconnected" + +5. Query local phone number Use the command hfp_cmd local_phone_number to query + the local phone number. When the local number is received, there will be a + print "the remote phone local number + phone number". Number acquisition + completion print: "get remote local phone number complete" + +6. Make a call Use the command hfp_cmd make_call [phone_number] to make a call. + Call result print: "make a call complete " + result + +7. Call status notification After a successful call, call status changes will be + received, with corresponding prints: "the remote phone call status type " + + type (callsetup) + status (2/3) outgoing call + +8. Hang up call Use the command hfp_cmd handup_call to hang up a call. Hang up + result print: "hangup a call complete " + result, followed by call status + notification + +9. Answer call Use the command hfp_cmd answer_call to answer a call. Answer + result print: "answer a call complete " + result, followed by call status + notification + +10. Connect call audio Use the command hfp_cmd audio_connect to connect call + audio. Successful call audio establishment print: "HFP HF audio_connected" + +11. Disconnect call audio Use the command hfp_cmd audio_disconnect to disconnect + call audio. Successful call audio disconnection print: "HFP HF + audio_disconnected" + +12. Adjust remote Bluetooth device volume Use the command hfp_cmd volume_control + [val] to implement this, where val is valid between 0-15. Call volume + adjustment completion print: "change volume value complete" ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_bt_hfp)). ++ One development board supported by this example ([Supported + Platforms](#Platform_bt_hfp)). ### menuconfig Configuration 1. Enable Bluetooth (`BLUETOOTH`): @@ -75,7 +84,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_BLUETOOTH` - Description: Enables Bluetooth functionality 2. Enable hands-free HF role: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (Optional) - Macro switch: `CONFIG_BT_FINSH` - Description: Enable finsh command line for Bluetooth control @@ -89,31 +99,35 @@ Before running this example, you need to prepare: ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - -After the example starts: -Mobile phone actively connects to device/device connects to mobile phone through commands. When mobile phone makes a call or device makes a call, mobile phone call status information can be obtained. + +After the example starts: Mobile phone actively connects to device/device +connects to mobile phone through commands. When mobile phone makes a call or +device makes a call, mobile phone call status information can be obtained. ## Exception Diagnosis + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/index_EN.md b/example/bt/index_EN.md index 235193fc2..e230fde8d 100644 --- a/example/bt/index_EN.md +++ b/example/bt/index_EN.md @@ -6,6 +6,4 @@ :glob: */* - - ``` diff --git a/example/bt/music_sink/README_EN.md b/example/bt/music_sink/README_EN.md index 3d0a015bd..eff98a2d3 100644 --- a/example/bt/music_sink/README_EN.md +++ b/example/bt/music_sink/README_EN.md @@ -4,7 +4,7 @@ Source code path: example/bt/music_sink {#Platform_music_sink} ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x @@ -12,30 +12,34 @@ Source code path: example/bt/music_sink + sf32lb56-lcd series + sf32lb58-lcd series - ## Overview - -This example demonstrates playing music from source devices on the local device after connecting to mobile phones and other A2DP Source devices via Bluetooth. + +This example demonstrates playing music from source devices on the local device +after connecting to mobile phones and other A2DP Source devices via Bluetooth. + ## Example Usage - + +The example enables Bluetooth Inquiry scan and page scan on startup, allowing +A2DP source devices like mobile phones to discover this device and initiate +connections. After connection, mobile phone music can be played. The default +Bluetooth name of this device is sifli_music_sink. -The example enables Bluetooth Inquiry scan and page scan on startup, allowing A2DP source devices like mobile phones to discover this device and initiate connections. After connection, mobile phone music can be played. -The default Bluetooth name of this device is sifli_music_sink. ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_music_sink)). ++ One development board supported by this example ([Supported + Platforms](#Platform_music_sink)). + Speakers. ### menuconfig Configuration - 1. Enable AUDIO CODEC and AUDIO PROC: - Path: On-chip Peripheral RTOS Drivers - Enable: Enable Audio Process driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_PRC` - - Description: Enable Audio process device, mainly used for audio data processing (including resampling, volume adjustment, etc.) + - Description: Enable Audio process device, mainly used for audio data + processing (including resampling, volume adjustment, etc.) - Enable: Enable Audio codec driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_CODEC` - Description: Enable Audio codec device, mainly used for DAC conversion @@ -54,7 +58,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_BLUETOOTH` - Description: Enable Bluetooth functionality 5. Enable A2DP SNK and AVRCP: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (Optional) - Macro switch: `CONFIG_BT_FINSH` - Description: Enable finsh command line for Bluetooth control @@ -71,7 +76,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_CFG_AVRCP` - Description: Enable AVRCP profile 6. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT connection manager - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - Description: Use connection manager module to manage BT connections @@ -79,36 +85,42 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - -After the example starts: -A2DP source devices like mobile phones can connect to this device and play music. + +After the example starts: A2DP source devices like mobile phones can connect to +this device and play music. ## Exception Diagnosis + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/music_sink_with_relay/README_EN.md b/example/bt/music_sink_with_relay/README_EN.md index dfe7e36ce..70a7ccc69 100644 --- a/example/bt/music_sink_with_relay/README_EN.md +++ b/example/bt/music_sink_with_relay/README_EN.md @@ -4,44 +4,44 @@ Source code path: example/bt/music_sink_with_relay {#Platform_music_sink} ## Supported Platforms - + + eh-lb52J ## Overview - -This example demonstrates a music_sink-based implementation that requires two boards to download this project, enabling simultaneous music playback from a mobile phone on both devices. + +This example demonstrates a music_sink-based implementation that requires two +boards to download this project, enabling simultaneous music playback from a +mobile phone on both devices. -## Example Usage - +## Example Usage + The example consists of two parts: -1. One part involves operations between the device and mobile phone, same as music_sink. The project enables Bluetooth Inquiry scan and page scan on startup, allowing A2DP source devices like mobile phones to discover this device and initiate connections. After connection, mobile phone music can be played. -2. The other part involves operations between two boards. The two boards need to complete pairing to achieve music forwarding. Only one board can connect to the mobile phone at a time. The board not connected to the mobile phone will receive forwarded music information. - -2.1 The board connected to the mobile phone will be configured as relay src role, otherwise you can set the role through the finsh command music set_role x (1 is relay sink; 2 is relay src). But ensure that relay src is the board connected to the mobile phone. -If pairing is in progress or already completed, setting the role will fail; you can check the current role through music get_role. Only src and sink can perform pairing. - -2.2 After the roles of both boards are determined, use music pair to perform pairing. Successful pairing will show the log "A2DP relay paired! Role is x" - -2.3 Use music unpair to cancel pairing between the two boards. - -2.4 Before the two boards are paired, you can set the audio channels of the two boards through music set_chnl x (0 represents src left channel/sink right channel, 1 represents src right channel/sink left channel, 2 represents both sides play left channel). - +1. One part involves operations between the device and mobile phone, same as + music_sink. The project enables Bluetooth Inquiry scan and page scan on + startup, allowing A2DP source devices like mobile phones to discover this + device and initiate connections. After connection, mobile phone music can be + played. +2. The other part involves operations between two boards. The two boards need to + complete pairing to achieve music forwarding. Only one board can connect to + the mobile phone at a time. The board not connected to the mobile phone will + receive forwarded music information. 3. The default Bluetooth name of this device is sifli_music_sink. ### Hardware Requirements Before running this example, you need to prepare: -+ Two development boards supported by this example ([Supported Platforms](#Platform_music_sink)). ++ Two development boards supported by this example ([Supported + Platforms](#Platform_music_sink)). + Speakers. ### menuconfig Configuration - 1. Enable AUDIO CODEC and AUDIO PROC: - Path: On-chip Peripheral RTOS Drivers - Enable: Enable Audio Process driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_PRC` - - Description: Enable Audio process device, mainly used for audio data processing (including resampling, volume adjustment, etc.) + - Description: Enable Audio process device, mainly used for audio data + processing (including resampling, volume adjustment, etc.) - Enable: Enable Audio codec driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_CODEC` - Description: Enable Audio codec device, mainly used for DAC conversion @@ -60,7 +60,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_BLUETOOTH` - Description: Enable Bluetooth functionality 5. Enable A2DP SNK and AVRCP: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (Optional) - Macro switch: `CONFIG_BT_FINSH` - Description: Enable finsh command line for Bluetooth control @@ -77,7 +78,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_CFG_AVRCP` - Description: Enable AVRCP profile 6. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT connection manager - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - Description: Use connection manager module to manage BT connections @@ -85,36 +87,42 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the relevant introduction in [Quick Start](/quickstart/get-started.md). +For detailed compilation and download steps, please refer to the relevant +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - -After the example starts: -Mobile phone music forwarding can be achieved with synchronized sound between forwarding devices without stuttering. + +After the example starts: Mobile phone music forwarding can be achieved with +synchronized sound between forwarding devices without stuttering. ## Exception Diagnosis + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/music_source/README_EN.md b/example/bt/music_source/README_EN.md index 21c47cb3c..659de03ed 100644 --- a/example/bt/music_source/README_EN.md +++ b/example/bt/music_source/README_EN.md @@ -4,7 +4,7 @@ Source code path: example/bt/music_source {#Platform_music_src} ## Supported Platforms - + + eh-lb525 + eh-lb563 + eh-lb567 @@ -13,53 +13,65 @@ Source code path: example/bt/music_source + sf32lb56-lcd series + sf32lb58-lcd series - ## Overview - -This example demonstrates local music playback and audio streaming to A2DP SINK devices such as headphones after connection, including: + +This example demonstrates local music playback and audio streaming to A2DP SINK +devices such as headphones after connection, including: + Pre-installed mp3 audio file in the root partition. ## Example Usage - -The example will enable Bluetooth by default at startup and is controlled via FINSH commands: - -1. Play local music: -Use the command `music play_default` to play the pre-installed .mp3 file. If no Bluetooth devices like headphones are connected, audio will be output directly from the speaker. -To play songs from the file system, use `music play [loop_time] [path]`, for example `music play 3 \A.mp3` will play A.mp3 from the root partition 4 times (loop_time+1) . - -2. Search for Bluetooth devices: -Use the command `music inquiry start` to search for headphone-type Bluetooth devices. This command will only report devices with COD Major Class 0x000400 (Audio device). -Found devices will be printed in the format "device [%s] searched" and "device COD is [%d], addr is xx:xx:xx:xx:xx:xx". - -3. Connect to Bluetooth devices: -Use the command `music conn [addr]` to connect, where addr is the address (xx:xx:xx:xx:xx:xx) of the device found above - simply copy the printed value. -If you already know the address of a headphone-type Bluetooth device, you can connect directly without searching. -When the A2DP profile is connected, the device's audio output will automatically switch from speaker to headphones, and switch back when disconnected. - -4. Adjust remote Bluetooth device volume: -Use the command `music set_vol [val]` where val is valid between 0-127. This example currently only supports adjusting the volume of headphones that support absolute volume functionality. If the headphones don't support this feature, volume adjustment will not be possible. + +The example will enable Bluetooth by default at startup and is controlled via +FINSH commands: +1. Play local music: Use the command `music play_default` to play the + pre-installed .mp3 file. If no Bluetooth devices like headphones are + connected, audio will be output directly from the speaker. To play songs from + the file system, use `music play [loop_time] [path]`, for example `music play + 3 \A.mp3` will play A.mp3 from the root partition 4 times (loop_time+1) . + +2. Search for Bluetooth devices: Use the command `music inquiry start` to search + for headphone-type Bluetooth devices. This command will only report devices + with COD Major Class 0x000400 (Audio device). Found devices will be printed + in the format "device [%s] searched" and "device COD is [%d], addr is + xx:xx:xx:xx:xx:xx". + +3. Connect to Bluetooth devices: Use the command `music conn [addr]` to connect, + where addr is the address (xx:xx:xx:xx:xx:xx) of the device found above - + simply copy the printed value. If you already know the address of a + headphone-type Bluetooth device, you can connect directly without searching. + When the A2DP profile is connected, the device's audio output will + automatically switch from speaker to headphones, and switch back when + disconnected. + +4. Adjust remote Bluetooth device volume: Use the command `music set_vol [val]` + where val is valid between 0-127. This example currently only supports + adjusting the volume of headphones that support absolute volume + functionality. If the headphones don't support this feature, volume + adjustment will not be possible. ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_music_src)). ++ One development board supported by this example ([Supported + Platforms](#Platform_music_src)). + A speaker. ### menuconfig Configuration - -1. This example needs to read and write files, so it requires a file system. Configure the `FAT` file system: +1. This example needs to read and write files, so it requires a file system. + Configure the `FAT` file system: - Path: RTOS → RT-Thread Components → Device virtual file system - Enable: Enable elm-chan fatfs - Macro switch: `CONFIG_RT_USING_DFS_ELMFAT` - Description: Enable fatfs file system ```{tip} - mnt_init mounts the root partition. + mnt_init mounts the root partition. ``` 2. Enable AUDIO CODEC and AUDIO PROC: - Path: On-chip Peripheral RTOS Drivers - Enable: Enable Audio Process driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_PRC` - - Description: Enable Audio process device, mainly used for audio data processing (including resampling, volume adjustment, etc.) + - Description: Enable Audio process device, mainly used for audio data + processing (including resampling, volume adjustment, etc.) - Enable: Enable Audio codec driver - Macro switch: `CONFIG_BSP_ENABLE_AUD_CODEC` - Description: Enable Audio codec device, mainly used for DAC conversion @@ -77,7 +89,8 @@ Before running this example, you need to prepare: - Enable: Enable local audio - Macro switch: `CONFIG_AUDIO_LOCAL_MUSIC` - Description: Enable local audio function -6. Pre-install audio file by placing it in the following \disk\ directory for pre-installation download: +6. Pre-install audio file by placing it in the following \disk\ directory for + pre-installation download: * Audio file is located at music_source/disk/test.mp3 7. Enable Bluetooth(`BLUETOOTH`): - Path: Sifli middleware → Bluetooth @@ -85,7 +98,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_BLUETOOTH` - Description: Enable bluetooth function 8. Enable A2DP source and AVRCP: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (optional) - Macro switch: `CONFIG_BT_FINSH` - Description: Enable finsh command line for Bluetooth control @@ -102,7 +116,8 @@ Before running this example, you need to prepare: - Macro switch: `CONFIG_CFG_AVRCP` - Description: Enable AVRCP profile 9. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT connection manager - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - Description: Use connection manager module to manage BT connections @@ -110,37 +125,44 @@ Before running this example, you need to prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the related introduction in [Quick Start](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the related +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - + After the example starts: 1. Play built-in music without Bluetooth connection -2. Can search for headphone-type Bluetooth devices and play built-in music after connection +2. Can search for headphone-type Bluetooth devices and play built-in music after + connection ## Troubleshooting + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 01/2025 | Initial version | +| | | | +| | | | diff --git a/example/bt/pan/README_EN.md b/example/bt/pan/README_EN.md index 1dfb64905..c16e2eb5d 100644 --- a/example/bt/pan/README_EN.md +++ b/example/bt/pan/README_EN.md @@ -4,7 +4,7 @@ Source code path: example/bt/pan (Platform_pan)= ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x @@ -12,138 +12,189 @@ Source code path: example/bt/pan + sf32lb56-lcd series + sf32lb58-lcd series - ## Overview - -This example demonstrates connecting to a phone's PAN protocol via Bluetooth, then using Finsh commands to retrieve current weather information from a specific website. + +This example demonstrates connecting to a phone's PAN protocol via Bluetooth, +then using Finsh commands to retrieve current weather information from a +specific website. ## Adding CA Certificates 1. Storing Root Certificates of Signing Authorities - -- `external/mbedtls_288/certs/default` The directory stores the commonly used CA certificate files. - +- `external/mbedtls_288/certs/default` The directory stores the commonly used CA + certificate files. - `certs` The directory stores the CA certificate files added by the users. -If the required CA root certificate is not present in the `certs/default` directory,
-users must copy their PEM-format CA certificate to the root `certs` directory. (Only PEM format is supported; DER format is not accepted).
-Added certificates should be placed alongside `DigiCert_Global_Root_CA2.crt` in this directory. -![alt text](./assets/list.png) +If the required CA root certificate is not present in the `certs/default` +directory,
users must copy their PEM-format CA certificate to the root +`certs` directory. (Only PEM format is supported; DER format is not +accepted).
Added certificates should be placed alongside +`DigiCert_Global_Root_CA2.crt` in this directory. ![alt text](./assets/list.png) 2. Certificate Format Specifications - - `PEM` format Certificates -**PEM format certificate** use **.pem** or **.cer** file with suffixes at the end. - -When opened in a text editor, content starts with `-----BEGIN CERTIFICATE-----` and ends with `-----END CERTIFICATE-----`. + **PEM certificates** typically use the **.pem** or **.cer** file extensions. + When opened with a text editor, the content begins with `-----BEGIN + CERTIFICATE-----` and ends with `-----END CERTIFICATE-----`. - `DERformat Certificates` - **The DER format certificate** is a binary file type. + **The DER format certificate** is a binary file type.
+ +3. Checking Configuration Verify in `proj.conf`: If + `PKG_USING_MBEDTLS_USER_CERTS` is enabled, all files in the root certs + directory will be merged into `ports/src/tls_certificate.c` during + compilation. ![alt text]{1} -3. Checking Configuration -Verify in `proj.conf`: If `PKG_USING_MBEDTLS_USER_CERTS` is enabled, all files in the root certs directory will be merged into `ports/src/tls_certificate.c` during compilation. -![alt text](./assets/proj.png) +**PEM format certificate** use **.pem** or **.cer** file with suffixes at the +end. ## Example Usage - -1. Before connecting, it's best to ensure the phone has already enabled network sharing. If network sharing is enabled after BT connection, you can reconnect to PAN using the finsh command "pan_cmd conn_pan" to connect to the network. - 1) iOS enables network sharing. iOS needs to ensure a SIM card is installed, then enable Personal Hotspot:\ - ![IOS_ENB](./assets/ios_enable_pan.png) - 2) Different Android devices have different paths to enable network sharing, but all can be found in Personal Hotspot sharing to find Bluetooth network sharing and enable it. Android can enable Bluetooth network sharing based on WiFi connection:\ - ![ANDRIOD_ENB](./assets/android_enable_pan.png) -2. The example will enable Bluetooth Inquiry scan and page scan at startup, allowing phones and other devices to discover and connect to this device. The default Bluetooth name is sifli_pan. -3. With the phone's network sharing enabled, the PAN protocol will connect successfully, and you can find "pan connect successed" in the log. With the phone itself having internet access, - input the finsh command "weather" to get current weather information. Successful output is shown below:\ + +1. Before connecting, it's best to ensure the phone has already enabled network + sharing. If network sharing is enabled after BT connection, you can reconnect + to PAN using the finsh command "pan_cmd conn_pan" to connect to the network. + 1) iOS enables network sharing. iOS needs to ensure a SIM card is installed, + then enable Personal Hotspot:\ + ![IOS_ENB](./assets/ios_enable_pan.png) + 2) Different Android devices have different paths to enable network sharing, + but all can be found in Personal Hotspot sharing to find Bluetooth + network sharing and enable it. Android can enable Bluetooth network + sharing based on WiFi connection:\ + ![ANDRIOD_ENB](./assets/android_enable_pan.png) +2. The example will enable Bluetooth Inquiry scan and page scan at startup, + allowing phones and other devices to discover and connect to this device. The + default Bluetooth name is sifli_pan. +3. With the phone's network sharing enabled, the PAN protocol will connect + successfully, and you can find "pan connect successed" in the log. With the + phone itself having internet access, input the finsh command "weather" to get + current weather information. Successful output is shown below:\ ![WEATHER_PRINT](./assets/weather_print.png) -4. By default, this example has OTA functionality enabled. Input the finsh command "pan_cmd ota_pan" to download and install the image specified by the URL in main.c via BT PAN. For OTA introduction, see the peripheral_with_ota project. -5. This example has added an autoconnect flag. You can enable it by entering the finsh command: pan_cmd set_retry_flag 1 / You can disable it by entering the command: pan_cmd set_retry_flag 0 -6. This example has added the number of autoconnect retries. You can set the maximum retry count by entering the finsh command: pan_cmd set_retry_time 5 (number of retries) -7. Ensure that the phone has enabled network sharing. After the phone disconnects from pan, if you want to automatically reconnect, you can enter the finsh command: pan_cmd autoconnect - -### Notes -- If weather retrieval fails, you need to first verify the validity of the local Bluetooth MAC address OUI: The first three bytes (OUI part) of the MAC address must be a valid value assigned by the IEEE. Using an unauthorized OUI may cause network issues.The address can be modified manually. -- MAC address get command format: nvds get_mac(Invalid address: xxxxxx52FD11) -- Command format for setting Bluetooth MAC: nvds update addr 6 xxxxxxYYYYYY -(where YYYYYY: OUI in byte‑reversed order (must be reversed); xxxxxx: user‑defined last 3 bytes)(Valid address: xxxxxx52FD5C) -- Example: A valid OUI E8:6A:64 → reversed to 646AE8 -- Auto-update is enabled (CONFIG_NVDS_AUTO_UPDATE_MAC_ADDRESS), manual nvds command overridden. -- If nvds get_mac does not change after a reboot (i.e., the command to set the address fails): Check if CONFIG_NVDS_AUTO_UPDATE_MAC_ADDRESS is enabled. If it is, disable this macro, then recompile and flash the firmware before attempting to manually set the MAC address again. +4. By default, this example has OTA functionality enabled. Input the finsh + command "pan_cmd ota_pan" to download and install the image specified by the + URL in main.c via BT PAN. For OTA introduction, see the peripheral_with_ota + project. +5. This example has added an autoconnect flag. You can enable it by entering the + finsh command: pan_cmd set_retry_flag 1 / You can disable it by entering the + command: pan_cmd set_retry_flag 0 +6. This example has added the number of autoconnect retries. You can set the + maximum retry count by entering the finsh command: pan_cmd set_retry_time 5 + (number of retries) +7. Ensure that the phone has enabled network sharing. After the phone + disconnects from pan, if you want to automatically reconnect, you can enter + the finsh command: pan_cmd autoconnect + +## Expected Results +- Failed to retrieve weather data. Verify the validity of the local Bluetooth + MAC address OUI: the first three bytes (OUI) must be a valid value assigned by + the IEEE. Using an unauthorized OUI may cause network issues; the address can + be modified manually. +- Command format to get the address: nvds get_mac (Invalid address example: + xxxxxx52FD11) +- Command format to set the Bluetooth MAC: nvds update addr 6 xxxxxxYYYYYY + (where YYYYYY is the byte-reversed OUI, and xxxxxx represents the user-defined + last 3 bytes. Note: The OUI must be reversed. Valid address example: + xxxxxx52FD5C) +- Example: A valid OUI E8:6A:64 is reversed as 646AE8. +- Enabling CONFIG_NVDS_AUTO_UPDATE_MAC_ADDRESS will override manual address + modifications (nvds update addr 6 xxxxxxYYYYYY). +- If the MAC address is not updated as expected after a device reboot via the + "nvds get_mac" command, verify whether "CONFIG_NVDS_AUTO_UPDATE_MAC_ADDRESS" + is enabled. If so, disable this macro, recompile, flash the firmware, and then + attempt to set the MAC address manually. ### Hardware Requirements -Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_pan)). -+ A phone. -+ A website that can provide weather information (default is api.seniverse.com). +Prerequisites: ++ A development board supported by this example ([Supported + Platforms](#Platform_pan)). ++ Mobile phone. ++ A URL to retrieve weather data (defaults to api.seniverse.com). ### menuconfig Configuration - 1. Enable Bluetooth (`BLUETOOTH`): - Path: Sifli middleware → Bluetooth - - Enable: Enable bluetooth - - Macro switch: `CONFIG_BLUETOOTH` - - Description: Enable bluetooth function -2. Enable PAN & A2DP, A2DP is to avoid iOS not supporting standalone PAN connection: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT finsh (optional) - - Macro switch: `CONFIG_BT_FINSH` - - Description: Enable finsh command line for Bluetooth control - - Enable: Manually select profiles - - Macro switch: `CONFIG_BT_PROFILE_CUSTOMIZE` - - Description: Manually select profiles to enable - - Enable: Enable PAN - - Macro switch: `CONFIG_CFG_PAN` - - Description: Enable PAN protocol -3. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: Enable BT connection manager - - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - - Description: Use connection manager module to manage BT connections + - To enable: Enable bluetooth + - Macro: `CONFIG_BLUETOOTH` + - Description: Enables Bluetooth functionality. +2. Enable PAN and A2DP (A2DP is required as iOS does not support standalone PAN + connections): + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service + - To enable: Enable BT finsh (Optional) + - Macro: `CONFIG_BT_FINSH` + - Description: Enables the FinSH command-line interface for Bluetooth + control. + - To enable: Manually select profiles + - Macro: `CONFIG_BT_PROFILE_CUSTOMIZE` + - Description: Allows manual selection of enabled Bluetooth profiles. + - To enable: Enable PAN + - Macro: `CONFIG_CFG_PAN` + - Description: Enables the PAN protocol. +3. Enable BT Connection Manager: + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service + - To enable: Enable BT connection manager + - Macro: `CONFIG_BSP_BT_CONNECTION_MANAGER` + - Description: Utilizes the Connection Manager module to manage + Bluetooth connections. 4. Enable NVDS: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled - -5. Menuconfig for Bluetooth auto-connection: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - Enable: After enabling BT connection manager, Re-connect to last device if connection timeout happened or system power on will be enabled by default - - Macro switch: `CONFIG_BT_AUTO_CONNECT_LAST_DEVICE` - - Description: Enable auto-connection to the last connected device. + - Macro: `CONFIG_BSP_BLE_NVDS_SYNC` + - Description: Enables synchronous access to Bluetooth Non-Volatile Data + Storage (NVDS). This option must be enabled when Bluetooth is + configured on the HCPU and disabled when it is configured on the LCPU. +5. Menuconfig settings for Bluetooth auto-connection: + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service + - Enable: Enabling "Enable BT connection manager" will automatically enable + "Re-connect to last device if connection timeout happened or system power + on" by default. + - Macro: `CONFIG_BT_AUTO_CONNECT_LAST_DEVICE` + - Description: Enables automatic reconnection to the last connected + device. - Path: Third party packages - - Enable: FlashDB: Lightweight embedded database, usually enabled by default - - Macro switch: `CONFIG_PKG_USING_FLASHDB` - - Description: Enable FlashDB database to retain important data after power-off or restart + - Enable: FlashDB: Lightweight embedded database (typically enabled by + default) + - Macro: `CONFIG_PKG_USING_FLASHDB` + - Description: Enables the FlashDB database to ensure critical data + persistence across power cycles or system reboots. ### Compilation and Flashing -Switch to the example project directory and run the scons command to compile: +Navigate to the project directory and run the `scons` command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Navigate to the `project/build_xx` directory and execute `uart_download.bat`. +Follow the prompts to select the appropriate port for downloading: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the related introduction in [Quick Start](/quickstart/get-started.md). - -## Expected Results - -The example can retrieve weather information from a specific website by connecting to the phone's PAN protocol. +For detailed compilation and download procedures, please refer to the [Quick +Start Guide](/quickstart/get-started.md). ## Troubleshooting + +This example retrieves weather information from a specified URL by connecting to +a smartphone via the Personal Area Networking (PAN) profile. ## Reference Documentation - +1. If a compilation error occurs because the selected chip type lacks a + configured `ptab.json` for OTA, the DFU function can be disabled as shown + below: ![dfu_sub](./assets/dfu_sub.png) ![dfu](./assets/dfu.png) ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |01/2025 |Initial version | -|0.0.2 |04/2025 |Added OTA | -|0.0.3 |07/2025 |Add CA certificate | -| | | | \ No newline at end of file + + +## Revision History +| Version | Date | Release Notes | +| ------- | ------- | -------------------- | +| 0.0.1 | 01/2025 | Initial release | +| 0.0.2 | 04/2025 | Added OTA support | +| 0.0.3 | 07/2025 | Added CA certificate | +| | | | diff --git a/example/bt/pan_ota/README_EN.md b/example/bt/pan_ota/README_EN.md index d942b3c5c..e1ef8839a 100644 --- a/example/bt/pan_ota/README_EN.md +++ b/example/bt/pan_ota/README_EN.md @@ -4,66 +4,90 @@ Source path: example/bt/pan_ota ## Supported Platforms - + + sf32lb52-lcd_n16r8 + sf32lb52-lchspi-ulp + sf32lb52-nano_a128r16 ## Overview - -This example demonstrates connecting to a mobile phone's PAN protocol via Bluetooth, registering the device to a specific server through Finsh commands, retrieving firmware version information, and supports firmware updates via OTA. + +This example demonstrates connecting to a mobile phone's PAN protocol via +Bluetooth, registering the device to a specific server through Finsh commands, +retrieving firmware version information, and supports firmware updates via OTA. ## Adding CA Certificates 1. Storing signing authority root certificates -- The `external/mbedtls_288/certs/default` directory stores commonly used CA certificate files +- The `external/mbedtls_288/certs/default` directory stores commonly used CA + certificate files - The `certs` directory stores user-added CA certificate files -If the `certs/default` directory does not contain the required CA root certificate file
-the user needs to copy their PEM format CA certificate to the "certs" root directory. (Only PEM format certificates are supported, DER format certificates are not supported)
-Add certificates stored alongside `DigiCert_Global_Root_CA2.crt` +If the `certs/default` directory does not contain the required CA root +certificate file
the user needs to copy their PEM format CA certificate to +the "certs" root directory. (Only PEM format certificates are supported, DER +format certificates are not supported)
Add certificates stored alongside +`DigiCert_Global_Root_CA2.crt`\ ![alt text](./assets/list.png) -2. Certificate format description +2. Certificate format description - `PEM Format Certificate` - **PEM Format Certificate** usually ends with **.pem** and **.cer** suffixes. + **PEM Format Certificate** usually ends with **.pem** and **.cer** suffixes. - When opened with a text editor, the file content starts with `-----BEGIN CERTIFICATE-----` and ends with `-----END CERTIFICATE-----`. + When opened with a text editor, the file content starts with `-----BEGIN + CERTIFICATE-----` and ends with `-----END CERTIFICATE-----`. - `DER Format Certificate` - **DER Format Certificate** is a binary file type.
+ **DER Format Certificate** is a binary file type.
3. View configuration -Check proj.conf; if PKG_USING_MBEDTLS_USER_CERTS is enabled, all files in the certs root directory will be merged into ports/src/tls_certificate.c -![alt text](./assets/proj.png) +Check proj.conf; if PKG_USING_MBEDTLS_USER_CERTS is enabled, all files in the +certs root directory will be merged into ports/src/tls_certificate.c ![alt +text](./assets/proj.png) ## Usage of the Example - -1. Before connecting, it's best to ensure the mobile phone has network sharing enabled. If network sharing is turned on after BT connection, you can reconnect to the PAN and thus connect to the network using the finsh command "pan_cmd conn_pan" - 1) Enable network sharing on iOS. iOS needs to ensure a SIM card is installed, then simply turn on Personal Hotspot:\ - ![IOS_ENB](./assets/ios_enable_pan.png) - 2) Different Android phones have different paths to enable network sharing, but they all involve finding and enabling Bluetooth network sharing within personal hotspot sharing. Android can open Bluetooth network sharing while connected to WiFi:\ - ![ANDROID_ENB](./assets/android_enable_pan.png) -2. On startup, the example enables Bluetooth Inquiry scan and page scan, allowing devices like phones to discover and initiate connections to this device. The default Bluetooth name is sifli_pan. -3. PAN protocol will only connect successfully when the phone has network sharing enabled. You can find the print "pan connect successed" in the log. Ensure that the phone itself has internet access before executing commands. -4. This example supports OTA functionality, enabling remote firmware upgrades. Before using the OTA function, add the following configuration in the SConstruct file: + +1. Before connecting, it's best to ensure the mobile phone has network sharing + enabled. If network sharing is turned on after BT connection, you can + reconnect to the PAN and thus connect to the network using the finsh command + "pan_cmd conn_pan" + 1) Enable network sharing on iOS. iOS needs to ensure a SIM card is + installed, then simply turn on Personal Hotspot:\ + ![IOS_ENB](./assets/ios_enable_pan.png) + 2) Different Android phones have different paths to enable network sharing, + but they all involve finding and enabling Bluetooth network sharing + within personal hotspot sharing. Android can open Bluetooth network + sharing while connected to WiFi:\ + ![ANDROID_ENB](./assets/android_enable_pan.png) +2. On startup, the example enables Bluetooth Inquiry scan and page scan, + allowing devices like phones to discover and initiate connections to this + device. The default Bluetooth name is sifli_pan. +3. PAN protocol will only connect successfully when the phone has network + sharing enabled. You can find the print "pan connect successed" in the log. + Ensure that the phone itself has internet access before executing commands. +4. This example supports OTA functionality, enabling remote firmware upgrades. + Before using the OTA function, add the following configuration in the + SConstruct file: ``` if GetDepend('USING_DFU_PAN'): AddDFU_PAN(SIFLI_SDK) ``` - + The OTA function provides the following commands: - - `check_dynamic_cmd` - Register device to OTA server and check for new firmware versions, sets update flag if new version exists - - `reset_to_dload_cmd` - Check update flag, restart device to enter OTA download mode + - `check_dynamic_cmd` - Register device to OTA server and check for new + firmware versions, sets update flag if new version exists + - `reset_to_dload_cmd` - Check update flag, restart device to enter OTA + download mode - `show_version_cmd` - Display current firmware version information ### Hardware Requirements Before running this example, prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_pan)). ++ One development board supported by this example ([Supported + Platforms](#Platform_pan)). + Mobile phone. -+ Version files deployed on the server, corresponding to the URL built by build_ota_query_url ++ Version files deployed on the server, corresponding to the URL built by + build_ota_query_url ### menuconfig Configuration @@ -72,8 +96,10 @@ Before running this example, prepare: - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Function: Enable Bluetooth functionality -2. Enable PAN & A2DP, A2DP is to avoid IOS not supporting standalone PAN connection: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service +2. Enable PAN & A2DP, A2DP is to avoid IOS not supporting standalone PAN + connection: + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (optional) - Macro switch: `CONFIG_BT_FINSH` - Function: Enable finsh command line for controlling Bluetooth @@ -84,7 +110,8 @@ Before running this example, prepare: - Macro switch: `CONFIG_CFG_PAN` - Function: Enable PAN protocol 3. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT connection manager - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - Function: Use connection manager module to manage bt connections @@ -92,39 +119,49 @@ Before running this example, prepare: - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Function: Bluetooth NVDS synchronization. When Bluetooth is configured to HCUP, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option should be disabled + - Function: Bluetooth NVDS synchronization. When Bluetooth is configured + to HCUP, BLE NVDS can be accessed synchronously, enable this option; + when Bluetooth is configured to LCPU, this option should be disabled 5. menuconfig options needed for Bluetooth auto connection: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service - - After enabling: Enable BT connection manager, Re-connect to last device if connection timeout happened or system power on will be enabled by default + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service + - After enabling: Enable BT connection manager, Re-connect to last device if + connection timeout happened or system power on will be enabled by default - Macro switch: `CONFIG_BT_AUTO_CONNECT_LAST_DEVICE` - - Function: Enable automatic connection to the last connected device. + - Function: Enable automatic connection to the last connected device. - Path: Third party packages - Enable: FlashDB: Lightweight embedded database, usually enabled by default - Macro switch: `CONFIG_PKG_USING_FLASHDB` - - Function: Enable FlashDB database to retain important data after power off or reboot. + - Function: Enable FlashDB database to retain important data after power + off or reboot. 6. Enable DFU PAN functionality: - Path: Sifli middleware → Using dfu pan - Enable: Using dfu pan - Macro switch: `CONFIG_USING_DFU_PAN` - + ### Compilation and Flashing -Switch to the example project directory and run the scons command for compilation: +Switch to the example project directory and run the scons command for +compilation: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run [uart_download.bat], select the port as prompted to proceed with downloading: +Switch to the example `project/build_xx` directory and run [uart_download.bat], +select the port as prompted to proceed with downloading: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the [Quick Start Guide](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the [Quick +Start Guide](/quickstart/get-started.md). ## Expected Results of the Example - -The example can connect to the mobile phone's PAN protocol, execute commands to properly register settings to the server, and query versions returning JSON formatted version information. + +The example can connect to the mobile phone's PAN protocol, execute commands to +properly register settings to the server, and query versions returning JSON +formatted version information. ```json Note: dfu_pan_query_latest_version() will retrieve JSON data returned from the server and write the firmware structure to flash address for direct download later. The JSON is as follows, where v1.1.bin is a placeholder file that needs to be placed together with the firmware file and match the current folder name. @@ -169,20 +206,20 @@ Executing the "check_dynamic_cmd" command will print the following information: ![](./assets/dfu_pan1.png) Executing the "reset_to_dload_cmd" command will print the following information: -![](./assets/dfu_pan2.png) -Upgrade progress can also be observed through screen UI -![](./assets/dfu_pan3.png) -Executing the "show_version_cmd" command will print the following information: +![](./assets/dfu_pan2.png) Upgrade progress can also be observed through screen +UI ![](./assets/dfu_pan3.png) Executing the "show_version_cmd" command will +print the following information: -Indicating successful upgrade from v1.0 to v1.1 -![](./assets/dfu_pan4.png) +Indicating successful upgrade from v1.0 to v1.1 ![](./assets/dfu_pan4.png) ## Troubleshooting ## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |12/2025 |Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2025 | Initial version | + + diff --git a/example/bt/spp/README_EN.md b/example/bt/spp/README_EN.md index 77c2751fb..f064595d4 100644 --- a/example/bt/spp/README_EN.md +++ b/example/bt/spp/README_EN.md @@ -4,7 +4,7 @@ Source code path: example/bt/spp {#Platform_spp} ## Supported Platforms - + + eh-lb52x + eh-lb56x + eh-lb58x @@ -12,101 +12,120 @@ Source code path: example/bt/spp + sf32lb56-lcd series + sf32lb58-lcd series - ## Overview - -This example demonstrates SPP connection and disconnection, data transmission, file transfer, and speed testing, including: + +This example demonstrates SPP connection and disconnection, data transmission, +file transfer, and speed testing, including: + SPP server + SPP client + SPP server and SPP client ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported Platforms](#Platform_spp)). -+ An Android phone (SPP only supports Android phones, iOS phones cannot use SPP), and you need to download an SPP Bluetooth serial port tool APP (e.g., SPP Bluetooth Serial Port, e-Debug, etc.). ++ One development board supported by this example ([Supported + Platforms](#Platform_spp)). ++ An Android phone (SPP only supports Android phones, iOS phones cannot use + SPP), and you need to download an SPP Bluetooth serial port tool APP (e.g., + SPP Bluetooth Serial Port, e-Debug, etc.). ## Example Usage - -The example will enable Bluetooth by default at startup, and the phone can enter the SPP Bluetooth serial port tool APP to search and connect (using e-Debug app as an example): - -1. Phone app connects to development board SPP: -Enter the classic Bluetooth device search interface on the phone to search for the development board: -![e-Debug Search Device](./assets/1.png) -After finding the specified device, you can long-press the device to modify the UUID of the SPP to connect (default is 0x1101 UUID). This example supports custom SPP UUIDs to increase the number of SPP connections, and supports up to 7 SPP connections with the same phone. Users can add custom UUIDs by implementing the bt_spp_srv_add_uuid_list interface. Also, if the phone wants to connect multiple SPP connections, it may need to establish one SPP connection in each app separately. -![e-Debug Modify Device UUID to Connect](./assets/2.png) -![e-Debug Connect Device](./assets/3.png) -You can see the successful connection log in the serial port output: -![e-Debug Connection Success](./assets/4.png) - -2. Phone sends data to development board -You can send data from the phone app to the development board, as shown below: -![e-Debug Send Data](./assets/7.png) -The development board's serial port log will print the received data size and speed: -![e-Debug Send Data](./assets/11.png) - -3. Development board sends data to phone -Use the command `spp send_data + address + service channel` to send test data to the phone, where the service channel can be obtained from the serial port output: -![Get Connected Service Channel](./assets/5.png) -The phone app will display the received data: -![Phone Receives Data from Development Board](./assets/6.png) - -4. Phone sends file to development board -In the phone app, you can select to send a file to the development board: -![Phone Sends File to Development Board](./assets/8.png) -![Set Send Interval and Data Size per Packet](./assets/9.png) -The development board's serial port log will print the received data size and speed, and the phone will also display the sending progress: -![e-Debug Send Data](./assets/11.png) -![e-Debug Send Data](./assets/10.png) - -5. Development board sends file to phone -If there are files on the development board, you can use the command `spp send_file + address + service channel + filename` to send the specified file to the phone, where the service channel can be obtained from the serial port output: -![Get Connected Service Channel](./assets/5.png) -![View Files on Development Board](./assets/12.png) -![Send File to Phone](./assets/13.png) -The phone will display the received content and data size: -![Send File to Phone](./assets/14.png) - -6. Development board initiates SPP connection -The development board can also initiate SPP connections, but since many phones only support 0x1101 SPP, and the development board will be quickly disconnected by the phone after actively connecting, you can choose to connect development board to development board. -Since this example supports custom SPP UUIDs to increase the number of SPP connections, you can flash this example to two development boards separately, allowing multiple SPP connections between development boards, with one acting as the phone role. -For example, if development board A needs to connect to development board B's 0x3001 SPP channel, you can use the command `spp search + address + uuid length + uuid` to first query whether the peer device supports 0x3001 SPP: -![Search Peer SPP](./assets/spp_search.png) -Development board A can use the command `spp connect + address + uuid length + uuid` to connect to the peer device's 0x3001 SPP: -![Connect to Peer SPP](./assets/spp_connect.png) - -7. Throughput test between development boards -The functions mentioned above also exist in connections between development boards. Here we mainly explain the throughput test between development boards. Development board A can use the command `spp through_put + address + service channel + transmitted data size` to transmit random data of specified size to development board B. Development board B will calculate the rate after receiving all data: -The service channel can be obtained from the serial port output: -![Get Connected Service Channel](./assets/5.png) -![SPP Throughput](./assets/spp_through_put.png) - -8. Disconnect specified SPP connection -The development board can use the command `spp disc + address + service channel` to disconnect the specified SPP connection: -The service channel can be obtained from the serial port output: -![Get Connected Service Channel](./assets/5.png) -![Disconnect SPP Service Channel](./assets/spp_disconnect.png) - -9. Disconnect all connected SPP -The development board can use the command `spp disc_all` to disconnect all SPP connections. + +The example will enable Bluetooth by default at startup, and the phone can enter +the SPP Bluetooth serial port tool APP to search and connect (using e-Debug app +as an example): +1. Phone app connects to development board SPP: Enter the classic Bluetooth + device search interface on the phone to search for the development board: + ![e-Debug Search Device](./assets/1.png) After finding the specified device, + you can long-press the device to modify the UUID of the SPP to connect + (default is 0x1101 UUID). This example supports custom SPP + UUIDs to increase the number of SPP connections, and supports up to 7 SPP + connections with the same phone. Users can add custom UUIDs by implementing + the bt_spp_srv_add_uuid_list interface. Also, if the phone wants to connect + multiple SPP connections, it may need to establish one SPP connection in each + app separately. ![e-Debug Modify Device UUID to + Connect](./assets/2.png) ![e-Debug Connect Device](./assets/3.png) You can + see the successful connection log in the serial port output: ![e-Debug + Connection Success](./assets/4.png) + +2. Phone sends data to development board You can send data from the phone app to + the development board, as shown below: ![e-Debug Send Data](./assets/7.png) + The development board's serial port log will print the received data size and + speed: ![e-Debug Send Data](./assets/11.png) + +3. Development board sends data to phone Use the command `spp send_data + + address + service channel` to send test data to the phone, where the service + channel can be obtained from the serial port output: ![Get Connected Service + Channel](./assets/5.png) The phone app will display the received data: + ![Phone Receives Data from Development Board](./assets/6.png) + +4. Phone sends file to development board In the phone app, you can select to + send a file to the development board: ![Phone Sends File to Development + Board](./assets/8.png) ![Set Send Interval and Data Size per + Packet](./assets/9.png) The development board's serial port log will print + the received data size and speed, and the phone will also display the sending + progress: ![e-Debug Send Data](./assets/11.png) ![e-Debug Send + Data](./assets/10.png) + +5. Development board sends file to phone If there are files on the development + board, you can use the command `spp send_file + address + service channel + + filename` to send the specified file to the phone, where the service channel + can be obtained from the serial port output: ![Get Connected Service + Channel](./assets/5.png) ![View Files on Development Board](./assets/12.png) + ![Send File to Phone](./assets/13.png) The phone will display the received + content and data size: ![Send File to Phone](./assets/14.png) + +6. Development board initiates SPP connection The development board can also + initiate SPP connections, but since many phones only support 0x1101 SPP, and + the development board will be quickly disconnected by the phone after + actively connecting, you can choose to connect development board to + development board. Since this example supports custom SPP UUIDs to increase + the number of SPP connections, you can flash this example to two development + boards separately, allowing multiple SPP connections between development + boards, with one acting as the phone role. For example, if development board + A needs to connect to development board B's 0x3001 SPP channel, you can use + the command `spp search + address + uuid length + uuid` to first query + whether the peer device supports 0x3001 SPP: ![Search Peer + SPP](./assets/spp_search.png) Development board A can use the command `spp + connect + address + uuid length + uuid` to connect to the peer device's + 0x3001 SPP: ![Connect to Peer SPP](./assets/spp_connect.png) + +7. Throughput test between development boards The functions mentioned above also + exist in connections between development boards. Here we mainly explain the + throughput test between development boards. Development board A can use the + command `spp through_put + address + service channel + transmitted data size` + to transmit random data of specified size to development board B. Development + board B will calculate the rate after receiving all data: The service channel + can be obtained from the serial port output: ![Get Connected Service + Channel](./assets/5.png) ![SPP Throughput](./assets/spp_through_put.png) + +8. Disconnect specified SPP connection The development board can use the command + `spp disc + address + service channel` to disconnect the specified SPP + connection: The service channel can be obtained from the serial port output: + ![Get Connected Service Channel](./assets/5.png) ![Disconnect SPP Service + Channel](./assets/spp_disconnect.png) + +9. Disconnect all connected SPP The development board can use the command `spp + disc_all` to disconnect all SPP connections. ### menuconfig Configuration - -1. This example needs to read and write files, so it requires a file system. Configure the `FAT` file system: +1. This example needs to read and write files, so it requires a file system. + Configure the `FAT` file system: - Path: RTOS → RT-Thread Components → Device virtual file system - Enable: Enable elm-chan fatfs - Macro switch: `CONFIG_RT_USING_DFS_ELMFAT` - Description: Enable fatfs file system - ```{tip} + ```{tip} mnt_init mounts the root partition. - ``` + ``` 2. Enable Bluetooth (`BLUETOOTH`): - Path: Sifli middleware → Bluetooth - Enable: Enable bluetooth - Macro switch: `CONFIG_BLUETOOTH` - Description: Enable bluetooth function 3. Enable SPP server and SPP client: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT finsh (optional) - Macro switch: `CONFIG_BT_FINSH` - Description: Enable finsh command line for Bluetooth control @@ -115,12 +134,15 @@ The development board can use the command `spp disc_all` to disconnect all SPP c - Description: Manually select profiles to enable - Enable: Enable SPP client - Macro switch: `CONFIG_CFG_SPP_CLT` - - Description: Enable SPP client function for actively initiating SPP connections, etc. + - Description: Enable SPP client function for actively initiating SPP + connections, etc. - Enable: Enable SPP server - Macro switch: `CONFIG_CFG_SPP_SRV` - - Description: Enable SPP server function so that peer devices can search and connect to SPP service + - Description: Enable SPP server function so that peer devices can + search and connect to SPP service 4. Enable BT connection manager: - - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT service + - Path: Sifli middleware → Bluetooth → Bluetooth service → Classic BT + service - Enable: Enable BT connection manager - Macro switch: `CONFIG_BSP_BT_CONNECTION_MANAGER` - Description: Use connection manager module to manage BT connections @@ -128,36 +150,42 @@ The development board can use the command `spp disc_all` to disconnect all SPP c - Path: Sifli middleware → Bluetooth → Bluetooth service → Common service - Enable: Enable NVDS synchronous - Macro switch: `CONFIG_BSP_BLE_NVDS_SYNC` - - Description: Bluetooth NVDS synchronization. When Bluetooth is configured to HCPU, BLE NVDS can be accessed synchronously, enable this option; when Bluetooth is configured to LCPU, this option needs to be disabled + - Description: Bluetooth NVDS synchronization. When Bluetooth is + configured to HCPU, BLE NVDS can be accessed synchronously, enable + this option; when Bluetooth is configured to LCPU, this option needs + to be disabled ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the related introduction in [Quick Start](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the related +introduction in [Quick Start](/quickstart/get-started.md). ## Expected Results - + After the example starts: 1. SPP functionality works normally ## Troubleshooting + ## Reference Documentation - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |03/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 03/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/audio_v1_mic/README_EN.md b/example/cherryusb/device/audio_v1_mic/README_EN.md index 2e5b9018f..9b21a79ab 100644 --- a/example/cherryusb/device/audio_v1_mic/README_EN.md +++ b/example/cherryusb/device/audio_v1_mic/README_EN.md @@ -3,57 +3,72 @@ Source path: example\cherryusb\device\audio_v1_mic ## Supported Platforms + + sf32lb52-lcd_n16r8 ## Overview -This example demonstrates the USB microphone recording functionality based on the USB audio class, the UAC protocol used is 1.0, including: -+ The host calls the recording function to record audio through the USB microphone. + +This example demonstrates the USB microphone recording functionality based on +the USB audio class, the UAC protocol used is 1.0, including: ++ The host calls the recording function to record audio through the USB + microphone. + PCM data is uploaded to the host via USB. ## Usage Instructions + + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A host device that supports USB. ### menuconfig Configuration -1. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -2. Enable AUDIO (`AUDIO`): -![AUDIO](./assets/mc_audio.png) +1. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +2. Enable AUDIO (`AUDIO`): ![AUDIO](./assets/mc_audio.png) 3. Enable AUDIO MANAGER (`AUDIO_USING_MANAGER`): -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) 4. Modify the default AUDIO RX Path: -![AUDIO_MIC_USING_CODEC](./assets/mc_audio_audio_rx_path.png) + ![AUDIO_MIC_USING_CODEC](./assets/mc_audio_audio_rx_path.png) ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j32 -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then follow the prompts to select the port for downloading: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then follow the prompts to select the port for downloading: > ./uart_download.bat -> Uart Download +> UART Download -> please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results -After starting the example: -The host connects to the board via the data cable, and a new microphone device (SiFli UAC DEMO) will appear in the audio input and output section of the host's device manager. When the host opens the recording device, it can select the microphone device for normal recording. + +After starting the example: The host connects to the board via the data cable, +and a new microphone device (SiFli UAC DEMO) will appear in the audio input and +output section of the host's device manager. When the host opens the recording +device, it can select the microphone device for normal recording. + ## Troubleshooting + ## Reference Documents + ## Change Log -| Version | Date | Release Notes | -|:---|:---|:---| -| 0.0.1 | 08/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 08/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/audio_v1_mic_speaker/README_EN.md b/example/cherryusb/device/audio_v1_mic_speaker/README_EN.md index 9f49bdefe..dc72873b0 100644 --- a/example/cherryusb/device/audio_v1_mic_speaker/README_EN.md +++ b/example/cherryusb/device/audio_v1_mic_speaker/README_EN.md @@ -3,41 +3,42 @@ Source path: example\cherryusb\device\audio_v1_mic ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates USB microphone recording and speaker audio playback functionality based on USB audio class, including: -+ The host can connect to devices via USB to enable microphone recording and speaker playback. + +This example demonstrates USB microphone recording and speaker audio playback +functionality based on USB audio class, including: ++ The host can connect to devices via USB to enable microphone recording and + speaker playback. ## Usage Instructions - + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A host device that supports USB. ### menuconfig Configuration -1. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -2. Enable AUDIO (`AUDIO`): -![AUDIO](./assets/mc_audio.png) +1. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +2. Enable AUDIO (`AUDIO`): ![AUDIO](./assets/mc_audio.png) 3. Enable AUDIO MANAGER (`AUDIO_USING_MANAGER`): -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) -4. Modify the default AUDIO RX Path: -![AUDIO_MIC_USING_CODEC](./assets/mc_audio_audio_rx_path.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then follow the prompts to select the port for downloading: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then follow the prompts to select the port for downloading: ```c $ ./uart_download.bat @@ -45,21 +46,28 @@ $ ./uart_download.bat please input the serial port num: ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example starts: -When the host connects to the board via the data cable, a new microphone device (SiFli UAC DEMO) and speaker device (SiFli UAC DEMO) will appear in the audio input and output section of the host's device manager. After the host opens the recording device, it can select the microphone device for normal recording. In the sound output section, you can select SiFli UAC DEMO as the output device for audio playback. + +After the example starts: When the host connects to the board via the data +cable, a new microphone device (SiFli UAC DEMO) and speaker device (SiFli UAC +DEMO) will appear in the audio input and output section of the host's device +manager. After the host opens the recording device, it can select the microphone +device for normal recording. In the sound output section, you can select SiFli +UAC DEMO as the output device for audio playback. + ## Troubleshooting + ## Reference Documents - + ## Change Log -| Version | Date | Release Notes | -|:---|:---|:---| -| 0.0.1 | 09/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/cdc_acm/README_EN.md b/example/cherryusb/device/cdc_acm/README_EN.md index 47aea40ef..84c78e225 100644 --- a/example/cherryusb/device/cdc_acm/README_EN.md +++ b/example/cherryusb/device/cdc_acm/README_EN.md @@ -1,16 +1,30 @@ # USB CDC ACM Example +This example demonstrates how to implement a CDC ACM (Communication Device Class +- Abstract Control Model) device using the CherryUSB stack, which emulates a USB +interface as a serial port device. The device can be recognized by the host as a +virtual serial port (COM port) and supports bidirectional data transmission. -This example demonstrates how to implement a CDC ACM (Communication Device Class - Abstract Control Model) device using the CherryUSB stack, which emulates a USB interface as a serial port device. The device can be recognized by the host as a virtual serial port (COM port) and supports bidirectional data transmission. +This example demonstrates how to implement a CDC ACM (Communication Device Class +– Abstract Control Model) device using the CherryUSB stack to emulate a USB +interface as a serial port. The device is recognized by the host as a Virtual +COM Port (VCP) and supports bidirectional data transmission. ## Features -- **CDC ACM Device Class Implementation**: Complies with USB CDC ACM standard, supports virtual serial port communication -- **Data Transfer Functionality**: Supports bidirectional data transfer between USB and UART -- **DTR (Data Terminal Ready) Control**: Supports DTR signal detection and control -- **High-Speed Transfer**: Supports high-speed USB transfer with maximum packet length up to 512 bytes (high-speed mode) -- **Automatic Data Transmission**: Periodically sends test data to demonstrate data transfer functionality -- **Real-Time Operating System Integration**: Based on RT-Thread RTOS implementation -- **CherryUSB Stack**: Uses lightweight, high-performance CherryUSB protocol stack +- **CDC ACM Device Class Implementation**: Complies with USB CDC ACM standard, + supports virtual serial port communication +- **Data Transfer Functionality**: Supports bidirectional data transfer between + USB and UART +- **DTR (Data Terminal Ready) Control**: Supports DTR signal detection and + control +- **High-Speed Transfer**: Supports high-speed USB transfer with maximum packet + length up to 512 bytes (high-speed mode) +- **Automatic Data Transmission**: Periodically sends test data to demonstrate + data transfer functionality +- **Real-Time Operating System Integration**: Based on RT-Thread RTOS + implementation +- **CherryUSB Stack**: Uses lightweight, high-performance CherryUSB protocol + stack ## Hardware Connection @@ -20,33 +34,37 @@ This example demonstrates how to implement a CDC ACM (Communication Device Class ### USB Connection - Connect the development board's USB interface to PC using a USB cable - Ensure USB interface power supply is normal -- Supports USB 2.0 full-speed mode and high-speed mode (depending on configuration) +- Supports USB 2.0 full-speed mode and high-speed mode (depending on + configuration) ### Pin Configuration -This example uses the internal USB controller, mainly involving the following configurations: +This example uses the internal USB controller, mainly involving the following +configurations: - **USB VID**: 0x38f4 (SiFli Technologies) - **USB PID**: 0xFFFF - **Endpoint Configuration**: - CDC data input endpoint: 0x85 - - CDC data output endpoint: 0x02 + - CDC data output endpoint: 0x02 - CDC interrupt endpoint: 0x86 ## Compilation and Usage ### 1 Compilation -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### 2 Usage @@ -66,8 +84,10 @@ please input the serial port num:5 #### 2.3 Data Transfer Test 1. **Automatic Data Transmission**: - - Program automatically sends 2048 bytes of test data every second (when DTR is enabled) - - Data content: First 10 bytes are "1234567890", followed by letter 'a' padding + - Program automatically sends 2048 bytes of test data every second (when DTR + is enabled) + - Data content: First 10 bytes are "1234567890", followed by letter 'a' + padding 2. **Serial Tool Connection**: - Use serial debugging tool to connect to the virtual COM port @@ -86,9 +106,12 @@ please input the serial port num:5 ## Technical Details ### Code Structure -- **main.c**: Main program entry, initializes CDC ACM device and starts data transmission loop -- **cdc_acm_template.c**: CDC ACM device implementation, including USB descriptors, endpoint configuration, and data processing -- **usb_config.h**: CherryUSB configuration file, defines various USB parameters and options +- **main.c**: Main program entry, initializes CDC ACM device and starts data + transmission loop +- **cdc_acm_template.c**: CDC ACM device implementation, including USB + descriptors, endpoint configuration, and data processing +- **usb_config.h**: CherryUSB configuration file, defines various USB parameters + and options ### Configuration Parameters - **Buffer Size**: 2048 bytes (read/write buffers) @@ -128,39 +151,43 @@ please input the serial port num:5 - Verify target board selection is correct ## Development Guide +* CDC ACM Device Class: + https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html +* CherryUSB Documentation: https://cherryusb.readthedocs.io/ +* Official CherryUSB Repository: https://github.com/cherry-embedded/CherryUSB +* RT-Thread Official Website: + https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README + +## Reference Documentation ### Custom Development -For custom development based on this example, you can modify the following: +To perform custom development based on this example, the following elements can +be modified: 1. **USB Descriptor Customization**: - - Modify VID/PID (requires legitimate USB ID) + - Modify the VID/PID (requires valid USB IDs) - Change device string descriptors - - Adjust endpoint configuration + - Adjust endpoint configurations 2. **Data Processing Logic**: - - Modify `usbd_cdc_acm_bulk_out()` function to handle received data - - Modify `cdc_acm_data_send_with_dtr_test()` function to customize sent data - - Add data format conversion or protocol processing + - Modify the `usbd_cdc_acm_bulk_out()` function to handle received data + - Modify the `cdc_acm_data_send_with_dtr_test()` function to customize + transmitted data + - Add data format conversion or protocol processing logic 3. **Configuration Parameter Adjustment**: - - Modify buffer size to fit application requirements - - Adjust transmission frequency and data volume - - Configure USB transfer mode (full-speed/high-speed) + - Modify buffer sizes to suit application requirements + - Adjust Transmission Frequency and Data Volume + - Configure USB Transmission Mode (Full-Speed/High-Speed) -### Related API Description -- `cdc_acm_init()`: Initialize CDC ACM device -- `usbd_ep_start_read()`: Start endpoint data reading -- `usbd_ep_start_write()`: Start endpoint data writing -- `usbd_cdc_acm_set_dtr()`: DTR status callback function - -## Reference Documentation -* CDC ACM Device Class: https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html -* CherryUSB Documentation: https://cherryusb.readthedocs.io/ -* CherryUSB Official Repository: https://github.com/cherry-embedded/CherryUSB -* RT-Thread Official Website: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README +### API Reference +- `cdc_acm_init()`: Initializes the CDC ACM device. +- `usbd_ep_start_read()`: Initiates data reading from an endpoint. +- `usbd_ep_start_write()`: Initiates data writing to an endpoint. +- `usbd_cdc_acm_set_dtr()`: Callback function for DTR state changes. ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|1.0.0 |11/2025 |Enhanced feature description and usage instructions, added technical details | -|0.0.1 |9/2025 |Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | ---------------------------------------------------------------------------- | +| 1.0.0 | 11/2025 | Enhanced feature description and usage instructions, added technical details | +| 0.0.1 | 9/2025 | Initial version | diff --git a/example/cherryusb/device/cdc_acm_uart/README_EN.md b/example/cherryusb/device/cdc_acm_uart/README_EN.md index eba32c516..8da08e252 100644 --- a/example/cherryusb/device/cdc_acm_uart/README_EN.md +++ b/example/cherryusb/device/cdc_acm_uart/README_EN.md @@ -1,18 +1,21 @@ # USB to Serial Bridge Example (CDC ACM UART) +A USB CDC ACM to UART bridge driver based on CherryUSB that transparently +forwards USB virtual serial port data to physical UART devices. -A USB CDC ACM to UART bridge driver based on CherryUSB that transparently forwards USB virtual serial port data to physical UART devices. +A CherryUSB-based USB CDC ACM-to-UART bridge driver that enables transparent +data forwarding between a USB virtual serial port and a physical UART interface. ## Features -- **USB CDC ACM Device**: Implements standard USB Communication Device Class, appears as a virtual serial port on PC +- **USB CDC ACM Device**: Implements standard USB Communication Device Class, + appears as a virtual serial port on PC - **Bidirectional Data Bridge**: Transparent USB ↔ UART data transmission -- **Dynamic Parameter Configuration**: Supports runtime modification of UART parameters (baud rate, data bits, stop bits, parity) +- **Dynamic Parameter Configuration**: Supports runtime modification of UART + parameters (baud rate, data bits, stop bits, parity) - **High-Performance Transmission**: Uses DMA/interrupt reception ## Hardware Connections - ### Supported Development Boards - - **SF32LB52_LCD_N16R8**: UART2 uses PA03(RX), PA04(TX) - **SF32LB58_LCD_N16R64N4**: UART2 uses PA29(RX), PA28(TX) @@ -21,14 +24,13 @@ A USB CDC ACM to UART bridge driver based on CherryUSB that transparently forwar ### 1. Compilation Switch to the example project directory and run the scons command to compile: - -```bash +``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as +prompted for downloading: -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as prompted for downloading: - -```bash +``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat Uart Download please input the serial port num:5 @@ -36,11 +38,20 @@ please input the serial port num:5 ### 2. Usage Instructions -1. **Hardware Connection**: Connect the configured UART2 pins RX and TX to the TX and RX of a USB-to-serial module respectively, then connect the module to the computer's USB port. Connect the Type-C interfaces labeled USB and UART on the development board to the computer's USB ports separately. The UART interface is used for downloading and debugging, while the USB interface is used for running the example program. - -2. **Flash Program**: Flash the compiled firmware to the development board. See "Compilation and Usage" section for flashing steps. - -3. **Open Serial Port**: To test transparent transmission between UART2 and USB virtual serial port, the host needs to run two serial debugging assistants, opening the "USB Serial Device" and the COM port where the USB-to-serial module is located respectively. After configuring the same baud rate, they can send and receive messages to each other. At this point, the development board functions as a USB-to-serial module. +1. **Hardware Connection**: Connect the configured UART2 pins RX and TX to the + TX and RX of a USB-to-serial module respectively, then connect the module to + the computer's USB port. Connect the Type-C interfaces labeled USB and UART + on the development board to the computer's USB ports separately. The UART + interface is used for downloading and debugging, while the USB interface is + used for running the example program. +2. **Flash Program**: Flash the compiled firmware to the development board. See + "Compilation and Usage" section for flashing steps. +3. **Open Serial Port**: To test transparent transmission between UART2 and USB + virtual serial port, the host needs to run two serial debugging assistants, + opening the "USB Serial Device" and the COM port where the USB-to-serial + module is located respectively. After configuring the same baud rate, they + can send and receive messages to each other. At this point, the development + board functions as a USB-to-serial module. ## Troubleshooting @@ -57,14 +68,14 @@ please input the serial port num:5 - Check hardware connections ## Reference Documentation - -* CDC ACM Device Class: https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html +* CDC ACM Device Class: + https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html * CherryUSB Documentation: https://cherryusb.readthedocs.io/ * CherryUSB Official Repository: https://github.com/cherry-embedded/CherryUSB -* RT-Thread Official Website: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README +* RT-Thread Official Website: + https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README ## Update Log - -| Version | Date | Release Notes | -|:--------|:-------|:--------------| -| 0.0.1 | 9/2025 | Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------ | --------------- | +| 0.0.1 | 9/2025 | Initial version | diff --git a/example/cherryusb/device/cdc_hid_msc/README_EN.md b/example/cherryusb/device/cdc_hid_msc/README_EN.md index a2d0e461c..8e2d079df 100644 --- a/example/cherryusb/device/cdc_hid_msc/README_EN.md +++ b/example/cherryusb/device/cdc_hid_msc/README_EN.md @@ -6,15 +6,18 @@ Source code path: example\cherryusb\device\cdc_hid_msc - SF32LB52_LCD_N16R8 ## Example Overview -This project demonstrates how to implement three different USB device functions simultaneously in a single USB connection: +This project demonstrates how to implement three different USB device functions +simultaneously in a single USB connection: - MSC (Mass Storage Class): RAM-based virtual USB drive -- CDC_ACM (Communications Device Class): Provides virtual serial port communication functionality +- CDC_ACM (Communications Device Class): Provides virtual serial port + communication functionality - HID (Human Interface Device): Simulates USB keyboard input functionality ## Features ### USB Composite Device Functions -- Virtual Disk: Access to device internal Flash storage with file read/write operations +- Virtual Disk: Access to device internal Flash storage with file read/write + operations - Virtual Serial Port: Data echo functionality for debugging and communication - Virtual Keyboard: Triggered by key presses, sends text input to host @@ -26,11 +29,15 @@ This project demonstrates how to implement three different USB device functions ## Compilation and Usage ### 1 Compilation -* Navigate to the example project directory and run the scons command to compile: + +* Navigate to the example project directory and run the scons command to + compile: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as prompted for downloading: +* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as + prompted for downloading: + ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat Uart Download @@ -38,13 +45,15 @@ please input the serial port num:5 ``` ### 2 Usage Instructions -1. Hardware Connection: Connect the host to the development board's UART port and USB port via USB data cable +1. Hardware Connection: Connect the host to the development board's UART port + and USB port via USB data cable 2. Program Flashing: Flash the compiled firmware to the development board -3. Open Serial Port: Use serial port utility to open both USB virtual serial port and onboard physical serial port +3. Open Serial Port: Use serial port utility to open both USB virtual serial + port and onboard physical serial port ### 3 Expected Behavior - -1. When pressing keys, the serial port outputs the following, with corresponding text input of "CherryUSB" and "SiFli" in text boxes, indicating USB keyboard input functionality is working properly: +Meanwhile, the same text is sent back in the serial assistant opened on the USB +virtual serial port: ``` button:11,0 button:11,3 @@ -57,28 +66,28 @@ KEY1 clicked, sending 'SiFli' HID: Sending string: SiFli button:34,1 ``` - -2. Opening File Explorer reveals a disk named "SiFli MSC" containing README.TXT. Opening this file shows the following content, indicating the RAM-based virtual USB drive functionality is working properly: +This indicates CDC_ACM is functioning properly. ``` -SiFli USB Composite Device Demo! +SiFli USB Composite Device Demo Features: - MSC: Virtual Disk (RAM-based) - CDC ACM: Virtual COM Port - HID: Virtual Keyboard ``` - -3. Messages sent from the USB virtual serial port will be echoed back, while the physical UART will print the message length. -Example: Sending "SiFli" from the USB virtual serial port will display the following in the serial assistant opened on the physical UART COM port(The length including line breaks): +3. Messages sent via the USB virtual serial port will be echoed. Simultaneously, +the physical UART will print the message length. For example, sending "SiFli" +via the USB virtual serial port will result in the physical UART serial +assistant displaying the message length (including line breaks). ``` CDC actual out len:7 CDC actual in len:7 ``` -Meanwhile, the same text is sent back in the serial assistant opened on the USB virtual serial port: +Meanwhile, the serial assistant connected to the USB virtual serial port will +display the same text echoed back. ``` SiFli ``` -This indicates CDC_ACM is functioning properly. - +If successful, the CDC_ACM is functioning correctly. ### Common Issues 1. Device Not Recognized @@ -97,12 +106,14 @@ This indicates CDC_ACM is functioning properly. - Check header file paths ## Reference Documentation -* CDC ACM Device Class: https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html +* CDC ACM Device Class: + https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html * CherryUSB Documentation: https://cherryusb.readthedocs.io/ * CherryUSB Official Repository: https://github.com/cherry-embedded/CherryUSB -* RT-Thread Official Website: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README +* RT-Thread Official Website: + https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |9/2025 |Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------ | --------------- | +| 0.0.1 | 9/2025 | Initial version | diff --git a/example/cherryusb/device/hid_mouse/README_EN.md b/example/cherryusb/device/hid_mouse/README_EN.md index 2a6fa1f80..426b3ed23 100644 --- a/example/cherryusb/device/hid_mouse/README_EN.md +++ b/example/cherryusb/device/hid_mouse/README_EN.md @@ -3,22 +3,27 @@ Source code path: example\cherryusb\device\hid_mouse ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates enumerating a mouse device based on cherryusb USB-HID, including: -+ Press the KEY2 button on sf32lb52-lcd_n16r8 to sequentially trigger left button press, right button press, middle button press, wheel scroll, mouse circle, left button press and move right. + +This example demonstrates enumerating a mouse device based on cherryusb USB-HID, +including: ++ Press the KEY2 button on sf32lb52-lcd_n16r8 to sequentially trigger left + button press, right button press, middle button press, wheel scroll, mouse + circle, left button press and move right. ## Usage of the Example - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). -+ Two USB-typec data cables with data transmission capability, one for burning and log viewing, one for connecting to the host. ++ A development board supported by this example ([Supported + Platforms](quick_start)). ++ Two USB-typec data cables with data transmission capability, one for burning + and log viewing, one for connecting to the host. + A host device that supports mouse input. ### menuconfig Configuration @@ -28,7 +33,8 @@ Switch to the example project directory, run the scons command to compile: ```c scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Switch to the example `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Switch to the example `project/build_xx` directory, run `uart_download.bat`, and +select the port as prompted to download: ```c $ ./uart_download.bat @@ -36,24 +42,27 @@ $ ./uart_download.bat please input the serial port num: ``` -For detailed steps on compilation and download, please refer to the introduction in [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to the introduction +in [Quick Start](quick_start). ## Expected Results of the Example - -After the example starts: -The host connects to the board via data cable, and a new mouse device will appear in the Mouse and other pointing devices section of the host's device manager. -Press the KEY2 button to sequentially trigger left button press, right button press, middle button press, wheel scroll, mouse circle, left button press and move right. + +After the example starts: The host connects to the board via data cable, and a +new mouse device will appear in the Mouse and other pointing devices section of +the host's device manager. Press the KEY2 button to sequentially trigger left +button press, right button press, middle button press, wheel scroll, mouse +circle, left button press and move right. ## Exception Diagnosis ## Reference Documents - + ## Update History | Version | Date | Release Notes | -| :------ | :------ | :-------------- | +| ------- | ------- | --------------- | | 0.0.1 | 08/2025 | Initial version | | | | | | | | | diff --git a/example/cherryusb/device/msc/emmc_disk/README_EN.md b/example/cherryusb/device/msc/emmc_disk/README_EN.md index 3bb611f23..398a90c40 100644 --- a/example/cherryusb/device/msc/emmc_disk/README_EN.md +++ b/example/cherryusb/device/msc/emmc_disk/README_EN.md @@ -3,66 +3,72 @@ Source Path: example\cherryusb\device\emmc_disk ## Supported Platforms - -+ sf32lb52-lcd_n16r8 + +sf32lb52-core_e8r16 ## Overview - -This example demonstrates using CherryUSB MSC with eMMC (via the SDIO interface) to implement a virtual USB flash drive (U disk). It includes: + +This example demonstrates using CherryUSB MSC with eMMC (via the SDIO interface) +to implement a virtual USB flash drive (U disk). It includes: + The PC can view a USB drive named "SiFli MSC DEMO" in the file manager. ## How to Use This Example - + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A host device that supports USB. ### menuconfig Configuration 1. Enable SDIO: - - Path: On-chip Peripheral RTOS Drivers → Enable SPI BUS - - Enable: Enable SDIO - - Macro: `BSP_USING_SDIO` - - Purpose: Enable the SDIO driver. + - Path: On-chip Peripheral RTOS Drivers → Enable SPI BUS + - Enable: Enable SDIO + - Macro: `BSP_USING_SDIO` + - Purpose: Enable the SDIO driver. 2. Enable and configure SD device: - - Path: RTOS → RT-Thread Components → Device Drivers - - Enable: Using SD/MMC device drivers - - Macro: `RT_USING_SDIO` - - Purpose: Use SDIO as the underlying interface, so `SDIO` must be enabled. - + - Path: RTOS → RT-Thread Components → Device Drivers + - Enable: Using SD/MMC device drivers + - Macro: `RT_USING_SDIO` + - Purpose: Use SDIO as the underlying interface, so `SDIO` must be + enabled. ### Compilation and Flashing Switch to the project directory and run the scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j32 -Switch to the `project/build_xx` directory and run `uart_download.bat`. Follow the prompts to select the port for downloading: +Switch to the `project/build_xx` directory and run `uart_download.bat`. Follow +the prompts to select the port for downloading: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and downloading, please refer to the [Quick Start Guide](quick_start). +For detailed steps on compilation and downloading, please refer to the [Quick +Start Guide](quick_start). ## Expected Results - -After the example starts: -The host connects to the board via the data cable. The PC can see a USB drive named "SiFli MSC DEMO" in the file manager. In Windows Device Manager, a new device appears under Universal Serial Bus controllers: USB Mass Storage Device. + +After the example starts: The host connects to the board via the data cable. The +PC can see a USB drive named "SiFli MSC DEMO" in the file manager. In Windows +Device Manager, a new device appears under Universal Serial Bus controllers: USB +Mass Storage Device. ## Troubleshooting ## Reference Documents - + ## Revision History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |09/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/msc/index_EN.md b/example/cherryusb/device/msc/index_EN.md index cb34830b5..92234f50e 100644 --- a/example/cherryusb/device/msc/index_EN.md +++ b/example/cherryusb/device/msc/index_EN.md @@ -6,6 +6,4 @@ :glob: */* - - ``` diff --git a/example/cherryusb/device/msc/nor_flash_disk/README_EN.md b/example/cherryusb/device/msc/nor_flash_disk/README_EN.md index e894d5871..583136671 100644 --- a/example/cherryusb/device/msc/nor_flash_disk/README_EN.md +++ b/example/cherryusb/device/msc/nor_flash_disk/README_EN.md @@ -1,18 +1,20 @@ - # USB Mass Storage Device Example (NOR FLASH) Source Path: example\cherryusb\device\nor_flash_disk ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview -This example demonstrates implementing a virtual USB mass storage (U disk) device using CherryUSB MSC with NOR Flash as the backend storage. It includes: + +This example demonstrates implementing a virtual USB mass storage (U disk) +device using CherryUSB MSC with NOR Flash as the backend storage. It includes: + A USB drive named "SiFli MSC DEMO" appears in the PC file manager. ## How to Use the Example - + ### Hardware Requirements Prepare the following before running the example: @@ -21,43 +23,38 @@ Prepare the following before running the example: + A USB-capable host (e.g., PC). ### menuconfig Configuration -Configuration items follow the default settings for this example unless special customization is required. (If additional configuration options are needed, list them here.) + ### Build and Flash In the example `project` directory, run the following `scons` command to build: > scons --board=sf32lb52-lcd_n16r8 -j32 -Then switch to the generated `project/build_xx` directory, run `uart_download.bat`, and follow the prompt to select the serial port for downloading: +Then switch to the generated `project/build_xx` directory, run +`uart_download.bat`, and follow the prompt to select the serial port for +downloading: > .\uart_download.bat -Example interaction: -> Uart Download +> UART Download -> please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed build and download steps, refer to the [Quick Start Guide](quick_start). +Example interaction: ## Expected Results + After startup: -1. Connect the board to the host using the USB data cable. -2. The PC file manager shows a removable drive named "SiFli MSC DEMO". -3. In the OS Device Manager (under Universal Serial Bus controllers) a new "USB Mass Storage Device" entry appears. ## Troubleshooting -| Issue | Possible Cause | Suggested Action | -|-------|----------------|------------------| -| USB disk not enumerated | Cable is power-only | Use a proper data cable | -| Drive name not shown / incorrect | Descriptor not updated | Check product string in USB descriptor configuration | -| Flash read/write errors | NOR Flash init failure | Verify Flash wiring and initialization sequence | + ## Reference Documents -Add related RT-Thread or CherryUSB documentation links here if needed. + ## Revision History -| Version | Date | Release Notes | -|:-------|:-------|:--------------| -| 0.0.1 | 09/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/msc/ram_disk/README_EN.md b/example/cherryusb/device/msc/ram_disk/README_EN.md index 64ebe8ccb..b22f594f8 100644 --- a/example/cherryusb/device/msc/ram_disk/README_EN.md +++ b/example/cherryusb/device/msc/ram_disk/README_EN.md @@ -3,21 +3,24 @@ Source Path: example\cherryusb\device\ram_disk ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates the virtualization of a USB flash drive using RAM based on cherryusb MSC, including: -+ The PC can view a USB flash drive named SiFli MSC DEMO through the file manager. + +This example demonstrates the virtualization of a USB flash drive using RAM +based on cherryusb MSC, including: ++ The PC can view a USB flash drive named SiFli MSC DEMO through the file + manager. ## How to Use This Example - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A host device that supports USB. @@ -29,30 +32,34 @@ Switch to the example project directory and run the scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j32 -Switch to the example `project/build_xx` directory, run `uart_download.bat`, and follow the prompts to select the port for downloading: +Switch to the example `project/build_xx` directory, run `uart_download.bat`, and +follow the prompts to select the port for downloading: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example starts: -The host connects to the board via the data cable, and the PC can view a USB flash drive named SiFli MSC in the file manager. There is a README.TXT file in the drive with the content "cherryusb device msc_ram demo!". + +After the example starts: The host connects to the board via the data cable, and +the PC can view a USB flash drive named SiFli MSC in the file manager. There is +a README.TXT file in the drive with the content "cherryusb device msc_ram +demo!". ## Troubleshooting ## Reference Documents - + ## Change Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |09/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/msc/ram_disk_dual/README_EN.md b/example/cherryusb/device/msc/ram_disk_dual/README_EN.md index 7666a8d2d..1fe79760f 100644 --- a/example/cherryusb/device/msc/ram_disk_dual/README_EN.md +++ b/example/cherryusb/device/msc/ram_disk_dual/README_EN.md @@ -3,21 +3,24 @@ Source Path: example\cherryusb\device\ram_disk_dual ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates the implementation of a virtual U disk based on cherryusb MSC, including: -+ The PC can see two USB drives named SiFli MSC1 and SiFli MSC2 in the file manager. + +This example demonstrates the implementation of a virtual U disk based on +cherryusb MSC, including: ++ The PC can see two USB drives named SiFli MSC1 and SiFli MSC2 in the file + manager. ## How to Use This Example - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A host device that supports USB. @@ -29,32 +32,32 @@ Switch to the example project directory and run the scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j32 -Switch to the example `project/build_xx` directory, run `uart_download.bat`, and follow the prompts to select the port for downloading: +Switch to the example `project/build_xx` directory, run `uart_download.bat`, and +follow the prompts to select the port for downloading: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example starts: -The host connects to the board via the data cable, and the PC can see two USB drives in the file manager: -+ One named SiFli MSC1, whose README.TXT contains: cherryusb device msc_ram_dual demo! Lun: 1. -+ One named SiFli MSC2, whose README.TXT contains: cherryusb device msc_ram_dual demo! Lun: 2. + +After the example starts: The host connects to the board via the data cable, and +the PC can see two USB drives in the file manager: ## Troubleshooting ## Reference Documents - + ## Change Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |09/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/device/msc/sdcard_disk/README_EN.md b/example/cherryusb/device/msc/sdcard_disk/README_EN.md index b3291e739..1dab09a1d 100644 --- a/example/cherryusb/device/msc/sdcard_disk/README_EN.md +++ b/example/cherryusb/device/msc/sdcard_disk/README_EN.md @@ -3,70 +3,79 @@ Source Path: example\cherryusb\device\sdcard_disk ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates implementing a virtual USB flash drive (MSC) using CherryUSB MSC with an SD card over SPI. It includes: + +This example demonstrates implementing a virtual USB flash drive (MSC) using +CherryUSB MSC with an SD card over SPI. It includes: + The PC can see a USB drive named "SiFli MSC DEMO" in the file manager. ## How to Use This Example - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + A USB-A to Type-C data cable with data transfer capability. + A USB-capable host (e.g. PC). ### menuconfig Configuration 1. Enable SPI1: - - Path: On-chip Peripheral RTOS Drivers → Enable SPI BUS - - Enable: Enable SPI1 BUS - - Macro: `BSP_USING_SPI1` - - Purpose: Use SPI1 as the SD card interface - - (Optional) Enable: Enable SPI1 TX DMA - - Macro: `BSP_SPI1_TX_USING_DMA` - - Purpose: Enable SPI TX DMA - - (Optional) Enable: Enable SPI1 RX DMA - - Macro: `BSP_SPI1_RX_USING_DMA` - - Purpose: Enable SPI RX DMA + - Path: On-chip Peripheral RTOS Drivers → Enable SPI BUS + - Enable: Enable SPI1 BUS + - Macro: `BSP_USING_SPI1` + - Purpose: Use SPI1 as the SD card interface + - (Optional) Enable: Enable SPI1 TX DMA + - Macro: `BSP_SPI1_TX_USING_DMA` + - Purpose: Enable SPI TX DMA + - (Optional) Enable: Enable SPI1 RX DMA + - Macro: `BSP_SPI1_RX_USING_DMA` + - Purpose: Enable SPI RX DMA 2. Enable MSD (SD card over SPI) driver: - - Path: RTOS → RT-Thread Components → Device Drivers - - Enable: Using SD/TF card driver with spi - - Macro: `RT_USING_SPI_MSD` - - Purpose: Use SPI for SD (TF) card driver, required for MSC storage backend + - Path: RTOS → RT-Thread Components → Device Drivers + - Enable: Using SD/TF card driver with spi + - Macro: `RT_USING_SPI_MSD` + - Purpose: Use SPI for SD (TF) card driver, required for MSC storage + backend ### Compilation and Flashing Switch to the example `project` directory and run the scons command to build: > scons --board=sf32lb52-lcd_n16r8 -j32 -Enter the example `project/build_xx` directory (actual build output folder) and run `uart_download.bat`, then follow the prompt to choose the serial port for download: +Enter the example `project/build_xx` directory (actual build output folder) and +run `uart_download.bat`, then follow the prompt to choose the serial port for +download: > ./uart_download.bat -> Uart Download +> UART Download -> please input the serial port num:5 +> Please enter the COM port number: 5 -For detailed compilation and download steps, refer to the [Quick Start Guide](quick_start). +For detailed compilation and download steps, refer to the [Quick Start +Guide](quick_start). ## Expected Results -After startup: -The host connects to the board via the USB data cable. The PC file manager shows a USB drive named "SiFli MSC DEMO". In Device Manager under Universal Serial Bus controllers, a new device "USB Mass Storage Device" appears. + +After startup: The host connects to the board via the USB data cable. The PC +file manager shows a USB drive named "SiFli MSC DEMO". In Device Manager under +Universal Serial Bus controllers, a new device "USB Mass Storage Device" +appears. ## Troubleshooting -TBD. + ## Reference Documents -TBD. + ## Revision History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |09/2025 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/host/cdc_acm_host/README_EN.md b/example/cherryusb/host/cdc_acm_host/README_EN.md index fff0a87c5..f49b48838 100644 --- a/example/cherryusb/host/cdc_acm_host/README_EN.md +++ b/example/cherryusb/host/cdc_acm_host/README_EN.md @@ -1,18 +1,32 @@ # USB CDC ACM Host Example - -This example demonstrates how to implement a CDC ACM (Communication Device Class - Abstract Control Model) host using the CherryUSB stack to identify and connect to USB CDC ACM devices (such as virtual serial port devices). The host can enumerate CDC ACM devices, receive data from devices, and support bidirectional data transfer. +This example demonstrates how to implement a CDC ACM (Communication Device Class +- Abstract Control Model) host using the CherryUSB stack to identify and connect +to USB CDC ACM devices (such as virtual serial port devices). The host can +enumerate CDC ACM devices, receive data from devices, and support bidirectional +data transfer. + +This example demonstrates how to implement a CDC ACM (Communication Device Class +– Abstract Control Model) host using the CherryUSB stack to identify and connect +to USB CDC ACM devices, such as virtual serial ports. The host is capable of +enumerating CDC ACM devices, receiving transmitted data, and supporting +bidirectional data communication. ## Features -- **CDC ACM Host Class Implementation**: Compliant with USB CDC ACM standard, supporting host connection to CDC devices -- **Automatic Device Recognition**: Automatic enumeration and identification of connected CDC ACM devices -- **Data Reception Capability**: Support for receiving data from USB CDC devices with real-time printing -- **DTR/RTS Control**: Support for setting DTR and RTS control signals of CDC devices -- **Interrupt Reception Mode**: Using interrupt-driven data reception for improved response speed -- **Real-Time Operating System Integration**: Implemented based on RT-Thread RTOS -- **CherryUSB Stack**: Utilizing lightweight, high-performance CherryUSB host protocol stack - - +- **CDC ACM Host Class Implementation**: Compliant with USB CDC ACM standard, + supporting host connection to CDC devices +- **Automatic Device Recognition**: Automatic enumeration and identification of + connected CDC ACM devices +- **Data Reception Capability**: Support for receiving data from USB CDC devices + with real-time printing +- **DTR/RTS Control**: Support for setting DTR and RTS control signals of CDC + devices +- **Interrupt Reception Mode**: Using interrupt-driven data reception for + improved response speed +- **Real-Time Operating System Integration**: Implemented based on RT-Thread + RTOS +- **CherryUSB Stack**: Utilizing lightweight, high-performance CherryUSB host + protocol stack ## Hardware Connection @@ -20,8 +34,10 @@ This example demonstrates how to implement a CDC ACM (Communication Device Class - **SF32LB52_LCD_N16R8**: LCD development board based on SF32LB52 chip ### USB Connection -- Connect USB CDC ACM devices (such as virtual serial port devices, Arduino, etc.) to the development board's USB Host port -- Ensure the development board's USB Host port is properly powered and capable of supplying power to external devices +- Connect USB CDC ACM devices (such as virtual serial port devices, Arduino, + etc.) to the development board's USB Host port +- Ensure the development board's USB Host port is properly powered and capable + of supplying power to external devices - Supports USB 2.0 full-speed mode (depending on configuration) ### Connection Topology @@ -31,7 +47,8 @@ This example demonstrates how to implement a CDC ACM (Communication Device Class ``` ### USB Host Configuration -This example uses the internal USB controller in host mode with the following main configurations: +This example uses the internal USB controller in host mode with the following +main configurations: - **USB Base Address**: USBC_BASE - **CDC Device Name**: ttyACM0 - **Receive Buffer**: 4096 bytes @@ -40,7 +57,7 @@ This example uses the internal USB controller in host mode with the following ma ## Build and Usage -### 1 Build +### 1 Build Navigate to the example's project directory and run the scons command to build: @@ -51,7 +68,8 @@ scons --board=sf32lb52-lcd_n16r8 -j8 ### 2 Download -Run the corresponding download script for the development board and select the port as prompted: +Run the corresponding download script for the development board and select the +port as prompted: **LCD development board download:** ```bash @@ -70,14 +88,17 @@ please input the serial port num:5 4. The system initializes the USB host controller #### 3.2 Connecting CDC Device -1. Connect the CDC ACM device via USB cable to the development board's USB Host port -2. Wait approximately 2 seconds for the system to automatically enumerate the device +1. Connect the CDC ACM device via USB cable to the development board's USB Host + port +2. Wait approximately 2 seconds for the system to automatically enumerate the + device 3. If the device is successfully recognized, it will print: "ttyACM0 found!" 4. If the device is not found, it will print: "ttyACM0 not found!" #### 3.3 Data Reception Test 1. **Automatic Data Reception**: - - When the CDC device sends data, the host automatically triggers the receive callback + - When the CDC device sends data, the host automatically triggers the receive + callback - Received data is immediately printed to the debug serial port - Each reception displays the data length and content @@ -99,20 +120,22 @@ please input the serial port num:5 #### 3.4 DTR/RTS Control - The host automatically sets the DTR signal to 1 after the device is opened - RTS signal is set to 0 -- These signals are passed to the CDC device and can be used to control device behavior +- These signals are passed to the CDC device and can be used to control device + behavior - For example, the CDC Device example only sends data when DTR is enabled - - ## Technical Details ### Code Structure -- **main.c**: Main program entry, initializes USB host controller and manages CDC ACM device connection -- **usb_config.h**: CherryUSB host configuration file, defines various USB parameters and options +- **main.c**: Main program entry, initializes USB host controller and manages + CDC ACM device connection +- **usb_config.h**: CherryUSB host configuration file, defines various USB + parameters and options ### Configuration Parameters - **Receive Buffer Size**: 4096 bytes -- **Device Enumeration Delay**: 2000 milliseconds (waiting for device enumeration to complete) +- **Device Enumeration Delay**: 2000 milliseconds (waiting for device + enumeration to complete) - **Device Name**: ttyACM0 - **Open Flags**: RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX - **DTR State**: Enabled (1) @@ -121,7 +144,8 @@ please input the serial port num:5 ### CherryUSB Host Features - Supports USB host controller initialization - Supports automatic CDC ACM device identification and enumeration -- Supports interrupt reception mode with automatic callback triggering when data arrives +- Supports interrupt reception mode with automatic callback triggering when data + arrives - Supports DTR/RTS control signal configuration - Integrated with RT-Thread device driver framework @@ -151,16 +175,20 @@ please input the serial port num:5 ### Common Issues 1. **Device Cannot Be Recognized (prints "ttyACM0 not found!")** - - Check if the CDC device is properly connected to the development board's USB Host port - - Confirm that the CDC device is properly powered (some devices require external power) + - Check if the CDC device is properly connected to the development board's + USB Host port + - Confirm that the CDC device is properly powered (some devices require + external power) - Check USB cable quality and data line integrity - Increase enumeration delay time (currently 2 seconds) - - Confirm that the CDC device itself is working properly (can test by connecting to PC first) + - Confirm that the CDC device itself is working properly (can test by + connecting to PC first) - Review debug logs to confirm USB enumeration process 2. **Device Recognized But No Data Reception** - Confirm whether the CDC device is sending data - - Check device-side DTR signal requirements (some devices only send data when DTR is enabled) + - Check device-side DTR signal requirements (some devices only send data when + DTR is enabled) - Verify that the receive callback function is properly registered - Check if USB host controller initialization was successful - Check if device open flags include INT_RX @@ -173,7 +201,8 @@ please input the serial port num:5 4. **System Instability** - Check if USB power supply capability is sufficient - - Confirm that external device power consumption does not exceed USB Host power supply capability + - Confirm that external device power consumption does not exceed USB Host + power supply capability - Verify memory usage to avoid memory shortage - Check for stack overflow issues @@ -186,22 +215,28 @@ please input the serial port num:5 ## Test Scenarios ### Testing with CDC ACM Device Example -1. Prepare two development boards: one running the CDC ACM Device example, one running this Host example +1. Prepare two development boards: one running the CDC ACM Device example, one + running this Host example 2. Connect the Device side via USB to the Host side's USB Host port -3. The Host side will automatically recognize the Device and start receiving data +3. The Host side will automatically recognize the Device and start receiving + data 4. You can see the Host side continuously printing test data sent by the Device ## Reference Documentation -* CDC ACM Host Class: https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html +* CDC ACM Host Class: + https://cherryusb.readthedocs.io/zh_CN/latest/quick_start/cdc_acm.html * CherryUSB Documentation: https://cherryusb.readthedocs.io/ * CherryUSB Official Repository: https://github.com/cherry-embedded/CherryUSB -* RT-Thread Official Website: https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README -* USB CDC Specification: https://www.usb.org/document-library/class-definitions-communication-devices-12 +* RT-Thread Official Website: + https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README +* USB CDC Specification: + https://www.usb.org/document-library/class-definitions-communication-devices-12 ## Development Guide ### Custom Development -If you need to perform custom development based on this example, you can modify the following: +If you need to perform custom development based on this example, you can modify +the following: 1. **Data Reception Processing**: - Modify the `rx_cb()` function to implement custom data processing logic @@ -238,17 +273,17 @@ If you need to perform custom development based on this example, you can modify #### RT-Thread Device Operations - `rt_device_find(name)`: Find device - Returns device handle, or RT_NULL on failure - + - `rt_device_open(dev, flags)`: Open device - flags: RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX - + - `rt_device_read(dev, pos, buffer, size)`: Read device data - pos: Offset position (typically 0 for CDC devices) - Returns actual number of bytes read - + - `rt_device_write(dev, pos, buffer, size)`: Write device data - Used to send data to CDC device - + - `rt_device_set_rx_indicate(dev, rx_ind)`: Set receive indication callback - rx_ind: Receive callback function pointer @@ -269,10 +304,11 @@ if (len > 0) { ## Related Examples -- **CDC ACM Device Example**: Companion CDC ACM device-side example, can be used to test host functionality +- **CDC ACM Device Example**: Companion CDC ACM device-side example, can be used + to test host functionality ## Version History -|Version |Date |Release Notes | -|:---|:---|:---| -|1.0.0 |11/2025 |Enhanced feature description and usage instructions, added technical details and development guide | -|0.0.1 |11/2025 |Initial version, implemented basic CDC ACM host functionality | +| Version | Date | Release Notes | +| ------- | ------- | -------------------------------------------------------------------------------------------------- | +| 1.0.0 | 11/2025 | Enhanced feature description and usage instructions, added technical details and development guide | +| 0.0.1 | 11/2025 | Initial version, implemented basic CDC ACM host functionality | diff --git a/example/cherryusb/host/hid/README_EN.md b/example/cherryusb/host/hid/README_EN.md index 5cb3ac9ad..606cb0cf4 100644 --- a/example/cherryusb/host/hid/README_EN.md +++ b/example/cherryusb/host/hid/README_EN.md @@ -3,39 +3,44 @@ Source Code Path: example\cherryusb\host\hid ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -This example demonstrates USB HID HOST functionality based on cherryusb, including: -+ When a keyboard is connected to the device, pressing keys will display keyboard data sent to the host via serial port. -+ When a mouse is connected to the device, clicking buttons will display mouse data sent to the host via serial port. + +This example demonstrates USB HID HOST functionality based on cherryusb, +including: ++ When a keyboard is connected to the device, pressing keys will display + keyboard data sent to the host via serial port. ++ When a mouse is connected to the device, clicking buttons will display mouse + data sent to the host via serial port. ## How to Use the Example - + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example (see [Supported Platforms](quick_start)). -+ A USB-A to Type-C data cable with data transmission capability to connect the development board and slave devices (keyboard, mouse). -+ A USB-B to Type-C data cable with data transmission capability to connect PC and development board (for flashing and serial printing). ++ A development board supported by this example (see [Supported + Platforms](quick_start)). ++ A USB-A to Type-C data cable with data transmission capability to connect the + development board and slave devices (keyboard, mouse). ++ A USB-B to Type-C data cable with data transmission capability to connect PC + and development board (for flashing and serial printing). + USB-compatible slave devices (keyboard, mouse). ### Menuconfig Configuration -1. Enable HOST MODE: -![USB HOST MODE](./assets/enable_host_mode.png) -2. Enable HOST HID Driver: -![USB HID DRIVER](./assets/enable_host_HID_mode.png) +1. Enable HOST MODE: ![USB HOST MODE](./assets/enable_host_mode.png) +2. Enable HOST HID Driver: ![USB HID DRIVER](./assets/enable_host_HID_mode.png) ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Switch to the example `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: +Switch to the example `project/build_xx` directory, run `uart_download.bat`, and +select the port as prompted to download: ```c $ ./uart_download.bat @@ -43,19 +48,21 @@ $ ./uart_download.bat please input the serial port num: ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results ### Keyboard Device Testing #### Device Connection -When a keyboard is connected to the development board USB port, the serial debug assistant will display device enumeration information: +When a keyboard is connected to the development board USB port, the serial debug +assistant will display device enumeration information: ``` cherryusb host demo! hid host test -msh />[I/usbh_hub] New low-speed device on Bus 0, Hub 1, Port 1 connected +msh />[I/usbh_hub] New low-speed device on Bus 0, Hub 1, Port 1 connected [I/usbh_core] New device found,idVendor:046d,idProduct:c31c,bcdDevice:4920 [I/usbh_core] The device has 1 bNumConfigurations [I/usbh_core] The device has 2 interfaces @@ -73,11 +80,11 @@ mount a keyboard HID keyboard uses **8-byte report format**, with the following data structure: -| Byte Position | Function Description | Notes | -| :------: | :--------- | :---------------------------- | -| Byte 0 | Modifier Key Status | Ctrl, Alt, Shift, Win and other combination keys | -| Byte 1 | Reserved Byte | Usually 0x00 | -| Bytes 2-7 | Key Scan Codes | Supports up to 6 regular keys pressed simultaneously | +| Byte Position | Function Description | Notes | +| :-----------: | -------------------- | ---------------------------------------------------- | +| Byte 0 | Modifier Key Status | Ctrl, Alt, Shift, Win and other combination keys | +| Byte 1 | Reserved Byte | Usually 0x00 | +| Bytes 2-7 | Key Scan Codes | Supports up to 6 regular keys pressed simultaneously | **Data Transmission Mechanism:** - **Key Press**: Sends 8-byte report containing key scan codes @@ -85,7 +92,8 @@ HID keyboard uses **8-byte report format**, with the following data structure: #### Keyboard Key Test Data -Serial port output example when pressing keyboard keys (pressing s-i-f-l-i as example): +Serial port output example when pressing keyboard keys (pressing s-i-f-l-i as +example): ``` 0x00 0x00 0x16 0x00 0x00 0x00 0x00 0x00 nbytes:8 ← Press 's' key (scan code 0x16) @@ -103,12 +111,13 @@ Serial port output example when pressing keyboard keys (pressing s-i-f-l-i as ex ### Mouse Device Testing #### Device Connection -When a mouse is connected to the development board USB port, the serial debug assistant displays: +When a mouse is connected to the development board USB port, the serial debug +assistant displays: ``` cherryusb host demo! hid host test -msh />[I/usbh_hub] New low-speed device on Bus 0, Hub 1, Port 1 connected +msh />[I/usbh_hub] New low-speed device on Bus 0, Hub 1, Port 1 connected [I/usbh_core] New device found,idVendor:046d,idProduct:c077,bcdDevice:7200 [I/usbh_core] The device has 1 bNumConfigurations [I/usbh_core] The device has 1 interfaces @@ -123,12 +132,12 @@ mount a mouse HID mouse uses **4-byte report format**, with the following data structure: -| Byte Position | Function Description | Value Range | -| :------: | :---------- | :------------------------------ | -| Byte 0 | Button Status | Bit0: Left button, Bit1: Right button, Bit2: Middle button | -| Byte 1 | X-axis Relative Displacement | -128 ~ +127 (signed) | -| Byte 2 | Y-axis Relative Displacement | -128 ~ +127 (signed) | -| Byte 3 | Scroll Wheel | -128 ~ +127 (signed) | +| Byte Position | Function Description | Value Range | +| :-----------: | ---------------------------- | ---------------------------------------------------------- | +| Byte 0 | Button Status | Bit0: Left button, Bit1: Right button, Bit2: Middle button | +| Byte 1 | X-axis Relative Displacement | -128 to +127 (signed) | +| Byte 2 | Y-axis Relative Displacement | -128 to +127 (signed) | +| Byte 3 | Scroll Wheel | -128 to +127 (signed) | #### Mouse Movement Test Data @@ -157,12 +166,13 @@ Serial port output example when moving the mouse: ## Reference Documentation - -Reference cherryUSB official documentation: https://cherryusb.readthedocs.io/zh-cn/latest/ + +Reference cherryUSB official documentation: +https://cherryusb.readthedocs.io/zh-cn/latest/ ## Update History -| Version | Date | Release Notes | -| :---- | :------ | :------- | -| 0.0.1 | 09/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 09/2025 | Initial version | +| | | | +| | | | diff --git a/example/cherryusb/host/msc_host/README_EN.md b/example/cherryusb/host/msc_host/README_EN.md index 85b0c5626..5c3015bb2 100644 --- a/example/cherryusb/host/msc_host/README_EN.md +++ b/example/cherryusb/host/msc_host/README_EN.md @@ -1,11 +1,13 @@ # USB MSC Host Example -English | [简体中文](README.md) +English | [简体中文](README_EN.md) Source Code Path: example/cherryusb/host/msc ## Overview -This example demonstrates how to implement USB Host Mass Storage Class (MSC) functionality using the CherryUSB stack. The example can recognize USB storage devices such as USB flash drives and perform file read/write operations. +This example demonstrates how to implement USB Host Mass Storage Class (MSC) +functionality using the CherryUSB stack. The example can recognize USB storage +devices such as USB flash drives and perform file read/write operations. Main Features: - Initialize USB Host controller @@ -18,7 +20,10 @@ Main Features: - USB cable - USB flash drive or other USB mass storage device -**Note**: It is recommended to use this example together with the `example/cherryusb/device/msc/ram_disk` example. That example can simulate a USB storage device with a pre-configured README.TXT file, which is convenient for testing the USB Host's file reading functionality. +**Note**: It is recommended to use this example together with the +`example/cherryusb/device/msc/ram_disk` example. That example can simulate a USB +storage device with a pre-configured README.TXT file, which is convenient for +testing the USB Host's file reading functionality. ## Usage @@ -31,39 +36,49 @@ Switch to the example project directory and run the scons command to build: > scons --board=sf32lb52-lcd_n16r8 -j8 -Switch to the `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted: +Switch to the `project/build_xx` directory and run `uart_download.bat`, then +select the port as prompted: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on building and flashing, please refer to the [Quick Start Guide](quick_start). +For detailed steps on building and flashing, please refer to the [Quick Start +Guide](quick_start). ### Running the Example **Method 1: Using Real USB Flash Drive** -1. Create a text file named `README.TXT` in the root directory of the USB drive (optional) +1. Create a text file named `README.TXT` in the root directory of the USB drive + (optional) 2. Flash the compiled firmware to the development board 3. Connect a serial terminal (baud rate is typically 1000000) 4. Reset the development board 5. The program will wait for a USB mass storage device to be connected 6. Insert the USB flash drive into the board's USB Host port -7. After the device is inserted, the program will automatically continue and perform file read/write operations +7. After the device is inserted, the program will automatically continue and + perform file read/write operations 8. Observe the serial output **Method 2: Testing with MSC Device Example (Recommended)** 1. Prepare two development boards 2. Flash this example (MSC Host) to one board -3. Flash `example/cherryusb/device/msc/ram_disk` example (MSC Device) to the other board -4. Start the Host board first, the program will wait for a USB mass storage device connection -5. Connect the two boards using a USB cable (Device board's USB Device port to Host board's USB Host port) +3. Flash `example/cherryusb/device/msc/ram_disk` example (MSC Device) to the + other board +4. Start the Host board first, the program will wait for a USB mass storage + device connection +5. Connect the two boards using a USB cable (Device board's USB Device port to + Host board's USB Host port) 6. Then start the Device board -7. The Host board will automatically recognize the storage device emulated by the Device board and continue to read the README.TXT file and perform other operations +7. The Host board will automatically recognize the storage device emulated by + the Device board and continue to read the README.TXT file and perform other + operations ### Debug Functions -In addition to the auto-running example code, you can also manually operate the file system on the USB storage device through the finsh console: +In addition to the auto-running example code, you can also manually operate the +file system on the USB storage device through the finsh console: - `ls` - List files and folders in the current directory - `cat ` - Display file content @@ -82,18 +97,23 @@ msh />mkdir newfolder # Create new folder ``` ## Example Output -If the example runs successfully, you will see the following output on the serial port: +If the example runs successfully, you will see the following output on the +serial port: ``` -cherryusb host demo! +CherryUSB host demo! Waiting for USB mass storage device connection... -msh />udisk: /dev/sda mount successfully -File content: -cherryusb device msc_ram demo! +msh />udisk: /dev/sda mounted successfully +File contents: +CherryUSB device msc_ram demo! ``` ## Troubleshooting -No specific troubleshooting information at this time. If you encounter any issues, please submit an [issue on GitHub](https://github.com/OpenSiFli/SiFli-SDK/issues). +No specific troubleshooting information at this time. If you encounter any +issues, please submit an [issue on +GitHub](https://github.com/OpenSiFli/SiFli-SDK/issues). ## Reference Documentation -- [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SiFli-SDK Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) \ No newline at end of file +- [SiFli-SDK Quick Start + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) diff --git a/example/cherryusb/index_EN.md b/example/cherryusb/index_EN.md index 5c34947ea..4782bc14b 100644 --- a/example/cherryusb/index_EN.md +++ b/example/cherryusb/index_EN.md @@ -1,9 +1,7 @@ -# cherryusb +# CherryUSB ```{toctree} :titlesonly: :glob: */* - - -``` \ No newline at end of file +``` diff --git a/example/dlmodule/README_EN.md b/example/dlmodule/README_EN.md index b1b9e57ef..6d7e2d74f 100644 --- a/example/dlmodule/README_EN.md +++ b/example/dlmodule/README_EN.md @@ -1,36 +1,185 @@ # Watch Interface Using LVGL v8, the included interfaces are: -- Honeycomb main menu -- Watch face -- Cube left-right rotation (not supported on SF32lb55x series chips) -```{note} -- Not supported on 520-hdk +## Specifying Fonts + ++ eh-lb525 ++ eh-lb523 + +## Overview + +This example demonstrates the usage of dynamic modules based on the RT-Thread +dynamic library framework. In this demonstration, the application code (CODE) +and resources are decoupled and packaged into separate shared objects (.so +files): ++ `module_name_res.so`: Resource component ++ `module_name.so`: Code component + +Upon execution, the example dynamic module creates a demonstration page. + +## Directory Structure + +```c +|--module -- Dynamic module project directory + |--module_name.h -- Header file for the dynamic module name (customizable) + |--src + | |--app -- Source code for the dynamic module (generates module_name.so) + |--app_demo.c -- Initializes the module and creates a page + |--SConscript + | |--resource -- Resource directory for the dynamic module (generates module_name_res.so) + |--font_bitmap -- Bitmap fonts + |--images -- Image assets + |--strings -- Multi-language translation files + |--SConscript + |--rtconfig.py + |--SConstruct +|--project -- Firmware project directory (host environment for the dynamic module) +|--src -- Firmware source directory +|--disk -- Pre-mounted files (used to pre-index .so files into the root partition) +|--README.md -- Documentation (Chinese) +|--README_EN.md -- Documentation (English) ``` -## Specifying Fonts -Refer to `src/resource/fonts/SConscript`. By adding the `FREETYPE_FONT_NAME` macro definition in CPPDEFINES, you can register the corresponding TTF font to LVGL -```python -CPPDEFINES += ["FREETYPE_FONT_NAME={}".format(font_name)] +## Usage Instructions + + +### Hardware Requirements +Prerequisites: ++ A supported development board ([Supported Platforms](quick_start)). + +### menuconfig Configuration +Firmware side: +1. Enable `RT_USING_MODULE`:\ + ![RT_USING_MODULE](./assets/conf_dlmodule.png) + + ```{tip} + + `use custom memory interface`: Allows overriding the default memory management interface for dynamic modules. To customize this, locate and modify `RT_MODULE_MEM_CUSTOM`. + ``` + +2. Enable `USING_MOD_INSTALLER`:\ + ![USING_MOD_INSTALLER](./assets/conf_mod_installer.png) +3. As dynamic modules rely on a file system, ensure that file system support is + enabled. +4. `RT_NAME_MAX` Configuration:\ + ![11](./assets/config_rt_name_max.png) + + ```{warning} + If the allocated configuration is too small, long module names may cause identification failures, leading to system exceptions. + ``` + +### Compilation and Flashing +Dynamic modules only support compilation using the `GCC` toolchain. +1. Compiling the Firmware: Navigate to the sample `project` directory and run + the scons command: +```c +> scons --board=eh-lb525 -j8 +``` +2. Generate dynamic module dependency files: +```c +> scons --board=eh-lb525 --target=ua -s +``` +3. Navigate to the `module` directory to compile the module: +```c +> scons --board=eh-lb525 -j8 ``` -If `font_name` is `DroidSansFallback`, it is equivalent to adding the following macro definition +```{tip} ++ Dependency files are copied from the firmware directory before compilation: + ![USING_MOD_INSTALLER](./assets/ua_files_copy.png) ++ Upon successful compilation, the module .so and _res.so files are generated in /module/output/. +``` + + +4. Packaging .so files into the file system partition:\ + Place the module .so and _res.so files into the /disk/app directory, then + recompile the firmware. +5. Flashing after compilation: Navigate to the sample `project/build_xx` + directory, run `uart_download.bat`, and select the appropriate port as + prompted to start the download: ```c -#define FREETYPE_FONT_NAME DroidSansFallback +$ ./uart_download.bat + + UART Download + +Please input the serial port number: 5 ``` +For detailed compilation and download procedures, please refer to the [Quick +Start](quick_start) guide. -During compilation, it will search for font files with `.ttf` suffix in the `freetype` subdirectory and convert them to C files for compilation +## Expected Results + +After the sample starts, use the following commands to test the dynamic module: +| Purpose | Command | Example | +| -------------------- | ---------------------------------------------- | ---------------------------------------------------- | +| Open dynamic module | mod_open [module_res.so_path] [module.so_path] | `mod_open "/app/mod_demo_res.so" "/app/mod_demo.so"` | +| Close dynamic module | mod_close [module_name] | `mod_close "mod_demo"` | -```python -objs = Glob('freetype/{}.ttf'.format(font_name)) -objs = Env.FontFile(objs) +Example: +```c +/* 1. Run the sample module */ +08-11 18:58:14:025 TX:mod_open /app/mod_demo_res.so /app/mod_demo.so +08-11 18:58:14:044 mod_open argc=3 +08-11 18:58:14:048 /app/mod_demo_res.so +08-11 18:58:14:053 dlmodule_find name=/app/mod_demo_res.so +08-11 18:58:14:064 dlmodule_load /app/mod_demo_res.so fd=4 +08-11 18:58:14:069 dlmodule_load_shared_object: invalid mod_demo_res, 0x6060429c, 44316 +08-11 18:58:14:078 dlmodule_load_shared_object: clean mod_demo_res, 0x6060429c, 44316 +08-11 18:58:14:083 /app/mod_demo.so +08-11 18:58:14:089 dlmodule_find name=/app/mod_demo.so +08-11 18:58:14:098 dlmodule_load /app/mod_demo.so fd=4 +08-11 18:58:14:102 dlmodule_load_shared_object: invalid mod_demo, 0x605f9d5c, 2204 +08-11 18:58:14:111 dlmodule_load_shared_object: clean mod_demo, 0x605f9d5c, 2204 +08-11 18:58:14:117 match lang +/* 2. Module executed successfully; creating [demo_p] page */ +08-11 18:58:14:122 app_init_func create demo page. +08-11 18:58:14:130 [20537952] D/APP.FWK tshell: send msg[GUI_APP_MSG_OPEN_PAGE] [0x2003f868] to gui_app_mbx tick:629133. +08-11 18:58:14:135 msh />msh />[20538378] D/APP.SCHE app_watch: ----------------app_schedule_task---------------start +08-11 18:58:14:144 [20538410] I/APP.SCHE app_watch: >>Execute msg[GUI_APP_MSG_OPEN_PAGE] tick:629133 +08-11 18:58:14:150 [20538440] D/APP.SCHE app_watch: app[Main] create page[demo_p] 2003e134 ``` -Macros like `FREETYPE_TINY_FONT_FULL` are defined in `Kconfig.proj` in the project directory, similar to the following: +## Troubleshooting + +1. Missing EXPORT for .so dependencies: +```c +08-11 10:04:12:999 /app/mod_demo.so +08-11 10:04:13:003 dlmodule_find name=/app/mod_demo.so +08-11 10:04:13:007 dlmodule_load /app/mod_demo.so fd=4 +08-11 10:04:13:017 dlmodule_load_shared_object: invalid mod_demo, 0x605f9d30, 2160 +08-11 10:04:13:020 [3253182] E/DLMD tshell: Module: can't find lv_ext_set_local_font_bitmap in kernel symbol table +08-11 10:04:13:024 [3253218] E/DLMD tshell: Module: can't find img_red_heart in kernel symbol table +08-11 10:04:13:032 [3253249] E/DLMD tshell: Module: can't find lv_font_montserrat_28_compressed in kernel symbol table +08-11 10:04:13:037 [3253286] E/DLMD tshell: Module: can't find lv_i18n_lang_pack in kernel symbol table +08-11 10:04:13:043 app_open open /app/mod_demo.so failed. +``` +Solution: Use EXPORT to expose the required interfaces on the firmware side, for +example: +```c +RTM_EXPORT(lv_ext_set_local_font_bitmap); +... ... +``` + +2. Insufficient memory: +```c +dlmodule_load length=500000 malloc fail. +``` +Memory required for module execution is allocated via `dlm_malloc`. The error +above indicates an allocation failure. To resolve this, either reduce the size +of the .so file, increase the memory pool available for modules, or enable +`RT_MODULE_MEM_CUSTOM` to redefine the module memory interface. + + +## References + + +1. [RT-Thread Documentation Center - Dynamic + Modules](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/libc/posix/dlmodule) -```kconfig -config FREETYPE_TINY_FONT_FULL - bool - default y -``` \ No newline at end of file +## Revision History +| Version | Date | Release Notes | +| ------- | -------- | --------------- | +| 0.0.1 | May 2025 | Initial release | +| | | | +| | | | diff --git a/example/get-started/blink/index_EN.md b/example/get-started/blink/index_EN.md index 5d954dfd0..afc003e8c 100644 --- a/example/get-started/blink/index_EN.md +++ b/example/get-started/blink/index_EN.md @@ -6,6 +6,4 @@ :glob: */* - - -``` \ No newline at end of file +``` diff --git a/example/get-started/blink/no-os/README_EN.md b/example/get-started/blink/no-os/README_EN.md index 12f45f6bd..c3aca3f2f 100644 --- a/example/get-started/blink/no-os/README_EN.md +++ b/example/get-started/blink/no-os/README_EN.md @@ -1,6 +1,8 @@ # LED Blink (NO-OS) +Source path: example/get-started/blink/no-os ## Overview -This example demonstrates LED blinking functionality using GPIO to better understand GPIO usage. +This example demonstrates LED blinking functionality using GPIO to better +understand GPIO usage. ## Supported Development Boards This example can run on the following development boards: @@ -14,10 +16,12 @@ This example can run on the following development boards: * sf32lb56-lcd series * sf32lb58-lcd series -**Note:** Generally, examples run on the chip's HCPU. If you want to run the example on LCPU, you can use "eh-lb563_lcpu". +**Note:** Generally, examples run on the chip's HCPU. If you want to run the +example on LCPU, you can use "eh-lb563_lcpu". ## Example Directory Structure -The Blink project contains 1 .c file (main.c). The tree structure below shows other files in the project directory. +The Blink project contains 1 .c file (main.c). The tree structure below shows +other files in the project directory. ```c |--Readme.md |--no-os @@ -35,17 +39,19 @@ The Blink project contains 1 .c file (main.c). The tree structure below shows ot ``` ## Example Usage ### Hardware Requirements -To run this example, you need to have a development board that supports this example. +To run this example, you need to have a development board that supports this +example. ### Pin Configuration -**Note:** The table below shows the pin configurations for LED control on each development board. -| | pin assign | -|---------------|-------------| -|eh-lb523 | PA25 | -|eh-lb520 | PA25 | -|eh-lb525 | PA25 | -|eh-lb561 | PA41 | -|eh-lb563 | PA41 | -|eh-ss6500 | PA41 | +**Note:** The table below shows the pin configurations for LED control on each +development board. +| | Pin assignment | +| --------- | -------------- | +| eh-lb523 | PA25 | +| eh-lb520 | PA25 | +| eh-lb525 | PA25 | +| eh-lb561 | PA41 | +| eh-lb563 | PA41 | +| eh-ss6500 | PA41 | ### Compilation and Flashing Follow these steps to complete compilation and flashing: @@ -55,21 +61,26 @@ scons --board=eh-lb523 -j8 .\build_eh-lb523\uart_download.bat ``` ## Example Output Results -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and troubleshooting is needed. +The following results show the log after the example runs on the development +board. If you cannot see these logs, it means the example did not run +successfully as expected and troubleshooting is needed. ```c Start example blink Turning the LED OFF Turning the LED ON ``` - ## Troubleshooting -If the expected logs do not appear, troubleshooting can be performed from the following aspects: +## Troubleshooting +If the expected logs do not appear, troubleshooting can be performed from the +following aspects: * Whether hardware connections are normal -* Whether pin configuration is correct +* Whether pin configuration is correct - ## Example Extension - - To control more LEDs, the following example shows how to extend the example by adding a second LED on development board eh-lb523: - 1. Modify the kconfig file **"\siflisdk\customer\boards\Kconfig.v2"** to add LED2 option: BSP_USING_LED2; +## Example Extension + +To control more LEDs, the following example shows how to extend the example by +adding a second LED on development board eh-lb523: + 1. Modify the kconfig file **"\siflisdk\customer\boards\Kconfig.v2"** to add + LED2 option: BSP_USING_LED2; ```c menuconfig BSP_USING_LED2 bool "Use LED2" @@ -81,46 +92,51 @@ If the expected logs do not appear, troubleshooting can be performed from the fo config BSP_LED2_ACTIVE_HIGH bool "Level is high if LED is on" default n - endif -``` - 2. Modify the development board configuration file **"\siflisdk\customer\boards\eh-lb523\hcpu\board.conf"** to enable LED2 and configure the corresponding pin and active level; + endif + ``` + 2. Modify the development board configuration file + **"\siflisdk\customer\boards\eh-lb523\hcpu\board.conf"** to enable LED2 and + configure the corresponding pin and active level; ```c -CONFIG_BSP_USING_LED2=y -CONFIG_BSP_LED2_PIN=26 -CONFIG_BSP_LED2_ACTIVE_HIGH=y -``` -The above configuration is the default configuration for **eh-lb523**, i.e., LED2 is configured to pin 26 by default; if you want to modify it to another pin, you can run **menuconfig --board eh-lb523** to modify it; + CONFIG_BSP_USING_LED2=y + CONFIG_BSP_LED2_PIN=26 + CONFIG_BSP_LED2_ACTIVE_HIGH=y + ``` +The above configuration is the default configuration for **eh-lb523**, i.e., +LED2 is configured to pin 26 by default; if you want to modify it to another +pin, you can run **menuconfig --board eh-lb523** to modify it; -3. Modify the code **main.c** to control BSP_LED2_PINs to implement LED blinking; +3. Modify the code in **main.c** to toggle the BSP_LED2_PIN and achieve the LED +blinking effect; ```c -int main(void) -{ - /*recode led state*/ + int main(void) + { + /*Record LED state*/ - /* Output a message on console using printf function */ + /* Output a message to the console using the printf function */ rt_kprintf("Start example blink\n"); - /*Init pin state */ + /*Initialize pin states */ rt_pin_mode(BSP_LED1_PIN, PIN_MODE_OUTPUT); - rt_pin_mode(BSP_LED2_PIN, PIN_MODE_OUTPUT); + rt_pin_mode(BSP_LED2_PIN, PIN_MODE_OUTPUT); bool state = RT_FALSE; - /* Infinite loop, len flash inter 1s */ + /* Infinite loop, LED flash interval: 1s */ while (1) { rt_kprintf("Turning the LED %s", state == RT_TRUE ? "ON" : "OFF"); -#ifndef BSP_LED1_ACTIVE_HIGH + #ifndef BSP_LED1_ACTIVE_HIGH rt_pin_write(BSP_LED1_PIN, !state); rt_pin_write(BSP_LED2_PIN, !state); -#else + #else rt_pin_write(BSP_LED1_PIN, state); - rt_pin_write(BSP_LED2_PIN, !state); -#endif - /*toggle the LED statu*/ + rt_pin_write(BSP_LED2_PIN, !state); + #endif + /*Toggle the LED state*/ state = !state; rt_thread_mdelay(1000); } return 0; -} -``` \ No newline at end of file + } + ``` diff --git a/example/get-started/blink/rtt/README_EN.md b/example/get-started/blink/rtt/README_EN.md index c5bea30ee..4dc015323 100644 --- a/example/get-started/blink/rtt/README_EN.md +++ b/example/get-started/blink/rtt/README_EN.md @@ -1,6 +1,8 @@ # LED Blink (RT-Thread) +Source Path: example/get-started/blink/rtt ## Overview -This example demonstrates LED blinking functionality using GPIO to better understand GPIO usage. +This example demonstrates LED blinking functionality using GPIO to better +understand GPIO usage. ## Supported Development Boards This example can run on the following development boards: @@ -14,10 +16,12 @@ This example can run on the following development boards: * sf32lb56-lcd series * sf32lb58-lcd series -**Note:** Generally, examples run on the chip's HCPU. If you want to run the example on LCPU, you can use "eh-lb563_lcpu". +**Note:** Generally, examples run on the chip's HCPU. If you want to run the +example on LCPU, you can use "eh-lb563_lcpu". ## Example Directory Structure -The Blink project contains 1 .c file (main.c). The tree structure below shows other files in the project directory. +The Blink project contains 1 .c file (main.c). The tree structure below shows +other files in the project directory. ```c |--Readme.md |--no-os @@ -35,41 +39,48 @@ The Blink project contains 1 .c file (main.c). The tree structure below shows ot ``` ## Example Usage ### Hardware Requirements -To run this example, you need to have a development board that supports this example. +To run this example, you need to have a development board that supports this +example. ### Pin Configuration -**Note:** The table below shows the pin configurations for LED control on each development board. -| | pin assign | -|---------------|-------------| -|eh-lb523 | PA25 | -|eh-lb520 | PA25 | -|eh-lb525 | PA25 | -|eh-lb561 | PA41 | -|eh-lb563 | PA41 | -|eh-ss6500 | PA41 | +**Note:** The table below shows the pin configurations for LED control on each +development board. +| | Pin Assignment | +| --------- | -------------- | +| eh-lb523 | PA25 | +| eh-lb520 | PA25 | +| eh-lb525 | PA25 | +| eh-lb561 | PA41 | +| eh-lb563 | PA41 | +| eh-ss6500 | PA41 | ### Compilation and Flashing Follow these steps to complete compilation and flashing: ```shell menuconfig --board=eh-lb523 scons --board=eh-lb523 -j8 - .\build_eh-lb523\uart_download.bat +.\build_eh-lb523\uart_download.bat ``` ## Example Output Results -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and troubleshooting is needed. +The following results show the log after the example runs on the development +board. If you cannot see these logs, it means the example did not run +successfully as expected and troubleshooting is needed. ``` Start example blink Turning the LED OFF Turning the LED ON ``` - ## Troubleshooting -If the expected logs do not appear, troubleshooting can be performed from the following aspects: +## Troubleshooting +If the expected logs do not appear, troubleshooting can be performed from the +following aspects: * Whether hardware connections are normal -* Whether pin configuration is correct +* Whether pin configuration is correct - ## Example Extension - - To control more LEDs, the following example shows how to extend the example by adding a second LED on development board eh-lb523: - 1. Modify the kconfig file **"\siflisdk\customer\boards\Kconfig.v2"** to add LED2 option: BSP_USING_LED2; +## Example Extension + +To control more LEDs, the following example shows how to extend the example by +adding a second LED on development board eh-lb523: + 1. Modify the kconfig file **"\siflisdk\customer\boards\Kconfig.v2"** to add + LED2 option: BSP_USING_LED2; ```kconfig menuconfig BSP_USING_LED2 bool "Use LED2" @@ -81,46 +92,50 @@ If the expected logs do not appear, troubleshooting can be performed from the fo config BSP_LED2_ACTIVE_HIGH bool "Level is high if LED is on" default n - endif -``` - 2. Modify the development board configuration file **"\siflisdk\customer\boards\eh-lb523\hcpu\board.conf"** to enable LED2 and configure the corresponding pin and active level; + endif + ``` + 2. Modify the development board configuration file + **"\siflisdk\customer\boards\eh-lb523\hcpu\board.conf"** to enable LED2 and + configure the corresponding pin and active level; ```c -CONFIG_BSP_USING_LED2=y -CONFIG_BSP_LED2_PIN=26 -CONFIG_BSP_LED2_ACTIVE_HIGH=y -``` -The above configuration is the default configuration for **eh-lb523**, i.e., LED2 is configured to pin 26 by default; if you want to modify it to another pin, you can run **menuconfig --board eh-lb523** to modify it; + CONFIG_BSP_USING_LED2=y + CONFIG_BSP_LED2_PIN=26 + CONFIG_BSP_LED2_ACTIVE_HIGH=y + ``` +The above configuration is the default configuration for **eh-lb523**, i.e., +LED2 is configured to pin 26 by default; if you want to modify it to another +pin, you can run **menuconfig --board eh-lb523** to modify it; -3. Modify the code **main.c** to control BSP_LED2_PINs to implement LED blinking; +3. Modify the code in **main.c** to toggle the BSP_LED2_PINs for LED blinking; ```c -int main(void) -{ - /*recode led state*/ + int main(void) + { + /*record led state*/ /* Output a message on console using printf function */ rt_kprintf("Start example blink\n"); /*Init pin state */ rt_pin_mode(BSP_LED1_PIN, PIN_MODE_OUTPUT); - rt_pin_mode(BSP_LED2_PIN, PIN_MODE_OUTPUT); + rt_pin_mode(BSP_LED2_PIN, PIN_MODE_OUTPUT); bool state = RT_FALSE; - /* Infinite loop, len flash inter 1s */ + /* Infinite loop, led flash interval 1s */ while (1) { rt_kprintf("Turning the LED %s", state == RT_TRUE ? "ON" : "OFF"); -#ifndef BSP_LED1_ACTIVE_HIGH + #ifndef BSP_LED1_ACTIVE_HIGH rt_pin_write(BSP_LED1_PIN, !state); rt_pin_write(BSP_LED2_PIN, !state); -#else + #else rt_pin_write(BSP_LED1_PIN, state); - rt_pin_write(BSP_LED2_PIN, !state); -#endif - /*toggle the LED statu*/ + rt_pin_write(BSP_LED2_PIN, !state); + #endif + /*toggle the LED status*/ state = !state; rt_thread_mdelay(1000); } return 0; -} -``` \ No newline at end of file + } + ``` diff --git a/example/get-started/dualcore/README_EN.md b/example/get-started/dualcore/README_EN.md index 7cad033e3..51d519d82 100644 --- a/example/get-started/dualcore/README_EN.md +++ b/example/get-started/dualcore/README_EN.md @@ -9,7 +9,11 @@ This example can run on the following development boards: * eh-lb523 ## Overview -This example demonstrates how to develop dual-core applications. The project supports Bluetooth and low power consumption, builds user interface based on LVGL v8 (referencing `multimedia/lvgl/watch`), with HCPU and LCPU running their respective programs (SF32LB52 series chips' LCPU is dedicated to Bluetooth and does not run user programs). +This example demonstrates how to develop dual-core applications. The project +supports Bluetooth and low power consumption, builds user interface based on +LVGL v8 (referencing `multimedia/lvgl/watch`), with HCPU and LCPU running their +respective programs (SF32LB52 series chips' LCPU is dedicated to Bluetooth and +does not run user programs). ## Directory Structure ``` @@ -21,7 +25,7 @@ This example demonstrates how to develop dual-core applications. The project sup └── src ├── hcpu // HCPU code directory └── lcpu // LCPU code directory -``` +``` ## Example Usage ### Compilation and Flashing @@ -31,14 +35,22 @@ Switch to the `project/hcpu` directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: + -Executing the `scons` command in the HCPU project directory will automatically compile the LCPU project, and the download script will download all firmware including the LCPU. +Executing the `scons` command in the HCPU project directory will automatically +compile the LCPU project, and the download script will download all firmware +including the LCPU. ### Code Analysis #### Build Script -Since LCPU is used, you need to add the following code to `project/hcpu/SConstruct` to include the LCPU project in the build. For `SF32LB52X`, because the LCPU is dedicated to Bluetooth and does not support custom projects, you should directly use the `AddLCPU` command to add the common LCPU project. -For other chip series, use the `AddChildProj` command to add the project under the `lcpu` directory as a subproject in the build. +Since LCPU is used, you need to add the following code to +`project/hcpu/SConstruct` to include the LCPU project in the build. For +`SF32LB52X`, because the LCPU is dedicated to Bluetooth and does not support +custom projects, you should directly use the `AddLCPU` command to add the common +LCPU project. For other chip series, use the `AddChildProj` command to add the +project under the `lcpu` directory as a subproject in the build. ```python # Add LCPU project @@ -53,34 +65,35 @@ else: #### HCPU -The HCPU's `main` function is in `src/hcpu/main.c`, completing Bluetooth initialization: +The HCPU's `main` function is in `src/hcpu/main.c`, completing Bluetooth +initialization: ```c int main(void) { int count = 0; app_env_t *env = ble_app_get_env(); - env->mb_handle = rt_mb_create("app", 8, RT_IPC_FLAG_FIFO); + env->mb_handle = rt_mb_create("app", 8, RT_IPC_FLAG_FIFO); sifli_ble_enable(); - env->time_handle = rt_timer_create("app", app_timeout_handler, NULL, + env->time_handle = rt_timer_create("app", app_timeout_handler, NULL, rt_tick_from_millisecond(BLE_APP_TIMEOUT_INTERVAL), RT_TIMER_FLAG_SOFT_TIMER); #ifdef SF32LB52X - env->rc10k_time_handle = rt_timer_create("rc10", rc10k_timeout_handler, NULL, + env->rc10k_time_handle = rt_timer_create("rc10", rc10k_timeout_handler, NULL, rt_tick_from_millisecond(15 * 1000), RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_SOFT_TIMER); // 15s - rt_timer_start(env->rc10k_time_handle); + rt_timer_start(env->rc10k_time_handle); #endif while (1) { uint32_t value; int ret; - rt_mb_recv(env->mb_handle, (rt_uint32_t *)&value, RT_WAITING_FOREVER); + rt_mb_recv(env->mb_handle, (rt_uint32_t *)&value, RT_WAITING_FOREVER); if (value == BLE_POWER_ON_IND) { - env->is_power_on = 1; - env->conn_para.mtu = 23; /* Default value. */ + env->is_power_on = 1; + env->conn_para.mtu = 23; /* Default value. */ ble_app_service_init(); - /* First enable connectable adv then enable non-connectable. */ + /* Start connectable advertising before non-connectable advertising. */ ble_app_advertising_start(); LOG_I("receive BLE power on!\r\n"); } @@ -89,7 +102,13 @@ int main(void) } ``` -Graphics initialization is triggered by `app_watch_init` in `src/hcpu/gui_apps/watch_demo.c`, which is registered as an `APP` level [automatic initialization function](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/basic/basic?id=rt-thread-%e8%87%aa%e5%8a%a8%e5%88%9d%e5%a7%8b%e5%8c%96%e6%9c%ba%e5%88%b6), executing earlier than the `main` function in `main.c`. In `app_watch_init`, the `app_watch` thread is created, and graphics initialization is actually completed in the `app_watch` thread. +Graphics initialization is triggered by `app_watch_init` in +`src/hcpu/gui_apps/watch_demo.c`, which is registered as an `APP` level +[automatic initialization +function](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/basic/basic?id=rt-thread-%e8%87%aa%e5%8a%a8%e5%88%9d%e5%a7%8b%e5%8c%96%e6%9c%ba%e5%88%b6), +executing earlier than the `main` function in `main.c`. In `app_watch_init`, the +`app_watch` thread is created, and graphics initialization is actually completed +in the `app_watch` thread. ```c INIT_APP_EXPORT(app_watch_init); @@ -119,8 +138,12 @@ int main(void) ``` #### Button -If button Key1 is connected to the LCPU's pin, the LCPU handles button events and forwards button events to the HCPU through data service. -The LCPU's button initialization code is in the `init_pin` function in `src/lcpu/main.c`. At the same time, the LCPU project configuration `proj.conf` enables `CONFIG_BUTTON_SERVICE_ENABLED`, which registers the button service, and the HCPU will subscribe to this service to receive button events. +If button Key1 is connected to the LCPU's pin, the LCPU handles button events +and forwards button events to the HCPU through data service. The LCPU's button +initialization code is in the `init_pin` function in `src/lcpu/main.c`. At the +same time, the LCPU project configuration `proj.conf` enables +`CONFIG_BUTTON_SERVICE_ENABLED`, which registers the button service, and the +HCPU will subscribe to this service to receive button events. ````{note} Since most boards' LCPU configuration files (i.e., `board.conf` in the board's lcpu directory) do not define button pins, a `proj.conf` is added for each supported board in the lcpu project directory to define button pin numbers. For example, in the `project/lcpu/eh-lb561_lcpu` directory, `proj.conf` has the following KEY1 configuration parameters, which are effective for the eh-lb561 development board: @@ -129,45 +152,57 @@ CONFIG_BSP_USING_KEY1=y CONFIG_BSP_KEY1_PIN=128 CONFIG_BSP_KEY1_ACTIVE_HIGH=y ``` - ```` -The HCPU's button initialization function is `init_pin` in `src/hcpu/gui_apps/watch_demo.c`. You can see that buttons are only initialized in the HCPU program when the button's corresponding GPIO pin is a PA pin, otherwise it just subscribes to the button data service. +The HCPU's button initialization function is `init_pin` in +`src/hcpu/gui_apps/watch_demo.c`. You can see that buttons are only initialized +in the HCPU program when the button's corresponding GPIO pin is a PA pin, +otherwise it just subscribes to the button data service. ```c -#if (SLEEP_CTRL_PIN < GPIO1_PIN_NUM) +#if (SLEEP_CTRL_PIN < GPIO1_PIN_NUM) button_cfg_t cfg; -#if defined(BSP_USING_PM) && !defined(SF32LB52X) +#if defined(BSP_USING_PM) && !defined(SF32LB52X) int8_t wakeup_pin; uint16_t gpio_pin; GPIO_TypeDef *gpio; -#endif /* BSP_USING_PM && !SF32LB52X */ - +#endif /* BSP_USING_PM && !SF32LB52X */ + cfg.pin = SLEEP_CTRL_PIN; cfg.active_state = BUTTON_ACTIVE_POL; cfg.mode = PIN_MODE_INPUT; cfg.button_handler = button_event_handler; - int32_t id = button_init(&cfg); - RT_ASSERT(id >= 0); + int32_t id = button_init(&cfg); + RT_ASSERT(id >= 0); RT_ASSERT(SF_EOK == button_enable(id)); key1_button_handle = id; -#endif /* SLEEP_CTRL_PIN < GPIO1_PIN_NUM */ +#endif /* SLEEP_CTRL_PIN < GPIO1_PIN_NUM */ button_handle = datac_open(); RT_ASSERT(DATA_CLIENT_INVALID_HANDLE != button_handle); - datac_subscribe(button_handle, "btn0", button_service_callback, SLEEP_CTRL_PIN); + datac_subscribe(button_handle, "btn0", button_service_callback, SLEEP_CTRL_PIN); ``` -For SF32LB52 series chips, the LCPU is dedicated to Bluetooth and does not run user programs. The button is connected to the HCPU's pin and is directly handled by the HCPU GPIO interrupt, but button events can still be handled uniformly by subscribing to the button service, where the button service is also located on the HCPU. + + +For SF32LB52 series chips, the LCPU is dedicated to Bluetooth and does not run +user programs. The button is connected to the HCPU's pin and is directly handled +by the HCPU GPIO interrupt, but button events can still be handled uniformly by +subscribing to the button service, where the button service is also located on +the HCPU. ```{note} SF32LB52 series needs to enable `DATA_SVC_MBOX_THREAD_DISABLED` to disable cross-core service ``` ## Expected Results -After power-on, a honeycomb interface appears. Clicking the clock icon opens the watch face. If there is no operation on the interface or button press for 10 seconds, the screen will automatically turn off. At this time, the HCPU sleeps and enters low power mode. Button (Key1) wakes up the HCPU and turns on the screen. +After power-on, a honeycomb interface appears. Clicking the clock icon opens the +watch face. If there is no operation on the interface or button press for 10 +seconds, the screen will automatically turn off. At this time, the HCPU sleeps +and enters low power mode. Button (Key1) wakes up the HCPU and turns on the +screen. ## Exception Diagnosis - -## Reference Documentation \ No newline at end of file + +## Reference Documentation diff --git a/example/get-started/hello_world/no-os/README_EN.md b/example/get-started/hello_world/no-os/README_EN.md index f037b07b3..4a4d636b3 100644 --- a/example/get-started/hello_world/no-os/README_EN.md +++ b/example/get-started/hello_world/no-os/README_EN.md @@ -1,4 +1,8 @@ # Hello World Example (NO-OS) +The Hello_world application will print "hello world!" on the board's serial +port. + +The Hello_world application outputs "hello world!" via the board's serial port. +- The application includes both no-os and RT-Thread versions, located in the + no-os and rtt subdirectories respectively. -The Hello_world application will print "hello world!" on the board's serial port. -- The application includes both no-os and RT-Thread versions, located in the no-os and rtt subdirectories respectively. diff --git a/example/get-started/hello_world/rtt/README_EN.md b/example/get-started/hello_world/rtt/README_EN.md index 68aab3db8..b28cc814d 100644 --- a/example/get-started/hello_world/rtt/README_EN.md +++ b/example/get-started/hello_world/rtt/README_EN.md @@ -3,7 +3,8 @@ Source Code Path: example/get-started/hello_world/rtt ## Overview -The Hello_world application will print "hello world!" on the board's serial port. +The Hello_world application will print "hello world!" on the board's serial +port. ## Usage @@ -23,7 +24,8 @@ scons --board=pc -j32 ``` ## Example Output -If the example runs successfully, you will see the following output on the serial port: +If the example runs successfully, you will see the following output on the +serial port: ``` Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000000 @@ -57,8 +59,11 @@ msh />Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000000 ``` ## Troubleshooting -No specific troubleshooting information available. For any issues, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +No specific troubleshooting information available. For any issues, please submit +an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SiFli-SDK Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) \ No newline at end of file +- [SiFli-SDK Quick + Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) diff --git a/example/get-started/index_EN.md b/example/get-started/index_EN.md index 7e7080e7c..bb7fff4ce 100644 --- a/example/get-started/index_EN.md +++ b/example/get-started/index_EN.md @@ -6,6 +6,4 @@ :glob: */* - - ``` diff --git a/example/hal/adc/adc_battery/README_EN.md b/example/hal/adc/adc_battery/README_EN.md index 672b6609f..f7d70177d 100644 --- a/example/hal/adc/adc_battery/README_EN.md +++ b/example/hal/adc/adc_battery/README_EN.md @@ -25,7 +25,7 @@ build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat Select the port as prompted to download: ```none -please input the serial port num:5 +Please enter the serial port number: 5 ``` #### Example Output Results Display: @@ -37,7 +37,8 @@ please input the serial port num:5 ![alt text](assets/last.png) -The log prints the value as the raw register value, and Voltage is the converted mV voltage +The log prints the value as the raw register value, and Voltage is the converted +mV voltage #### ADC Configuration Flow @@ -54,22 +55,32 @@ menuconfig --board=sf32lb52-lcd_n16r8 ![alt text](assets/2.png) -**Note**: -* Enable the corresponding ADC clock source (enabled by default in code, not mandatory here) +**Note**: +* Enable the corresponding ADC clock source (enabled by default in code, not + mandatory here) ```c -/* 2, open adc clock source */ +/* * 2. Enable the ADC clock source * */ HAL_RCC_EnableModule(RCC_MOD_GPADC); ``` * ADC Calibration -1. To improve ADC accuracy, SiFli series chips undergo ADC calibration at the factory (calibration parameters are written to the chip's internal OTP area). Different series have different calibration methods. -To ensure ADC accuracy, it needs to be called once every power-on. The following is the calibration function, which reads OTP parameters to calculate the slope `adc_vol_ratio` and offset `adc_vol_offset`: +1. To improve ADC accuracy, SiFli series chips undergo ADC calibration at the + factory (calibration parameters are written to the chip's internal OTP area). + Different series have different calibration methods.\ + To ensure ADC accuracy, it needs to be called once every power-on. The + following is the calibration function, which reads OTP parameters to + calculate the slope `adc_vol_ratio` and offset `adc_vol_offset`: ```c static int utest_adc_calib(void) ``` -2. After ADC sampling obtains the raw register value, call the function `example_adc_get_float_mv` and calculate the final voltage value based on the calibrated slope `adc_vol_ratio` and offset `adc_vol_offset`. -3. For 52 series chips, CH8 (Channel 7) is internally connected to Vbat through two equal voltage divider resistors. To get the Vbat value, conversion is needed. To reduce voltage divider resistor errors, the two resistors have been calibrated at the factory: +2. After ADC sampling obtains the raw register value, call the function + `example_adc_get_float_mv` and calculate the final voltage value based on the + calibrated slope `adc_vol_ratio` and offset `adc_vol_offset`. +3. For 52 series chips, CH8 (Channel 7) is internally connected to Vbat through + two equal voltage divider resistors. To get the Vbat value, conversion is + needed. To reduce voltage divider resistor errors, the two resistors have + been calibrated at the factory: ```c static float adc_vbat_factor = 2.01; /* Calibrate the two voltage divider resistors from 52 chip internal CH8 (Channel 7) to Vbat */ static void example_adc_vbat_fact_calib(uint32_t voltage, uint32_t reg) @@ -88,20 +99,25 @@ static void example_adc_vbat_fact_calib(uint32_t voltage, uint32_t reg) ``` ## Exception Diagnosis * ADC sampled voltage value is incorrect -1. Check if ADC hardware is connected correctly. ADC sampling channels are fixed IO ports and cannot be arbitrarily assigned. For which IO corresponds to CH0-7, refer to the chip manual. -2. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), cannot exceed the input range -3. Use debugging tools like Ozone or LightWork. After starting ADC sampling, connect online and check the corresponding register configuration status against the chip manual. +1. Check if ADC hardware is connected correctly. ADC sampling channels are fixed + IO ports and cannot be arbitrarily assigned. For which IO corresponds to + CH0-7, refer to the chip manual. +2. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), + cannot exceed the input range +3. Use debugging tools like Ozone or LightWork. After starting ADC sampling, + connect online and check the corresponding register configuration status + against the chip manual. * ADC accuracy is insufficient 1. Check if ADC calibration parameters are obtained and used 2. Check if voltage divider resistor accuracy meets requirements -3. Check if ADC reference voltage is stable and has excessive ripple (refer to ADC voltage reference chip manual for specifics) +3. Check if ADC reference voltage is stable and has excessive ripple (refer to + ADC voltage reference chip manual for specifics) - ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf +* DS0052-SF32LB52x-Datasheet V0p3.pdf ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | diff --git a/example/hal/adc/index_EN.md b/example/hal/adc/index_EN.md index be52aa14a..9d349b431 100644 --- a/example/hal/adc/index_EN.md +++ b/example/hal/adc/index_EN.md @@ -5,5 +5,4 @@ :glob: */* - ``` diff --git a/example/hal/adc/multichannel/README_EN.md b/example/hal/adc/multichannel/README_EN.md index c59795eb1..bddbdd9b5 100644 --- a/example/hal/adc/multichannel/README_EN.md +++ b/example/hal/adc/multichannel/README_EN.md @@ -5,11 +5,14 @@ The example can run on the following development boards - sf32lb52-lcd_n16r8 ## Overview -* Operating HAL functions for single-channel ADC or DMA six-channel sampling demonstration +* Operating HAL functions for single-channel ADC or DMA six-channel sampling + demonstration ## Example Usage ### Compilation and Programming -The demonstration code defaults to single-channel ADC sampling demonstration. If you want to run the DMA six-channel demonstration, please enable the macro in `main.c` under the project path: +The demonstration code defaults to single-channel ADC sampling demonstration. If +you want to run the DMA six-channel demonstration, please enable the macro in +`main.c` under the project path: ```c #define BSP_GPADC_USING_DMA 1 ``` @@ -17,87 +20,92 @@ Switch to the example project directory and run the scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j8 -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: > build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 ### Hardware Connection -* PA28 is the fixed output IO for ADC1 Channel 0 (DMA six-channel demonstration uses PA28-PA33, not marked here) -![alt text](assets/SF32LB52_DevKit_ADC.png) +* PA28 is the fixed output IO for ADC1 Channel 0 (DMA six-channel demonstration + uses PA28-PA33, not marked here)\ + ![alt text](assets/SF32LB52_DevKit_ADC.png) #### Example Output Results Display: * Single-channel ADC mode log output (PA28 input 2.5V): ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000080 \ | / - SiFli Corporation / | \ build on Nov 6 2024, 2.2.0 build 00000000 - 2020 - 2022 Copyright by SiFli team - mount /dev sucess + 2020 - 2022 Copyright by SiFli team + mount /dev success [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [I/drv.rtc] RTC use LXT RTC_CR=00000001 [I/drv.rtc] Init RTC, wake = 0 [I/drv.audprc] init 00 ADC_PATH_CFG0 0x606 [I/drv.audprc] HAL_AUDPRC_Init res 0 [I/drv.audcodec] HAL_AUDCODEC_Init res 0 - [32m][I/TOUCH] Regist touch screen driver, probe=1203c2d5 [0m] + [32m][I/TOUCH] Registered touch screen driver, probe=1203c2d5 [0m] call par CFG1(35bb) fc 9, xtal 2000, pll 2050 call par CFG1(35bb) fc 9, xtal 2000, pll 2050 - Start adc demo! - ADC Get calibration res 0 - ADC reg value 3192 voltage 2519.12 mv - adc demo end! + Starting ADC demo... + ADC calibration result: 0 + ADC register value: 3192, Voltage: 2519.12 mV + ADC demo finished. ``` -The log prints the value as the raw register value, and Voltage is the converted mV voltage -* DMA six-channel mode log output (PA28 input 2.5V, PA29 connected to GND, other IOs based on board internal voltage): +The log prints the value as the raw register value, and Voltage is the converted +mV voltage +* DMA six-channel mode log output (PA28 input 2.5V, PA29 connected to GND, other + IOs based on board internal voltage): ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000080 \ | / - SiFli Corporation / | \ build on Nov 6 2024, 2.2.0 build 00000000 2020 - 2022 Copyright by SiFli team - mount /dev sucess + mount /dev success [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [I/drv.rtc] RTC use LXT RTC_CR=00000001 [I/drv.rtc] Init RTC, wake = 0 [I/drv.audprc] init 00 ADC_PATH_CFG0 0x606 [I/drv.audprc] HAL_AUDPRC_Init res 0 [I/drv.audcodec] HAL_AUDCODEC_Init res 0 - [32m][I/TOUCH] Regist touch screen driver, probe=1203c685 [0m] + [32m][I/TOUCH] Registered touch screen driver, probe=1203c685 [0m] call par CFG1(35bb) fc 9, xtal 2000, pll 2050 call par CFG1(35bb) fc 9, xtal 2000, pll 2050 - Start adc demo! - ADC Get calibration res 0 - ADC reg value[0] 3199 voltage 2526.56 mv - ADC reg value[1] 831 voltage 10.98 mv - ADC reg value[2] 3950 voltage 3324.36 mv - ADC reg value[3] 1757 voltage 994.69 mv - ADC reg value[4] 1082 voltage 277.62 mv - ADC reg value[5] 3951 voltage 3325.43 mv - Loop 0 done === - adc demo end! + Starting ADC demo... + ADC calibration result: 0 + ADC register value[0]: 3199, Voltage: 2526.56 mV + ADC register value[1]: 831, Voltage: 10.98 mV + ADC register value[2]: 3950, Voltage: 3324.36 mV + ADC register value[3]: 1757, Voltage: 994.69 mV + ADC register value[4]: 1082, Voltage: 277.62 mV + ADC register value[5]: 3951, Voltage: 3325.43 mV + Loop 0 complete. + ADC demo finished. ``` -The log prints value[0] as the corresponding channel 0 raw register value, and Voltage is the converted mV voltage +The log prints value[0] as the corresponding channel 0 raw register value, and +Voltage is the converted mV voltage #### ADC Configuration Flow * Set the corresponding ADC IO port (single-channel ADC mode) ```c - /* 52 chip default channel 0 is PA28, set PA28 to analog input mode, disable internal pull-up/pull-down */ +/* 52 chip default channel 0 is PA28, set PA28 to analog input mode, disable internal pull-up/pull-down */ HAL_PIN_Set_Analog(PAD_PA28, 1); ``` * Set the corresponding ADC IO ports (DMA six-channel mode) ```c - /* 52 chip demonstration uses channels 0-5, all configured as analog input mode, disable internal pull-up/pull-down */ +/* 52 chip demonstration uses channels 0-5, all configured as analog input mode, disable internal pull-up/pull-down */ HAL_PIN_Set_Analog(PAD_PA28, 1); /* channel 0 */ HAL_PIN_Set_Analog(PAD_PA29, 1); HAL_PIN_Set_Analog(PAD_PA30, 1); @@ -105,24 +113,28 @@ The log prints value[0] as the corresponding channel 0 raw register value, and V HAL_PIN_Set_Analog(PAD_PA32, 1); HAL_PIN_Set_Analog(PAD_PA33, 1); /* channel 5 */ ``` -**Note**: -1. ADC input ports are fixed IO ports, as shown in the following diagram:
52 chip ADC CH1-7 distribution, corresponding to software configured Channel0-6. The last channel CH8 (Channel 7) is internally connected to battery Vbat detection and not mapped to external IO
-![alt text](assets/ADC_MAP.png) -2. `HAL_PIN_Set` `HAL_PIN_Set_Analog` last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu
-* Enable the corresponding ADC clock source (enabled by default in code, not mandatory here) +**Note**: +1. ADC input ports are fixed IO ports, as shown in the following diagram:
52 + chip ADC CH1-7 distribution, corresponding to software configured Channel0-6. + The last channel CH8 (Channel 7) is internally connected to battery Vbat + detection and not mapped to external IO
![alt text](assets/ADC_MAP.png) +2. `HAL_PIN_Set` `HAL_PIN_Set_Analog` last parameter is for hcpu/lcpu selection, + 1: select hcpu, 0: select lcpu
+* Enable the corresponding ADC clock source (enabled by default in code, not + mandatory here) ``` - /* 2, open adc clock source */ +/* * 2. Enable ADC clock source * */ HAL_RCC_EnableModule(RCC_MOD_GPADC); ``` * ADC initialization settings 1. ADC channel modification
```c - #define ADC_DEV_CHANNEL 0 /* Single-channel ADC mode ADC channel */ +#define ADC_DEV_CHANNEL 0 /* Single-channel ADC mode ADC channel */ /* 52 chip default channel 0 is PA28, set PA28 to analog input mode, disable internal pull-up/pull-down */ HAL_PIN_Set_Analog(PAD_PA28, 1); ``` ```c - /* Select which channels to sample with DMA */ +/* Select which channels to sample with DMA */ /* set pinmux of channel 0 to analog input */ HAL_PIN_Set_Analog(PAD_PA28, 1); /* channel 0 */ HAL_PIN_Set_Analog(PAD_PA29, 1); @@ -138,14 +150,23 @@ The log prints value[0] as the corresponding channel 0 raw register value, and V HAL_ADC_ConfigChannel(&hadc, &ADC_ChanConf); ``` * ADC Calibration -1. To improve ADC accuracy, SiFli series chips undergo ADC calibration at the factory (calibration parameters are written to the chip's internal OTP area). Different series have different calibration methods. -To ensure ADC accuracy, it needs to be called once every power-on. The following is the calibration function, which reads OTP parameters to calculate the slope `adc_vol_ratio` and offset `adc_vol_offset`: +1. To improve ADC accuracy, SiFli series chips undergo ADC calibration at the + factory (calibration parameters are written to the chip's internal OTP area). + Different series have different calibration methods.\ + To ensure ADC accuracy, it needs to be called once every power-on. The + following is the calibration function, which reads OTP parameters to + calculate the slope `adc_vol_ratio` and offset `adc_vol_offset`: ```c static int utest_adc_calib(void) ``` -2. After ADC sampling obtains the raw register value, call the function `example_adc_get_float_mv` and calculate the final voltage value based on the calibrated slope `adc_vol_ratio` and offset `adc_vol_offset`. -3. For 52 series chips, CH8 (Channel 7) is internally connected to Vbat through two equal voltage divider resistors. To get the Vbat value, conversion is needed. To reduce voltage divider resistor errors, the two resistors have been calibrated at the factory: +2. After ADC sampling obtains the raw register value, call the function + `example_adc_get_float_mv` and calculate the final voltage value based on the + calibrated slope `adc_vol_ratio` and offset `adc_vol_offset`. +3. For 52 series chips, CH8 (Channel 7) is internally connected to Vbat through + two equal voltage divider resistors. To get the Vbat value, conversion is + needed. To reduce voltage divider resistor errors, the two resistors have + been calibrated at the factory: ```c static float adc_vbat_factor = 2.01; /* Calibrate the two voltage divider resistors from 52 chip internal CH8 (Channel 7) to Vbat */ static void example_adc_vbat_fact_calib(uint32_t voltage, uint32_t reg) @@ -164,20 +185,25 @@ static void example_adc_vbat_fact_calib(uint32_t voltage, uint32_t reg) ``` ## Exception Diagnosis * ADC sampled voltage value is incorrect -1. Check if ADC hardware is connected correctly. ADC sampling channels are fixed IO ports and cannot be arbitrarily assigned. For which IO corresponds to CH0-7, refer to the chip manual. -2. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), cannot exceed the input range -3. Use debugging tools like Ozone or LightWork. After starting ADC sampling, connect online and check the corresponding register configuration status against the chip manual. +1. Check if ADC hardware is connected correctly. ADC sampling channels are fixed + IO ports and cannot be arbitrarily assigned. For which IO corresponds to + CH0-7, refer to the chip manual. +2. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), + cannot exceed the input range +3. Use debugging tools like Ozone or LightWork. After starting ADC sampling, + connect online and check the corresponding register configuration status + against the chip manual. * ADC accuracy is insufficient 1. Check if ADC calibration parameters are obtained and used 2. Check if voltage divider resistor accuracy meets requirements -3. Check if ADC reference voltage is stable and has excessive ripple (refer to ADC voltage reference chip manual for specifics) +3. Check if ADC reference voltage is stable and has excessive ripple (refer to + ADC voltage reference chip manual for specifics) - ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf +* DS0052-SF32LB52x-Datasheet V0p3.pdf ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | diff --git a/example/hal/aes/README_EN.md b/example/hal/aes/README_EN.md index 4352ccb87..c8c2ce09a 100644 --- a/example/hal/aes/README_EN.md +++ b/example/hal/aes/README_EN.md @@ -1,13 +1,13 @@ # AES Example Source code path: example/hal/aes ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - + This example demonstrates using AES for encryption and decryption, including: + AES encryption/decryption (synchronous mode) - AES CBC mode encryption/decryption @@ -17,11 +17,12 @@ This example demonstrates using AES for encryption and decryption, including: - AES CBC mode encryption ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -31,18 +32,20 @@ Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: 1. AES CBC mode encryption and decryption: ```c @@ -50,10 +53,10 @@ After the example starts, the serial port outputs the following: 10-19 23:26:22:009 Raw data: 10-19 23:26:22:010 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:012 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, -10-19 23:26:22:014 Encry. ciphertext: +10-19 23:26:22:014 Encrypted ciphertext: 10-19 23:26:22:016 0xd5, 0xb2, 0xe1, 0x75, 0x68, 0x6d, 0xb2, 0x03, 10-19 23:26:22:017 0x63, 0x96, 0xe1, 0x70, 0xc3, 0xf9, 0xf4, 0xf3, -10-19 23:26:22:019 Decry. plaintext: +10-19 23:26:22:019 Decrypted plaintext: 10-19 23:26:22:063 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:068 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, ``` @@ -63,10 +66,10 @@ After the example starts, the serial port outputs the following: 10-19 23:26:22:082 Raw data: 10-19 23:26:22:086 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:091 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, -10-19 23:26:22:096 Encry. ciphertext: +10-19 23:26:22:096 Encrypted ciphertext: 10-19 23:26:22:100 0x86, 0xe9, 0x35, 0x58, 0xb9, 0xdd, 0x7d, 0x0b, 10-19 23:26:22:106 0x74, 0x85, 0x6c, 0x07, 0x1a, 0xe1, 0xbd, 0x9c, -10-19 23:26:22:111 Decry. plaintext: +10-19 23:26:22:111 Decrypted plaintext: 10-19 23:26:22:114 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:118 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, ``` @@ -76,10 +79,10 @@ After the example starts, the serial port outputs the following: 10-19 23:26:22:132 Raw data: 10-19 23:26:22:137 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:142 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, -10-19 23:26:22:147 Encry. ciphertext: +10-19 23:26:22:147 Encrypted ciphertext: 10-19 23:26:22:152 0x6d, 0xf0, 0x28, 0xcd, 0x3c, 0xf5, 0x29, 0x79, 10-19 23:26:22:156 0x85, 0x06, 0xb9, 0xba, 0x35, 0x34, 0xf9, 0x46, -10-19 23:26:22:161 Decry. plaintext: +10-19 23:26:22:161 Decrypted plaintext: 10-19 23:26:22:165 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:170 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, ``` @@ -89,7 +92,7 @@ After the example starts, the serial port outputs the following: 10-19 23:26:22:184 Raw data: 10-19 23:26:22:188 0x43, 0x4a, 0x4b, 0x2f, 0x31, 0x38, 0x32, 0x31, 10-19 23:26:22:192 0x39, 0x31, 0x31, 0x32, 0x31, 0x35, 0x36, 0x2e, -10-19 23:26:22:197 Encry. ciphertext: +10-19 23:26:22:197 Encrypted ciphertext: 10-19 23:26:22:201 0xd5, 0xb2, 0xe1, 0x75, 0x68, 0x6d, 0xb2, 0x03, 10-19 23:26:22:206 0x63, 0x96, 0xe1, 0x70, 0xc3, 0xf9, 0xf4, 0xf3, ``` @@ -102,11 +105,13 @@ AES directly reads and writes memory through hardware. If AES input and output m ``` ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | + + diff --git a/example/hal/crc/README_EN.md b/example/hal/crc/README_EN.md index 205ab00f4..ed15c8c77 100644 --- a/example/hal/crc/README_EN.md +++ b/example/hal/crc/README_EN.md @@ -1,24 +1,26 @@ # CRC Example Source code path: example/hal/crc ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -This example demonstrates using the CRC module for CRC checksum calculations, including: + +This example demonstrates using the CRC module for CRC checksum calculations, +including: + CRC standard model calculations - Supported standard models are defined in the enumeration `HAL_CRC_Mode`. + Custom polynomial and initial value calculations ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -28,18 +30,20 @@ Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: 1. Print raw data: ```c @@ -57,98 +61,98 @@ After the example starts, the serial port outputs the following: ``` 2. CRC-7/MMC calculation result: ```c -10-20 20:35:31:710 CRC Result(mode:0): +10-20 20:35:31:710 CRC Result (mode: 0): 10-20 20:35:31:717 0x61 ``` 3. CRC_8 calculation result: ```c -10-20 20:35:31:722 CRC Result(mode:1): +10-20 20:35:31:722 CRC Result (mode: 1): 10-20 20:35:31:726 0x62 ``` 4. CRC-8/ITU calculation result: ```c -10-20 20:35:31:730 CRC Result(mode:2): +10-20 20:35:31:730 CRC Result (mode: 2): 10-20 20:35:31:734 0x37 ``` 5. CRC-8/ROHC calculation result: ```c -10-20 20:35:31:740 CRC Result(mode:3): +10-20 20:35:31:740 CRC Result (mode: 3): 10-20 20:35:31:746 0xCD ``` 6. CRC-8/MAXIM calculation result: ```c -10-20 20:35:31:750 CRC Result(mode:4): +10-20 20:35:31:750 CRC Result (mode: 4): 10-20 20:35:31:754 0xBA ``` 7. CRC-16/IBM calculation result: ```c -10-20 20:35:31:758 CRC Result(mode:5): +10-20 20:35:31:758 CRC Result (mode: 5): 10-20 20:35:31:762 0x5263 ``` 8. CRC-16/MAXIM calculation result: ```c -10-20 20:35:31:767 CRC Result(mode:6): +10-20 20:35:31:767 CRC Result (mode: 6): 10-20 20:35:31:775 0xAD9C ``` 9. CRC-16/USB calculation result: ```c -10-20 20:35:31:781 CRC Result(mode:7): +10-20 20:35:31:781 CRC Result (mode: 7): 10-20 20:35:31:785 0x72F2 ``` 10. CRC-16/MODBUS calculation result: ```c -10-20 20:35:31:794 CRC Result(mode:8): +10-20 20:35:31:794 CRC Result (mode: 8): 10-20 20:35:31:799 0x8D0D ``` 11. CRC-16/CCITT calculation result: ```c -10-20 20:35:31:806 CRC Result(mode:9): +10-20 20:35:31:806 CRC Result (mode: 9): 10-20 20:35:31:810 0xFC57 ``` 12. CRC-16/CCITT-FALSE calculation result: ```c -10-20 20:35:31:814 CRC Result(mode:10): +10-20 20:35:31:814 CRC Result (mode: 10): 10-20 20:35:31:819 0xBED ``` 13. CRC-16/X25 calculation result: ```c -10-20 20:35:31:823 CRC Result(mode:11): +10-20 20:35:31:823 CRC Result (mode: 11): 10-20 20:35:31:826 0xA52A ``` 14. CRC-16/XMODEM calculation result: ```c -10-20 20:35:31:830 CRC Result(mode:12): +10-20 20:35:31:830 CRC Result (mode: 12): 10-20 20:35:31:834 0x4A88 ``` 15. CRC-16/DNP calculation result: ```c -10-20 20:35:31:839 CRC Result(mode:13): +10-20 20:35:31:839 CRC Result (mode: 13): 10-20 20:35:31:843 0xD423 ``` 16. CRC-32 calculation result: ```c -10-20 20:35:31:847 CRC Result(mode:14): +10-20 20:35:31:847 CRC Result (mode: 14): 10-20 20:35:31:854 0x15B6B604 ``` 17. CRC-32/MPEG_2 calculation result: ```c -10-20 20:35:31:858 CRC Result(mode:15): +10-20 20:35:31:858 CRC Result (mode: 15): 10-20 20:35:31:862 0x42F1290F ``` 18. Custom polynomial and initialization calculation result: ```c -10-20 20:35:31:866 CRC Result(CRC_8 initial value:0xFF poly:0x1D): -10-20 20:35:31:869 0x45 +10-20 20:35:31:866 CRC Result (CRC_8 initial value: 0xFF, poly: 0x1D): +10-20 20:35:31:869 0x45 ``` ## Exception Diagnosis ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/hal/epic/README_EN.md b/example/hal/epic/README_EN.md index 8ac046f8c..66a9ae6ca 100644 --- a/example/hal/epic/README_EN.md +++ b/example/hal/epic/README_EN.md @@ -1,10 +1,14 @@ # HAL EPIC Example - -EPIC (ePicasso) is our self-developed graphics engine, a hardware acceleration module specifically designed for 2D/2.5D image processing, mainly used to offload CPU load in image operations and improve image processing efficiency. - +EPIC (ePicasso) is our self-developed graphics engine, a hardware acceleration +module specifically designed for 2D/2.5D image processing, mainly used to +offload CPU load in image operations and improve image processing efficiency. ## Overview -This program is a graphics blending example based on **HAL (Hardware Abstraction Layer)** interface and **EPIC**. It demonstrates how to use the HAL interface to control the EPIC hardware module for layer blending (Alpha Blending), superimposing two rectangular layers with transparency, and finally displaying them on the LCD screen. +This program is a graphics blending example based on **HAL (Hardware Abstraction +Layer)** interface and **EPIC**. It demonstrates how to use the HAL interface to +control the EPIC hardware module for layer blending (Alpha Blending), +superimposing two rectangular layers with transparency, and finally displaying +them on the LCD screen. --- @@ -22,7 +26,8 @@ This program is a graphics blending example based on **HAL (Hardware Abstraction ### Main process as follows: 1. Initialize EPIC and its underlying EZIP module. -2. Use HAL_EPIC_FillStart() to draw blue and red rectangles in two display memory buffers respectively. +2. Use HAL_EPIC_FillStart() to draw blue and red rectangles in two display + memory buffers respectively. 3. Set layer parameters and call HAL_EPIC_BlendStartEx() for layer blending. 4. Output the blended result to the LCD display device. @@ -40,36 +45,37 @@ build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat ``` Select the port as prompted for download: ```none -please input the serial port num:6 +Please input the serial port number: 6 ``` #### Example Output Result Display: -Serial port window prints as shown: -![alt text](assets/log.png) -Will display on the LCD screen as shown: -![alt text](assets/show.png) +Serial port window prints as shown: ![alt text](assets/log.png) Will display on +the LCD screen as shown: ![alt text](assets/show.png) --- - ## Example Explanation ### Key interfaces used: -| Interface Name | Function Description | -|-----------------------------|------------------------------| -| HAL_EZIP_Init() | Initialize EZIP module | -| HAL_EPIC_Init() | Initialize EPIC graphics controller | -| HAL_EPIC_LayerConfigInit()| Initialize layer configuration structure | +| Interface Name | Function Description | +| ----------------------------- | ---------------------------------------- | +| HAL_EZIP_Init() | Initialize EZIP module | +| HAL_EPIC_Init() | Initialize EPIC graphics controller | +| HAL_EPIC_LayerConfigInit() | Initialize layer configuration structure | | HAL_EPIC_LayerSetDataOffset() | Set layer data offset (for cropping) | -| HAL_EPIC_FillStart() | Start color fill operation | -| HAL_EPIC_BlendStartEx() | Start multi-layer blending operation | +| HAL_EPIC_FillStart() | Start color fill operation | +| HAL_EPIC_BlendStartEx() | Start multi-layer blending operation | --- ### Notes -Crop area settings need to be careful -Default cropping behavior: -If HAL_EPIC_LayerSetDataOffset() is not called, it defaults to cropping image data from the first address pointed to by the layer.data pointer, which is (0, 0) in this example. +Crop area settings need to be careful Default cropping behavior: If +HAL_EPIC_LayerSetDataOffset() is not called, it defaults to cropping image data +from the first address pointed to by the layer.data pointer, which is (0, 0) in +this example. #### Common issues: -If the fill area is not within the crop area, valid image data cannot be extracted, causing layer blending to fail. -Example: If the fill area is (100~250, 100~200), but the crop area is (0~150, 0~100), then the actual cropped blending data will be empty. -Solution: +If the fill area is not within the crop area, valid image data cannot be +extracted, causing layer blending to fail. Example: If the fill area is +(100~250, 100~200), but the crop area is (0~150, 0~100), then the actual cropped +blending data will be empty. Solution: * Method 1: Adjust the fill area to be within the crop area. -* Method 2: Call HAL_EPIC_LayerSetDataOffset(layer, x, y) to set the crop offset, note that the x/y passed should be target coordinates + layer.x_offset / layer.y_offset. \ No newline at end of file +* Method 2: Call HAL_EPIC_LayerSetDataOffset(layer, x, y) to set the crop + offset, note that the x/y passed should be target coordinates + layer.x_offset + / layer.y_offset. diff --git a/example/hal/ezip/README_EN.md b/example/hal/ezip/README_EN.md index 3f041b272..b4a737c84 100644 --- a/example/hal/ezip/README_EN.md +++ b/example/hal/ezip/README_EN.md @@ -3,25 +3,25 @@ Source code path: example/hal/ezip ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - + This example demonstrates EZIP usage, including: + Decompressing ezip format data. + Decompressing lz4 format data. + Decompressing gzip format data. - ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -31,44 +31,46 @@ Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - -After the example starts, the serial port outputs the following: -1. EZIP decompression (AHB output mode, polling mode), verify output results: + +After the example starts, the serial port outputs the following: +1. EZIP decompression (AHB output mode, polling mode), verify output results: ```c - 11-16 16:37:14:846 [EZIP]EZIP initialization OK. - 11-16 16:37:14:847 [EZIP]EZIP AHB (polling mode). - 11-16 16:37:14:849 [EZIP]Output is correct. - 11-16 16:37:14:851 [EZIP]EZIP AHB (polling mode) --- end. + 11-16 16:37:14:846 [EZIP] EZIP initialization successful. + 11-16 16:37:14:847 [EZIP] EZIP AHB (polling mode). + 11-16 16:37:14:849 [EZIP] Output verified. + 11-16 16:37:14:851 [EZIP] EZIP AHB (polling mode) --- completed. ``` -2. EZIP decompression (AHB output mode, interrupt mode), verify output results: +2. EZIP decompression (AHB output mode, interrupt mode), verify output results: ```c - 11-16 16:37:14:854 [EZIP]EZIP AHB (intrInterrupt mode). - 11-16 16:37:14:855 msh />[EZIP]ezip_done. - 11-16 16:37:14:857 [EZIP]Output is correct. - 11-16 16:37:14:858 [EZIP]EZIP AHB (intrInterrupt mode) --- end. + 11-16 16:37:14:854 [EZIP] EZIP AHB (interrupt mode). + 11-16 16:37:14:855 msh />[EZIP] ezip_done. + 11-16 16:37:14:857 [EZIP] Output verified. + 11-16 16:37:14:858 [EZIP] EZIP AHB (interrupt mode) --- completed. ``` 3. LZ4 decompression (AHB output mode, polling mode), verify output results: ```c - 11-16 16:37:14:859 [EZIP]LZ4 AHB (polling mode). - 11-16 16:37:14:861 [EZIP]Output is correct. - 11-16 16:37:14:863 [EZIP]LZ4 AHB (polling mode) --- end. + 11-16 16:37:14:859 [EZIP] LZ4 AHB (polling mode). + 11-16 16:37:14:861 [EZIP] Output verified. + 11-16 16:37:14:863 [EZIP] LZ4 AHB (polling mode) --- completed. ``` 3. GZIP decompression (AHB output mode, polling mode), verify output results: ```c - 11-16 16:37:14:865 [EZIP]GZIP AHB (polling mode). - 11-16 16:37:14:867 [EZIP]Output is correct. - 11-16 16:37:14:868 [EZIP]GZIP AHB (polling mode) --- end. + 11-16 16:37:14:865 [EZIP] GZIP AHB (polling mode). + 11-16 16:37:14:867 [EZIP] Output verified. + 11-16 16:37:14:868 [EZIP] GZIP AHB (polling mode) --- completed. ``` ```{tip} If you have an LCD, you can enable the following configuration. In this example, the decompressed image will be sent to the LCD for display (steps 1, 2). @@ -79,11 +81,11 @@ After the example starts, the serial port outputs the following: ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/hal/facc/README_EN.md b/example/hal/facc/README_EN.md index f4318e722..4fabc6752 100644 --- a/example/hal/facc/README_EN.md +++ b/example/hal/facc/README_EN.md @@ -1,19 +1,20 @@ # FACC Example - Source Code Path: example/hal/facc ## Supported Platforms The example can run on the following development boards: * sf32lb56-lcd series * sf32lb58-lcd series - ## Example Overview -* This example demonstrates how to initialize and use a hardware accelerator module called FACC for performing FIR (Finite Impulse Response) filtering operations, and verifies whether the output results are correct. +* This example demonstrates how to initialize and use a hardware accelerator + module called FACC for performing FIR (Finite Impulse Response) filtering + operations, and verifies whether the output results are correct. ## Example Usage ### Hardware Requirements -Before running this example, you need to prepare a supported development board and a USB data cable. +Before running this example, you need to prepare a supported development board +and a USB data cable. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: @@ -24,14 +25,13 @@ Execute the flashing command: ``` build_sf32lb58-lcd_n16r64n4_hcpu\download.bat ``` - ### Example Output * After successful flashing, the serial port will print filtering information -* If the log shows "ok" after comparison, it indicates successful filtering -![facc_result](assets/facc1.png) ### Troubleshooting -* Log information for filtering errors -![facc_fail](assets/facc2.png) -* First check if the input parameters are correct. If the input parameters are incorrect, please verify them. If the input parameters are correct, please check if the filter is working properly -* Check if the array used to store filtered data is out of bounds: `uint8_t facc_output [1024];` \ No newline at end of file +* Log information for filtering errors ![facc_fail](assets/facc2.png) +* First check if the input parameters are correct. If the input parameters are + incorrect, please verify them. If the input parameters are correct, please + check if the filter is working properly +* Check if the array used to store filtered data is out of bounds: `uint8_t + facc_output [1024];` diff --git a/example/hal/fft/index_EN.md b/example/hal/fft/index_EN.md index 64bcaf1ee..cbe2a0523 100644 --- a/example/hal/fft/index_EN.md +++ b/example/hal/fft/index_EN.md @@ -5,6 +5,4 @@ :glob: */* - - ``` diff --git a/example/hal/fft/simple/README_EN.md b/example/hal/fft/simple/README_EN.md index 1bb76c7d4..c829c60f7 100644 --- a/example/hal/fft/simple/README_EN.md +++ b/example/hal/fft/simple/README_EN.md @@ -15,14 +15,18 @@ This example demonstrates the following basic FFT operations: ## Usage -The following sections provide only absolutely necessary information. For complete steps on configuring SiFli-SDK and building/running projects, please refer to the [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +The following sections provide only absolutely necessary information. For +complete steps on configuring SiFli-SDK and building/running projects, please +refer to the [SiFli-SDK Quick Start +Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) ### Hardware Requirements -This example requires no special hardware configuration. Simply connect the development board to your computer via USB. +This example requires no special hardware configuration. Simply connect the +development board to your computer via USB. -## Example Output +### Expected Results -Under normal circumstances, you will see the following output: +The expected output is as follows: ```log ========================================= @@ -80,16 +84,16 @@ Inverse FFT completed successfully ========================================= ``` -## Troubleshooting +## Example Output -For any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +Under normal circumstances, you will see the following output: -## Reference Documentation +## Troubleshooting - [SiFli-SDK Official Documentation](https://docs.sifli.com/) -## Update History -| Version | Date | Release Notes | -|:--------|:--------|:--------------| -| 1.0.0 | 6/2025 | Initial version | -| | | | \ No newline at end of file +## Reference Documentation +| Version | Date | Release Notes | +| ------- | --------- | --------------- | +| 1.0.0 | June 2025 | Initial release | +| | | | diff --git a/example/hal/gpio/README_EN.md b/example/hal/gpio/README_EN.md index 06896be5c..fc5970cbc 100644 --- a/example/hal/gpio/README_EN.md +++ b/example/hal/gpio/README_EN.md @@ -6,38 +6,47 @@ The example can run on the following development boards. * sf32lb52-lcd series * sf32lb58-lcd series * sf32lb56-lcd series +* sf32lb56-lcd series + ## Example Overview -* Configure GPIO output and input interrupt operations to demonstrate GPIO HAL functions -* Toggle GPIO_out level value every second, input GPIO triggers interrupt on rising and falling edges, printing interrupt information via serial port +* Configure GPIO output and input interrupt operations to demonstrate GPIO HAL + functions +* Toggle GPIO_out level value every second, input GPIO triggers interrupt on + rising and falling edges, printing interrupt information via serial port ## GPIO Overview -The HAL GPIO module provides an abstract software interface to operate the hardware GPIO module. -HPSYS and LPSYS each have a GPIO module, with supported features including: +The HAL GPIO module provides an abstract software interface to operate the +hardware GPIO module. HPSYS and LPSYS each have a GPIO module, with supported +features including: - Output mode -- Input mode, can detect input level to trigger interrupts, supports high level, low level, rising edge, falling edge, and dual edge detection +- Input mode, can detect input level to trigger interrupts, supports high level, + low level, rising edge, falling edge, and dual edge detection -The hardware GPIO module of HPSYS is `hwp_gpio1` (or called GPIO_A), and the hardware GPIO module of LPSYS is `hwp_gpio2` (or called GPIO_B). +The hardware GPIO module of HPSYS is `hwp_gpio1` (or called GPIO_A), and the +hardware GPIO module of LPSYS is `hwp_gpio2` (or called GPIO_B). ```{note} If you need to set GPIO pins for other functions, or change pull-up/pull-down drive capability, please refer to pinmux settings [PINMUX](#hal-pinmux) ``` -For detailed API description, refer to [GPIO](#hal-gpio) +For detailed API description, refer to [GPIO](#hal-gpio) ## Example Usage ### Hardware Connection -* Note: Connect the input GPIO and output GPIO with a jumper wire, so that the GPIO_out level transition can be assigned to GPIO_in to achieve the effect of entering the interrupt and printing information +* Note: Connect the input GPIO and output GPIO with a jumper wire, so that the + GPIO_out level transition can be assigned to GPIO_in to achieve the effect of + entering the interrupt and printing information -|Development Board |OUT Pin |OUT Pin Name|IN Pin |IN Pin Name | -|:--- |:--- |:--- |:--- |:--- | -|sf32lb52-lcd_n16r8 |5 |PA41 |3 |PA42 | -|sf32lb58-lcd_n16r64n4 |5 |PB28 |3 |PB29 | -|sf32lb56-lcd_n16r12n1 |5 |PA20 |3 |PB12 | +| Development Board | OUT Pin | OUT Pin Name | IN Pin | IN Pin Name | +| --------------------- | ------- | ------------ | ------ | ----------- | +| sf32lb52-lcd_n16r8 | 5 | PA41 | 3 | PA42 | +| sf32lb58-lcd_n16r64n4 | 5 | PA41 | 3 | PA42 | +| sf32lb56-lcd_n16r12n1 | 5 | PA20 | 3 | PB12 | +| sf32lb56-lcd | 5 | PA20 | 3 | PB12 | -* For more detailed pin definitions, please refer to -`[sf32lb52-lcd_n16r8]()` -`[sf32lb58-lcd_n16r64n4]()` +* For more detailed pin definitions, please refer to `[sf32lb52-lcd_n16r8]()` + `[sf32lb58-lcd_n16r64n4]()` ### Compilation and Programming #### SF525 Project Code Compilation @@ -47,14 +56,15 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` #### SF587 Project Code Compilation @@ -64,7 +74,8 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -Run `build_sf32lb58-lcd_n16r64n4_hcpu\download.bat`, the program downloads automatically via JLink: +Run `build_sf32lb58-lcd_n16r64n4_hcpu\download.bat`, the program downloads +automatically via JLink: ``` build_sf32lb58-lcd_n16r64n4_hcpu\download.bat @@ -74,43 +85,43 @@ build_sf32lb58-lcd_n16r64n4_hcpu\download.bat ### Example Output Results Display: * Log output: ``` - Serial:c2,Chip:2,Package:0,Rev:1 Reason:00000000 +Serial:c2,Chip:2,Package:0,Rev:1 Reason:00000000 \ | / - SiFli Corporation - / | \ build on Dec 18 2024, 2.1.7 build bb6471d6 + / | \ Build on Dec 18 2024, 2.1.7 build bb6471d6 2020 - 2022 Copyright by SiFli team - mount /dev sucess - [D/USBD] No class register on usb device + mount /dev success + [D/USBD] No class registered on USB device [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [I/drv.rtc] RTC use LXT RTC_CR=00000000 [I/drv.rtc] Init RTC, wake = 0 [I/drv.sdhci] rt_hw_sdmmc_init 2 begin - [I/drv.sdhci] host version = 2 + [I/drv.sdhci] Host version = 2 [I/drv.sdhci] SDHCI clock 288000000 - [I/drv.sdhci] Maximum Clock Supported by HOST : 288 MHz - [I/drv.sdhci] host minclock 400000 host maxclock 288000000 + [I/drv.sdhci] Maximum Clock Supported by HOST: 288 MHz + [I/drv.sdhci] Host minclock 400000 host maxclock 288000000 [I/drv.sdhci] SDHCI controller on sdmmc2 using DMA [I/drv.sdhci] Add host success [I/drv.sdhci] rt_hw_sdmmc_init 2 done - [I/drv.audprc] init 00 ADC_PATH_CFG0 0x924 + [I/drv.audprc] Init 00 ADC_PATH_CFG0 0x924 [I/drv.audprc] HAL_AUDPRC_Init res 0 [I/drv] HAL_AUDCODEC_Init res 0 - call par CFG1(35bb) + Call par CFG1(35bb) fc 9, xtal 2000, pll 2054 - call par CFG1(35bb) + Call par CFG1(35bb) fc 9, xtal 2000, pll 2054 - Start gpio demo! + Start GPIO demo! ``` When GPIO_out level inverts every second: ``` Interrupt occurred! -Pin_Out 41 has been toggle, value = 1 +Pin_Out 41 has been toggled, value = 1 Pin_In 42, value = 1 ``` After 1 second toggle: ``` Interrupt occurred! -Pin_Out 41 has been toggle, value = 0 +Pin_Out 41 has been toggled, value = 0 Pin_In 42, value = 0 ``` ## Example Description @@ -144,32 +155,34 @@ Adapt to different pin configurations on different development boards #endif ``` -### Output Mode +### Output mode Configure `GPIO1 pin41` (i.e., GPIO_A41) as output mode ```C GPIO_InitStruct.Pin = Pin_Out; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; -HAL_GPIO_Init(hwp_gpio, &GPIO_InitStruct); +HAL_GPIO_Init(hwp_gpio, &GPIO_InitStruct); ``` ### Input Mode (with interrupt) #### GPIO Initialization -Configure `GPIO1 pin42` (i.e., GPIO_A42) as input mode with rising and falling edge detection +Configure `GPIO1 pin42` (i.e., GPIO_A42) as input mode with rising and falling +edge detection ```C -PIO_InitStruct.Pin = Pin_In; -GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; //Set interrupt to trigger on raising and falling edge +GPIO_InitStruct.Pin = Pin_In; +GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; // Set interrupt to trigger on rising and falling edges GPIO_InitStruct.Pull = GPIO_NOPULL; -HAL_GPIO_Init(hwp_gpio, &GPIO_InitStruct); +HAL_GPIO_Init(hwp_gpio, &GPIO_InitStruct); HAL_NVIC_SetPriority(GPIO_IRQn, 2, 1); // Configure NVIC priority ``` #### Interrupt Service Function -Find the interrupt service function according to the interrupt vector table in the startup file +Find the interrupt service function according to the interrupt vector table in +the startup file ```C -void GPIO1_IRQHandler(void) // Define the interrupt siervice routine (ISR) according to the interrupt vector table +void GPIO1_IRQHandler(void) // Define the Interrupt Service Routine (ISR) according to the interrupt vector table { HAL_GPIO_IRQHandler(hwp_gpio); } @@ -177,23 +190,23 @@ void GPIO1_IRQHandler(void) // Define the interrupt siervice routine (ISR) accor #### Interrupt Callback Function ```C -// override the weak Callback to add user defined action, it's called by HAL_GPIO_EXTI_IRQHandler +// Override the weak callback to implement user-defined actions; called by HAL_GPIO_EXTI_IRQHandler void HAL_GPIO_EXTI_Callback(GPIO_TypeDef *hgpio, uint16_t GPIO_Pin) { if (GPIO_Pin == Pin_In) { rt_kprintf("Interrupt occurred!\n"); - rt_kprintf("Pin_Out %d has been toggle, value = %d\n", Pin_Out, HAL_GPIO_ReadPin(hwp_gpio, Pin_Out)); + rt_kprintf("Pin_Out %d has been toggled, value = %d\n", Pin_Out, HAL_GPIO_ReadPin(hwp_gpio, Pin_Out)); rt_kprintf("Pin_In %d, value = %d\n", Pin_In, HAL_GPIO_ReadPin(hwp_gpio, Pin_In)); rt_kprintf(" \n"); } } ``` ## API Reference -[](#hal-gpio) +[] ## Update Log -|Version |Date |Release Notes | -|:--- |:--- |:--- | -|0.0.1 |12/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | diff --git a/example/hal/hash/README_EN.md b/example/hal/hash/README_EN.md index 63d84cb45..f0ece7d44 100644 --- a/example/hal/hash/README_EN.md +++ b/example/hal/hash/README_EN.md @@ -1,13 +1,14 @@ # HASH Example Source code path: example/hal/hash ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series ## Overview - -This example demonstrates using the HASH engine for HASH calculations, including: + +This example demonstrates using the HASH engine for HASH calculations, +including: + Single HASH calculation (data not split, synchronous polling mode) - SHA1 - SHA224 @@ -19,11 +20,12 @@ This example demonstrates using the HASH engine for HASH calculations, including - SHA1 ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -33,18 +35,20 @@ Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: 1. Print raw data: ```c @@ -118,16 +122,16 @@ After the example starts, the serial port outputs the following: ``` 6. SHA1 algorithm calculation (interrupt mode): ```c -10-19 22:13:46:349 SHA1(IT): -10-19 22:13:46:353 HASH Result(IT): +10-19 22:13:46:349 SHA1 (Iterative): +10-19 22:13:46:353 HASH Result (Iterative): 10-19 22:13:46:357 0x8a, 0x50, 0x60, 0xae, 0x38, 0xfd, 0x7c, 0x73, 10-19 22:13:46:362 0x5b, 0x85, 0x53, 0x41, 0x51, 0x99, 0x77, 0xb7, 10-19 22:13:46:368 0x8f, 0x91, 0xee, 0x70, ``` 7. SHA1 algorithm calculation (multiple calculation mode with data splitting): ```c -10-19 22:13:46:373 SHA1(multiple): -10-19 22:13:46:377 HASH Result(multiple): +10-19 22:13:46:373 SHA1 (Multiple Blocks): +10-19 22:13:46:377 HASH Result (Multiple Blocks): 10-19 22:13:46:382 0x8a, 0x50, 0x60, 0xae, 0x38, 0xfd, 0x7c, 0x73, 10-19 22:13:46:386 0x5b, 0x85, 0x53, 0x41, 0x51, 0x99, 0x77, 0xb7, 10-19 22:13:46:391 0x8f, 0x91, 0xee, 0x70, @@ -141,11 +145,11 @@ If HASH input and output memory uses PSRAM, attention must be paid to cache sync ``` ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/hal/hwtimer/README_EN.md b/example/hal/hwtimer/README_EN.md index aedfff69d..e37a20eb4 100644 --- a/example/hal/hwtimer/README_EN.md +++ b/example/hal/hwtimer/README_EN.md @@ -3,25 +3,26 @@ Source code path: example/hal/hwtimer0 ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series - ## Overview - + This example uses GPTIM1, ATIM1, and BTIM1 to demonstrate HWTIMER usage: + GPTIM single-shot and repetitive interrupts. -+ ATIM single-shot and multiple interrupts (ATIM supports configurable repeat count, generating interrupts after completing the configured count). ++ ATIM single-shot and multiple interrupts (ATIM supports configurable repeat + count, generating interrupts after completing the configured count). + BTIM single-shot and repetitive interrupts. ## Example Usage - - + + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -31,25 +32,27 @@ Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -`build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +`build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted +to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: 1. GPTIM single-shot mode, timeout time 3.5s: ```c 12-05 21:47:16:619 GPTIM1: SINGLE. Timeout is 3.5 seconds 12-05 21:47:16:621 Prescaler:12000 PCLK:120000000 period:35000 12-05 21:47:16:623 Timer init ok -12-05 21:47:16:730 msh /> +12-05 21:47:16:730 msh /> 12-05 21:47:20:091 GPTIM1 timeout 3501 12-05 21:47:20:094 GPTIM1: SINGLE. END. ``` @@ -81,7 +84,8 @@ After the example starts, the serial port outputs the following: 12-05 21:47:58:596 ATIM1: SINGLE. END. ``` -4. ATIM repetitive mode, timeout time 3.5s each time, configured repeat count 10, interrupt generated after 3.5s * 10 times: +4. ATIM repetitive mode, timeout time 3.5s each time, configured repeat count + 10, interrupt generated after 3.5s * 10 times: ```c 12-05 21:47:58:600 ATIM1: REPETITIVE. Timeout is (3.5 * 10) seconds. 12-05 21:47:58:645 Prescaler:12000 PCLK:120000000 period:35000 @@ -120,23 +124,22 @@ After the example starts, the serial port outputs the following: ## Exception Diagnosis -1. Counting inaccuracy -GPTIM/BTIM prescaler configuration is 16-bit, based on PCLK division. Need to confirm if the prescaler overflows 16-bit: +1. Counting inaccuracy GPTIM/BTIM prescaler configuration is 16-bit, based on + PCLK division. Need to confirm if the prescaler overflows 16-bit: ```c -tim->Init.Prescaler = HAL_RCC_GetPCLKFreq(core_id, 1) / FREQENCY; /*Prescaler is 16 bits, please select correct frequency*/ +tim->Init.Prescaler = HAL_RCC_GetPCLKFreq(core_id, 1) / FREQENCY; /*Prescaler is 16 bits; ensure the correct frequency is selected*/ ``` -2. HWTIM not working -Confirm if RCC is enabled, for example: +2. HWTIM not working Confirm if RCC is enabled, for example: ```c -HAL_RCC_EnableModule(RCC_MOD_BTIM1); /* Enable btim1 rcc */ +HAL_RCC_EnableModule(RCC_MOD_BTIM1); /* Enable BTIM1 RCC clock */ ``` ## Reference Documents ## Update Log -|Version |Date |Release Notes| -|:---|:---|:---| -|0.0.1|12/2024|Initial version| -|||| -|||| \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | +| | | | diff --git a/example/hal/i2c/eeprom/README_EN.md b/example/hal/i2c/eeprom/README_EN.md index 3f7a71aaa..5a14f990f 100644 --- a/example/hal/i2c/eeprom/README_EN.md +++ b/example/hal/i2c/eeprom/README_EN.md @@ -6,31 +6,29 @@ The example can run on the following development boards. * sf32lb58-lcd series * sf32lb56-lcd series - ## Overview -* Demonstrate I2C HAL functions through read/write operations on EEPROM chip AT24CO8SC module +* Demonstrate I2C HAL functions through read/write operations on EEPROM chip + AT24CO8SC module ## Example Usage ### Hardware Connection Connect AT24CO8SC's VCC and GND to 5V and GND respectively for power supply -Connect AT24CO8SC's SDA and SCK according to the table below based on the development board model +Connect AT24CO8SC's SDA and SCK according to the table below based on the +development board model -|Development Board |SDA Pin|SDA Pin Name|SCL Pin|SCL Pin Name| -|:--- |:--- |:--- |:--- |:--- | -|sf32lb52-lcd |3 |PA42 |5 |PA41 | -|sf32lb58-lcd |3 (CONN1) |PB29 |5 (CONN1) |PB28 | -|sf32lb56-lcd |3 |PA12 |5 |PA20 | +| Development Board | SDA Pin | SDA Pin Name | SCL Pin | SCL Pin Name | +| ----------------- | --------- | ------------ | --------- | ------------ | +| sf32lb52-lcd | 3 | PA42 | 5 | PA41 | +| sf32lb58-lcd | 3 (CONN1) | PB29 | 5 (CONN1) | PB28 | +| sf32lb56-lcd | 3 | PA12 | 5 | PA20 | * For more detailed pin definitions, please refer to -[sf32lb52-lcd](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) -[sf32lb56-lcd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) -[sf32lb58-lcd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) - - -* AT24C08SC -![alt text](assets/at24c08sc.png) + [sf32lb52-lcd](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) + [sf32lb56-lcd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) + [sf32lb58-lcd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) +* AT24C08SC ![alt text](assets/at24c08sc.png) ### Compilation and Programming #### SF525 Project Code Compilation @@ -40,14 +38,15 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` #### SF587 Project Code Compilation @@ -57,7 +56,8 @@ Switch to the example project directory and run the scons command to compile: scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -`build_sf32lb52-lcd_n16r8_hcpu\download.bat`, the program downloads automatically via JLink: +`build_sf32lb52-lcd_n16r8_hcpu\download.bat`, the program downloads +automatically via JLink: ``` build_sf32lb58-lcd_n16r64n4_hcpu\download.bat @@ -66,20 +66,20 @@ build_sf32lb58-lcd_n16r64n4_hcpu\download.bat ### Example Output Results Display: * Log output: ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000000 \ | / - SiFli Corporation / | \ build on Nov 29 2024, 2.1.7 build 91ecc2d9 Copyright by SiFli team - mount /dev sucess + mount /dev success [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [I/drv.rtc] RTC use LXT RTC_CR=00000001 [I/drv.rtc] Init RTC, wake = 0 [I/drv.audprc] init 00 ADC_PATH_CFG0 0x606 [I/drv.audprc] HAL_AUDPRC_Init res 0 [I/drv.audcodec] HAL_AUDCODEC_Init res 0 - [32m][I/TOUCH] Regist touch screen driver, probe=1203ba81 [0m] + [32m][I/TOUCH] Registered touch screen driver, probe=1203ba81 [0m] call par CFG1(35bb) fc 9, xtal 2000, pll 2123 call par CFG1(35bb) @@ -98,66 +98,67 @@ build_sf32lb58-lcd_n16r64n4_hcpu\download.bat ``` ### I2C Read/Write Waveforms #### I2C read/write waveforms required by AT24C08SC chip manual -* I2C write waveform -![alt text](assets/i2c_byte_write.png) -* I2C read waveform -![alt text](assets/i2c_random_read.png) +* I2C write waveform ![alt text](assets/i2c_byte_write.png) +* I2C read waveform ![alt text](assets/i2c_random_read.png) #### Logic analyzer captured partial waveforms -* I2C write waveform -![alt text](assets/i2c_w.png) -* I2C read waveform -![alt text](assets/i2c_r.png) +* I2C write waveform ![alt text](assets/i2c_w.png) +* I2C read waveform ![alt text](assets/i2c_r.png) #### I2C Parameter Modification * See comments in EEPROM_init function ```c -/// @brief Initialization work before power on EEPROM +/// @brief Performs initialization before powering on the EEPROM. /// @param void EEPROM_init(void) { - uint8_t slaveAddr = EEPROM_I2C_ADDRESS; // 7bit address of device + uint8_t slaveAddr = EEPROM_I2C_ADDRESS; // 7-bit device address HAL_StatusTypeDef ret; - //1. pin mux + //1. Pin multiplexing configuration #ifdef SF32LB52X - HAL_RCC_EnableModule(RCC_MOD_I2C2); // enable i2c2 - #define EXAMPLE_I2C I2C2 // i2c number of cpu - #define EXAMPLE_I2C_IRQ I2C2_IRQn // i2c number of interruput when using interrupte mode - HAL_PIN_Set(PAD_PA41, I2C2_SCL, PIN_PULLUP, 1); // i2c io select + HAL_RCC_EnableModule(RCC_MOD_I2C2); // Enable I2C2 clock + #define EXAMPLE_I2C I2C2 // CPU I2C instance + #define EXAMPLE_I2C_IRQ I2C2_IRQn // I2C interrupt number for interrupt mode + HAL_PIN_Set(PAD_PA41, I2C2_SCL, PIN_PULLUP, 1); // Select I2C IO HAL_PIN_Set(PAD_PA42, I2C2_SDA, PIN_PULLUP, 1); #elif defined(SF32LB58X) - #define EXAMPLE_I2C I2C6 // i2c number of cpu - #define EXAMPLE_I2C_IRQ I2C6_IRQn // i2c number of interruput when using interrupte mode - HAL_PIN_Set(PAD_PB28, I2C6_SCL, PIN_PULLUP, 1); // i2c io select + #define EXAMPLE_I2C I2C6 // CPU I2C instance + #define EXAMPLE_I2C_IRQ I2C6_IRQn // I2C interrupt number for interrupt mode + HAL_PIN_Set(PAD_PB28, I2C6_SCL, PIN_PULLUP, 1); // Select I2C IO HAL_PIN_Set(PAD_PB29, I2C6_SDA, PIN_PULLUP, 1); #elif defined(SF32LB56X) -#define EXAMPLE_I2C I2C3 // i2c number of cpu -#define EXAMPLE_I2C_IRQ I2C3_IRQn // i2c number of interruput when using interrupte mode - HAL_PIN_Set(PAD_PA20, I2C3_SCL, PIN_PULLUP, 1); // i2c io select +#define EXAMPLE_I2C I2C3 // CPU I2C instance +#define EXAMPLE_I2C_IRQ I2C3_IRQn // I2C interrupt number for interrupt mode + HAL_PIN_Set(PAD_PA20, I2C3_SCL, PIN_PULLUP, 1); // Select I2C IO HAL_PIN_Set(PAD_PA12, I2C3_SDA, PIN_PULLUP, 1); #endif - // 2. i2c init + // 2. I2C peripheral initialization i2c_Handle.Instance = EXAMPLE_I2C; - i2c_Handle.Mode = HAL_I2C_MODE_MASTER; // i2c master mode - i2c_Handle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; // i2c 7bits device address mode - i2c_Handle.Init.ClockSpeed = 400000; // i2c speed (hz) + i2c_Handle.Mode = HAL_I2C_MODE_MASTER; // I2C master mode + i2c_Handle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; // 7-bit addressing mode + i2c_Handle.Init.ClockSpeed = 400000; // I2C clock speed (Hz) i2c_Handle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; - ret = HAL_I2C_Init(&i2c_Handle); + ret = HAL_I2C_Init(&i2c_Handle); rt_kprintf("EEPROM_init%d\n", ret); } ``` -* Distinguish development boards based on chip type. In the initialization function, configure corresponding I2C pins for specific chips -* For example, use `#elif defined(SF32LB52X)` chip to determine which development board is being used -* Use `#define EXAMPLE_I2C I2C2` for the I2C controller number used by that chip (such as I2C6, I2C3) -* Use `#define EXAMPLE_I2C_IRQ I2C6_IRQn` for the interrupt number corresponding to that I2C controller (for interrupt mode) -* Finally configure I2C SCL and SDA pins through HAL_PIN_Set() function, and need to set to pull-up mode - -**Note**: -1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART function to output I2C SDA, SCLK waveforms -2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu - -* AT24C08SC device address -![alt text](assets/at24c08sc_device_address.png) - +* Distinguish development boards based on chip type. In the initialization + function, configure corresponding I2C pins for specific chips +* For example, use `#elif defined(SF32LB52X)` chip to determine which + development board is being used +* Use `#define EXAMPLE_I2C I2C2` for the I2C controller number used by that chip + (such as I2C6, I2C3) +* Use `#define EXAMPLE_I2C_IRQ I2C6_IRQn` for the interrupt number corresponding + to that I2C controller (for interrupt mode) +* Finally configure I2C SCL and SDA pins through HAL_PIN_Set() function, and + need to set to pull-up mode + +**Note**: +1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART function + to output I2C SDA, SCLK waveforms +2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select + hcpu, 0: select lcpu + +* AT24C08SC device address ![alt text](assets/at24c08sc_device_address.png) #### I2C Register Read Method Modification In EEPROM_read_data function @@ -167,31 +168,32 @@ void EEPROM_read_data(uint8_t addr, uint8_t *pdata) HAL_StatusTypeDef ret; uint8_t buf = 0; - __HAL_I2C_ENABLE(&i2c_Handle); // for master, enable it before transmit + __HAL_I2C_ENABLE(&i2c_Handle); // Enable the I2C master before transmission // 5. Read register value after write - // device need stop condition before read - // ret = HAL_I2C_Master_Transmit(&i2c_Handle, EEPROM_I2C_ADDRESS, &addr, 1, 1000); - // ret = HAL_I2C_Master_Receive(&i2c_Handle, EEPROM_I2C_ADDRESS, (uint8_t *)pdata, 2, 1000); + // Device requires a STOP condition before reading + // ret = HAL_I2C_Master_Transmit(&i2c_Handle, EEPROM_I2C_ADDRESS, &addr, 1, 1000); + // ret = HAL_I2C_Master_Receive(&i2c_Handle, EEPROM_I2C_ADDRESS, (uint8_t *)pdata, 2, 1000); - // device can read without stop condition, restart condition instead - ret = HAL_I2C_Mem_Read(&i2c_Handle, EEPROM_I2C_ADDRESS, addr, 1, &buf, 2, 1000); + // Device supports reading via a RESTART condition without a STOP condition + ret = HAL_I2C_Mem_Read(&i2c_Handle, EEPROM_I2C_ADDRESS, addr, 1, &buf, 2, 1000); *pdata = buf; rt_kprintf("i2c read reg:0x%x,pdata:0x%x,ret:%d\n", addr, *pdata, ret); - __HAL_I2C_DISABLE(&i2c_Handle); // for master, disable it after transmit to reduce error status + __HAL_I2C_DISABLE(&i2c_Handle); // Disable the I2C master after transmission to minimize error flags } ``` -Some I2C peripherals require a STOP signal after sending the register address when reading a specific register. This requires +Some I2C peripherals require a STOP signal after sending the register address +when reading a specific register. This requires ```c -ret = HAL_I2C_Mem_Read(&i2c_Handle, EEPROM_I2C_ADDRESS, addr, 1, &buf, 2, 1000); +ret = HAL_I2C_Mem_Read(&i2c_Handle, EEPROM_I2C_ADDRESS, addr, 1, &buf, 2, 1000); ``` to be modified to the following method ```c -ret = HAL_I2C_Master_Transmit(&i2c_Handle, EEPROM_I2C_ADDRESS, &addr, 1, 1000); -ret = HAL_I2C_Master_Receive(&i2c_Handle, EEPROM_I2C_ADDRESS, (uint8_t *)pdata, 2, 1000); +ret = HAL_I2C_Master_Transmit(&i2c_Handle, EEPROM_I2C_ADDRESS, &addr, 1, 1000); +ret = HAL_I2C_Master_Receive(&i2c_Handle, EEPROM_I2C_ADDRESS, (uint8_t *)pdata, 2, 1000); ``` @@ -200,15 +202,14 @@ ret = HAL_I2C_Master_Receive(&i2c_Handle, EEPROM_I2C_ADDRESS, (uint8_t *)pdata, 1. Check against chip manual if CPU I2C selection is correct 2. Check if IO configuration and connection are correct * Consecutive write failures, I2C waveform normal, no acknowledge signal -1. AT24C08SC requires up to 5ms Write Cycle Time wait for data programming during write input - - +1. AT24C08SC requires up to 5ms Write Cycle Time wait for data programming + during write input ## Reference Documents * [AT24C08SC](./assets/at24c02sc.pdf) ## Update Log -|Version |Date |Release Notes | -|:--- |:--- |:--- | -|0.0.1 |12/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | diff --git a/example/hal/i2c/index_EN.md b/example/hal/i2c/index_EN.md index b97ec4cc9..87ab88327 100644 --- a/example/hal/i2c/index_EN.md +++ b/example/hal/i2c/index_EN.md @@ -5,5 +5,4 @@ :glob: */* - ``` diff --git a/example/hal/index_EN.md b/example/hal/index_EN.md index f3c23485b..6c74a65d5 100644 --- a/example/hal/index_EN.md +++ b/example/hal/index_EN.md @@ -1,12 +1,12 @@ # HAL interface example -This example demonstrates how to access hardware modules using HAL layer interfaces. +This example demonstrates how to access hardware modules using HAL layer +interfaces. + ```{toctree} :titlesonly: :glob: */* - - ``` diff --git a/example/hal/nnacc/README_EN.md b/example/hal/nnacc/README_EN.md index 3c6016baa..73087d762 100644 --- a/example/hal/nnacc/README_EN.md +++ b/example/hal/nnacc/README_EN.md @@ -1,20 +1,20 @@ # NNACC Example - Source Path: example/hal/nnacc - ## Supported Platforms This example can run on the following development boards: * sf32lb58-lcd_a128r32n1_dsi ## Overview -NNACC (Neural Network Accelerator) is a dedicated hardware module in Sifli chips designed to accelerate the following tasks: +NNACC (Neural Network Accelerator) is a dedicated hardware module in Sifli chips +designed to accelerate the following tasks: + Convolutional calculations (Conv2D) + Depthwise separable convolution + Gaussian filtering + Other AI inference-related operations -This example verifies whether the hardware accelerator on the chip can correctly perform Depthwise Convolution operations. +This example verifies whether the hardware accelerator on the chip can correctly +perform Depthwise Convolution operations. ## Example Usage @@ -32,29 +32,32 @@ main() ``` ### Compilation and Flashing -Switch to the example project directory and run the scons command to compile (board=board_type): +Switch to the example project directory and run the scons command to compile +(board=board_type): ``` scons --board=sf32lb58-lcd_a128r32n1_dsi -j8 ``` -Execute `build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat` and select the port as prompted to download: +Execute `build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat` and select the +port as prompted to download: ``` build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please enter the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example (with nnacc support) +Before running this example, you need to prepare a development board supported +by this example (with nnacc support) ``` **Note**: 1. In sf32lb58x, the big core uses hwp_nnacc1 by default, and the small core uses hwp_nnacc2 by default. For specific chip configurations, please refer to the corresponding register.h file 2. sf32lb56x only has one hwp_nnacc1 in the big core, and no nnacc in the small core. For specific chip configurations, please refer to the corresponding register.h file - ``` ### menuconfig Configuration @@ -75,15 +78,19 @@ HAL_NNACC_Start. Test passed: NNACC result is correct. msh /> ``` - - +``` Routine Log: ``` Buffers initialized successfully. testcase start. +fill_with_random_data. 2000fc60 20012808 20012894 200182bc, sp=2000e35f +HAL_NNACC_Start. Test passed: NNACC result is correct. msh /> +``` ## Troubleshooting -If the expected log does not appear, you can troubleshoot from the following aspects: -* Whether the hardware supports nnacc +If the expected log output does not appear, check the following: +* Verify whether the hardware supports NNACC. -## Reference Documentation -## Update History -| Version | Date | Release Notes | +## Reference Documents + +## Revision History +| Version | Date | Release Notes | |:---|:---|:---| -| 0.0.1 | 7/2025 | Initial version | \ No newline at end of file +| 0.0.1 | 07/2025 | Initial release | +``` diff --git a/example/hal/pwm/README_EN.md b/example/hal/pwm/README_EN.md index 56410df12..50ca2d891 100644 --- a/example/hal/pwm/README_EN.md +++ b/example/hal/pwm/README_EN.md @@ -10,24 +10,26 @@ The example can run on the following development boards. * Contains examples of GPtimer outputting PWM through IO ports * Contains examples of using Atimer to output complementary PWM through IO - ## Example Usage ### Compilation and Programming -Switch to the example project directory and run the scons command to compile (board=board type): +Switch to the example project directory and run the scons command to compile +(board=board type): ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -`build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +`build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted +to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ### GPtimer Output PWM #### Example Output Results Display: * Log output: @@ -36,31 +38,35 @@ SFBL Start gtimer pwm demo! GPT_clock 24000000,psc 2, Period 60000,Pulse 12000 gtimer pwm demo end! -msh /> +msh /> ``` -* PA09 outputs PWM waveform (default 200Hz, 20% duty cycle) -![alt text](assets/gptimer_pwm.jpg) +* PA09 outputs PWM waveform (default 200Hz, 20% duty cycle) ![alt + text](assets/gptimer_pwm.jpg) #### PWM Parameter Modification * IO output modification Physical position refers to the actual pin position on the board's header -|Board Name | PWM | CHX | Pin (Physical Position) | -|--------|------------|--------|---------| -|sf32lb52-nano | GPTIM2 | CH1 | PA09 (manually routed from back side) | -|sf32lb52-lcd | GPTIM2 | CH1 | PA09 (37) | -|sf32lb56-lcd | GPTIM2 | CH1 | PA36 (40) | -|sf32lb58-lcd | GPTIM1 | CH2 | PA51 (CONN2 28) | +| Board Name | PWM | CHX | Pin (Physical Position) | +| ------------- | ------ | --- | ------------------------------------- | +| sf32lb52-nano | GPTIM2 | CH1 | PA09 (manually routed from back side) | +| sf32lb52-lcd | GPTIM2 | CH1 | PA09 (37) | +| sf32lb56-lcd | GPTIM2 | CH1 | PA36 (40) | +| sf32lb58-lcd | GPTIM1 | CH2 | PA51 (CONN2 28) | ```c - #define PAD_PA_09 PAD_PA09 /* 52 series default PA09 output (physical position 37) */ +#define PAD_PA_09 PAD_PA09 /* 52 series default PA09 output (physical position 37) */ HAL_PIN_Set(PAD_PA_09, cfg->pad_func, PIN_PULLUP, 1);/*Configure PA09 as GPTIM2_CH1 function*/ #define PAD_PA_51 PAD_PA51/* 58 series default PA51 output (physical position CONN2 28) */ HAL_PIN_Set(PAD_PA_51, cfg->pad_func, PIN_PULLUP, 1);/*Configure PA51 as GPTIM1_CH2 function*/ ``` -**Note**: -1. Except for 55x chips, can be configured to any IO with PA_TIM function to output PWM waveform (to query pin multiplexing table, you can search for the corresponding board type pin multiplexing in the project path files such as: bf0_pin_const.c) -2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +**Note**: +1. Except for 55x chips, can be configured to any IO with PA_TIM function to + output PWM waveform (to query pin multiplexing table, you can search for the + corresponding board type pin multiplexing in the project path files such as: + bf0_pin_const.c) +2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select + hcpu, 0: select lcpu * PWM period period, pulse width pulse modification ```c @@ -77,7 +83,8 @@ Physical position refers to the actual pin position on the board's header #endif ``` 1. Parameter: 5000000 unit is ns, corresponding period is 1/0.005s=200Hz -2. Parameter: 1000000 unit is ns, represents the pulse width of PWM output 1 in one period, cannot be greater than the above parameter, +2. Parameter: 1000000 unit is ns, represents the pulse width of PWM output 1 in + one period, cannot be greater than the above parameter, - 1000000/5000000=1/5=20% duty cycle ### ATtimer Output Complementary PWM #### Example Output Results Display: @@ -107,26 +114,33 @@ ATIM1_Stop! atimer pwm demo end! ``` Physical position refers to the pin position corresponding to the board's header -|Board Name | PWM | Output Channel1 | Output Channel2 | -|--------|------------|---------------|-------------------| -|525 | ATIM1 | PAD_PA00 (physical position 32), PAD_PA02 (physical position 36) | PAD_PA03 (physical position 40), PAD_PA03 (physical position 38) | -|587 | ATIM2 | PAD_PA84 (conn2 21), PAD_PA86 (conn2 24) |PAD_PA90 (conn2 27), PAD_PA91 (conn2 26) | -* 52 series: PA00, PA02 output Channel1 complementary PWM waveform, PA03, PA04 output Channel2 complementary PWM waveform: -* 587 series: PA84, PA86 output Channel1 complementary PWM waveform, PA90, PA91 output Channel2 complementary PWM waveform: -![alt text](assets/atimer_ch1_ch2_pwm-1.jpg) +| Board Name | PWM | Output Channel1 | Output Channel2 | +| ------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | +| sf32lb52-nano | ATIM1 | PAD_PA00 (physical position 32), PAD_PA02 (physical position 36) | PAD_PA03 (physical position 40), PAD_PA03 (physical position 38) | +| sf32lb52-lcd | ATIM1 | PAD_PA84 (conn2 21), PAD_PA86 (conn2 24) | PAD_PA90 (conn2 27), PAD_PA91 (conn2 26) | +| sf32lb56-lcd | ATIM1 | PAD_PA24, PAD_PA25 (PA24 corresponds to module pin 55, PA25 corresponds to module pin 51; jumper wires are required from the module) | PAD_PA29, PAD_PA30 (PA29 corresponds to module pin 23, PA30 corresponds to module pin 49; jumper wires are required from the module) | +| sf32lb58-lcd | ATIM2 | PAD_PA84 (conn2 21), PAD_PA86 (conn2 24) | PAD_PA90 (conn2 27), PAD_PA91 (conn2 26) | +* 52 series: PA00, PA02 output Channel1 complementary PWM waveform, PA03, PA04 + output Channel2 complementary PWM waveform: +* 587 series: PA84, PA86 output Channel1 complementary PWM waveform, PA90, PA91 + output Channel2 complementary PWM waveform: ![alt text]{1} +* 587 Series: PA84 and PA86 output complementary PWM waveforms for Channel 1; + PA90 and PA91 output complementary PWM waveforms for Channel 2: ![alt + text](assets/atimer_ch1_ch2_pwm-1.jpg) + #### PWM Parameter Modification + * ATIM modification: 52 series selects ATIM1, 587 selects ATIM2 ```c - #if defined(BSP_USING_BOARD_EM_LB525XXX) +#if defined(BSP_USING_BOARD_EM_LB525XXX) atim_Handle.Instance = (GPT_TypeDef *)hwp_atim1; #elif defined (BSP_USING_BOARD_EM_LB587XXX) atim_Handle.Instance = (GPT_TypeDef *)hwp_atim2; #endif ``` -* IO output modification -Except for 55x chips, can be configured to any IO with PA_TIM function to output PWM waveform -![alt text](assets/image-1.png) +* IO output modification Except for 55x chips, can be configured to any IO with + PA_TIM function to output PWM waveform ![alt text](assets/image-1.png) ```c #if defined(BSP_USING_BOARD_EM_LB525XXX) HAL_PIN_Set(PAD_PA00, ATIM1_CH1, PIN_PULLUP, 1); @@ -141,9 +155,10 @@ Except for 55x chips, can be configured to any IO with PA_TIM function to output HAL_PIN_Set(PAD_PA91, ATIM2_CH2N, PIN_PULLUP, 1); #endif ``` -* PWM period period, pulse width pulse modification, use delay function to maintain waveform for 2s +* PWM period period, pulse width pulse modification, use delay function to + maintain waveform for 2s ```c - freq = 50000; /* 50000 is PWM frequency (unit hz) minimum 1Hz, maximum 200000Hz */ +freq = 50000; /* 50000 is PWM frequency (unit hz) minimum 1Hz, maximum 200000Hz */ percentage1=50; /* 50 is Channel 1 duty cycle 50% (unit %) minimum 0(0%), maximum 100(100%)*/ percentage2=50; /* 50 is Channel 2 duty cycle 50% (unit %) minimum 0(0%), maximum 100(100%)*/ HAL_Delay(2000) @@ -158,20 +173,23 @@ Except for 55x chips, can be configured to any IO with PA_TIM function to output ``` * Waveform change diagrams between different parameters -![alt text](./assets/change1.png) -![alt text](./assets/change2.png) +![alt text](./assets/change1.png) ![alt text](./assets/change2.png) ## Exception Diagnosis -If the expected logs and PWM waveform output do not appear, troubleshooting can be performed from the following aspects: +If the expected logs and PWM waveform output do not appear, troubleshooting can +be performed from the following aspects: * Whether hardware connection is normal -* Whether pin configuration is correct -* Whether the pin corresponds to the correct channel +* Whether pin configuration is correct +* Whether the pin corresponds to the correct channel ## Reference Documents ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 |12/2024 |2.0 | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +``` + +``` diff --git a/example/hal/rng/README_EN.md b/example/hal/rng/README_EN.md index 24c4aa172..8e5052a6d 100644 --- a/example/hal/rng/README_EN.md +++ b/example/hal/rng/README_EN.md @@ -1,42 +1,47 @@ # RNG Example Source code path: example/hal/rng ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series + ## Overview - -This example demonstrates using RNG (Random Number Generator) to generate random number seeds and random numbers. + +This example demonstrates using RNG (Random Number Generator) to generate random +number seeds and random numbers. ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example + + - - ### Compilation and Programming Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: -1. Print a group (16) of random numbers every 500ms. +1. Print a group (16) of random numbers every 500ms. ```c SFBL RND_BUFFER: @@ -50,18 +55,20 @@ After the example starts, the serial port outputs the following: 53B59A81 28B15E6A 6BCB5A60 979D54B1 4D470A5E 001C491C F70875DA 8DD9FD34 RND_BUFFER: 234A3E47 1AB20C8F 3D06FD8D DA68708D 7C463B6E C31EDA11 1BE0B91E E0A46D41 - 2D6E9838 74A6C7F1 68117920 BCCFB254 13F8BC97 E2AFB62B 7025ADBC D995DC5E + 2D6E9838 74A6C7F1 68117920 BCCFB254 13F8BC97 E2AFB62B 7025ADBC D995DC5E ``` ## Exception Diagnosis ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | + + diff --git a/example/hal/rtc/README_EN.md b/example/hal/rtc/README_EN.md index bda6b5c54..43b89fd27 100644 --- a/example/hal/rtc/README_EN.md +++ b/example/hal/rtc/README_EN.md @@ -1,83 +1,90 @@ # RTC Example Source code path: example/hal/rtc ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series + ## Overview - + This example demonstrates HAL layer RTC usage, including: + RTC initialization configuration. + Setting date and time, reading date and time. + Setting Alarm. ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration -1. This example is based on external 32k crystal, need to configure LXT enable (LXT_DISABLE not checked, this example is already configured OK): -![LXT ENABLE](./assets/mc_lxt_enable.png) +1. This example is based on external 32k crystal, need to configure LXT enable + (LXT_DISABLE not checked, this example is already configured OK): ![LXT + ENABLE](./assets/mc_lxt_enable.png) ### Compilation and Programming Switch to the example project directory and run the scons command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs the following: 1. Initialization ```c 10-08 23:04:30:177 SFBL -10-08 23:04:32:397 RTC use LXT RTC_CR=00000001 -10-08 23:04:32:399 RTC Init success. +10-08 23:04:32:397 RTC using LXT; RTC_CR=00000001 +10-08 23:04:32:399 RTC initialization successful. ``` 2. Set system time to `2025/01/01 08:30:00` ```c -10-08 23:04:32:401 SET RTC TIME : Wed Jan 1 08:30:00 2025 -10-08 23:04:32:403 GET RTC TIME : Wed Jan 1 08:30:00 2025 +10-08 23:04:32:401 Set RTC time: Wed Jan 1 08:30:00 2025 +10-08 23:04:32:403 Get RTC time: Wed Jan 1 08:30:00 2025 ``` 3. Set Alarm, arrival time: `08:31:00` ```c -10-08 23:04:32:405 SET ALARM : [8 31 0] +10-08 23:04:32:405 Set alarm: [8 31 0] ``` 4. Alarm arrives ```c -10-08 23:05:31:464 GET RTC TIME : Wed Jan 1 08:30:59 2025 +10-08 23:05:31:464 Get RTC time: Wed Jan 1 08:30:59 2025 10-08 23:05:32:394 Alarm triggered. -10-08 23:05:32:462 GET RTC TIME : Wed Jan 1 08:31:00 2025 +10-08 23:05:32:462 Get RTC time: Wed Jan 1 08:31:00 2025 ``` 5. Periodically get system time (every second) ```c -10-08 23:05:34:633 GET RTC TIME : Wed Jan 1 08:31:02 2025 -10-08 23:05:35:460 GET RTC TIME : Wed Jan 1 08:31:03 2025 -10-08 23:05:36:473 GET RTC TIME : Wed Jan 1 08:31:04 2025 +10-08 23:05:34:633 Get RTC time: Wed Jan 1 08:31:02 2025 +10-08 23:05:35:460 Get RTC time: Wed Jan 1 08:31:03 2025 +10-08 23:05:36:473 Get RTC time: Wed Jan 1 08:31:04 2025 ``` ## Exception Diagnosis ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | + + diff --git a/example/hal/spi/dma/README_EN.md b/example/hal/spi/dma/README_EN.md index e2b981429..42d371313 100644 --- a/example/hal/spi/dma/README_EN.md +++ b/example/hal/spi/dma/README_EN.md @@ -7,13 +7,16 @@ The example can run on the following development boards: - sf32lb58-lcd_n16r64n4 ## Overview -This example demonstrates the continuous transmission and reception of SPI HAL in **DMA Circular mode**: +This example demonstrates the continuous transmission and reception of SPI HAL +in **DMA Circular mode**: - SPI1 master mode, `2Lines`, 8bit, default `SPI MODE0` -- TX DMA + RX DMA working simultaneously, continuously triggering clock and circularly transferring data +- TX DMA + RX DMA working simultaneously, continuously triggering clock and + circularly transferring data - Statistics of operation status through DMA half-full/full callbacks - Statistics of exceptions and printing of error codes through error callbacks -The focus of this example is to verify "whether the DMA circular link is stable", not to read NOR ID in blocking mode. +The focus of this example is to verify "whether the DMA circular link is +stable", not to read NOR ID in blocking mode. ## Usage of the Example @@ -31,7 +34,8 @@ Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat` and select the port as pro please input the serial port num:5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and download, please refer to the relevant +introduction in [](/quickstart/get-started.md). Enable SPI1 DMA related switches in `project/proj.conf`: @@ -43,9 +47,12 @@ CONFIG_BSP_SPI1_RX_USING_DMA=y ### Hardware Connection - Only short `MOSI(DIO/DO)` to `MISO(DI)` -- `CLK` and `CS` remain normal output, no need to connect to external slave devices +- `CLK` and `CS` remain normal output, no need to connect to external slave + devices -You can also connect to a real slave device (another board as SPI Slave), in which case connect according to the standard four-wire connection and share ground. +You can also connect to a real slave device (another board as SPI Slave), in +which case connect according to the standard four-wire connection and share +ground. ```{eval-rst} +--------------+----------+---------------+---------------------+ @@ -69,15 +76,14 @@ You can also connect to a real slave device (another board as SPI Slave), in whi +--------------+--------------+--------------+----------------------+ ``` Refer to the following diagram for the hardware schematic of sf32lb52-lcd_n16r8: -![alt text](assets/52-DevKit-lcd-V1.0.png) -![alt text](assets/nor_flash.png) +![alt text](assets/52-DevKit-lcd-V1.0.png) ![alt text](assets/nor_flash.png) #### Example Output Results: ### Startup Log ```text -Start spi dma circular demo! -spi dma running, tx/rx circular started. -tip: short SPI1 MOSI(DIO/DO) to MISO(DI) for loopback verification. +Starting SPI DMA circular mode demo. +SPI DMA active; TX/RX circular transfer initiated. +Note: Short SPI1 MOSI (DIO/DO) to MISO (DI) for loopback verification. ``` ### Running Log (Example) @@ -89,16 +95,19 @@ rx[0..7]: 00 01 02 03 04 05 06 07, rx[mid..mid+7]: 80 81 82 83 84 85 86 87 ``` Description: -- `half/full` will continuously increase, indicating that DMA is working in circular mode +- `half/full` will continuously increase, indicating that DMA is working in + circular mode - `err` should normally remain `0` -- In loopback short-circuit scenario, `rx` is commonly a cyclic sequence of 0x00~0xFF (may have phase offset) +- In loopback short-circuit scenario, `rx` is commonly a cyclic sequence of + 0x00~0xFF (may have phase offset) ## Functional Flow 1. Configure SPI1 pinmux and clock 2. Initialize SPI1 (Master, 2Lines, 8bit) 3. Initialize RX/TX DMA, both in `DMA_CIRCULAR` mode -4. Call `HAL_SPI_TransmitReceive_DMA()` to start continuous transmission and reception +4. Call `HAL_SPI_TransmitReceive_DMA()` to start continuous transmission and + reception 5. Statistics status in DMA half-full/full callbacks 6. Print status and sample RX data in main loop @@ -118,10 +127,10 @@ Description: ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf +* DS0052-SF32LB52x-Datasheet V0p3.pdf * PY25Q128HA_datasheet_V1.1.pdf ## Update Records -| Version | Date | Release Notes | -|:---|:---|:---| -| 0.1.0 | 03/2026 | Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.1.0 | 03/2026 | Initial version | diff --git a/example/hal/spi/polling/README_EN.md b/example/hal/spi/polling/README_EN.md index 345c422de..9b7455f77 100644 --- a/example/hal/spi/polling/README_EN.md +++ b/example/hal/spi/polling/README_EN.md @@ -6,7 +6,8 @@ Source path: `example/hal/spi/polling` - `sf32lb58-lcd_n16r64n4` ## Overview -This example demonstrates SPI HAL in **blocking polling mode** with self loopback verification. +This example demonstrates SPI HAL in **blocking polling mode** with self +loopback verification. Core behavior: - SPI1 master mode, 2Lines, 8-bit, default MODE0. @@ -24,7 +25,8 @@ For `sf32lb58-lcd_n16r64n4`: scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -After build, enter the generated `build_*` directory and run the download script. +After build, enter the generated `build_*` directory and run the download +script. ## Hardware Setup ### Single-board loopback (recommended) @@ -34,17 +36,18 @@ Short SPI1 MOSI and MISO: Keep: - `CLK`: `PA28` -- `CS`: `PA29` +- `CS`: `PA29` Notes: -- This example uses one-shot `HAL_SPI_TransmitReceive` per round; no manual `TAKE/RELEASE CS` is used. +- This example uses one-shot `HAL_SPI_TransmitReceive` per round; no manual + `TAKE/RELEASE CS` is used. - Without loopback wiring, `mismatch` is usually high or data appears random. ## Expected Logs Startup logs: ```text -Start spi polling loopback demo! -tip: short SPI1 MOSI(DIO/DO) to MISO(DI) for loopback verification. +Starting SPI polling loopback demo... +Note: Short SPI1 MOSI (DIO/DO) to MISO (DI) to verify loopback. ``` Runtime logs: @@ -84,9 +87,9 @@ Field meanings: ## Reference Documents - `EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx` -- `DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf` +- `DS0052-SF32LB52x-Datasheet-V0p3.pdf` ## Update Log -| Version | Date | Notes | -|:---|:---|:---| -| 0.1.0 | 03/2026 | Switched to polling loopback self TX/RX demo | +| Version | Date | Notes | +| ------- | ------- | -------------------------------------------- | +| 0.1.0 | 03/2026 | Switched to polling loopback self TX/RX demo | diff --git a/example/hal/tsen/README_EN.md b/example/hal/tsen/README_EN.md index 250f51d93..2bb6c6e0d 100644 --- a/example/hal/tsen/README_EN.md +++ b/example/hal/tsen/README_EN.md @@ -1,74 +1,78 @@ # TSEN Example Source code path: example/hal/tsen - ## Supported Platforms * sf32lb52-lcd series * sf32lb56-lcd series * sf32lb58-lcd series ## Overview -Used to represent the "Temperature Sensor" hardware module. Specifically, TSEN is an integrated temperature sensor designed to measure on-chip temperature, helping to implement temperature monitoring and temperature-related system functions. +Used to represent the "Temperature Sensor" hardware module. Specifically, TSEN +is an integrated temperature sensor designed to measure on-chip temperature, +helping to implement temperature monitoring and temperature-related system +functions. ## Example Usage ### Compilation and Programming ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted for download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted for download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). - +For detailed steps on compilation and download, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Methods for Using TSEN The following are general steps for using TSEN: ### Initialize TSEN: -The initialization function internally enables TSEN and starts temperature measurement: +The initialization function internally enables TSEN and starts temperature +measurement: ```c - HAL_TSEN_Init(TSEN_HandleTypeDef *htsen) +HAL_TSEN_Init(TSEN_HandleTypeDef *htsen) ``` - ### Read Temperature Data: #### Method 1: Synchronous Reading ```c -temperature = HAL_TSEN_Read(&TsenHandle); +temperature = HAL_TSEN_Read(&TsenHandle); ``` #### Method 2: Asynchronous Reading (Interrupt) ```c -HAL_TSEN_Read_IT(&TsenHandle) +HAL_TSEN_Read_IT(&TsenHandle) ``` - #### Interrupt Function Content ```c void TSEN_IRQHandler(void) { printf("IRQ Fired\n"); - HAL_TSEN_IRQHandler(&TsenHandle); + HAL_TSEN_IRQHandler(&TsenHandle); } __HAL_ROM_USED void HAL_TSEN_IRQHandler(TSEN_HandleTypeDef *htsen) { - htsen->Instance->TSEN_IRQ |= TSEN_TSEN_IRQ_TSEN_ICR; - htsen->temperature = HAL_TSEN_Data(htsen); + htsen->Instance->TSEN_IRQ |= TSEN_TSEN_IRQ_TSEN_ICR; + htsen->temperature = HAL_TSEN_Data(htsen); HAL_TSEN_Disable(htsen); NVIC_DisableIRQ(TSEN_IRQn); } ``` - #### Interrupt Function Content Jump Changes State Value -In the interrupt method, use `while (HAL_TSEN_GetState(&TsenHandle) != HAL_TSEN_STATE_READY)` to monitor whether new data is generated +In the interrupt method, use `while (HAL_TSEN_GetState(&TsenHandle) != +HAL_TSEN_STATE_READY)` to monitor whether new data is generated ![state_change](./assets/state_change.png) + + ## Code Section ```c static TSEN_HandleTypeDef TsenHandle; @@ -77,7 +81,7 @@ void TSEN_IRQHandler(void) { printf("IRQ Fired\n"); - HAL_TSEN_IRQHandler(&TsenHandle); + HAL_TSEN_IRQHandler(&TsenHandle); } @@ -89,23 +93,22 @@ static void testcase(void) /*##-1- Initialize TSEN peripheral #######################################*/ TsenHandle.Instance = hwp_tsen; - if (HAL_TSEN_Init(&TsenHandle) == HAL_OK) + if (HAL_TSEN_Init(&TsenHandle) == HAL_OK) { - temperature = HAL_TSEN_Read(&TsenHandle); /* Read synchronized*/ + temperature = HAL_TSEN_Read(&TsenHandle); /* Synchronous read*/ printf("Sync: Current temperature is %d degree\n", temperature); HAL_NVIC_SetPriority(TSEN_IRQn, 5, 0); /* Set interrupt priority*/ - if (HAL_TSEN_Read_IT(&TsenHandle) == HAL_TSEN_STATE_BUSY) /* Read Async, interrupt will be enabled*/ + if (HAL_TSEN_Read_IT(&TsenHandle) == HAL_TSEN_STATE_BUSY) /* Asynchronous read; interrupt will be enabled*/ { printf("state1:%d\n",TsenHandle.State); - while (HAL_TSEN_GetState(&TsenHandle) != HAL_TSEN_STATE_READY); + while (HAL_TSEN_GetState(&TsenHandle) != HAL_TSEN_STATE_READY); } printf("state2:%d\n",TsenHandle.State); printf("Async: Current temperature is %d degree\n", TsenHandle.temperature); } } ``` - ### Example Output Results Display: ```c Start tsen demo! @@ -118,13 +121,17 @@ Async: Current temperature is 19 degree ![tsen_Serial_print](./assets/tsen_Serial_print.png) ## Exception Diagnosis -If the expected log temperature changes do not appear, troubleshooting can be performed from the following aspects: +If the expected log temperature changes do not appear, troubleshooting can be +performed from the following aspects: * Whether hardware connections are normal * Whether interrupt handling functions are normal * Whether state value changes to HAL_TSEN_STATE_READY ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 |12/2024 |2.0 | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +``` + +``` diff --git a/example/hal/uart/README_EN.md b/example/hal/uart/README_EN.md index f4016b72a..a9239bd14 100644 --- a/example/hal/uart/README_EN.md +++ b/example/hal/uart/README_EN.md @@ -1,6 +1,5 @@ # UART Example Source code path: example/hal/uart - ## Supported Platforms Examples can run on the following development boards: * sf32lb52-nano series @@ -9,22 +8,30 @@ Examples can run on the following development boards: * sf32lb56-lcd series ## Overview -* Operate UART hal functions using RX DMA method, operate UART2 to verify its serial port transmission and reception capabilities -* Note: After the development board resets, if uart2 prints logs consistent with the image below, it indicates success -* Note: If the computer-side serial port is closed, this serial port will not print logs - +* Operate UART hal functions using RX DMA method, operate UART2 to verify its + serial port transmission and reception capabilities +* Note: After the development board resets, if uart2 prints logs consistent with + the image below, it indicates success +* Note: If the computer-side serial port is closed, this serial port will not + print logs ## Example Usage ### Compilation and Programming -For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and download, please refer to the relevant +introduction in [](/quickstart/get-started.md). -Confirm that rtconfig.h cannot contain the following two macros, otherwise the rt-thread system driver will also initialize the RT system uart once, causing uart redefinition: +Confirm that rtconfig.h cannot contain the following two macros, otherwise the +rt-thread system driver will also initialize the RT system uart once, causing +uart redefinition: ```c #define CONFIG_BSP_USING_UART 1 #define CONFIG_RT_USING_SERIAL is set 1 ``` ![alt text](assets/define_erro.png) -Note: Directly modifying macros in rtconfig.h will still be ineffective. We need to enable it through the menuconfig command as follows. Enter the following command in the programming interface (board=board model): + +Note: Directly modifying macros in rtconfig.h will still be ineffective. We need +to enable it through the menuconfig command as follows. Enter the following +command in the programming interface (board=board model): ````{note} This example redirected printf to serial port transmission, but to avoid activating unnecessary semihosting code during Keil compilation, `proj.conf` is configured to use microlib: @@ -33,76 +40,92 @@ CONFIG_USING_MICROLIB=y ``` ```` + ``` menuconfig --board=sf32lb52-lcd_n16r8 ``` ![alt text](assets/common.png) -The resource selection in the menu is for rt-thread system driver usage. Here we are using hal, so uncheck the resources you want to use to prevent redefinition (press D+Enter to save after checking or unchecking): -![alt text](assets/menuconfig1.png) -![alt text](assets/menuconfig2.png) +The resource selection in the menu is for rt-thread system driver usage. Here we +are using hal, so uncheck the resources you want to use to prevent redefinition +(press D+Enter to save after checking or unchecking): ![alt +text](assets/menuconfig1.png) ![alt text](assets/menuconfig2.png) -Switch to the example project directory and run the scons command to execute compilation: (board=board model) +Switch to the example project directory and run the scons command to execute +compilation: (board=board model) ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted for download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted for download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### Hardware Connection -Physical position refers to the pin header position corresponding to the pins on the board -|Board Name | UART | TX(Physical Position) | RX(Physical Position) | -|--------|------------|---------------|-------------------| -|525 | UART2 | PAD_PA27(8) | PAD_PA20(10) | -|587 | UART2 | PAD_PA28 (CONN2 5) |PAD_PA29 (CONN2 3) | -|56 | UART2 | PAD_PA37 (38) |PAD_PA36 (40) | - -* PA27 is software-configured as UART2's TX, connected to the computer's USB-to-serial RX -* PA20 is software-configured as UART2's RX, connected to the computer's USB-to-serial TX +Physical position refers to the pin header position corresponding to the pins on +the board +| Board Name | UART | TX(Physical Position) | RX(Physical Position) | +| ---------- | ----- | --------------------- | --------------------- | +| 525 | UART2 | PAD_PA27(8) | PAD_PA20(10) | +| 587 | UART2 | PAD_PA28 (CONN2 5) | PAD_PA29 (CONN2 3) | +| 56 | UART2 | PAD_PA37 (38) | PAD_PA36 (40) | +| 56 | UART2 | PAD_PA37 (38) | PAD_PA36 (40) | + + +* PA27 is software-configured as UART2's TX, connected to the computer's + USB-to-serial RX +* PA20 is software-configured as UART2's RX, connected to the computer's + USB-to-serial TX * GND is connected to the USB-to-serial GND, as shown below: ![alt text](assets/52-DevKit-lcd-V1.0.png) + + #### Example Output Results Display: -* Log output: - Log ends with uart2 sending: +* Log output: Log ends with uart2 sending: ``` - Start uart demo! - uart2 hal demo! - uart2 - uart demo end! + Initialising UART demo... + UART2 HAL demo... + UART2 + UART demo completed. ``` -* Send `abc` to uart2, receive `abc` characters, newline character, carriage return character, total 5 character ASCII codes, print the following content: +* Send `abc` to uart2, receive `abc` characters, newline character, carriage + return character, total 5 character ASCII codes, print the following content: ``` TX:abc - rev:abc + RX:abc ``` #### Example Output Results Display: ![alt text](assets/uart_log.png) -The `rev: ` at the end of the log is the characters received from the computer's USB-to-serial TX: + +The `rev: ` at the end of the log is the characters received from the computer's +USB-to-serial TX: ``` -Start uart demo! -uart2 hal demo! -uart2 -uart demo end! +Initialising UART demo... +UART2 HAL demo... +UART2 +UART demo completed. TX:abc -rev:abc +RX:abc ``` #### UART2 Configuration Process -* Note that different board types may have different corresponding DMAC1_CHX_IRQHandler -* Configure corresponding Uart2 and RX DMA interrupts, refer to the definitions within the `BSP_USING_UART2` macro and `UART2_RX_DMA_INSTANCE` macro in `dma_config.h` and `uart_config.h`: +* Note that different board types may have different corresponding + DMAC1_CHX_IRQHandler +* Configure corresponding Uart2 and RX DMA interrupts, refer to the definitions + within the `BSP_USING_UART2` macro and `UART2_RX_DMA_INSTANCE` macro in + `dma_config.h` and `uart_config.h`: ```c #if defined(BSP_USING_BOARD_EM_LB525XXX) @@ -125,6 +148,9 @@ rev:abc #define UART_RX_DMA_IRQ_HANDLER UART2_DMA_RX_IRQHandler ``` + + + * Set corresponding IO ports for Uart2: ```c #if defined(BSP_USING_BOARD_EM_LB525XXX) @@ -140,23 +166,24 @@ HAL_PIN_Set(PAD_PA28, USART2_TXD, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA37, USART2_TXD, PIN_PULLUP, 1); #endif ``` - -**Note**: -1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART function to output UART2 waveform (to query pin multiplexing table, search for corresponding board type pin multiplexing in project path files such as: bf0_pin_const.c) -2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu -3. Hcpu's PA port cannot be configured as Lcpu's uart peripheral, such as uart5, uart6 output - +**Note**: +1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART function + to output UART2 waveform (to query pin multiplexing table, search for + corresponding board type pin multiplexing in project path files such as: + bf0_pin_const.c) +2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select + hcpu, 0: select lcpu +3. Hcpu's PA port cannot be configured as Lcpu's uart peripheral, such as + uart5, uart6 output * Enable corresponding uart2 clock source: ```c - /* 2, open uart2 clock source */ +/** 2. Enable UART2 clock source **/ HAL_RCC_EnableModule(RCC_MOD_USART2); ``` - * UART2 baud rate setting, example baud rate is 1000000: ```c - UartHandle.Init.BaudRate = 1000000; +UartHandle.Init.BaudRate = 1000000; ``` - * UART2 DMA configuration: ```c // Start RX DMA @@ -182,7 +209,6 @@ HAL_NVIC_EnableIRQ(UART_RX_DMA_IRQ); HAL_NVIC_EnableIRQ(UART_INTERRUPT);/* Enable uart2 interrupt */ } ``` - * Use state to represent current DMA reception progress: ```c typedef enum { @@ -193,7 +219,6 @@ typedef enum { // Current reception state ReceiveState currentState = STATE_UNFULL; ``` - * Half-full, full, uart idle processing: ```c In the void UART_IRQ_HANDLER(void) function, after uart idle, judge the current reception state to execute half-full or full or idle processing @@ -251,10 +276,10 @@ void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) //Full void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { - + if(huart->Instance == hwp_usart2) { - + // Implement full processing logic, such as writing middle to last data to FIFO or preliminary processing uint16_t fullLength = BUFFER_SIZE; @@ -267,28 +292,29 @@ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) * UART2 send data: ```c - /* Send data from uart2 through printf */ +/* Send data from uart2 through printf */ printf("uart2 hal demo!\n"); /* Send data from uart2 through HAL_UART_Transmit interface */ uint8_t ptr[] = {'u','a','r','t','2','\n'}; int len = 6 ; HAL_UART_Transmit(&UartHandle, ptr, len, 0xFFFF); ``` - ## Exception Diagnosis * UART2 no waveform output: -1. Check step by step according to the configuration process to see if all configurations are successful -2. Check hardware connections, including whether uart2 output level matches computer uart level +1. Check step by step according to the configuration process to see if all + configurations are successful +2. Check hardware connections, including whether uart2 output level matches + computer uart level 3. Whether there is redefinition in menuconfig ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf -* DS0058-SF32LB58x-芯片技术规格书 V1p8.pdf +* DS0052-SF32LB52x-Datasheet V0p3.pdf +* DS0058-SF32LB58x-Datasheet V1p8.pdf ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 |12/2024 |2.0 | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +| | | | diff --git a/example/hal/wdt/index_EN.md b/example/hal/wdt/index_EN.md index 271f060a2..08b9ed37e 100644 --- a/example/hal/wdt/index_EN.md +++ b/example/hal/wdt/index_EN.md @@ -5,5 +5,4 @@ :glob: */* - ``` diff --git a/example/hal/wdt/iwdt/README_EN.md b/example/hal/wdt/iwdt/README_EN.md index 5d785d2cc..c2afaf8be 100644 --- a/example/hal/wdt/iwdt/README_EN.md +++ b/example/hal/wdt/iwdt/README_EN.md @@ -3,42 +3,45 @@ Source code path: example/hal/wdt/iwdt ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - + This example demonstrates IWDT usage, including: + IWDT configuration and enabling. + IWDT feeding. + IWDT timeout response. ## Example Usage - + ### Hardware Requirements -Before running this example, prepare a development board supported by this example +Before running this example, prepare a development board supported by this +example ### menuconfig Configuration ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted for download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted for download: ``` ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please enter the serial port number: 5 ``` For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). @@ -46,37 +49,32 @@ For detailed steps on compilation and download, please refer to the relevant int After the example starts, the serial port outputs as follows: 1. IWDT initialization configuration and enabling successful: -```c -10-28 23:44:00:340 WDT Example: -10-28 23:44:00:342 IWDT init OK. Timeout: 10(s) -10-28 23:44:00:343 WDT_CVR0:0x50000 WDT_CVR1:0x0 ``` -```{tip} -IWDT cannot generate interrupts. Here the working mode (`respond mode`) is configured as `reset only`, counting only one round, with timeout set to 10 seconds. +10-28 23:44:00:340 WDT Example: 10-28 23:44:00:342 IWDT initialization +successful. Timeout: 10(s) 10-28 23:44:00:343 WDT_CVR0:0x50000 WDT_CVR1:0x0 +``` + +``` +IWDT cannot generate interrupts. Here the working mode (`respond mode`) is +configured as `reset only`, counting only one round, with timeout set to 10 +seconds. ``` 2. Feeding the dog (every 5 seconds): -```c -10-28 23:44:05:270 Watchdog feeding. -10-28 23:44:10:298 Watchdog feeding. -10-28 23:44:15:262 Watchdog feeding. -10-28 23:44:20:291 Watchdog feeding. -10-28 23:44:25:280 Watchdog feeding. -10-28 23:44:31:132 Watchdog feeding. -10-28 23:44:35:300 Watchdog feeding. -10-28 23:44:40:301 Watchdog feeding. -10-28 23:44:45:304 Watchdog feeding. -10-28 23:44:50:320 Watchdog feeding. +``` +10-28 23:44:05:270 Feeding watchdog. 10-28 23:44:10:298 Feeding watchdog. 10-28 +23:44:15:262 Feeding watchdog. 10-28 23:44:20:291 Feeding watchdog. 10-28 +23:44:25:280 Feeding watchdog. 10-28 23:44:31:132 Feeding watchdog. 10-28 +23:44:35:300 Feeding watchdog. 10-28 23:44:40:301 Feeding watchdog. 10-28 +23:44:45:304 Feeding watchdog. 10-28 23:44:50:320 Feeding watchdog. ``` 3. After stopping feeding the dog, the first round of counting ends (10s), directly resetting the system: -```c -10-28 23:44:50:320 Watchdog feeding. -10-28 23:45:03:215 SFBL -10-28 23:45:04:945 Serial:c2,Chip:4,Package:3,Rev:2 Reason:00000020 - -10-28 23:45:04:950 NAND ID 0x7070cd -10-28 23:45:04:957 det bbm table with 1, 1, 2 ``` +10-28 23:44:50:320 Feeding watchdog. 10-28 23:45:03:215 SFBL 10-28 23:45:04:945 +Serial:c2, Chip:4, Package:3, Rev:2 Reason:00000020 +10-28 23:45:04:950 NAND ID 0x7070cd 10-28 23:45:04:957 Detecting BBM table with +1, 1, 2 +``` ## Exception Diagnosis 1. Confirm WDT configuration status (enable status, count configuration, working mode) through WDT registers: @@ -97,4 +95,5 @@ Need to confirm whether `reboot cause` is correctly configured, `HAL_PMU_SetWdt( |:---|:---|:---| |0.0.1 |10/2024 |Initial version | | | | | -| | | | \ No newline at end of file +| | | | +``` diff --git a/example/hal/wdt/wdt1/README_EN.md b/example/hal/wdt/wdt1/README_EN.md index 75bb15a5f..2163ebdbf 100644 --- a/example/hal/wdt/wdt1/README_EN.md +++ b/example/hal/wdt/wdt1/README_EN.md @@ -3,78 +3,83 @@ Source code path: example/hal/wdt/wdt1 ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - + This example demonstrates WDT1 usage, including: + WDT1 configuration and enabling. + WDT1 feeding. + WDT1 timeout response. ## Example Usage - + ### Hardware Requirements -Before running this example, prepare a development board supported by this example +Before running this example, prepare a development board supported by this +example ### menuconfig Configuration ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted for download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted for download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and download, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results of Example - + After the example starts, the serial port outputs as follows: 1. WDT1 initialization configuration and enabling successful: ```c 10-28 21:27:41:364 WDT Example: -10-28 21:27:41:366 WDT init OK. Timeout: 10(s) Reload2: 60(s) +10-28 21:27:41:366 WDT initialized successfully. Timeout: 10(s) Reload2: 60(s) 10-28 21:27:41:368 WDT_CVR0:0x50000 WDT_CVR1:0x1E0000 ``` ```{tip} -In this example, WDT1 working mode (`respond mode`) is configured as `interrupt and reset`, counting two rounds, with first round counting timeout of 10 seconds and second round counting timeout of 60 seconds. +In this example, WDT1 working mode (`respond mode`) is configured as `interrupt and reset`, counting two rounds, with first round counting timeout of 10 seconds and second round counting timeout of 60 seconds. ``` 2. Feeding the dog (every 5 seconds): ```c -10-28 21:27:46:419 Watchdog feeding. -10-28 21:27:51:332 Watchdog feeding. -10-28 21:27:56:328 Watchdog feeding. -10-28 21:28:01:339 Watchdog feeding. -10-28 21:28:06:329 Watchdog feeding. -10-28 21:28:11:360 Watchdog feeding. -10-28 21:28:16:356 Watchdog feeding. -10-28 21:28:21:368 Watchdog feeding. -10-28 21:28:26:361 Watchdog feeding. -10-28 21:28:31:373 Watchdog feeding. +10-28 21:27:46:419 Feeding watchdog. +10-28 21:27:51:332 Feeding watchdog. +10-28 21:27:56:328 Feeding watchdog. +10-28 21:28:01:339 Feeding watchdog. +10-28 21:28:06:329 Feeding watchdog. +10-28 21:28:11:360 Feeding watchdog. +10-28 21:28:16:356 Feeding watchdog. +10-28 21:28:21:368 Feeding watchdog. +10-28 21:28:26:361 Feeding watchdog. +10-28 21:28:31:373 Feeding watchdog. ``` -3. After stopping feeding the dog, the first round of counting ends (10s), generating an interrupt: +3. After stopping feeding the dog, the first round of counting ends (10s), + generating an interrupt: ```c -10-28 21:28:31:373 Watchdog feeding. +10-28 21:28:31:373 Feeding watchdog. 10-28 21:28:43:793 WDT timeout. Interrupt triggered. ``` 4. The second round of counting ends (60s), resetting the system: ```c 10-28 21:29:58:197 SFBL -10-28 21:29:59:394 Serial:c2,Chip:4,Package:3,Rev:2 Reason:00000002 +10-28 21:29:59:394 Serial:c2, Chip:4, Package:3, Rev:2 Reason:00000002 10-28 21:29:59:398 NAND ID 0x7070cd 10-28 21:29:59:402 det bbm table with 1, 1, 2 @@ -83,22 +88,23 @@ In this example, WDT1 working mode (`respond mode`) is configured as `interrupt ## Exception Diagnosis -1. Confirm WDT configuration status (enable status, count configuration, working mode) through WDT registers: -![WDT regmap](./assets/wdt_regmap.png) +1. Confirm WDT configuration status (enable status, count configuration, working + mode) through WDT registers: ![WDT regmap](./assets/wdt_regmap.png) -2. After WDT is configured correctly, WDT timeout cannot reset the system: -Need to confirm whether `reboot cause` is correctly configured, `HAL_PMU_SetWdt()` can be used to add the corresponding WDT's `reboot cause`: +2. After WDT is configured correctly, WDT timeout cannot reset the system:\ + Need to confirm whether `reboot cause` is correctly configured, + `HAL_PMU_SetWdt()` can be used to add the corresponding WDT's `reboot cause`: ```c - /* Add reboot cause for watchdog. */ + /* Set watchdog as reboot cause. */ HAL_PMU_SetWdt((uint32_t)hwdt.Instance); ``` ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/hal_example/README_EN.md b/example/hal_example/README_EN.md index a22618560..dac1609b1 100644 --- a/example/hal_example/README_EN.md +++ b/example/hal_example/README_EN.md @@ -3,30 +3,37 @@ Source Code Path: example/hal_example ## Overview -The HAL comprehensive example demonstrates how to use the Hardware Abstraction Layer (HAL) features of SiFli-SDK. This example provides a series of test commands that allow users to run different module test cases through serial port interaction. - -## Usage - -### Supported Development Boards -- eh-lb525 +The HAL comprehensive example demonstrates how to use the Hardware Abstraction +Layer (HAL) features of SiFli-SDK. This example provides a series of test +commands that allow users to run different module test cases through serial port +interaction. ### Hardware Requirements -No special hardware requirements; a standard development board is sufficient. +No special hardware is required; the project runs on standard development +boards. + +## Usage +The project can be compiled for a specific target board by specifying the +`board` parameter. +- For example, to compile a project for the HDK 525, run `scons + --board=eh-lb525` to generate the image file. +- Firmware can be flashed using the `download.bat` script located in the `build` + directory. For instance, to flash the 525 project generated in the previous + step via J-Link, execute `.`build_eh-lb525\download.bat``. +- Note: For the SF32LB52x series, an additional `uart_download.bat` script is + generated. Execute this script and enter the designated UART port number to + perform the download. ## Project Compilation and Download The project can be compiled for specific boards by specifying the board name: -- Compilation command: `scons --board=eh-lb525` -- Download method: Execute `build_eh-lb525\download.bat` for J-Link download -- For SF32LB52x series, execute `uart_download.bat` and enter the UART port number for download +1. Compilation command: `scons --board=eh-lb525` +2. Download method: Execute `build_eh-lb525\download.bat` for J-Link download +3. For SF32LB52x series, execute `uart_download.bat` and enter the UART port + number for download ## Example Usage Use the following commands in the serial port to interact: -1. `help` - Display all supported commands -2. `utest_list` - Show all available test cases -3. `utest_run example_xxx` - Run a specific module test case ## Troubleshooting -No specific troubleshooting information available. For issues, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. - -## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) \ No newline at end of file +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) diff --git a/example/jpeg_dec/README_EN.md b/example/jpeg_dec/README_EN.md index 005903c49..cc0cb2693 100644 --- a/example/jpeg_dec/README_EN.md +++ b/example/jpeg_dec/README_EN.md @@ -1,6 +1,9 @@ # JPEG Hardware Decoding Example Program +The program will obtain the image dimensions, then decode to RGB format and +display on the screen. ```{warning} Not verified ``` -The program will obtain the image dimensions, then decode to RGB format and display on the screen. \ No newline at end of file +The program retrieves the image dimensions, decodes the data into RGB format, +and renders it to the display. diff --git a/example/lcd_stress_test/README_EN.md b/example/lcd_stress_test/README_EN.md index 22d097d34..875123e32 100644 --- a/example/lcd_stress_test/README_EN.md +++ b/example/lcd_stress_test/README_EN.md @@ -1,12 +1,20 @@ # LCD Module Stress Test Program +Source Path: example/lcd_stress_test ```{warning} Not verified ``` ## Overview -This is a test example program for testing the screen by using the "lcd" rt_device. The program will repeatedly call the following test cases: -1. In 3 RTOS threads, separately call the interfaces for setting screen brightness, synchronous screen refresh, and asynchronous screen refresh -2. Single thread repeatedly calls: close screen (rt_device_close), open screen (rt_device_open), refresh screen -3. Single thread repeatedly calls: close screen (RTGRAPHIC_CTRL_POWEROFF), system standby sleep, system wake up, open screen (RTGRAPHIC_CTRL_POWERON), refresh screen -4. Single thread repeatedly calls: screen enters idle mode, system standby sleep, system wake up, screen exits idle mode, refresh screen -5. Single thread repeatedly calls: system standby sleep, system wake up, refresh screen \ No newline at end of file +This is a test example program for testing the screen by using the "lcd" +rt_device. The program will repeatedly call the following test cases: +1. In 3 RTOS threads, separately call the interfaces for setting screen + brightness, synchronous screen refresh, and asynchronous screen refresh +2. Single thread repeatedly calls: close screen (rt_device_close), open screen + (rt_device_open), refresh screen +3. Single thread repeatedly calls: close screen (RTGRAPHIC_CTRL_POWEROFF), + system standby sleep, system wake up, open screen (RTGRAPHIC_CTRL_POWERON), + refresh screen +4. Single thread repeatedly calls: screen enters idle mode, system standby + sleep, system wake up, screen exits idle mode, refresh screen +5. Single thread repeatedly calls: system standby sleep, system wake up, refresh + screen diff --git a/example/lvgl_v8_ttf/README_EN.md b/example/lvgl_v8_ttf/README_EN.md index 316f0967d..98b53475f 100644 --- a/example/lvgl_v8_ttf/README_EN.md +++ b/example/lvgl_v8_ttf/README_EN.md @@ -6,21 +6,28 @@ Unverified Source Path: example/lvgl_v8_ttf -This example is used to test the API for using LVGL V8 TTF fonts, utilizing the schrift TTF library. It demonstrates how to integrate and use TrueType font rendering functionality in SiFli-SDK. +This example is used to test the API for using LVGL V8 TTF fonts, utilizing the +schrift TTF library. It demonstrates how to integrate and use TrueType font +rendering functionality in SiFli-SDK. ### Project Compilation and Download +Projects located in the `project` directory can be compiled for a specific +target by specifying the `board` parameter. +- For example, to compile a project for the HDK 563, execute `scons + --board=eh-lb563` to generate the project files. +- Firmware can be programmed using the `download.bat` script located in the + `build` directory. To flash the 563 project generated in the previous step, + run `.\build_eh-lb563\download.bat` to perform the download via J-Link. +- Note: For the SF32LB52x and SF32LB56x series, an additional + `uart_download.bat` script is generated. Run this script and enter the + appropriate COM port number to perform the download via UART. #### Development Board Project -The board project is located in the project directory. You can compile for specific development boards by specifying the board parameter: +The board project is located in the project directory. You can compile for +specific development boards by specifying the board parameter: - Compile for HDK 563: Execute `scons --board=eh-lb563` to generate the project -- Download method: Use download.bat in the build directory, e.g., flash eh-lb563 project: `./build_eh-lb563/download.bat` (via J-Link) -- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. Execute this script and enter the UART port number for UART download - -#### Simulator Project -The simulator project is located in the simulator directory: -- Compile with `scons` (requires modifying simulator/msvc_setup.bat to match local MSVC configuration first) -- Generate Visual Studio project: `scons --target=vs2017` to generate project.vcxproj, compile with Visual Studio - > Note: If using a version other than VS2017 (e.g., VS2022), you'll be prompted to upgrade the MSVC SDK when loading the project. After upgrading, it can be used normally +- Download method: Use download.bat in the build directory, e.g., flash eh-lb563 + project: `./build_eh-lb563/download.bat` (via J-Link) ## Supported Development Boards @@ -31,19 +38,21 @@ This example supports the following development boards: ## Hardware Requirements -- The development board must be connected to the computer via USB for program download and debugging -- For UART download method, ensure the UART port of the development board is correctly connected and configured +- The development board must be connected to the computer via USB for program + download and debugging +- For UART download method, ensure the UART port of the development board is + correctly connected and configured ## Example Output -No specific serial output information is provided for this example. When run, it will display TTF font rendering test results, including text display effects with different font sizes and styles. +No specific serial output information is provided for this example. When run, it +will display TTF font rendering test results, including text display effects +with different font sizes and styles. ## Troubleshooting -For any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. - -## Reference Documentation - -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) - [LVGL V8 Official Documentation](https://docs.lvgl.io/v8/) -- [schrift Font Library Documentation](https://github.com/turbolent/schrift) \ No newline at end of file +- [schrift Font Library Documentation](https://github.com/turbolent/schrift) + diff --git a/example/micropython/README_EN.md b/example/micropython/README_EN.md index e27365cb1..c81eb30cc 100644 --- a/example/micropython/README_EN.md +++ b/example/micropython/README_EN.md @@ -1,27 +1,35 @@ # MicroPython Example +Source path: example/micropython ```{warning} Not verified ``` - ## User Guide ### Introduction -The micropython application will verify micropython functionality on the board flash. The file system uses FAT format. Common file commands can be called in the UART console, such as: +The micropython application will verify micropython functionality on the board +flash. The file system uses FAT format. Common file commands can be called in +the UART console, such as: ``` -df - Disk free -mountfs - Mount device to file system -mkfs - Format disk with file system -mkdir - Create the DIRECTORY. +df - Display free disk space. +mountfs - Mount a device to the file system. +mkfs - Format a disk with a file system. +mkdir - Create a directory. pwd - Print the name of the current working directory. cd - Change the shell working directory. -rm - Remove(unlink) the FILE(s). -cat - Concatenate FILE(s) +rm - Remove (unlink) files. +cat - Concatenate and display file content. mv - Rename SOURCE to DEST. cp - Copy SOURCE to DEST. -ls - List information about the FILEs. -python - run python script or start with python REPL. +ls - List information about files. +python - Execute a Python script or start the Python REPL. ``` - + ## Project Description -- Compilation method: Enter the project directory and execute the command `scons --board= -j8`, where board_name is the board name. For example, to compile the eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8` - The compiled image file is stored in the HCPU's build_ directory. For common project usage, refer to <> -- Simulator compilation method: Enter the simulator directory and execute the command 'scons -j8'. When running, execute build\bf0_ap.exe in the simulator directory \ No newline at end of file +- Compilation method: Enter the project directory and execute the command `scons + --board= -j8`, where board_name is the board name. For example, to + compile the eh-lb561 board, the complete command is `scons --board=eh-lb561 + -j8` The compiled image file is stored in the HCPU's build_ + directory. For common project usage, refer to <{1}> +- Simulator compilation method: Enter the simulator directory and execute the + command 'scons -j8'. When running, execute build\bf0_ap.exe in the simulator + directory + diff --git a/example/misc/adc_button/README_EN.md b/example/misc/adc_button/README_EN.md index 21eff4d6c..543979c5f 100644 --- a/example/misc/adc_button/README_EN.md +++ b/example/misc/adc_button/README_EN.md @@ -1,20 +1,36 @@ # GPADC button +Source Path: example/misc/adc_button ## Supported Platforms * sf32-oed-epd_v11 ## Overview -GPADC (General Purpose ADC) button is a technology that realizes multi-key detection through ADC sampling, and its core principle is to use a resistive voltage divider network to convert the state of different keys into different voltage values, and then identify specific key actions through ADC sampling. GPADC keys significantly reduce pin footprint compared to traditional standalone GPIO keys (one ADC pin can support multiple keys), especially for embedded devices with tight pin resources. -This document describes the GPADC buttons, which can detect the key state through ADC, support two basic operations: click and long-press, and can be mapped to specific operation actions (up, down, select, and exit). +GPADC (General Purpose ADC) button is a technology that realizes multi-key +detection through ADC sampling, and its core principle is to use a resistive +voltage divider network to convert the state of different keys into different +voltage values, and then identify specific key actions through ADC sampling. +GPADC keys significantly reduce pin footprint compared to traditional standalone +GPIO keys (one ADC pin can support multiple keys), especially for embedded +devices with tight pin resources. This document describes the GPADC buttons, +which can detect the key state through ADC, support two basic operations: click +and long-press, and can be mapped to specific operation actions (up, down, +select, and exit). ## Explanation of principle and function -- When a key is pressed, the corresponding resistor branch is turned on with GND, and the voltage of the ADC pin is determined by the resistance of the conduction branch and the pull-up resistor (or series resistor). For example: +- When a key is pressed, the corresponding resistor branch is turned on with + GND, and the voltage of the ADC pin is determined by the resistance of the + conduction branch and the pull-up resistor (or series resistor). For example: -When key 1 is pressed, ADC voltage = VCC × (R1 parallel other resistors) / total resistance; -When key 2 is pressed, ADC voltage = VCC × (R2 parallel other resistors) / total resistance; -When different keys are pressed, the ADC pins produce a unique and distinguishable voltage value. +When key 1 is pressed, ADC voltage = VCC × (R1 parallel other resistors) / total +resistance;\ +When key 2 is pressed, ADC voltage = VCC × (R2 parallel other resistors) / total +resistance;\ +When different keys are pressed, the ADC pins produce a unique and +distinguishable voltage value. -By properly designing the resistance value, it is possible to ensure that the voltage value range corresponding to each button does not overlap, so that the specific button can be identified by the ADC sample value. +By properly designing the resistance value, it is possible to ensure that the +voltage value range corresponding to each button does not overlap, so that the +specific button can be identified by the ADC sample value. - This routine mainly implements the following functions: 1. Initialize the GPADC button hardware and driver configuration; @@ -25,34 +41,52 @@ By properly designing the resistance value, it is possible to ensure that the vo ## Use of routines ### Compilation and burning The hardware mainly uses the development board (SF32-OED-6'-EPD_V1.1) + #### Program compilation and burning -Switch to the routine project directory and run the scons command to perform the compilation ('.. 'Add the sf32-oed-epd_v11 storage path for the development board): +Switch to the routine project directory and run the scons command to perform the +compilation ('.. 'Add the sf32-oed-epd_v11 storage path for the development +board): ``` -scons --board=sf32-oed-epd_v11 --board_search_path=.. -j8 +scons --board=sf32-oed-epd_v11 --board_search_path=.. -j8 ``` -run`build_sf32-oed-epd_hcpu\uart_download.bat`,Follow the prompts to select a port to download: +run`build_sf32-oed-epd_hcpu\uart_download.bat`,Follow the prompts to select a +port to download: ``` build_sf32l-oed-epd_hcpu\uart_download.bat Uart Download please input the serial port num: 5 (Fill in the appropriate port number) ``` -This is only a brief explanation, please check for details[Compile the burning link](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/build.html) +This is only a brief explanation, please check for details[Compile the burning +link](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/build.html) #### menuconfig configuration -Run the menuconfig command to perform the compilation ('..'Add the sf32-oed-epd_v11 storage path for the development board): +Run the menuconfig command to perform the compilation ('..'Add the +sf32-oed-epd_v11 storage path for the development board): ``` menuconfig --board=sf32-oed-epd_v11 --board_search_path=.. ``` -- If you want to change the time of the long press, you can set it by modifying the macro 'BUTTON_ADV_ACTION_CHECK_DELAY' in Menuconfig. Open the Menuconfig configuration under 'SiFli Middleware->Enable button library'. -![alt text](assets/menuconfig_action.png) +- If you want to change the time of the long press, you can set it by modifying + the macro 'BUTTON_ADV_ACTION_CHECK_DELAY' in Menuconfig. Open the Menuconfig + configuration under 'SiFli Middleware->Enable button library'. ![alt + text](assets/menuconfig_action.png) #### Configuration process -- First, check whether the hardware supports the use of GPADC buttons, as shown in the hardware schematic diagram below, mark the voltage range and reference voltage of the GPADC buttons, for example, set the reference voltage under the directory of the board according to the figure below (take the middle value of the voltage range)`CONFIG_ADC_BUTTON_GROUP1_BUTTON1_VOLT=2992`、 -`CONFIG_ADC_BUTTON_GROUP1_BUTTON2_VOLT=2345`, and the amplitude of the voltage range for each ADC button (take half of the voltage range)`CONFIG_ADC_BUTTON_GROUP1_BUTTON1_RANGE=315`、`CONFIG_ADC_BUTTON_GROUP1_BUTTON2_RANGE=245`。 -![alt text](assets/adc.png) - +- First, check whether the hardware supports the use of GPADC buttons, as shown + in the hardware schematic diagram below, mark the voltage range and reference + voltage of the GPADC buttons, for example, set the reference voltage under the + directory of the board according to the figure below (take the middle value of + the voltage range)`CONFIG_ADC_BUTTON_GROUP1_BUTTON1_VOLT=2992`、 + `CONFIG_ADC_BUTTON_GROUP1_BUTTON2_VOLT=2345`, and the amplitude of the voltage + range for each ADC button (take half of the voltage + range)`CONFIG_ADC_BUTTON_GROUP1_BUTTON1_RANGE=315`、`CONFIG_ADC_BUTTON_GROUP1_BUTTON2_RANGE=245`。 + ![alt text](assets/adc.png) ## Software design -1. ADC key event processing function to parse key actions and trigger corresponding callbacks. First, determine whether the key action type is a click or a long press, then determine which button is based on the key index (pin value), and finally trigger the corresponding operation action by calling the global callback function action_cbk, so as to realize the mapping and transmission of key hardware events to business logic. +1. ADC key event processing function to parse key actions and trigger + corresponding callbacks. First, determine whether the key action type is a + click or a long press, then determine which button is based on the key index + (pin value), and finally trigger the corresponding operation action by + calling the global callback function action_cbk, so as to realize the mapping + and transmission of key hardware events to business logic. ```c static void adc_button_handler(uint8_t group_idx, int32_t pin, button_action_t action) { @@ -78,8 +112,13 @@ static void adc_button_handler(uint8_t group_idx, int32_t pin, button_action_t a } } ``` -2. Create and initialize a key controller, complete the key hardware initialization, and bind the event handling function. -Create a ButtonControls instance by allocating memory, configure the keystroke pins, activation level, mode, and other parameters, invoke button_init initialize the key driver, bind the ADC key processing function to the corresponding button, enable the key detection function, and save the callback function and key ID to complete the creation and initialization of the button controller. +2. Create and initialize a key controller, complete the key hardware + initialization, and bind the event handling function. Create a ButtonControls + instance by allocating memory, configure the keystroke pins, activation + level, mode, and other parameters, invoke button_init initialize the key + driver, bind the ADC key processing function to the corresponding button, + enable the key detection function, and save the callback function and key ID + to complete the creation and initialization of the button controller. ```c static ButtonControls* button_controls_create(ActionCallback_t on_action) { @@ -100,7 +139,9 @@ static ButtonControls* button_controls_create(ActionCallback_t on_action) } ``` -3. Action processing functions that execute specific business logic based on key actions. As a logical entry point, specific functions can be implemented here according to actual needs. +3. Action processing functions that execute specific business logic based on key + actions. As a logical entry point, specific functions can be implemented here + according to actual needs. ```c static void handle_action(ActionType action) { switch(action) { @@ -123,20 +164,22 @@ static void handle_action(ActionType action) { ``` #### Troubleshooting -|problem|possible cause| Workaround | -|----|----|----| -|keys are unresponsive|pin definition error| Check if the 'EPD_KEY_GPADC' definition is correct | -|keys not responding |driver not enabled|Confirm that 'RT_USING_BUTTON' and 'USING_ADC_BUTTON' | -|Key recognition error| ADC sample value interval overlap| Adjust the hardware voltage divider resistor to increase the difference in sampling values of different buttons -|Long press does not trigger |Long press time setting is too long |Reduce the 'BUTTON_ADV_ACTION_CHECK_DELAY' value| -|Frequent false triggers |Insufficient debrating time| Increased key debounce time (adjusted in button driver) | -|initialization failure |insufficient memory|Check the system memory usage and adjust the thread stack size| +| problem | possible cause | Workaround | +| --------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| Button unresponsive | pin definition error | Check if the 'EPD_KEY_GPADC' definition is correct | +| Button unresponsive | driver not enabled | Confirm that 'RT_USING_BUTTON' and 'USING_ADC_BUTTON' | +| Key recognition error | ADC sample value interval overlap | Adjust the hardware voltage divider resistor to increase the difference in sampling values of different buttons | +| Long press does not trigger | Long press time setting is too long | Reduce the 'BUTTON_ADV_ACTION_CHECK_DELAY' value | +| Frequent false triggers | Insufficient debrating time | Increased key debounce time (adjusted in button driver) | +| initialization failure | insufficient memory | Check the system memory usage and adjust the thread stack size | #### Routine output results display: -You can see the successful initialization of the button controller, as well as the printing effect of the button presses by short and long presses, as well as the current voltage value. +You can see the successful initialization of the button controller, as well as +the printing effect of the button presses by short and long presses, as well as +the current voltage value. ``` Button controller initialized successfully, ID:0 -msh />adc control origin data 3194, Voltage 24863 +msh />adc control origin data 3194, Voltage 24863 Second button clicked → Down adc control origin data 3853, Voltage 31785 First button clicked → Up @@ -148,7 +191,7 @@ First button long pressed → Select ## Update the record -|version |date |release notes | -|:---|:---|:---| -|0.0.1 |08/2025 |initial version | -`` \ No newline at end of file +| version | date | release notes | +| ------- | ------- | --------------- | +| 0.0.1 | 08/2025 | initial version | +`` diff --git a/example/misc/button/README_EN.md b/example/misc/button/README_EN.md index 4c55c5c7d..c7f97f065 100644 --- a/example/misc/button/README_EN.md +++ b/example/misc/button/README_EN.md @@ -7,59 +7,74 @@ Source code path: example/misc/button + sf32lb58-lcd series ## Overview -The button library uses pin devices to detect various button actions. It uses one timer to handle debouncing, and another timer to detect long press actions. +The button library uses pin devices to detect various button actions. It uses +one timer to handle debouncing, and another timer to detect long press actions. It supports the following operations: - Press: Button is pressed - Release: Button is released -- Long Press: Button is pressed and held for the time specified by `BUTTON_ADV_ACTION_CHECK_DELAY` -- Click: Button is pressed and released without triggering a long press action in between +- Long Press: Button is pressed and held for the time specified by + `BUTTON_ADV_ACTION_CHECK_DELAY` +- Click: Button is pressed and released without triggering a long press action + in between -Users can register handlers for each button to be notified when any action occurs. Button active state is configurable. +Users can register handlers for each button to be notified when any action +occurs. Button active state is configurable. ## Example Usage + ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation (board=board type): +Switch to the example project directory and run the scons command to execute +compilation (board=board type): ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted for download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted for download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -Confirm that rtconfig.h contains the following two macros. -The maximum number of supported buttons and long press action detection threshold are configured by the following macros: +Confirm that rtconfig.h contains the following two macros. The maximum number of +supported buttons and long press action detection threshold are configured by +the following macros: ```c #define BUTTON_MAX_NUM 2 #define BUTTON_ADV_ACTION_CHECK_DELAY 3000 ``` -They can be configured under `SiFli Middleware->Enable button library`. You can enter by typing `menuconfig` in the compilation interface: -![alt text](assets/button_menu.png) +They can be configured under `SiFli Middleware->Enable button library`. You can +enter by typing `menuconfig` in the compilation interface: ![alt +text](assets/button_menu.png) + + + + + ## Using the Button Library -In the following example, it first initializes the button, i.e., binds the button with the pin device and registers button action handlers. Then enables button detection, i.e., enables pin IRQ. +In the following example, it first initializes the button, i.e., binds the +button with the pin device and registers button action handlers. Then enables +button detection, i.e., enables pin IRQ. ### Hardware Connection -* Note: 587 pins are divided into groups A and B, group B pin numbers need to add 96 +* Note: 587 pins are divided into groups A and B, group B pin numbers need to + add 96 54+96->150\ 56+96->152\ -button52 -![button52](./assets/button_Schematic_52.png) -button587 -![button587](./assets/button_Schematic_587.png) -button56 +button52 ![button52](./assets/button_Schematic_52.png) button587 +![button587](./assets/button_Schematic_587.png) button56 ![button587](./assets/button_Schematic_56.png) + #### Button Configuration Process ```c static void button_event_handler(int32_t pin, button_action_t action) @@ -68,15 +83,15 @@ static void button_event_handler(int32_t pin, button_action_t action) } -// Initialization button +// Initialize button button_cfg_t cfg; cfg.pin = BSP_KEY1_PIN; cfg.active_state = BUTTON_ACTIVE_HIGH; cfg.mode = PIN_MODE_INPUT; cfg.button_handler = button_event_handler; - int32_t id = button_init(&cfg); - RT_ASSERT(id >= 0); + int32_t id = button_init(&cfg); + RT_ASSERT(id >= 0); RT_ASSERT(SF_EOK == button_enable(id)); @@ -84,13 +99,18 @@ static void button_event_handler(int32_t pin, button_action_t action) cfg.active_state = BUTTON_ACTIVE_HIGH; cfg.mode = PIN_MODE_INPUT; cfg.button_handler = button_event_handler; - id = button_init(&cfg); - RT_ASSERT(id >= 0); + id = button_init(&cfg); + RT_ASSERT(id >= 0); RT_ASSERT(SF_EOK == button_enable(id)); ``` -* Pay attention The pin numbers of `BSP_KEY1_PIN` and `BSP_KEY2_PIN` are derived from the `board.conf` configuration used during compilation, such as `sf32lb52-lcd_n16r8`. We can view this information in the file `sf32lb52-lcd_n16r8/hcpu/board.conf`. +* Pay attention The pin numbers of `BSP_KEY1_PIN` and `BSP_KEY2_PIN` are + derived from the `board.conf` configuration used during compilation, such as + `sf32lb52-lcd_n16r8`. We can view this information in the file + `sf32lb52-lcd_n16r8/hcpu/board.conf`. #### Button Pin Parameter Modification +![Serial](./assets/button_Serial_print.png) +* Log output: ```c #if defined(BSP_USING_BOARD_EM_LB525XXX) @@ -102,39 +122,30 @@ static void button_event_handler(int32_t pin, button_action_t action) #endif ``` -#### Example Output Results Display: -![Serial](./assets/button_Serial_print.png) -* Log output: - -```c -button:34,0 -button:34,3 -button:34,1 -button:11,0 -button:11,3 -button:11,1 -``` - -* Meaning of actions represented by states 0,1,2,3: +* Definitions of actions for states 0, 1, 2, and 3: ```c - action: +action: BUTTON_PRESSED = 0, Indicates that a button is pressed BUTTON_RELEASED = 1, Indicates that a button is released BUTTON_LONG_PRESSED = 2, Indicates that a button is long released BUTTON_CLICKED = 3, Indicates that a button is clicked ``` - -**Note**: -1. Interrupt handling functions can be viewed in startup_bf0_hcpu.S -2. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +**Note**: +1. The interrupt service routines (ISRs) can be found in startup_bf0_hcpu.S. +2. The last parameter of HAL_PIN_Set selects between HCPU and LCPU (1: HCPU, 0: + LCPU). ## Exception Diagnosis -If button press does not produce expected print results, troubleshooting can be performed from the following aspects: +If button press does not produce expected print results, troubleshooting can be +performed from the following aspects: * Whether hardware connections are normal * Whether pin configuration (especially pin mode configuration) is correct ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 |12/2024 |2.0 | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +``` + +``` diff --git a/example/misc/elm_rw/README_EN.md b/example/misc/elm_rw/README_EN.md index fcc36498d..4ef4a3ea9 100644 --- a/example/misc/elm_rw/README_EN.md +++ b/example/misc/elm_rw/README_EN.md @@ -1,6 +1,8 @@ # ELM_RW Example +Source path: example/misc/elm_rw ## Overview -This example demonstrates file data read/write operations using ELM, paired with FsrwTool for visual file transfer. +This example demonstrates file data read/write operations using ELM, paired with +FsrwTool for visual file transfer. ## Supported Development Boards The example can run on the following development boards.
@@ -8,11 +10,14 @@ The example can run on the following development boards.
+ sf32lb56-lcd series + sf32lb58-lcd series - -**Note:** Generally, examples run on the chip's HCPU. "eh-lb563_v2" is equivalent to "eh-lb563_v2_hcpu". If you want to run the example on LCPU, you can use "eh-lb563_v2_lcpu". Currently, USB functionality is temporarily only supported on HCPU. +**Note:** Generally, examples run on the chip's HCPU. "eh-lb563_v2" is +equivalent to "eh-lb563_v2_hcpu". If you want to run the example on LCPU, you +can use "eh-lb563_v2_lcpu". Currently, USB functionality is temporarily only +supported on HCPU. ## Example Directory Structure -The ELM_RW project contains 1 .c file (main.c). The tree structure below shows other files in the project directory. +The ELM_RW project contains 1 .c file (main.c). The tree structure below shows +other files in the project directory. ```c |--README.md |--src @@ -28,8 +33,10 @@ The ELM_RW project contains 1 .c file (main.c). The tree structure below shows o ``` ## Using the Example ### Hardware Requirements -1. The prerequisite for running the example is having a development board that supports this example. -2. A USB data cable capable of data transmission. +1. Prerequisites include a development board that supports this routine.\ +2. A USB data cable with data transmission capabilities is required. + + ### menuconfig Configuration ```c @@ -37,22 +44,24 @@ The ELM_RW project contains 1 .c file (main.c). The tree structure below shows o menuconfig --board=sf32lb52-lcd_n16r8 ``` #### menuconfig Configuration 1 -Controls whether to compile and enable support for NOR Flash devices. -![alt text](assets/Using_MTD_Nor_Flash.png) +Controls whether to compile and enable support for NOR Flash devices. ![alt +text](assets/Using_MTD_Nor_Flash.png) -Support for NAND flash devices corresponding to the board -![alt text](assets/nand_flash.png) +Support for NAND flash devices corresponding to the board ![alt +text](assets/nand_flash.png) #### menuconfig Configuration 2 -Enable Device File System (DFS) and ELM FAT file system support. DFS is an abstraction layer in the RT-Thread operating system used to uniformly manage different types of file systems. -![alt text](assets/Enable_elm_chan_fatfs.png) +Enable Device File System (DFS) and ELM FAT file system support. DFS is an +abstraction layer in the RT-Thread operating system used to uniformly manage +different types of file systems. ![alt text](assets/Enable_elm_chan_fatfs.png) #### menuconfig Configuration 3 -Enable ELM module read/write functionality. -![alt text](assets/Use_elm_trans_tool.png) +Enable ELM module read/write functionality. ![alt +text](assets/Use_elm_trans_tool.png) + ### Compilation and Programming Following these steps, you can complete compilation and programming. -> scons --board=sf32lb52-lcd_n16r8 +> scons --board=sf32lb52-lcd_n16r8 > .\build_sf32lb52-lcd_n16r8\uart_download.bat @@ -60,10 +69,11 @@ Following these steps, you can complete compilation and programming. The results below show the logs after the example runs on the development board. System startup - > mount /dev sucess\ - > mount fs on flash to root success\ - > Use help to check elm_rw file system command!\ - > msh /> +> mount /dev sucess\ +> mount fs on flash to root success\ +> Use help to check elm_rw file system command!\ +> msh /> + ![alt text](assets/elm_rw_success.png) @@ -73,20 +83,23 @@ System startup ![alt text](assets/Instructions.png) ### File Import: -We drag the files we want to import into the list box, click file import, and pay attention to serial port connection and baud rate configuration -![alt text](assets/file_in_out.png) +We drag the files we want to import into the list box, click file import, and +pay attention to serial port connection and baud rate configuration ![alt +text](assets/file_in_out.png) ### View Information of Imported Files: -Use the `ls` command to view file information. The a.txt in the example has no content so it shows 0 characters. Use the `echo "123" a.txt` command to add file content, where the content in quotes is what you want to add to the file -![alt text](assets/file.png) -![alt text](assets/add_message.png) +Use the `ls` command to view file information. The a.txt in the example has no +content so it shows 0 characters. Use the `echo "123" a.txt` command to add file +content, where the content in quotes is what you want to add to the file ![alt +text](assets/file.png) ![alt text](assets/add_message.png) ### File Export: -* FsrwTool file export does not move files from the development board but copies them out (the board will still retain the previously imported files) -* You can see that after adding content, the opened a.txt file content has changed -![alt text](assets/fiel_message.png) +* FsrwTool file export does not move files from the development board but copies + them out (the board will still retain the previously imported files) +* You can see that after adding content, the opened a.txt file content has + changed ![alt text](assets/fiel_message.png) ### File Deletion: -* Enter `rm file` to delete files imported to the development board -![alt text](assets/rm_file.png) +* Enter `rm file` to delete files imported to the development board ![alt + text](assets/rm_file.png) ### FsrwTool-log * File import log @@ -97,9 +110,13 @@ Use the `ls` command to view file information. The a.txt in the example has no c ![alt text](assets/FsrwTool_log_out.png) - ## Troubleshooting -If the expected logs do not appear, troubleshooting can be performed from the following aspects: + + +## Troubleshooting +If the expected logs do not appear, troubleshooting can be performed from the +following aspects: * Whether hardware connections are normal * Whether menuconfig configuration is set * Whether the development board flash is normal -* Whether imported/exported files are empty or duplicated \ No newline at end of file +* Whether imported/exported files are empty or duplicated + diff --git a/example/misc/generate_lib/README_EN.md b/example/misc/generate_lib/README_EN.md index 59035571f..20db15b81 100644 --- a/example/misc/generate_lib/README_EN.md +++ b/example/misc/generate_lib/README_EN.md @@ -1,32 +1,36 @@ # Generate Library Example +Source path: example/misc/generate_lib ## Supported Platforms and Build Environments - + - Independent of board and which SiFli MCU series is used -- The build environment for compiling libraries depends on the build environment configuration used by normal projects +- The build environment for compiling libraries depends on the build environment + configuration used by normal projects - Verified environments include KeilC and GCC ## Overview -Some customers, due to confidentiality requirements or other reasons, are unwilling to disclose source code and need to compile lib libraries for customer use, hence this example is provided. +Some customers, due to confidentiality requirements or other reasons, are +unwilling to disclose source code and need to compile lib libraries for customer +use, hence this example is provided. + ## Compilation Method -1. Set up build environment
-The prerequisite for compiling lib is that normal projects can be compiled with KeilC or GCC
-2. Place the source files that need to be generated into lib in the `example\misc\generate_lib\lib` directory. -All source files `*.c,*.h` in this directory will be packaged and compiled into a lib_rvds.lib file -3. Compile lib
-Switch to the example `example\misc\generate_lib\project` directory and run the scons command to execute compilation:
+1. Set up build environment
The prerequisite for compiling lib is that + normal projects can be compiled with KeilC or GCC
+2. Place the source files that need to be generated into lib in the + `example\misc\generate_lib\lib` directory. All source files `*.c,*.h` in this + directory will be packaged and compiled into a lib_rvds.lib file +3. Compile lib
Switch to the example `example\misc\generate_lib\project` + directory and run the scons command to execute compilation:
``` scons -j16 ``` -Where the parameter `-j16` is for 16-thread compilation
-Compilation process:
-![alt text](./assert/lib001.png)
-Generated lib as follows:
-![alt text](./assert/lib002.png)
-**Note**
-Files compiled into lib are those defined as `lib` group in the `SConscript` file. The compilation group is specified in the libname of `rtconfig.py`. You can modify them synchronously if needed;
-Configuration in `example\misc\generate_lib\lib\SConscript`:
+Where the parameter `-j16` is for 16-thread compilation
Compilation +process:
![alt text](assert/lib001.png)
Generated lib as follows:
+![alt text](assert/lib002.png)
**Note**
Files compiled into lib are +those defined as `lib` group in the `SConscript` file. The compilation group is +specified in the libname of `rtconfig.py`. You can modify them synchronously if +needed;
Configuration in `example\misc\generate_lib\lib\SConscript`:
``` group = DefineGroup('lib', src, depend = [''], CPPPATH = CPPPATH) ``` @@ -35,24 +39,33 @@ Configuration in `example\misc\generate_lib\project\rtconfig.py`:
libname="lib" ``` ## Usage Method -1. Copy the generated `lib_rvds.lib` file to the project directory that needs to be compiled, and modify the SConscript file in the corresponding directory. Here we use the `example\get-started\hello_world\rtt` example as an illustration, as shown below:
-![alt text](./assert/lib003.png)
+1. Copy the generated `lib_rvds.lib` file to the project directory that needs to + be compiled, and modify the SConscript file in the corresponding directory. + Here we use the `example\get-started\hello_world\rtt` example as an + illustration, as shown below:
![alt text](assert/lib003.png)
``` path = GetCurrentDir() lib = ['lib_rvds'] group = DefineGroup('lib', src, depend = [''], LIBS = lib, CPPPATH = path, LIBPATH = path) ``` -2. During compilation, if functions in `lib_rvds.lib` can be found, the lib linking is successful
+2. During compilation, if functions in `lib_rvds.lib` can be found, the lib + linking is successful
## Troubleshooting -- **Compilation Failure**: Ensure source files have no syntax errors and build environment is configured correctly -- **Linking Errors**: Check library file path is correct and function declarations match -- **Library File Not Generated**: Verify `SConscript` and `rtconfig.py` configurations +- **Compilation Failure**: Ensure source files have no syntax errors and build + environment is configured correctly +- **Linking Errors**: Check library file path is correct and function + declarations match +- **Library File Not Generated**: Verify `SConscript` and `rtconfig.py` + configurations -For any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub +For any technical questions, please submit an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub ## Reference Documentation -- [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SCons Build System Documentation](https://scons.org/documentation.html) \ No newline at end of file +- [SiFli-SDK Quick Start + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SCons Build System Documentation](https://scons.org/documentation.html) + diff --git a/example/misc/index_EN.md b/example/misc/index_EN.md index 6497acd7d..75c60be6d 100644 --- a/example/misc/index_EN.md +++ b/example/misc/index_EN.md @@ -4,6 +4,4 @@ :glob: */* - - ``` diff --git a/example/multicore/acpu_task/README_EN.md b/example/multicore/acpu_task/README_EN.md index 79b6b0bc2..ef3342574 100644 --- a/example/multicore/acpu_task/README_EN.md +++ b/example/multicore/acpu_task/README_EN.md @@ -1,23 +1,28 @@ -# ACPU Executes Custom Tasks -Source Code Path: `example/multicore/acpu_task` +# ACPU Custom Task Execution. Source code path: `example/multicore/acpu_task` ## Usage -### Supported Development Boards - +### Supported Boards + + ec-lb583 + ec-lb587 ## Overview -This example demonstrates how to configure ACPU to execute custom tasks, send task instructions through HCPU, and receive execution results. This example mainly uses the multi-core communication framework and task scheduling functions of SiFli-SDK. -Based on this example, developers can build application scenarios that require heterogeneous multi-core collaboration, such as assigning computationally intensive tasks to ACPU for processing to improve overall system performance. - -This example demonstrates how to configure ACPU to execute custom tasks +This example demonstrates how to configure the ACPU to execute custom tasks, +with the HCPU issuing task commands and receiving execution results. The +implementation leverages the multi-core communication framework and task +scheduling capabilities of the SiFli-SDK. Developers can use this as a reference +for heterogeneous multi-core collaboration scenarios, such as offloading +computationally intensive tasks to the ACPU to enhance overall system +performance. + +This example demonstrates how to configure the ACPU to execute custom tasks. ### Hardware Requirements -No special hardware requirements, just use a supported development board to run normally. +No specialized hardware is required; the example runs on any supported +development board. ### Compilation and Flashing @@ -30,41 +35,61 @@ No special hardware requirements, just use a supported development board to run ### Compilation and Flashing -Execute the `scons --board=` command in the `project/hcpu` directory to compile and generate the image file for the required board. For example, execute the `scons --board=ec-lb587` command to generate the image file for the `587-evb` development board. After compilation, run the command `build_\download.bat` to flash the image file, such as `build_ec-lb587\download.bat` +Navigate to the `project/hcpu` directory and execute the `scons +--board=` command to compile the image for the target board. For +example, run `scons --board=ec-lb587` to generate the image for the `587-evb` +development board. Once compilation is complete, run +`build_\download.bat` to flash the image (e.g., +`build_ec-lb587\download.bat`). -## Expected Result of the Example +## Expected Results -Send the `run_acpu ` command (with carriage return) in the serial console window, where `` is a number greater than or equal to 0, corresponding to TASK_0, TASK_1, etc. in sequence. The running result is as follows +Send the command `run_acpu ` (followed by a carriage return) via the +serial console. The `` should be an integer starting from 0, +corresponding to TASK_0, TASK_1, etc. The expected output is as +follows: ``` -12-28 20:17:23:794 msh /> -12-28 20:17:23:844 msh /> +12-28 20:17:23:794 msh /> +12-28 20:17:23:844 msh /> 12-28 20:17:26:560 TX:run_acpu 0 12-28 20:17:26:732 run_acpu 0 12-28 20:17:26:772 [I/main] task_0 -12-28 20:17:26:790 msh /> -12-28 20:17:26:809 msh /> +12-28 20:17:26:790 msh /> +12-28 20:17:26:809 msh /> 12-28 20:17:29:006 TX:run_acpu 1 12-28 20:17:29:149 run_acpu 1 12-28 20:17:29:160 [I/main] task_1 -12-28 20:17:29:179 msh /> -12-28 20:17:29:194 msh /> +12-28 20:17:29:179 msh /> +12-28 20:17:29:194 msh /> 12-28 20:17:30:203 TX:run_acpu 2 12-28 20:17:30:332 run_acpu 2 12-28 20:17:30:347 [I/main] unknown task -12-28 20:17:30:358 msh /> -12-28 20:17:30:366 msh /> +12-28 20:17:30:358 msh /> +12-28 20:17:30:366 msh /> 12-28 20:17:31:285 TX:run_acpu 3 12-28 20:17:31:425 run_acpu 3 12-28 20:17:31:437 [I/main] unknown task -12-28 20:17:31:464 msh /> +12-28 20:17:31:464 msh /> ``` -## Code Explanation +## Code Description +The function `acpu_main` in `src/acpu/main.c` serves as the entry point for ACPU +task processing, executing the corresponding code block based on the received +task ID. + +The `acpu_run_task` function in `src/hcpu/main.c` is called to configure a task +for ACPU execution. This function operates in blocking mode and does not return +until the ACPU provides a result; during this execution, the calling thread is +suspended while waiting for a semaphore. + +The ACPU image is stored in Flash and programmed via a flashing script. The +secondary bootloader copies the ACPU code to the RAM address corresponding to +address 0 in the ACPU instruction space. For example, the following code is +excerpted from the generated file `ftab.c`: `.base=0x69100000` indicates that +the ACPU image starts at Flash address 0x69100000, while `xip_base=0x20200000` +specifies that the secondary bootloader will copy the ACPU code to RAM starting +at 0x20200000, which maps to address 0 in the ACPU instruction space. -The function `acpu_main` in `src/acpu/main.c` is the entry function for ACPU to process tasks, executing corresponding code according to the received task ID -The `acpu_run_task` function is called in `src/hcpu/main.c` to configure ACPU to execute a certain task. This function runs in blocking mode and will not return until ACPU returns the result. During this period, the thread calling this function will be suspended due to waiting for a semaphore -The ACPU image file is stored in Flash and programmed into Flash by the programming script. The secondary boot copies the ACPU code to the RAM corresponding to address 0 of the ACPU instruction space. -For example, the following code is excerpted from the compiled ftab.c. `.base=0x69100000` indicates that the ACPU image file is stored in Flash starting from address 0x69100000. `xip_base=0x20200000` indicates that the secondary boot will copy the ACPU code to the RAM starting from 0x20200000. 0x20200000 corresponds to address 0 of the ACPU instruction space. ```c RT_USED const struct sec_configuration sec_config = { @@ -73,9 +98,12 @@ RT_USED const struct sec_configuration sec_config = .imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_HCPU_EXT2)] = {.length = 0x00000AE4, .blksize = 512, .flags = DFU_FLAG_AUTO}, }; ``` -The implementation of the secondary boot copying ACPU code can be found in the `boot_images` function in `example\boot_loader\project\sf32lb58x_v2\board\main.c` as follows: + +The implementation for the secondary bootloader copying the ACPU code can be +found in the `boot_images` function within +`example\boot_loader\project\sf32lb58x_v2\board\main.c`, as shown below: ```c -if (g_sec_config->imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_HCPU_EXT2)].length != FLASH_UNINIT_32) +if (g_sec_config->imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_HCPU_EXT2)].length != FLASH_UNINIT_32) { dfu_boot_img_in_flash(DFU_FLASH_HCPU_EXT2); } @@ -83,10 +111,15 @@ if (g_sec_config->imgs[DFU_FLASH_IMG_IDX(DFU_FLASH_HCPU_EXT2)].length != FLASH_U ## Troubleshooting -- **Compilation Errors**: Ensure the SiFli-SDK development environment is configured correctly and check that the board name is correct -- **Programming Failure**: Confirm the development board is connected correctly and try re-plugging the USB cable +- **Compilation Error**: Verify that the SiFli-SDK development environment is + correctly configured and ensure the board model name is correct. +- **Flashing Failed**: Confirm the development board is properly connected and + try reconnecting the USB cable. + +## References -## Reference Documents +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [Multicore Communication Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/multicore/index.html) -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [Multi-core Communication Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/multicore/index.html) \ No newline at end of file diff --git a/example/multicore/data_service/README_EN.md b/example/multicore/data_service/README_EN.md index 0e2d9c0c9..6affb60d5 100644 --- a/example/multicore/data_service/README_EN.md +++ b/example/multicore/data_service/README_EN.md @@ -1,15 +1,25 @@ # Data Service Example -(For an overview of examples and their usage, please refer to the `README.md` file in the parent "examples" directory.) +(For an overview of examples and their usage, please refer to the `README.md` +file in the parent "examples" directory.) Source Code Path: example/multicore/data_service -This is an example demonstrating data service communication between HCPU and LCPU in a multi-core system. Its core features include: -- Platform UART Configuration: For 55x platforms, HCPU uses UART1 (second enumerated UART) as console, LCPU uses UART3 (first enumerated UART); For 58x platforms, HCPU uses UART1 (first enumerated UART) as console, LCPU uses UART4 (third enumerated UART) -- Service Communication Mechanism: LCPU registers a "test" service, and HCPU subscribes to this service to achieve bidirectional communication -- Command Interaction Flow: HCPU sends `request` command to obtain responses with count values, LCPU sends `trigger`/`trigger2` commands to trigger notification messages with count values +This is an example demonstrating data service communication between HCPU and +LCPU in a multi-core system. Its core features include: +- Platform UART Configuration: For 55x platforms, HCPU uses UART1 (second + enumerated UART) as console, LCPU uses UART3 (first enumerated UART); For 58x + platforms, HCPU uses UART1 (first enumerated UART) as console, LCPU uses UART4 + (third enumerated UART) +- Service Communication Mechanism: LCPU registers a "test" service, and HCPU + subscribes to this service to achieve bidirectional communication +- Command Interaction Flow: HCPU sends `request` command to obtain responses + with count values, LCPU sends `trigger`/`trigger2` commands to trigger + notification messages with count values -This example uses the multi-core communication framework and service registration/subscription mechanism of SiFli-SDK, serving as a basic reference for developing inter-process communication in multi-core heterogeneous systems. +This example uses the multi-core communication framework and service +registration/subscription mechanism of SiFli-SDK, serving as a basic reference +for developing inter-process communication in multi-core heterogeneous systems. ## Usage ### Supported Development Boards @@ -24,12 +34,13 @@ This example can run on the following development boards: - sf32lb58-lcd series ### Hardware Requirements -The supported development boards mentioned above are required; no additional hardware is needed. +The supported development boards mentioned above are required; no additional +hardware is needed. ### Compilation Method Navigate to the hcpu directory and execute the following command to compile: ```bash -scons --board= -j8 +scons --board= -j8 ``` The compiled image files are stored in the HCPU's build_ directory. @@ -41,12 +52,19 @@ The compiled image files are stored in the HCPU's build_ directory. - ec-lb587 - eh-lb561 - eh-lb563 -- Compilation method: Navigate to the hcpu directory and execute the command `scons --board= -j8`, where board_name is the board model. For example, to compile for the eh-lb561 board, use the complete command `scons --board=eh-lb561 -j8` - The compiled image files are stored in the HCPU's build_ directory. For project usage, refer to the <> -- Custom message IDs and structures for the test service are defined in `src/common/test_service.h` - - `test_service_data_rsp_t`: Structure for `MSG_SERVICE_TEST_DATA_RSP` message body - - `test_service_data_ntf_ind_t`: Structure for `MSG_SERVICE_DATA_NTF_IND` message body - - `test_service_data2_ind_t`: Structure for `MSG_SERVICE_TEST_DATA2_IND` message body +- Compilation method: Navigate to the hcpu directory and execute the command + `scons --board= -j8`, where board_name is the board model. For + example, to compile for the eh-lb561 board, use the complete command `scons + --board=eh-lb561 -j8` The compiled image files are stored in the HCPU's + build_ directory. For project usage, refer to the <{1}> +- Custom message IDs and structures for the test service are defined in + `src/common/test_service.h` + - `test_service_data_rsp_t`: Structure for `MSG_SERVICE_TEST_DATA_RSP` message + body + - `test_service_data_ntf_ind_t`: Structure for `MSG_SERVICE_DATA_NTF_IND` + message body + - `test_service_data2_ind_t`: Structure for `MSG_SERVICE_TEST_DATA2_IND` + message body - Code implementation locations - HCPU: `src/hcpu/main.c` - LCPU: `src/lcpu/main.c` @@ -54,19 +72,16 @@ The compiled image files are stored in the HCPU's build_ directory. ## Example Output Interact with the service through console commands: - Send the `request` command in the HCPU console to send a request message -- Send the `trigger` or `trigger2` command in the LCPU console to trigger notification messages +- Send the `trigger` or `trigger2` command in the LCPU console to trigger + notification messages -The logs of HCPU and LCPU are as follows: -![alt text](assets/image1.png) -HCPU发送request命令 -![alt text](assets/image2.png) -LCPU发送trigger命令 -![alt text](assets/image3.png) -LCPU发送trigger2命令 -![alt text](assets/image4.png) +The logs of HCPU and LCPU are as follows: ![alt text](assets/image1.png) +HCPU发送request命令 ![alt text](assets/image2.png) LCPU发送trigger命令 ![alt +text](assets/image3.png) LCPU发送trigger2命令 ![alt text](assets/image4.png) ## Troubleshooting -No specific troubleshooting information is available. If you encounter issues, please refer to the SiFli-SDK official documentation or submit an issue. +No specific troubleshooting information is available. If you encounter issues, +please refer to the SiFli-SDK official documentation or submit an issue. ## Reference Documentation -- [SiFli-SDK Official Documentation](https://docs.sifli.com) \ No newline at end of file +- [SiFli-SDK Official Documentation](https://docs.sifli.com) diff --git a/example/multicore/index_EN.md b/example/multicore/index_EN.md index eba9cb634..5b27a6254 100644 --- a/example/multicore/index_EN.md +++ b/example/multicore/index_EN.md @@ -4,4 +4,4 @@ :glob: */* -``` \ No newline at end of file +``` diff --git a/example/multicore/ipc_queue/README_EN.md b/example/multicore/ipc_queue/README_EN.md index f8ea52c2c..2d826a299 100644 --- a/example/multicore/ipc_queue/README_EN.md +++ b/example/multicore/ipc_queue/README_EN.md @@ -1,9 +1,15 @@ # IPC Queue Example -Source Code Path: example/multicore/ipc_queue -The IPC Queue example demonstrates how to use inter-core queues (IPC Queue) in SiFli-SDK to implement bidirectional communication between HCPU and LCPU. This example utilizes the SDK's IPC queue management API, supporting reliable inter-core message delivery, suitable for multi-core application scenarios requiring efficient inter-core communication. +Source Code Path: example/multicore/ipc_queue The IPC Queue example demonstrates +how to use inter-core queues (IPC Queue) in SiFli-SDK to implement bidirectional +communication between HCPU and LCPU. This example utilizes the SDK's IPC queue +management API, supporting reliable inter-core message delivery, suitable for +multi-core application scenarios requiring efficient inter-core communication. ## Usage -The following sections provide only essential information. For complete steps on configuring SiFli-SDK and building/running projects, please refer to the [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). +The following sections provide only essential information. For complete steps on +configuring SiFli-SDK and building/running projects, please refer to the +[SiFli-SDK Quick Start +Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). ### Supported Development Boards This example can run on the following development boards: @@ -16,39 +22,53 @@ This example can run on the following development boards: - sf32lb56-lcd series - sf32lb58-lcd series - ### Hardware Requirements -This example requires no special hardware and can run directly on supported development boards. +This example requires no special hardware and can run directly on supported +development boards. ### Compilation and Flashing Execute the compilation command in the hcpu directory: ```bash -scons --board= -j8 +scons --board= -j8 ``` -Where board_name is the board model. For example, to compile for the eh-lb561 board, use the complete command: +Where board_name is the board model. For example, to compile for the eh-lb561 +board, use the complete command: ```bash scons --board=eh-lb561 -j8 ``` -The compiled image files are stored in the HCPU's build_ directory. Use the following command to flash: +The compiled image files are stored in the HCPU's build_ directory. +Use the following command to flash: ```bash -build_/download.bat +build_/download.bat ``` ### Console Configuration -- For 55x platforms, HCPU uses UART1 (second enumerated serial port) as console, LCPU uses UART3 as console (first enumerated serial port). - For 58x platforms, HCPU uses UART1 (first enumerated serial port) as console, LCPU uses UART4 as console (third enumerated serial port). -- Send command `lcpu on` in HCPU console to start LCPU. After successful startup, you can see the startup log on LCPU console. -- Both HCPU and LCPU consoles can use the command `send message` to send a string to the other core, - where `message` is the content to send. If the string contains spaces, it needs to be enclosed in double quotes. - The other core will print the received string. - For example, sending `send "Hello LCPU, this is HCPU"` in HCPU console will result in `rx: Hello LCPU, this is HCPU` being printed in LCPU console. +- For 55x platforms, HCPU uses UART1 (second enumerated serial port) as console, + LCPU uses UART3 as console (first enumerated serial port). For 58x platforms, + HCPU uses UART1 (first enumerated serial port) as console, LCPU uses UART4 as + console (third enumerated serial port). +- Send command `lcpu on` in HCPU console to start LCPU. After successful + startup, you can see the startup log on LCPU console. +- Both HCPU and LCPU consoles can use the command `send message` to send a + string to the other core, where `message` is the content to send. If the + string contains spaces, it needs to be enclosed in double quotes. The other + core will print the received string. For example, sending `send "Hello LCPU, + this is HCPU"` in HCPU console will result in `rx: Hello LCPU, this is HCPU` + being printed in LCPU console. ## Troubleshooting -- **Compilation Errors**: Ensure the SiFli-SDK development environment is properly configured and check that the board name is correct. -- **Flashing Failures**: Verify the development board is properly connected and try reconnecting the USB cable. -- **Communication Issues**: Check IPC queue configuration and confirm macro definitions in `src/common/ipc_config.h` and `linker_scripts/custom_mem_map.h`. +- **Compilation Errors**: Ensure the SiFli-SDK development environment is + properly configured and check that the board name is correct. +- **Flashing Failures**: Verify the development board is properly connected and + try reconnecting the USB cable. +- **Communication Issues**: Check IPC queue configuration and confirm macro + definitions in `src/common/ipc_config.h` and + `linker_scripts/custom_mem_map.h`. ## Reference Documentation -- [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [Multi-core Communication Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/multicore/index.html) -- [IPC Queue API Documentation](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/api/ipc_queue.html) \ No newline at end of file +- [SiFli-SDK Quick Start + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [Multi-core Communication Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/multicore/index.html) +- [IPC Queue API + Documentation](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/api/ipc_queue.html) diff --git a/example/multicore/rpmsg-lite/README_EN.md b/example/multicore/rpmsg-lite/README_EN.md index c76c8884d..ae123c8ee 100644 --- a/example/multicore/rpmsg-lite/README_EN.md +++ b/example/multicore/rpmsg-lite/README_EN.md @@ -1,30 +1,92 @@ # RPMsg-Lite Example -### Supported Development Boards -This example can run on the following development boards: + +(For a general overview of the examples and their usage, please refer to the +`README.md` file in the parent "examples" directory.) + +Source Path: example/multicore/rpmsg-lite + +The RPMsg-Lite example demonstrates bidirectional communication between the HCPU +and LCPU within the SiFli-SDK. Leveraging the SDK's RPMsg-Lite API, the example +utilizes shared memory and mailbox interrupt mechanisms for inter-processor +communication (IPC), making it suitable for multi-core applications requiring +high-efficiency data transfer. + +RPMsg-Lite is a lightweight Remote Processor Messaging protocol that supports +asynchronous cross-core communication, using an endpoint mechanism to achieve +multi-channel communication isolation. +## Overview + +### Supported Boards +This example can be executed on the following development boards: - eh-lb551 - eh-lb555 - sf32lb56-lcd series - sf32lb58-lcd series -## Overview -This example demonstrates the basic usage of the RPMsg-Lite component. +The following sections provide only essential information. For complete steps on +configuring the SiFli-SDK and using it to build and run projects, please refer +to the [SiFli-SDK Quick Start +Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). -## How to Use the Example -- RPMsg-Lite uses queue4 and queue5 as bidirectional communication channels. HCPU acts as master and LCPU acts as remote. The master's endpoint is 30, and the remote's endpoint is 40. - The shared buffer must be allocated in LCPU's RAM, with the address specified by the macro `RPMSG_BUF_ADDR_MASTER`, and buffer size specified by the macro `RPMSG_BUF_SIZE`. - These macros are defined in header files `src\common\ipc_config.h`, `project\hcpu\custom_mem_map.h`, and `project\lcpu\custom_mem_map.h`. -- It is recommended to initialize the RPMsg-Lite module during the `INIT_APP_EXPORT` stage to avoid premature mailbox interrupt activation affecting the data_service module. -- HCPU's main function is located in `src/hcpu/main.c`, and LCPU's main function is in `src/lcpu/main.c`. -- For compilation methods, refer to the general project compilation. For example, execute `scons --board=eh-lb551 -j8` in the `project\hcpu` directory to compile programs running on the eh-lb551 board, where --board is followed by the board name. - To compile programs for 555hdk, execute the command `scons --board=eh-lb555 -j8`. After compilation, use the `build_eh-lb551/download.bat` command to download the bin file to the board. +### Hardware Requirements +No special hardware is required; this example runs directly on the supported +development boards. -## Example Output -HCPU and LCPU automatically send messages to each other at regular intervals: -- When LCPU receives a message, it prints: `rx: hello_from_hcpu` -- When HCPU receives a message, it prints: `rx: hello_from_lcpu` -- The master core can send a string to the other core using the console command `send message`, where `message` is the content to send. If the string contains spaces, it must be enclosed in double quotes. The other core will print the received string. +### Project Configuration +- RPMsg-Lite utilizes queue4 and queue5 as bidirectional communication channels, + where the HCPU acts as the master and the LCPU as the remote. The master + endpoint is set to 30, and the remote endpoint is 40. The shared buffer must + be allocated in the LCPU RAM. The buffer address is specified by the + `RPMSG_BUF_ADDR_MASTER` macro, and the size is defined by the `RPMSG_BUF_SIZE` + macro. These macros are defined in `src\common\ipc_config.h`, + `project\hcpu\custom_mem_map.h`, and `project\lcpu\custom_mem_map.h`. +- It is recommended to initialize the RPMsg-Lite module during the + `INIT_APP_EXPORT` stage to prevent early mailbox interrupts from affecting the + data_service module. +- The HCPU main function is located in `src/hcpu/main.c`, and the LCPU main + function is in `src/lcpu/main.c`. + +### Compilation and Flashing +Refer to the standard project compilation process. Execute the following in the +`project/hcpu` directory: ```bash -# Send message in HCPU console +scons --board= -j8 +``` +The `board_name` parameter specifies the target board. For example, to compile +the program for the `eh-lb551` board, use the following command: +```bash +scons --board=eh-lb551 -j8 +``` +After compilation is complete, use the following command to flash the binary +file to the board: +```bash +build_/download.bat +``` + +### Console Configuration +- Select the serial ports for HCPU and LCPU logging according to the development + board documentation. Some boards use separate serial ports for HCPU and LCPU + logs, while others multiplex a single serial port for both. +- Upon power-up, the HCPU automatically invokes `lcpu_power_on` to boot the + LCPU. Once the boot process completes, the startup logs will be displayed on + the LCPU console. + +## How to Use the Example +The HCPU and LCPU exchange periodic messages automatically: +- RPMsg-Lite uses queue4 and queue5 as bidirectional communication channels. + HCPU acts as master and LCPU acts as remote. The master's endpoint is 30, and + the remote's endpoint is 40. The shared buffer must be allocated in LCPU's + RAM, with the address specified by the macro `RPMSG_BUF_ADDR_MASTER`, and + buffer size specified by the macro `RPMSG_BUF_SIZE`. These macros are defined + in header files `src\common\ipc_config.h`, `project\hcpu\custom_mem_map.h`, + and `project\lcpu\custom_mem_map.h`. +- It is recommended to initialize the RPMsg-Lite module during the + `INIT_APP_EXPORT` stage to avoid premature mailbox interrupt activation + affecting the data_service module. +- HCPU's main function is located in `src/hcpu/main.c`, and LCPU's main function + is in `src/lcpu/main.c`. +```bash +# Send a message from the HCPU console send "Hello LCPU, this is HCPU" ``` The LCPU console will display: @@ -32,8 +94,12 @@ The LCPU console will display: rx: Hello LCPU, this is HCPU ``` -> To demonstrate sleep functionality, HCPU will enter sleep state after executing the send command, and LCPU will also sleep. Both will be woken up by timers or messages. +> To demonstrate power management features, the HCPU enters a sleep state after +> executing the `send` command, and the LCPU follows suit. Both processors can +> only be awakened by timers or incoming messages; they cannot be awakened via +> the `send` command. + +## Example Output +- When LCPU receives a message, it prints: `rx: hello_from_hcpu` +- When HCPU receives a message, it prints: `rx: hello_from_lcpu` -## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [Multi-core Communication Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/multicore/index.html) \ No newline at end of file diff --git a/example/multimedia/agif/lvgl/README_EN.md b/example/multimedia/agif/lvgl/README_EN.md index d2b46aa3f..b69ab0159 100644 --- a/example/multimedia/agif/lvgl/README_EN.md +++ b/example/multimedia/agif/lvgl/README_EN.md @@ -3,170 +3,183 @@ Source Code Path: example/multimedia/agif/lvgl ## Supported Platforms - + + eh-lb525 ## Overview - -This example contains two watch faces with GIF animations and one watch face with APNG animation, demonstrating animation implementation based on agif/apng + lvgl, including: + +This example contains two watch faces with GIF animations and one watch face +with APNG animation, demonstrating animation implementation based on agif/apng + +lvgl, including: + .gif conversion to .c using eZIP.exe: - Placement location: `src/resource/images/common/gif/` - - Resource processing: `src/resource/images/SConscript` will compile .gif files in the above path. The generated .c files can be found in `project/build_xxx/src/resource/images/common/gif` path. + - Resource processing: `src/resource/images/SConscript` will compile .gif + files in the above path. The generated .c files can be found in + `project/build_xxx/src/resource/images/common/gif` path. ```{tip} Resources can also be processed manually using `/tools/png2ezip/eZIP.exe`. Run eZIP.exe to view help for command format. ``` + + gif display - `src/gui_apps/clock/app_clock_agif.c`: * Resource declaration: ```c - /* Image decalration */ + /* * Image declaration * */ LV_IMG_DECLARE(agif_icon); ``` * gif widget creation and configuration: ```c - /* Create agif. */ + /* * Create animated GIF * */ lv_color_t bg_color; - p_clk_agif->gif = lv_gif_dec_create(parent, LV_EXT_IMG_GET(agif_icon), &bg_color, LV_COLOR_DEPTH); - RT_ASSERT(p_clk_agif->gif); - lv_obj_align(p_clk_agif->gif, LV_ALIGN_CENTER, 0, 0); - - /* loop is enabled by default. */ - lv_gif_dec_loop(p_clk_agif->gif, 1, 16); - /* This callback function is executed at the end of GIF playback. */ - lv_gif_dec_end_cb_register(p_clk_agif->gif, agif_loop_end_func); + p_clk_agif->gif = lv_gif_dec_create(parent, LV_EXT_IMG_GET(agif_icon), &bg_color, LV_COLOR_DEPTH); + RT_ASSERT(p_clk_agif->gif); + lv_obj_align(p_clk_agif->gif, LV_ALIGN_CENTER, 0, 0); + + /* * Looping is enabled by default * */ + lv_gif_dec_loop(p_clk_agif->gif, 1, 16); + /* * This callback is executed when GIF playback completes * */ + lv_gif_dec_end_cb_register(p_clk_agif->gif, agif_loop_end_func); ``` * gif refresh pause and resume: ```c static rt_int32_t resume_callback(void) { - /* Resume gif animation refresh */ - lv_gif_dec_task_resume(p_clk_agif->gif); + /* * Resume GIF animation refresh * */ + lv_gif_dec_task_resume(p_clk_agif->gif); return RT_EOK; } static rt_int32_t pause_callback(void) { - /* Pause gif animation refresh */ - lv_gif_dec_task_pause(p_clk_agif->gif, 0); + /* * Pause GIF animation refresh * */ + lv_gif_dec_task_pause(p_clk_agif->gif, 0); return RT_EOK; } ``` * gif destruction ```c - /* Release gif context. */ - lv_gif_dec_destroy(p_clk_agif->gif); - p_clk_agif->gif = NULL; + /* * Release GIF context * */ + lv_gif_dec_destroy(p_clk_agif->gif); + p_clk_agif->gif = NULL; ``` - - `src/gui_apps/clock/app_clock_agif_2.c`: - `lv_gif_dec_create` automatically creates an lv timer for periodic GIF refreshing. This example demonstrates pausing (`lv_gif_dec_task_pause`) the automatically created lv timer and creating an external lv timer for refreshing. The refresh code is as follows: + - `src/gui_apps/clock/app_clock_agif_2.c`:\ + `lv_gif_dec_create` automatically creates an lv timer for periodic GIF + refreshing. This example demonstrates pausing (`lv_gif_dec_task_pause`) + the automatically created lv timer and creating an external lv timer for + refreshing. The refresh code is as follows: ```c static void agif_refresh_timer_cb(struct _lv_timer_t * t) { - /* Next frame. */ - int ret = lv_gif_dec_next_frame(p_clk_agif->gif); + /* * Advance to the next frame * */ + int ret = lv_gif_dec_next_frame(p_clk_agif->gif); - /* if ret == 0, it means that reach the last frame. */ + /* * A return value of 0 indicates the last frame has been reached * */ if (0 == ret) { - /* Playback complete. */ + /* * Playback complete * */ agif_loop_end_func(); - /* Replay it. */ - lv_gif_dec_restart(p_clk_agif->gif); + /* * Restart playback */ + lv_gif_dec_restart(p_clk_agif->gif); } } ``` + + apng resource: - Same as PNG, placed in: ` src/resource/images/common/ezip/` - APNG image production: can be made online:` https://ezgif.com/ ` + apng display: - `src/gui_apps/clock/app_clock_apng.c`: - * Resource declaration: + * Resource declaration: ```c - /* Image decalration */ + /* * Image declaration * */ LV_IMG_DECLARE(apng_dice); ``` * apng widget creation and configuration: ```c - /* Create apng. */ + /* * Create APNG * */ lv_obj_t *dice_img = lv_ezipa_create(parent); RT_ASSERT(dice_img); - /* Set image source */ + /* * Set image source * */ lv_ezipa_set_src(dice_img, apng_dice.data); - /* Set surface */ + /* * Set surface * */ // lv_ezipa_set_surface(dice_img, xxx); - /* Set interval */ + /* * Set interval */ lv_ezipa_set_interval(dice_img, 60); ``` * apng refresh pause and resume: ```c static rt_int32_t resume_callback(void) { - /* Resume apng animation refresh */ - lv_ezipa_resume(p_clk_apng->apng); + /* * Resume APNG animation refresh * */ + lv_ezipa_resume(p_clk_apng->apng); return RT_EOK; } static rt_int32_t pause_callback(void) { - /* Pause apng animation refresh */ - lv_ezipa_pause(p_clk_apng->apng); + /* * Pause APNG animation refresh * */ + lv_ezipa_pause(p_clk_apng->apng); return RT_EOK; } - ``` + ``` ## Example Usage - + ### Hardware Requirements Running this example requires: -+ A development board supported by this example ([Supported Platforms](quick_start)). - ++ A development board supported by this example ([Supported + Platforms](quick_start)). ### menuconfig Configuration -1. Enable LVGL: -![RTT_LVGL](./assets/agif_cfg_lvgl.png) -2. Enable EPIC/EZIP: -![EPIC](./assets/agif_cfg_epic.png) -![EZIP](./assets/agif_cfg_ezip.png) -3. Enable `USING_EZIPA_DEC` (If apng is used.): -![EZIPA](./assets/apng_cfg_ezipa_dec.png) -4. Configure the LCD driver according to the LCD used. +1. Enable LVGL:\ + ![RTT_LVGL](./assets/agif_cfg_lvgl.png) +2. Enable EPIC/EZIP:\ + ![EPIC](./assets/agif_cfg_epic.png) ![EZIP](./assets/agif_cfg_ezip.png) +3. Enable `USING_EZIPA_DEC` (If apng is used.):\ + ![EZIPA](./assets/apng_cfg_ezipa_dec.png) +4. Configure the LCD driver according to the LCD used. ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, then select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +then select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed compilation and download steps, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed compilation and download steps, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - + After the example starts: -+ Defaults to the `agif` watch face, with `agif_icon.gif` refreshing and displaying in a loop. ++ Defaults to the `agif` watch face, with `agif_icon.gif` refreshing and + displaying in a loop. + Swipe left and right to switch between `aigf` \ `agif02` \ `apng` watch faces. -+ `agif.h` \ `lvsf_ezipa.h` also provides some other control APIs that can be modified in the example to see the effects. ++ `agif.h` \ `lvsf_ezipa.h` also provides some other control APIs that can be + modified in the example to see the effects. ## Troubleshooting -+ Compilation error, gif resource not found: As described in [Overview](#overview), confirm whether the .c file of the gif is generated normally. ++ Compilation error, gif resource not found: As described in [Overview]{1}, + confirm whether the .c file of the gif is generated normally. ## Reference Documents - + ## Update History -| Version | Date | Release Notes | -|:---|:---|:---| -| 0.0.1 | 05/2025 | Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | -------- | --------------- | +| 0.0.1 | May 2025 | Initial version | +| | | | +| | | | diff --git a/example/multimedia/audio/local_music/README_EN.md b/example/multimedia/audio/local_music/README_EN.md index 78a1342a4..4d0291fe4 100644 --- a/example/multimedia/audio/local_music/README_EN.md +++ b/example/multimedia/audio/local_music/README_EN.md @@ -3,82 +3,85 @@ Source code path: example/multimedia/audio/local_music ## Supported Platforms - + + eh-lb525 + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - + This example demonstrates local music playback, including: + Preset a wav audio file in the root partition. + Play the preset wav file. ## Example Usage - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + Speaker. ### menuconfig Configuration -1. This example needs to read and write files, so it needs to use a file system. Configure the `FAT` file system: -![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) +1. This example needs to read and write files, so it needs to use a file system. + Configure the `FAT` file system: ![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) ```{tip} Mount root partition in mnt_init. ``` -2. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -3. Enable AUDIO(`AUDIO`): -![AUDIO](./assets/mc_audio.png) +2. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +3. Enable AUDIO(`AUDIO`): ![AUDIO](./assets/mc_audio.png) 4. Enable AUDIO MANAGER.(`AUDIO_USING_MANAGER`) -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) -5. (`AUDIO_LOCAL_MUSIC`) -![AUDIO_LOCAL_MUSIC](./assets/mc_local_music.png) -6. Preset audio files (also supports MP3), place them in the \disk\ directory below for preset download: + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) +5. (`AUDIO_LOCAL_MUSIC`) ![AUDIO_LOCAL_MUSIC](./assets/mc_local_music.png) +6. Preset audio files (also supports MP3), place them in the \disk\ directory + below for preset download: * Audio files are under multimedia/audio/local_music/disk - ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted for download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted for download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results of Example - -After the example starts: -Play the preset 16k.wav audio file once. Expected to complete normal playback. + +After the example starts: Play the preset 16k.wav audio file once. Expected to +complete normal playback. ```{tip} If you need to play MP3 files, you can preset an MP3 file (note whether the audio file size exceeds the file system capacity) and configure the playback path: -```c +``` #define MUSIC_FILE_PATH "/Cloudy_Day.mp3" ``` + ``` ## Exception Diagnosis ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/multimedia/audio/mp3_sd_player/README_EN.md b/example/multimedia/audio/mp3_sd_player/README_EN.md index fc8d3a16a..cc1216327 100644 --- a/example/multimedia/audio/mp3_sd_player/README_EN.md +++ b/example/multimedia/audio/mp3_sd_player/README_EN.md @@ -3,20 +3,23 @@ Source code path: example/multimedia/audio/mp3_sd_player ## Supported Platforms - + + sf32lb52-lchspi-ulp ## Overview - -This example will demonstrate playing MP3 or wav audio files in the `music` directory on the SD card, and provides a shell interface for modifying playback volume. + +This example will demonstrate playing MP3 or wav audio files in the `music` +directory on the SD card, and provides a shell interface for modifying playback +volume. ## Example Usage - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + Speaker. ```{warning} @@ -25,58 +28,67 @@ Note that on the `sf32lb52-lchspi-ulp` platform, an external battery is required ### menuconfig Configuration -1. This example needs to read and write files, so it needs to use a file system. Configure the `FAT` file system: -![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) +1. This example needs to read and write files, so it needs to use a file system. + Configure the `FAT` file system: ![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) 1. This example uses SPI1 as the SD card interface, so SPI1 needs to be enabled: -![RT_USING_SPI1](./assets/mc_spi1.png) -1. The SD card in this example is driven using SPI, so the `MSD` driver needs to be enabled: -![RT_USING_MSD](./assets/mc_msd.png) -1. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -1. Enable AUDIO(`AUDIO`): -![AUDIO](./assets/mc_audio.png) + ![RT_USING_SPI1](./assets/mc_spi1.png) +1. The SD card in this example is driven using SPI, so the `MSD` driver needs to + be enabled: ![RT_USING_MSD](./assets/mc_msd.png) +1. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +1. Enable AUDIO(`AUDIO`): ![AUDIO](./assets/mc_audio.png) 1. Enable AUDIO MANAGER.(`AUDIO_USING_MANAGER`) -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) -1. (`AUDIO_LOCAL_MUSIC`) -![AUDIO_LOCAL_MUSIC](./assets/mc_local_music.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) +1. (`AUDIO_LOCAL_MUSIC`) ![AUDIO_LOCAL_MUSIC](./assets/mc_local_music.png) ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```bash scons --board=sf32lb52-lchspi-ulp -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted for download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted for download: ```bash $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to [Quick +Start](quick_start). ## Expected Results of Example - -After the example runs, it will play MP3 or wav files in the `music` directory on the SD card. After power-on, it is in stop playback state by default. When the music in the list finishes playing, it will automatically loop from the first song. + +After the example runs, it will play MP3 or wav files in the `music` directory +on the SD card. After power-on, it is in stop playback state by default. When +the music in the list finishes playing, it will automatically loop from the +first song. -For the `sf32lb52-lchspi-ulp` platform, long press the `KEY1` button to start playback. Long pressing `KEY1` during playback will stop playback, and the next start will begin from the first song. Short press `KEY1` button to pause/resume playback, short press `KEY2` button to switch to the next music. +For the `sf32lb52-lchspi-ulp` platform, long press the `KEY1` button to start +playback. Long pressing `KEY1` during playback will stop playback, and the next +start will begin from the first song. Short press `KEY1` button to pause/resume +playback, short press `KEY2` button to switch to the next music. -The example also provides a shell interface. You can use the `volume` command to get or set the volume. Enter the `volume` command to view the current volume, enter `volume set ` to set the volume, where `` ranges from 0-15. +The example also provides a shell interface. You can use the `volume` command to +get or set the volume. Enter the `volume` command to view the current volume, +enter `volume set ` to set the volume, where `` ranges from 0-15. ![shell](./assets/mc_volume_shell.png) ## Exception Diagnosis ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |6/2025 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | --------- | --------------- | +| 0.0.1 | June 2025 | Initial version | +| | | | diff --git a/example/multimedia/audio/opus/README_EN.md b/example/multimedia/audio/opus/README_EN.md index 384d06f7b..bad720528 100644 --- a/example/multimedia/audio/opus/README_EN.md +++ b/example/multimedia/audio/opus/README_EN.md @@ -3,80 +3,99 @@ Source code path: example/multimedia/audio/opus ## Supported Platforms - + + eh-lb525 ## Overview - -This example demonstrates how to use the Opus audio codec library for recording, encoding, decoding, and playback, including: - -+ Record PCM audio data at a 16kHz sampling rate from the microphone via mic recording -+ Encoding: Compress PCM data using the Opus codec (10ms frame length, approximately 16kbps bitrate) + +This example demonstrates how to use the Opus audio codec library for recording, +encoding, decoding, and playback, including: + ++ Record PCM audio data at a 16kHz sampling rate from the microphone via mic + recording ++ Encoding: Compress PCM data using the Opus codec (10ms frame length, + approximately 16kbps bitrate) + Decoding: Decompress audio data using the Opus decoder + Playback: Play the decoded audio data through the speakers ## Example Usage - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + Speaker. ### menuconfig Configuration -1. This example needs to read and write files, so it needs to use a file system. Configure the `FAT` file system: -![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) +1. This example needs to read and write files, so it needs to use a file system. + Configure the `FAT` file system: ![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) ```{tip} Mount root partition in mnt_init. ``` -2. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -3. Enable AUDIO(`AUDIO`): -![AUDIO](./assets/mc_audio.png) +2. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +3. Enable AUDIO(`AUDIO`): ![AUDIO](./assets/mc_audio.png) 4. Enable AUDIO MANAGER.(`AUDIO_USING_MANAGER`) -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) ### **Routine Description** -```c -If the opus_test() function contains opus_encoder_ctl(encoder, OPUS_SET_FORCE_MODE(MODE_SILK_ONLY));then define OPUS_STACK_SIZE as 20k. +If the `opus_test()` function contains `opus_encoder_ctl(encoder, +OPUS_SET_FORCE_MODE(MODE_SILK_ONLY));`, + +define `OPUS_STACK_SIZE` as 20k. + +If the `opus_test()` function does not contain `opus_encoder_ctl(encoder, +OPUS_SET_FORCE_MODE(MODE_SILK_ONLY));`, -If the opus_test() function does not call opus_encoder_ctl(encoder, OPUS_SET_FORCE_MODE(MODE_SILK_ONLY));, then define `OPUS_STACK_SIZE` as 200k. -``` +define `OPUS_STACK_SIZE` as 200k. ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: > scons --board=eh-lb525 -j32 -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted for download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted for download: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and download, please refer to [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to [Quick +Start](quick_start). ## Expected Results of Example - -After the example starts: -Start recording for ten seconds, then automatically play back after recording is complete. Expected successful recording and automatic playback. + +After the example starts: Start recording for ten seconds, then automatically +play back after recording is complete. Expected successful recording and +automatic playback. + +Manual Commands: + * opus: Record 10 seconds of audio to `/mic16k.pcm`, then play back after + encoding and decoding. + * opus /mic16k.pcm: Read PCM data from the specified file, then play back + after encoding and decoding. + * opus xxxxx: If the file does not exist, perform real-time recording and + loopback playback (simultaneous record and play). ## Exception Diagnosis ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/multimedia/audio/record/README_EN.md b/example/multimedia/audio/record/README_EN.md index 50ff8c9d3..02450e607 100644 --- a/example/multimedia/audio/record/README_EN.md +++ b/example/multimedia/audio/record/README_EN.md @@ -3,71 +3,77 @@ Source code path: example/multimedia/audio/record ## Supported Platforms - + + eh-lb525 + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -This example demonstrates recording and playback based on audio manager, including: + +This example demonstrates recording and playback based on audio manager, +including: + Recording through mic, saving pcm data to file. + Reading recorded file and playing it back. ## Example Usage - + ### Hardware Requirements Before running this example, prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + Speaker. ### menuconfig Configuration -1. This example needs to read and write files, so it needs to use a file system. Configure the `FAT` file system: -![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) +1. This example needs to read and write files, so it needs to use a file system. + Configure the `FAT` file system: ![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) ```{tip} Mount root partition in mnt_init. ``` -2. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -3. Enable AUDIO(`AUDIO`): -![AUDIO](./assets/mc_audio.png) +2. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +3. Enable AUDIO(`AUDIO`): ![AUDIO](./assets/mc_audio.png) 4. Enable AUDIO MANAGER.(`AUDIO_USING_MANAGER`) -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: > scons --board=eh-lb525 -j32 -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted for download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted for download: - >./uart_download.bat +> ./uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 -For detailed steps on compilation and download, please refer to [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to [Quick +Start](quick_start). ## Expected Results of Example - -After the example starts: -Start recording for ten seconds, then automatically play back after recording is complete. Expected successful recording and automatic playback. + +After the example starts: Start recording for ten seconds, then automatically +play back after recording is complete. Expected successful recording and +automatic playback. + ## Exception Diagnosis ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/multimedia/index_EN.md b/example/multimedia/index_EN.md index 772478316..565a0a5a4 100644 --- a/example/multimedia/index_EN.md +++ b/example/multimedia/index_EN.md @@ -5,4 +5,4 @@ :glob: */* -``` \ No newline at end of file +``` diff --git a/example/multimedia/lvgl/compass/README_EN.md b/example/multimedia/lvgl/compass/README_EN.md index 6980afdb8..2f5f5288e 100644 --- a/example/multimedia/lvgl/compass/README_EN.md +++ b/example/multimedia/lvgl/compass/README_EN.md @@ -1,13 +1,18 @@ # Electronic Compass Example -Made using LVGL v8 (v9 version will be available later), displays a circular compass dial, pointer that rotates with orientation, and shows current direction and angle - +Made using LVGL v8 (v9 version will be available later), displays a circular +compass dial, pointer that rotates with orientation, and shows current direction +and angle ## Supported Platforms + sf32lb52-lchspi-ulp ## Introduction to Electronic Compass -* Uses 3-axis magnetic values obtained from MMC56x3 sensor, reads data through I2C interface, converts the data to angles using the atan2f function in the math library, sets each obtained angle as the pointer's deflection angle to control pointer rotation. -* This example uses APIs in LVGL V8 to complete interface layout and application. +* Uses 3-axis magnetic values obtained from MMC56x3 sensor, reads data through + I2C interface, converts the data to angles using the atan2f function in the + math library, sets each obtained angle as the pointer's deflection angle to + control pointer rotation. +* This example uses APIs in LVGL V8 to complete interface layout and + application. ## Example Usage @@ -18,8 +23,11 @@ Before running this example, prepare: ### Hardware Configuration -* The sensor communicates with the development board through I2C protocol, with specific connection pins being PA40 (SCL clock line) and PA39 (SDA data line) -* Configure IO pins to I2C mode using HAL_PIN_Set() function, set to pull-up mode, the last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +* The sensor communicates with the development board through I2C protocol, with + specific connection pins being PA40 (SCL clock line) and PA39 (SDA data line) +* Configure IO pins to I2C mode using HAL_PIN_Set() function, set to pull-up + mode, the last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select + lcpu ```c static void board_io_init(void) { @@ -28,17 +36,20 @@ static void board_io_init(void) } ``` + ### menuconfig Configuration Process * Enable MMC5603 sensor and I2C2 in menuconfig -* These configurations are already enabled by default, users don't need to enable them manually +* These configurations are already enabled by default, users don't need to + enable them manually ``` -scons --board= --menuconfig +scons --board= --menuconfig ``` -![alt text](./assets/LP2.png) -![alt text](./assets/LP3.png) +![alt text](./assets/LP2.png) ![alt text](./assets/LP3.png) + ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lchspi-ulp -j8 ``` @@ -48,23 +59,29 @@ build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat ``` Select the port as prompted for download: ```none -please input the serial port num:10 +Please enter the serial port number: 10 ``` ## Expected Results -* Capable of simulating phone compass functionality, indicating direction and angle +* Capable of simulating phone compass functionality, indicating direction and + angle * Input: lcd_ctrl fps to view frame rate -* Specific demonstration video reference link: [Compass Demo Video](https://www.bilibili.com/video/BV1BxKmzaEVc/?spm_id_from=333.337.search-card.all.click&vd_source=00a26cb15a9627841023f7adb1c7c7f4) -![alt text](./assets/Compass_log.png) -![alt text](./assets/sram.png) +* Specific demonstration video reference link: [Compass Demo + Video](https://www.bilibili.com/video/BV1BxKmzaEVc/?spm_id_from=333.337.search-card.all.click&vd_source=00a26cb15a9627841023f7adb1c7c7f4) + ![alt text](./assets/Compass_log.png) ![alt text](./assets/sram.png) ## Exception Diagnosis -If the demonstration video effect is not achieved, troubleshooting can be performed from the following aspects: -* Check if there are magnets or devices that can affect the local magnetic field nearby +If the demonstration video effect is not achieved, troubleshooting can be +performed from the following aspects: +* Check if there are magnets or devices that can affect the local magnetic field + nearby ### Custom Compass Interface -If you find the dial and pointer in the compass not beautiful enough or need to customize some dials and pointers, this is also supported +If you find the dial and pointer in the compass not beautiful enough or need to +customize some dials and pointers, this is also supported * First ensure that custom images are in .png format * Second, place the images in the asset folder -* Place the custom dial in the asset folder, then place the custom pointer in the ezip folder. Of course, images should not be too large, otherwise it will affect the overall compass frame rate. Dial (390x390), pointer (230x230) -![alt text](./assets/ezip.png) \ No newline at end of file +* Place the custom dial in the asset folder, then place the custom pointer in + the ezip folder. Of course, images should not be too large, otherwise it will + affect the overall compass frame rate. Dial (390x390), pointer (230x230) ![alt + text](./assets/ezip.png) diff --git a/example/multimedia/lvgl/ezip/README_EN.md b/example/multimedia/lvgl/ezip/README_EN.md index d61d30a68..c7ffb22db 100644 --- a/example/multimedia/lvgl/ezip/README_EN.md +++ b/example/multimedia/lvgl/ezip/README_EN.md @@ -1,21 +1,25 @@ # Dynamic EZIP Loading Example(LVGL V8) -English | [简体中文](README.md) +English | [简体中文](README_EN.md) Source Path: example/multimedia/lvgl/ezip ## Overview -This example demonstrates how to dynamically load ezip format image files using LVGL in RT-Thread environment. The example supports: +This example demonstrates how to dynamically load ezip format image files using +LVGL in RT-Thread environment. The example supports: - Loading ezip images from Flash file system or SD card - Choosing to load images into SRAM or PSRAM - Displaying images via file path or preloaded descriptor - Dynamically switching image sources through finsh command line ## Features -- **Multiple Loading Methods**: Support direct loading from file or preloading to memory +- **Multiple Loading Methods**: Support direct loading from file or preloading + to memory - **Flexible Memory Management**: Optional SRAM or PSRAM storage for image data -- **File System Support**: Support reading images from Flash file system and SD card -- **Command Line Control**: Dynamically switch image sources through finsh commands +- **File System Support**: Support reading images from Flash file system and SD + card +- **Command Line Control**: Dynamically switch image sources through finsh + commands ## Usage @@ -43,22 +47,25 @@ To use custom images: - `-convert`: Specify the PNG image path to convert - `-rgb565`: Set output color format to RGB565 - `-binfile 2`: Set output as binary file format - - `-binext .ezip`: Specify output file extension as .ezip, can be customized up to 20 characters + - `-binext .ezip`: Specify output file extension as .ezip, can be customized + up to 20 characters - `-lvgl_version`: Specify target LVGL version, supports 8 or 9 - + **Usage Examples**: ``` # Convert to LVGL V8 format ezip -convert images\logo.png -rgb565 -binfile 2 -binext .ezip -lvgl_version 8 - + # Convert to LVGL V9 format ezip -convert images\logo.png -rgb565 -binfile 2 -binext .ezip -lvgl_version 9 ``` - Place the image file in the `disk` directory and rebuild/reflash -- Or copy the image file to the SD card root directory (SD card insertion required) +- Or copy the image file to the SD card root directory (SD card insertion + required) ## Example Output -If the example runs successfully, you will see the following output on the serial port: +If the example runs successfully, you will see the following output on the +serial port: ``` (...system initialization information omitted...) @@ -72,7 +79,8 @@ The LCD screen will display the loaded ezip image, centered on the screen. ## Using finsh Commands -After the program starts, you can dynamically switch image sources through serial port commands: +After the program starts, you can dynamically switch image sources through +serial port commands: ### Command Format ``` @@ -89,8 +97,10 @@ set_image [path] [file/dsc] [sram/psram] - `psram`: Use PSRAM **Important Note**: LVGL V8 and V9 have different file path format requirements: -- **LVGL V8**: Use file name directly, e.g., `example.ezip` or `/sdcard/image.ezip` -- **LVGL V9**: Need to add drive prefix, e.g., `A:/example.ezip` or `A:/sdcard/image.ezip` +- **LVGL V8**: Use file name directly, e.g., `example.ezip` or + `/sdcard/image.ezip` +- **LVGL V9**: Need to add drive prefix, e.g., `A:/example.ezip` or + `A:/sdcard/image.ezip` ### Usage Examples ``` @@ -136,22 +146,28 @@ Unload ezip image and release memory. - `use_psram`: 1 to release from PSRAM, 0 to release from SRAM ## Notes -1. Ensure the development board has sufficient SRAM or PSRAM space to store image data +1. Ensure the development board has sufficient SRAM or PSRAM space to store + image data 2. The ezip format must match the LVGL version (V8 or V9) 3. **LVGL V8 and V9 have different file path formats**: - V8: Use path directly, e.g., `example_v8.ezip` - V9: Need drive prefix, e.g., `A:/example_v9.ezip` 4. When using SD card, ensure it is properly formatted as FAT32 -5. Preload method (dsc) has better performance but uses memory, file method (file) saves memory but has lower performance +5. Preload method (dsc) has better performance but uses memory, file method + (file) saves memory but has lower performance ## Troubleshooting -- **Image cannot be displayed**: Check if the ezip file exists and the path is correct +- **Image cannot be displayed**: Check if the ezip file exists and the path is + correct - **Memory allocation failed**: Check if SRAM or PSRAM has sufficient space - **SD card mount failed**: Ensure the SD card is formatted as FAT32 -For other issues, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +For other issues, please submit an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SiFli-SDK Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) +- [SiFli-SDK Quick + Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) - [LVGL Documentation](https://docs.lvgl.io/) diff --git a/example/multimedia/lvgl/ezip_v9/README_EN.md b/example/multimedia/lvgl/ezip_v9/README_EN.md index 72acd030b..4eb1b546f 100644 --- a/example/multimedia/lvgl/ezip_v9/README_EN.md +++ b/example/multimedia/lvgl/ezip_v9/README_EN.md @@ -1,21 +1,25 @@ # Dynamic EZIP Loading Example(LVGL V9) -English | [简体中文](README.md) +English | [简体中文](README_EN.md) Source code path: example/multimedia/lvgl/ezip_v9 ## Overview -This example demonstrates how to dynamically load ezip format image files using LVGL in an RT-Thread environment. The example supports: +This example demonstrates how to dynamically load ezip format image files using +LVGL in an RT-Thread environment. The example supports: - Loading ezip images from Flash filesystem or SD card - Selecting to load images to SRAM or PSRAM - Displaying images via file path or preloaded descriptor - Dynamically switching image sources through finsh command line ## Features -- **Multiple Loading Methods**: Support direct file loading or preloading to memory +- **Multiple Loading Methods**: Support direct file loading or preloading to + memory - **Flexible Memory Management**: Option to store image data in SRAM or PSRAM -- **Filesystem Support**: Support reading images from Flash filesystem and SD card -- **Command Line Control**: Dynamically switch image sources through finsh commands +- **Filesystem Support**: Support reading images from Flash filesystem and SD + card +- **Command Line Control**: Dynamically switch image sources through finsh + commands ## Usage @@ -43,14 +47,15 @@ To use custom images, you can: - `-convert`: Specify the PNG image path to convert - `-rgb565`: Set output color format to RGB565 - `-binfile 2`: Set output to binary file format - - `-binext .ezip`: Specify output file extension as .ezip, can be customized to an extension up to 20 characters + - `-binext .ezip`: Specify output file extension as .ezip, can be customized + to an extension up to 20 characters - `-lvgl_version`: Specify target LVGL version, supports 8 or 9 - + **Usage Examples**: ``` # Convert to LVGL V8 format ezip -convert images\logo.png -rgb565 -binfile 2 -binext .ezip -lvgl_version 8 - + # Convert to LVGL V9 format ezip -convert images\logo.png -rgb565 -binfile 2 -binext .ezip -lvgl_version 9 ``` @@ -58,7 +63,8 @@ To use custom images, you can: - Or copy the image file to SD card root directory (requires SD card insertion) ## Example Output -If the example runs successfully, you will see the following output on the serial port: +If the example runs successfully, you will see the following output on the +serial port: ``` (...system initialization information omitted...) @@ -72,7 +78,8 @@ The LCD screen will display the loaded ezip image, centered on the screen. ## Using finsh Commands -After program startup, you can dynamically switch image sources through serial commands: +After program startup, you can dynamically switch image sources through serial +commands: ### Command Format ``` @@ -89,8 +96,10 @@ set_image [path] [file/dsc] [sram/psram] - `psram`: Use PSRAM **Important Note**: LVGL V8 and V9 have different file path format requirements: -- **LVGL V8**: Use filename directly, e.g., `example.ezip` or `/sdcard/image.ezip` -- **LVGL V9**: Need to add drive letter prefix, e.g., `A:/example.ezip` or `A:/sdcard/image.ezip` +- **LVGL V8**: Use filename directly, e.g., `example.ezip` or + `/sdcard/image.ezip` +- **LVGL V9**: Need to add drive letter prefix, e.g., `A:/example.ezip` or + `A:/sdcard/image.ezip` ### Usage Examples ``` @@ -136,22 +145,27 @@ Unload ezip image and free memory. - `use_psram`: 1 to free from PSRAM, 0 to free from SRAM ## Notes -1. Ensure the development board has sufficient SRAM or PSRAM space to store image data +1. Ensure the development board has sufficient SRAM or PSRAM space to store + image data 2. The ezip format must match the LVGL version (V8 or V9) 3. **LVGL V8 and V9 have different file path formats**: - V8: Use path directly, e.g., `example.ezip` - V9: Need drive letter prefix, e.g., `A:/example.ezip` 4. When using SD card, ensure the card is properly formatted as FAT32 -5. Preload method (dsc) has better performance but uses memory, file method (file) saves memory but has lower performance +5. Preload method (dsc) has better performance but uses memory, file method + (file) saves memory but has lower performance ## Troubleshooting - **Image not displaying**: Check if ezip file exists and path is correct - **Memory allocation failure**: Check if SRAM or PSRAM has sufficient space - **SD card mount failure**: Ensure SD card is formatted as FAT32 -For other issues, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +For other issues, please submit an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SiFli-SDK Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) +- [SiFli-SDK Quick + Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) - [LVGL Documentation](https://docs.lvgl.io/) diff --git a/example/multimedia/lvgl/games/index_EN.md b/example/multimedia/lvgl/games/index_EN.md index 2910798ec..434f5174a 100644 --- a/example/multimedia/lvgl/games/index_EN.md +++ b/example/multimedia/lvgl/games/index_EN.md @@ -5,4 +5,4 @@ :glob: */* -``` \ No newline at end of file +``` diff --git a/example/multimedia/lvgl/lvgl_tools_example/NXP_GUI_guider/README_EN.md b/example/multimedia/lvgl/lvgl_tools_example/NXP_GUI_guider/README_EN.md index f6f690778..9abd3d64a 100644 --- a/example/multimedia/lvgl/lvgl_tools_example/NXP_GUI_guider/README_EN.md +++ b/example/multimedia/lvgl/lvgl_tools_example/NXP_GUI_guider/README_EN.md @@ -1,70 +1,124 @@ # SquareLine Example (RT-Thread) +Source path: example/multimedia/lvgl/lvgl_tools_example/NXP_GUI_guider ## Supported Platforms - -- Any board (including [pc](file://d:\SiFli-SDK\SiFli-SDK\external\ffmpeg\libavcodec\aac_ac3_parser.h#L40-L40)) + +- Any board (including [pc]{1}) -## Example Overview -This example creates two screens, each containing other controls, and implements mutual switching between the two screens through button controls. The document details how to adapt and run the generated code in the current SDK environment. +## Example Overview +This example creates two screens, each containing other controls, and implements +mutual switching between the two screens through button controls. The document +details how to adapt and run the generated code in the current SDK environment. ## Using Squareline Software -Squareline software download address: [SquareLine Download](https://squareline.io/downloads#lastRelease). After entering the page, you need to register an account first before downloading and installing. +Squareline software download address: [SquareLine +Download](https://www.nxp.com.cn/design/design-center/software/development-software/gui-guider:GUI-GUIDER). +After entering the page, you need to register an account first before +downloading and installing. +* After downloading and installing, open the SquareLine software, enter your + registered email and password, click `LOG_IN` to log in, and check the + obtained license ![alt test](assets/gui1.png) -![alt test](assets/sqline_down2.png) -![alt test](assets/sqline_down1.png) +* After successful login, select Create to create a multi-platform UI project, + configure the project information, and click `Create` ![alt + test](assets/gui_create.png) -* After downloading and installing, open the SquareLine software, enter your registered email and password, click `LOG_IN` to log in, and check the obtained license -![alt test](assets/sqline_down3.png) +* The following demonstrates adding controls, where you can modify layout, + events, set styles and other properties ![alt test](assets/gui_create2.png) -* After successful login, select Create to create a multi-platform UI project, configure the project information, and click `Create` -![alt test](assets/sqline1.png) +* After completion, compile to generate .c files ![alt + test](assets/gui_create3.png) -* The following demonstrates adding controls, where you can modify layout, events, set styles and other properties -![alt test](assets/sqline3.png) +* Once the UI interface design is complete, you can use the simulator to compile + and run the project to verify that the results meet expectations. ![alt + text](assets/gui_ui.png) -* After completion, compile to generate .c files -![alt test](assets/sqline2.png) +* After verification, you can export the generated files. ![alt + text](assets/gui_build_code.png) -For other detailed operations, please refer to: [squareline tutorial](https://www.bilibili.com/video/BV1Bu411p7cM) +![alt test](https://www.bilibili.com/video/BV1RcRqYuENA/) ![alt test]{2} ## Squareline Generated Project Files +![alt test](assets/gui_code.png) +* components: This directory contains part of the embedded graphical interface + development project, including component definitions, initialization and event + handling code for the UI interface. If events and components are used in the + software, they will be created in this directory. -![alt test](assets/sqcode.png) +* images: This directory contains generated image resource .c files for + displaying PNG format images in the LVGL graphical interface -* components: This directory contains part of the embedded graphical interface development project, including component definitions, initialization and event handling code for the UI interface. If events and components are used in the software, they will be created in this directory. +* screens/ui_Screen1.c, ui_Screen1.h: ui_Screen1.c is the specific + implementation file of the (UI interface), containing the creation and + destruction logic of the screen and its components. ui_Screen1.h declares + screen-related variables and function interfaces for reference by other files. + If multiple screens are created in Squareline software, multiple .c files will + be generated, each corresponding to one screen with filenames consistent with + screen names. -* images: This directory contains generated image resource .c files for displaying PNG format images in the LVGL graphical interface +* CMakeLists.txt: This is a CMake build configuration file used to define and + manage compilation rules for the entire UI project's source files. -* screens/ui_Screen1.c, ui_Screen1.h: ui_Screen1.c is the specific implementation file of the (UI interface), containing the creation and destruction logic of the screen and its components. ui_Screen1.h declares screen-related variables and function interfaces for reference by other files. If multiple screens are created in Squareline software, multiple .c files will be generated, each corresponding to one screen with filenames consistent with screen names. +* filelist.txt: Manages and compiles the entire LVGL user interface project, + defining source file lists and creating static libraries -* CMakeLists.txt: This is a CMake build configuration file used to define and manage compilation rules for the entire UI project's source files. +* ui_events.h: Event handling header file used to declare and manage UI + component event callback functions. When event handling is added, this file + will contain similar callback function declarations. Currently the file is + almost empty, only containing basic header file protection structure. -* filelist.txt: Manages and compiles the entire LVGL user interface project, defining source file lists and creating static libraries +* ui_helpers.c/ui_helpers.h: Common auxiliary function collection in the + generated UI project, used to simplify common operations such as UI component + property setting, animation control, and screen switching. They are the core + utility function library of Squareline Studio generated code. -* ui_events.h: Event handling header file used to declare and manage UI component event callback functions. When event handling is added, this file will contain similar callback function declarations. Currently the file is almost empty, only containing basic header file protection structure. +* ui.c/ui.h: The ui.c file implements UI interface functions, including UI + initialization and screen destruction. The ui.h file defines public interfaces + of the UI module for main program and other modules to call. -* ui_helpers.c/ui_helpers.h: Common auxiliary function collection in the generated UI project, used to simplify common operations such as UI component property setting, animation control, and screen switching. They are the core utility function library of Squareline Studio generated code. - -* ui.c/ui.h: The ui.c file implements UI interface functions, including UI initialization and screen destruction. The ui.h file defines public interfaces of the UI module for main program and other modules to call. +* widgets_init.c/.h: Provides a unified entry point for widget initialization. ## Porting Squareline Generated Project Files -### Pre-porting Preparation -* "Since the SDK uses ezip software to further compress generated image resources to reduce space occupation, before porting we need to create a folder named image_ezip under the Square_Line directory, and then create another folder named ezip under this directory." The ezip folder is used to store image resources that need compression. Finally, a SConscript file needs to be created under the image_ezip folder for ezip hardware acceleration during compilation. If compression is not needed, images can be moved to the image directory, and the script will automatically decide whether compression is needed based on file location during compilation. The compilation linking script can refer to: [SConscript](image/SConscript). -![alt test](assets/image_ezip.png) -* After completing the above operations, add the following content in the SConscript in the project directory under `# Add application source code`, otherwise the ezip function will not be available during compilation. +* The SDK employs the ezip utility to further compress generated image assets, + thereby reducing the storage footprint. During porting, users can choose + whether to apply ezip compression. Before proceeding, create a folder named + `image` within the `gui_guider` directory, and then create two subdirectories + named `ezip` and `no_ezip` within it. Place image assets that require + compression into the `ezip` folder, and assets that do not require or cannot + support compression into the `no_ezip` folder. The build script will + automatically determine whether to apply compression during the compilation + process based on the file location. For details, refer to the build script: + [SConscript](image/SConscript). + +* After completing the steps above, add the following content under `# Add + application source code ` in the project's SConscript file; otherwise, the + ezip functionality will not be enabled during compilation: ```python -objs.extend(SConscript(cwd+'/../image_ezip/SConscript', variant_dir="image_ezip", duplicate=0)) +objs.extend(SConscript(cwd+'/../image/SConscript', variant_dir="image", duplicate=0)) ``` -### Start Porting -![alt text](assets/code_file.png) -* Step 1: After completing preparations, copy the generated images/ui_img_test_png.c file to the image_ezip/ezip folder in the SDK. During compilation, image resource files can be further compressed. (There is no mandatory requirement to use ezip compression, it can also be placed in the image/no_ezip folder without compression, but it is recommended to use ezip compression for better performance) - -* Step 2: Except for the files already copied in the first step, copy all other files to the src directory. However, if copied directly, files in subdirectories will not be compiled, so we need to modify the SConscript compilation linking script, adding the following content to the SConscript file. -![alt test](assets/SConscript.png) - -* Step 3: Call `ui_init();` in the main function in the main.c file to generate the UI interface startup function interface. +### Pre-porting Preparation +![alt test](assets/move_code.png) +* "Since the SDK uses ezip software to further compress generated image + resources to reduce space occupation, before porting we need to create a + folder named image_ezip under the Square_Line directory, and then create + another folder named ezip under this directory." The ezip folder is used to + store image resources that need compression. Finally, a SConscript file needs + to be created under the image_ezip folder for ezip hardware acceleration + during compilation. If compression is not needed, images can be moved to the + image directory, and the script will automatically decide whether compression + is needed based on file location during compilation. The compilation linking + script can refer to: [SConscript]{1}. ![alt test]{2} + +* After completing the above operations, add the following content in the + SConscript in the project directory under `# Add application source code`, + otherwise the ezip function will not be available during compilation. +* Step 3: Include the header files `#include "generated/events_init.h"` and + `#include "generated/gui_guider.h"` in the `main.c` file. Declare `lv_ui + guider_ui;` in this file, and within the `main` function, call the UI startup + interface functions `setup_ui(&guider_ui);` and + `events_init(&guider_ui);`. ## Using the Example ### Hardware Requirements @@ -73,12 +127,10 @@ objs.extend(SConscript(cwd+'/../image_ezip/SConscript', variant_dir="image_ezip" ### menuconfig Configuration Process * LVGL is enabled by default, no configuration needed -* Enable LittlevGL2RTT adaptation layer in menuconfig -![alt test](assets/menuconfig1.png) -* Select LVGL version in menuconfig -![alt test](assets/menuconfig2.png) -* Since the generated code uses default theme functionality, LVGL's default theme function needs to be enabled in menuconfig, -![alt test](assets/menu3.png) +* Enable LittlevGL2RTT adaptation layer in menuconfig ![alt + test](assets/menuconfig1.png) +* Select LVGL version in menuconfig ![alt test](assets/menuconfig2.png) + ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ``` @@ -89,8 +141,10 @@ build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ``` ### Running Results -* The screen will first run screen1, as shown in the figure below. -![alt test](assets/result1.jpg) -* By clicking the button in screen1, you can switch to screen2 for display, as shown in the figure below. -![alt test](assets/result2.jpg) -* Clicking the button in screen2 can return to screen1 for display. \ No newline at end of file +* The screen will first run screen1, as shown in the figure below. ![alt + test](assets/result1.jpg) + +* By clicking the button in screen1, you can switch to screen2 for display, as + shown in the figure below. ![alt test](assets/result2.jpg) + +* Clicking the button in screen2 can return to screen1 for display. diff --git a/example/multimedia/lvgl/lvgl_tools_example/Square_Line/README_EN.md b/example/multimedia/lvgl/lvgl_tools_example/Square_Line/README_EN.md index f6f690778..30972151e 100644 --- a/example/multimedia/lvgl/lvgl_tools_example/Square_Line/README_EN.md +++ b/example/multimedia/lvgl/lvgl_tools_example/Square_Line/README_EN.md @@ -1,70 +1,116 @@ # SquareLine Example (RT-Thread) +Source path: example/multimedia/lvgl/lvgl_tools_example/Square_Line ## Supported Platforms - -- Any board (including [pc](file://d:\SiFli-SDK\SiFli-SDK\external\ffmpeg\libavcodec\aac_ac3_parser.h#L40-L40)) + +- Any board (including [pc]{1}) -## Example Overview -This example creates two screens, each containing other controls, and implements mutual switching between the two screens through button controls. The document details how to adapt and run the generated code in the current SDK environment. +## Example Overview +This example creates two screens, each containing other controls, and implements +mutual switching between the two screens through button controls. The document +details how to adapt and run the generated code in the current SDK environment. ## Using Squareline Software -Squareline software download address: [SquareLine Download](https://squareline.io/downloads#lastRelease). After entering the page, you need to register an account first before downloading and installing. +Squareline software download address: [SquareLine +Download](https://squareline.io/downloads#lastRelease). After entering the page, +you need to register an account first before downloading and installing. -![alt test](assets/sqline_down2.png) -![alt test](assets/sqline_down1.png) +![alt test](assets/sqline_down2.png) ![alt test](assets/sqline_down1.png) -* After downloading and installing, open the SquareLine software, enter your registered email and password, click `LOG_IN` to log in, and check the obtained license -![alt test](assets/sqline_down3.png) +* After downloading and installing, open the SquareLine software, enter your + registered email and password, click `LOG_IN` to log in, and check the + obtained license ![alt test](assets/sqline_down3.png) -* After successful login, select Create to create a multi-platform UI project, configure the project information, and click `Create` -![alt test](assets/sqline1.png) +* After successful login, select Create to create a multi-platform UI project, + configure the project information, and click `Create` ![alt + test](assets/sqline1.png) -* The following demonstrates adding controls, where you can modify layout, events, set styles and other properties -![alt test](assets/sqline3.png) +* The following demonstrates adding controls, where you can modify layout, + events, set styles and other properties ![alt test](assets/sqline3.png) -* After completion, compile to generate .c files -![alt test](assets/sqline2.png) +* After completion, compile to generate .c files ![alt test](assets/sqline2.png) -For other detailed operations, please refer to: [squareline tutorial](https://www.bilibili.com/video/BV1Bu411p7cM) +For other detailed operations, please refer to: [squareline +tutorial](https://www.bilibili.com/video/BV1Bu411p7cM) ## Squareline Generated Project Files ![alt test](assets/sqcode.png) -* components: This directory contains part of the embedded graphical interface development project, including component definitions, initialization and event handling code for the UI interface. If events and components are used in the software, they will be created in this directory. +* components: This directory contains part of the embedded graphical interface + development project, including component definitions, initialization and event + handling code for the UI interface. If events and components are used in the + software, they will be created in this directory. -* images: This directory contains generated image resource .c files for displaying PNG format images in the LVGL graphical interface +* images: This directory contains generated image resource .c files for + displaying PNG format images in the LVGL graphical interface -* screens/ui_Screen1.c, ui_Screen1.h: ui_Screen1.c is the specific implementation file of the (UI interface), containing the creation and destruction logic of the screen and its components. ui_Screen1.h declares screen-related variables and function interfaces for reference by other files. If multiple screens are created in Squareline software, multiple .c files will be generated, each corresponding to one screen with filenames consistent with screen names. +* screens/ui_Screen1.c, ui_Screen1.h: ui_Screen1.c is the specific + implementation file of the (UI interface), containing the creation and + destruction logic of the screen and its components. ui_Screen1.h declares + screen-related variables and function interfaces for reference by other files. + If multiple screens are created in Squareline software, multiple .c files will + be generated, each corresponding to one screen with filenames consistent with + screen names. -* CMakeLists.txt: This is a CMake build configuration file used to define and manage compilation rules for the entire UI project's source files. +* CMakeLists.txt: This is a CMake build configuration file used to define and + manage compilation rules for the entire UI project's source files. -* filelist.txt: Manages and compiles the entire LVGL user interface project, defining source file lists and creating static libraries +* filelist.txt: Manages and compiles the entire LVGL user interface project, + defining source file lists and creating static libraries -* ui_events.h: Event handling header file used to declare and manage UI component event callback functions. When event handling is added, this file will contain similar callback function declarations. Currently the file is almost empty, only containing basic header file protection structure. +* ui_events.h: Event handling header file used to declare and manage UI + component event callback functions. When event handling is added, this file + will contain similar callback function declarations. Currently the file is + almost empty, only containing basic header file protection structure. -* ui_helpers.c/ui_helpers.h: Common auxiliary function collection in the generated UI project, used to simplify common operations such as UI component property setting, animation control, and screen switching. They are the core utility function library of Squareline Studio generated code. +* ui_helpers.c/ui_helpers.h: Common auxiliary function collection in the + generated UI project, used to simplify common operations such as UI component + property setting, animation control, and screen switching. They are the core + utility function library of Squareline Studio generated code. -* ui.c/ui.h: The ui.c file implements UI interface functions, including UI initialization and screen destruction. The ui.h file defines public interfaces of the UI module for main program and other modules to call. +* ui.c/ui.h: The ui.c file implements UI interface functions, including UI + initialization and screen destruction. The ui.h file defines public interfaces + of the UI module for main program and other modules to call. ## Porting Squareline Generated Project Files ### Pre-porting Preparation -* "Since the SDK uses ezip software to further compress generated image resources to reduce space occupation, before porting we need to create a folder named image_ezip under the Square_Line directory, and then create another folder named ezip under this directory." The ezip folder is used to store image resources that need compression. Finally, a SConscript file needs to be created under the image_ezip folder for ezip hardware acceleration during compilation. If compression is not needed, images can be moved to the image directory, and the script will automatically decide whether compression is needed based on file location during compilation. The compilation linking script can refer to: [SConscript](image/SConscript). -![alt test](assets/image_ezip.png) - -* After completing the above operations, add the following content in the SConscript in the project directory under `# Add application source code`, otherwise the ezip function will not be available during compilation. +* "Since the SDK uses ezip software to further compress generated image + resources to reduce space occupation, before porting we need to create a + folder named image_ezip under the Square_Line directory, and then create + another folder named ezip under this directory." The ezip folder is used to + store image resources that need compression. Finally, a SConscript file needs + to be created under the image_ezip folder for ezip hardware acceleration + during compilation. If compression is not needed, images can be moved to the + image directory, and the script will automatically decide whether compression + is needed based on file location during compilation. The compilation linking + script can refer to: [SConscript](image/SConscript). ![alt + test](assets/image_ezip.png) + +* After completing the above operations, add the following content in the + SConscript in the project directory under `# Add application source code`, + otherwise the ezip function will not be available during compilation. ```python objs.extend(SConscript(cwd+'/../image_ezip/SConscript', variant_dir="image_ezip", duplicate=0)) ``` ### Start Porting ![alt text](assets/code_file.png) -* Step 1: After completing preparations, copy the generated images/ui_img_test_png.c file to the image_ezip/ezip folder in the SDK. During compilation, image resource files can be further compressed. (There is no mandatory requirement to use ezip compression, it can also be placed in the image/no_ezip folder without compression, but it is recommended to use ezip compression for better performance) - -* Step 2: Except for the files already copied in the first step, copy all other files to the src directory. However, if copied directly, files in subdirectories will not be compiled, so we need to modify the SConscript compilation linking script, adding the following content to the SConscript file. -![alt test](assets/SConscript.png) - -* Step 3: Call `ui_init();` in the main function in the main.c file to generate the UI interface startup function interface. +* Step 1: After completing preparations, copy the generated + images/ui_img_test_png.c file to the image_ezip/ezip folder in the SDK. During + compilation, image resource files can be further compressed. (There is no + mandatory requirement to use ezip compression, it can also be placed in the + image/no_ezip folder without compression, but it is recommended to use ezip + compression for better performance) + +* Step 2: Except for the files already copied in the first step, copy all other + files to the src directory. However, if copied directly, files in + subdirectories will not be compiled, so we need to modify the SConscript + compilation linking script, adding the following content to the SConscript + file. ![alt test](assets/SConscript.png) + +* Step 3: Call `ui_init();` in the main function in the main.c file to generate + the UI interface startup function interface. ## Using the Example ### Hardware Requirements @@ -73,12 +119,12 @@ objs.extend(SConscript(cwd+'/../image_ezip/SConscript', variant_dir="image_ezip" ### menuconfig Configuration Process * LVGL is enabled by default, no configuration needed -* Enable LittlevGL2RTT adaptation layer in menuconfig -![alt test](assets/menuconfig1.png) -* Select LVGL version in menuconfig -![alt test](assets/menuconfig2.png) -* Since the generated code uses default theme functionality, LVGL's default theme function needs to be enabled in menuconfig, -![alt test](assets/menu3.png) +* Enable LittlevGL2RTT adaptation layer in menuconfig ![alt + test](assets/menuconfig1.png) +* Select LVGL version in menuconfig ![alt test](assets/menuconfig2.png) +* Since the generated code uses default theme functionality, LVGL's default + theme function needs to be enabled in menuconfig, ![alt + test](assets/menu3.png) ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ``` @@ -89,8 +135,8 @@ build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ``` ### Running Results -* The screen will first run screen1, as shown in the figure below. -![alt test](assets/result1.jpg) -* By clicking the button in screen1, you can switch to screen2 for display, as shown in the figure below. -![alt test](assets/result2.jpg) -* Clicking the button in screen2 can return to screen1 for display. \ No newline at end of file +* The screen will first run screen1, as shown in the figure below. ![alt + test](assets/result1.jpg) +* By clicking the button in screen1, you can switch to screen2 for display, as + shown in the figure below. ![alt test](assets/result2.jpg) +* Clicking the button in screen2 can return to screen1 for display. diff --git a/example/multimedia/lvgl/lvgl_tools_example/eez_studio/README_EN.md b/example/multimedia/lvgl/lvgl_tools_example/eez_studio/README_EN.md index ebcd57174..ce31dd855 100644 --- a/example/multimedia/lvgl/lvgl_tools_example/eez_studio/README_EN.md +++ b/example/multimedia/lvgl/lvgl_tools_example/eez_studio/README_EN.md @@ -1,56 +1,154 @@ # EEZ Studio Example (RT-Thread) +Source path: example/multimedia/lvgl/lvgl_tools_example/eez_studio ## Supported Platforms - + - Any board (including `pc`) ## Example Overview -Using the EEZ Studio tool, convert PNG images into image arrays and LVGL image structures, and generate C files. Place the generated .c files into the project, modify and compile (due to interface differences in the generated structures), and use SDK's LVGL interface to display images on the screen. +Using the EEZ Studio tool, convert PNG images into image arrays and LVGL image +structures, and generate C files. Place the generated .c files into the project, +modify and compile (due to interface differences in the generated structures), +and use SDK's LVGL interface to display images on the screen. ## Using EEZ Studio Software -EEZ Studio software download link: [EEZ Studio Download](https://github.com/eez-open/studio/releases), select the .exe file to download +EEZ Studio software download link: [EEZ Studio +Download](https://github.com/eez-open/studio/releases), select the .exe file to +download -* After downloading and installing, open EEZ Studio and create a project on the home page -![alt text](assets/eez3.png) +* After downloading and installing, open EEZ Studio and create a project on the + home page ![alt text](assets/eez3.png) -* After creating the project, add items as shown in the figures -![alt text](assets/eez1.png) -![alt text](assets/eez2.png) +* After creating the project, add items as shown in the figures ![alt + text](assets/eez1.png) ![alt text](assets/eez2.png) -* Interface usage: you can set project size, layout, styles, flags, widgets, events, actions, etc. -![alt text](assets/eez4.png) +* Interface usage: you can set project size, layout, styles, flags, widgets, + events, actions, etc. ![alt text](assets/eez4.png) -* The following demonstrates adding an image control -![alt text](assets/eez5.png) +* The following demonstrates adding an image control ![alt + text](assets/eez5.png) -* After completion, compile to generate .c files -![alt text](assets/eez6.png) +* After completion, compile to generate .c files ![alt text](assets/eez6.png) -For more detailed operations, please refer to: [EEZ Studio Tutorial](https://www.bilibili.com/video/BV1vkp2egERj?spm_id_from=333.788.videopod.sections&vd_source=00a26cb15a9627841023f7adb1c7c7f4) +For more detailed operations, please refer to: [EEZ Studio +Tutorial](https://www.bilibili.com/video/BV1vkp2egERj) ## Modifications to Generated Code -* Due to slight differences between the generated code and the SDK's header file references, it cannot be fully used directly and requires modification. (However, most of the code can be reused) -* For generated code, we can refer to the ui_image_xxx.c file, which stores our image data and interfaces. There is also a screens file -* We need to make some modifications to use it in our SDK, mainly header file issues, requiring the operations shown in the figure -![alt test](assets/image2.png) -* Next is creating the LVGL interface. The generated code is stored in the screens.c file, which also has some differences in writing style, so adjustments are needed (but most of the code can be reused) -![alt test](assets/main1.png) +![alt text](assets/eez_code1.png) +* Due to slight differences between the generated code and the SDK's header file + references, it cannot be fully used directly and requires modification. + (However, most of the code can be reused) + +* For generated code, we can refer to the ui_image_xxx.c file, which stores our + image data and interfaces. There is also a screens file + +* We need to make some modifications to use it in our SDK, mainly header file + issues, requiring the operations shown in the figure ![alt test]{1} + +* Next is creating the LVGL interface. The generated code is stored in the + screens.c file, which also has some differences in writing style, so + adjustments are needed (but most of the code can be reused) ![alt test]{1} + +* images.c/images.h: These files manage image resources within the UI, + containing image resource declarations and definitions for image resource + descriptor structures. + +* screens.c/screens.h: These files implement the logic for UI screen creation, + widget layout, and event binding (including the entry function for UI + creation). + +* structs.h: This is the core module for data structure modeling. Although + currently empty, it is an essential component for bridging UI and Flow logic. + It is recommended to define structures here according to project requirements + to enhance code maintainability and scalability. + +* styles.c/styles.h: styles.c implements style definitions (such as initializing + objects and setting attributes like color, font, and borders). styles.h + declares style resources and provides global style interfaces for UI creation. + Style-related code generated during the EEZ Studio layout process is stored in + these files. + +* ui.c/ui.h: ui.c implements the core logic of the UI interface, including + initialization, screen loading, periodic updates, and the management of + objects and image resources. ui.h defines the public interfaces and + initialization functions for the UI module, declaring functions for UI + initialization, periodic refreshing, and screen loading for use by the main + program and other modules. + +* vars.h: This header file is used for declaring and managing global variables + within the UI architecture, providing interface declarations for global state + management. ## Example Usage +![alt text](assets/code_file.png) ### Hardware Requirements * A board that supports this example + +```python +# for module compiling +import os +from building import * + + +cwd = GetCurrentDir() + +src = [] + +cwd = GetCurrentDir() # get current dir path +objs_no_ezip = [] +objs_ezip = [] +objs_no_ezip += Glob('*.png') +objs_ezip += Glob('ezip/*.c') + +if 16 == GetConfigValue('LV_COLOR_DEPTH'): + img_flags = '-rgb565' +else: + img_flags = '-rgb888' + +src = Env.ImgResource(objs_ezip, img_flags+' -cfile 2 -pal_support') + +group = DefineGroup('image_ezip', src, depend = ['PKG_USING_LITTLEVGL2RTT']) + +Return ('group') +``` +![alt test](assets/image_ezip.png) + +* A USB data cable + +```python +objs.extend(SConscript(cwd+'/../image_ezip/SConscript', variant_dir="image_ezip", duplicate=0)) +``` + +* Step 1: After completing the preparations, copy the generated file from + images/ui_image_shanghai.c to the image_ezip/ezip folder in the SDK. Rename + the file to match the image resource array name in images.c. This is necessary + because the ezip software performs compression based on the filename and + replaces the compressed image resource variable name with the .c filename. + Renaming ensures minimal code modifications during porting. ![alt + text](assets/image1.png) ![alt text](assets/ezip.png) + +* Step 2: Copy all folders except for the image folder ported in the previous + step into the src directory. + +* Step 3: Call `ui_init(); and ui_tick();` in the main function of main.c to + invoke the UI entry functions. +## Usage Instructions +### Hardware Requirements +* A development board supported by this example * A USB data cable -### menuconfig Configuration Process -* LVGL is enabled by default, no additional configuration is needed -* Enable LVGL in menuconfig -![alt test](assets/menuconfig1.png) -* Select LVGL display driver in menuconfig -![alt test](assets/menuconfig2.png) +### menuconfig configuration process +* LVGL is enabled by default and requires no additional configuration. +* Enable the LittlevGL2RTT adaptation layer in menuconfig. ![alt + test](assets/menuconfig1.png) +* Select the LVGL version in menuconfig. ![alt test](assets/menuconfig2.png) +* Enable the default theme in menuconfig to support the default theme code + generated by EEZ Studio. ![alt test](assets/menuconfig3.png) + ### Compilation and Flashing -Switch to the example project directory and run the scons command to compile: +Navigate to the project directory and run the `scons` command to compile: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` @@ -58,6 +156,5 @@ scons --board=sf32lb52-lcd_n16r8 -j32 build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ``` -### Running Results -* The converted image will be displayed on the screen -![lvgl_result](assets/result.png) \ No newline at end of file +### Execution Results +* The image will be displayed on the screen. ![lvgl_result](assets/result.png) diff --git a/example/multimedia/lvgl/lvgl_tools_example/index_EN.md b/example/multimedia/lvgl/lvgl_tools_example/index_EN.md index cabaeb5c0..721ad9820 100644 --- a/example/multimedia/lvgl/lvgl_tools_example/index_EN.md +++ b/example/multimedia/lvgl/lvgl_tools_example/index_EN.md @@ -5,4 +5,4 @@ :glob: */* -``` \ No newline at end of file +``` diff --git a/example/multimedia/lvgl/lvgl_v8_demos/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/README_EN.md index 8d1500142..c73a77051 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/README_EN.md @@ -2,10 +2,15 @@ Source Path: example/multimedia/lvgl/lvgl_v8_demos -This example demonstrates various features and component usages of the LVGL V8 graphics library. It serves as a learning resource for creating graphical interface applications with LVGL. +This example demonstrates various features and component usages of the LVGL V8 +graphics library. It serves as a learning resource for creating graphical +interface applications with LVGL. ## Usage -The following sections provide only essential information. For complete steps on configuring SiFli-SDK and building/running projects, please refer to the [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +The following sections provide only essential information. For complete steps on +configuring SiFli-SDK and building/running projects, please refer to the +[SiFli-SDK Quick Start +Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) ## Supported Development Boards @@ -16,8 +21,9 @@ This example can run on the following development boards: + sf32lb58-lcd series ## Introduction -This example is used to demonstrate LVGL V8 official examples, using official demo applications. -You can use menuconfig to select the demo application to demonstrate. The included applications are: +This example is used to demonstrate LVGL V8 official examples, using official +demo applications. You can use menuconfig to select the demo application to +demonstrate. The included applications are: - Show some widget demonstrates the usage of lvgl widgets - Demonstrate the usage of encoder and keyboard demonstrates keyboard - Benchmark your system demonstrates benchmark @@ -25,16 +31,23 @@ You can use menuconfig to select the demo application to demonstrate. The includ - Music player demo demonstrates music playback ## Project Compilation and Download: -Board projects in the project directory can be compiled by specifying the board to compile projects adapted to the corresponding board. -- For example, to compile a project that can run on HDK 563, execute scons --board=eh-lb563 to generate the project -- Download can be done through download.bat in the build directory. For example, to program the 563 project generated in the previous step, execute .\build_eh-lb563\download.bat to download via jlink -- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. You can execute this script and input the download UART port number to perform download -Simulator project is located in the simulator directory: -- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to match your local MSVC configuration -- You can also use scons --target=vs2017 to generate MSVC project project.vcxproj, and use Visual Studio for compilation. - -``` +Board projects in the project directory can be compiled by specifying the board +to compile projects adapted to the corresponding board. +- For example, to compile a project that can run on HDK 563, execute scons + --board=eh-lb563 to generate the project +- Download can be done through download.bat in the build directory. For example, + to program the 563 project generated in the previous step, execute + .\build_eh-lb563\download.bat to download via jlink +- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat + will be generated. You can execute this script and input the download UART + port number to perform download Simulator project is located in the simulator + directory: +- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified + accordingly to match your local MSVC configuration +- You can also use scons --target=vs2017 to generate MSVC project + project.vcxproj, and use Visual Studio for compilation. +```{note} ## Troubleshooting For any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub @@ -42,4 +55,14 @@ For any technical questions, please submit an [issue](https://github.com/OpenSiF ## Reference Documentation - [SiFli-SDK Quick Start Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html){note} If not using VS2017, for example VS2022, when loading the project, it will prompt to upgrade the MSVC SDK. After upgrading, it can be used. -``` \ No newline at end of file +``` + +## Troubleshooting + +For technical inquiries, please open an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. + +## References +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) + diff --git a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/README_EN.md index f6920954f..ef95fa676 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/README_EN.md @@ -1,9 +1,11 @@ # Demos for LVGL +Source path: example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos ## Add the examples to your projects 1. demos can be found in the 'demos' folder once you clone the lvgl. -2. In the ***lv_conf.h*** or equivalent places, you can find demo related macros, change its value to enable or disable specified demos: +2. In the ***lv_conf.h*** or equivalent places, you can find demo related + macros, change its value to enable or disable specified demos: ```c ... @@ -38,8 +40,11 @@ ... ``` -3. If your development environment or toolchain does not add source files inside '***lvgl***' folder automatically, ensure the `demos` folder is included for compilation. -4. Include "***demos/lv_demos.h***" in your application source file, for example: +3. If your development environment or toolchain does not add source files inside + '***lvgl***' folder automatically, ensure the `demos` folder is included for + compilation. +4. Include "***demos/lv_demos.h***" in your application source file, for + example: ```c //! main.c @@ -53,13 +58,15 @@ ## Demos ### Widgets -Shows how the widgets look like out of the box using the built-in material theme. +Shows how the widgets look like out of the box using the built-in material +theme. See in [widgets](https://github.com/lvgl/lvgl/tree/master/demos/widgets) folder. -Basic demo to show the widgets of LVGL +显示LVGL小部件的基本演示 -For running this demo properly, please make sure **LV_MEM_SIZE** is at least **38KB** (and **48KB** is recommended): +For running this demo properly, please make sure **LV_MEM_SIZE** is at least +**38KB** (and **48KB** is recommended): ```c #define LV_MEME_SIZE (38ul * 1024ul) @@ -68,30 +75,39 @@ For running this demo properly, please make sure **LV_MEM_SIZE** is at least **3 ### Music player -The music player demo shows what kind of modern, smartphone-like user interfaces can be created on LVGL. It works the best with display with 480x272 or 272x480 resolution. +The music player demo shows what kind of modern, smartphone-like user interfaces +can be created on LVGL. It works the best with display with 480x272 or 272x480 +resolution. See in [music](https://github.com/lvgl/lvgl/tree/master/demos/music) folder. -Music player demo with LVGL +LVGL音乐播放器演示 ### Keypad and encoder -LVGL allows you to control the widgets with a keypad and/or encoder without a touchpad. This demo shows how to handle buttons, drop-down lists, rollers, sliders, switches, and text inputs without touchpad. -Learn more about the touchpad-less usage of LVGL [here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). +LVGL allows you to control the widgets with a keypad and/or encoder without a +touchpad. This demo shows how to handle buttons, drop-down lists, rollers, +sliders, switches, and text inputs without touchpad. Learn more about the +touchpad-less usage of LVGL +[here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). -See in [keypad_encoder](https://github.com/lvgl/lvgl/tree/master/demos/keypad_encoder) folder. +See in +[keypad_encoder](https://github.com/lvgl/lvgl/tree/master/demos/keypad_encoder) +folder. -Keypad and encoder navigation in LVGL embedded GUI library +LVGL嵌入式GUI库中的键盘和编码器导航 ### Benchmark -A demo to measure the performance of LVGL or to compare different settings. -See in [benchmark](https://github.com/lvgl/lvgl/tree/master/demos/benchmark) folder. -Benchmark demo with LVGL embedded GUI library +A demo to measure the performance of LVGL or to compare different settings. See +in [benchmark](https://github.com/lvgl/lvgl/tree/master/demos/benchmark) folder. +LVGL嵌入式GUI库的基准测试演示 ### Stress -A stress test for LVGL. It contains a lot of object creation, deletion, animations, style usage, and so on. It can be used if there is any memory corruption during heavy usage or any memory leaks. -See in [stress](https://github.com/lvgl/lvgl/tree/master/demos/stress) folder. -Stress test for LVGL +A stress test for LVGL. It contains a lot of object creation, deletion, +animations, style usage, and so on. It can be used if there is any memory +corruption during heavy usage or any memory leaks. See in +[stress](https://github.com/lvgl/lvgl/tree/master/demos/stress) folder. +LVGL压力测试 ## Contributing -For contribution and coding style guidelines, please refer to the file docs/CONTRIBUTING.md in the main LVGL repo: - https://github.com/lvgl/lvgl \ No newline at end of file +For contribution and coding style guidelines, please refer to the file +docs/CONTRIBUTING.md in the main LVGL repo: https://github.com/lvgl/lvgl diff --git a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/benchmark/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/benchmark/README_EN.md index 2ca97ee0e..fb6a8f258 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/benchmark/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/benchmark/README_EN.md @@ -1,41 +1,59 @@ # Benchmark demo +Source path: example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/benchmark ## Overview -The benchmark demo tests the performance in various cases. -For example rectangle, border, shadow, text, image blending, image transformation, blending modes, etc. -All tests are repeated with 50% opacity. +The benchmark demo tests the performance in various cases. For example +rectangle, border, shadow, text, image blending, image transformation, blending +modes, etc. All tests are repeated with 50% opacity. -The size and position of the objects during testing are set with a pseudo random number to make the benchmark repeatable. +The size and position of the objects during testing are set with a pseudo random +number to make the benchmark repeatable. -On to top of the screen the title of the current test step, and the result of the previous step is displayed. +On to top of the screen the title of the current test step, and the result of +the previous step is displayed. ## Run the benchmark - In `lv_conf.h` or equivalent places set `LV_USE_DEMO_BENCHMARK 1` - After `lv_init()` and initializing the drivers call `lv_demo_benchmark()` -- If you only want to run a specific scene for any purpose (e.g. debug, performance optimization etc.), you can call `lv_demo_benchmark_run_scene()` instead of `lv_demo_benchmark()`and pass the scene number. -- If you enabled trace output by setting macro `LV_USE_LOG` to `1` and trace level `LV_LOG_LEVEL` to `LV_LOG_LEVEL_USER` or higher, benchmark results are printed out in `csv` format. -- If you want to know when the testing is finished, you can register a callback function via `lv_demo_benchmark_register_finished_handler()` before calling `lv_demo_benchmark()` or `lv_demo_benchmark_run_scene()`. -- If you want to know the maximum rendering performance of the system, call `lv_demo_benchmark_set_max_speed(true)` before `lv_demo_benchmark()`. +- If you only want to run a specific scene for any purpose (e.g. debug, + performance optimization etc.), you can call `lv_demo_benchmark_run_scene()` + instead of `lv_demo_benchmark()`and pass the scene number. +- If you enabled trace output by setting macro `LV_USE_LOG` to `1` and trace + level `LV_LOG_LEVEL` to `LV_LOG_LEVEL_USER` or higher, benchmark results are + printed out in `csv` format. +- If you want to know when the testing is finished, you can register a callback + function via `lv_demo_benchmark_register_finished_handler()` before calling + `lv_demo_benchmark()` or `lv_demo_benchmark_run_scene()`. +- If you want to know the maximum rendering performance of the system, call + `lv_demo_benchmark_set_max_speed(true)` before `lv_demo_benchmark()`. ## Interpret the result The FPS is measured like this: - load the next step -- in the display driver's `monitor_cb` accumulate the time-to-render and the number of cycles +- in the display driver's `monitor_cb` accumulate the time-to-render and the + number of cycles - measure for 1 second - calculate `FPS = time_sum / render_cnt` -Note that it can result in very high FPS results for simple cases. -E.g. if some simple rectangles are drawn in 5 ms, the benchmark will tell it's 200 FPS. -So it ignores `LV_DISP_REFR_PERIOD` which tells LVGL how often it should refresh the screen. -In other words, the benchmark shows the FPS from the pure rendering time. +Note that it can result in very high FPS results for simple cases. E.g. if some +simple rectangles are drawn in 5 ms, the benchmark will tell it's 200 FPS. So it +ignores `LV_DISP_REFR_PERIOD` which tells LVGL how often it should refresh the +screen. In other words, the benchmark shows the FPS from the pure rendering +time. -By default, only the changed areas are refreshed. It means if only a few pixels are changed in 1 ms the benchmark will show 1000 FPS. To measure the performance with full screen refresh uncomment `lv_obj_invalidate(lv_scr_act())` in `monitor_cb()` in `lv_demo_benchmark.c`. +By default, only the changed areas are refreshed. It means if only a few pixels +are changed in 1 ms the benchmark will show 1000 FPS. To measure the performance +with full screen refresh uncomment `lv_obj_invalidate(lv_scr_act())` in +`monitor_cb()` in `lv_demo_benchmark.c`. ![LVGL benchmark running](screenshot1.png) -If you are doing performance analysis for 2D image processing optimization, LCD latency (flushing data to LCD) introduced by `disp_flush()` might dilute the performance results of the LVGL drawing process, hence make it harder to see your optimization results (gain or loss). To avoid such problem, please: +If you are doing performance analysis for 2D image processing optimization, LCD +latency (flushing data to LCD) introduced by `disp_flush()` might dilute the +performance results of the LVGL drawing process, hence make it harder to see +your optimization results (gain or loss). To avoid such problem, please: 1. Use a flag to control the LCD flushing inside `disp_flush()`. For example: @@ -72,7 +90,8 @@ static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_colo } ``` -2. Disable flushing before calling `lv_demo_benchmark()` or `lv_demo_benchmark_run_scene()`, for example: +2. Disable flushing before calling `lv_demo_benchmark()` or + `lv_demo_benchmark_run_scene()`, for example: ```c extern void disp_enable_update(void); @@ -94,11 +113,11 @@ int main(void) LV_LOG("NOTE: You will NOT see anything until the end."); disp_disable_update(); - + lv_demo_benchmark_set_finished_cb(&on_benchmark_finished); lv_demo_benchmark_set_max_speed(true); lv_demo_benchmark(); - + //lv_demo_benchmark_run_scene(43); // run scene no 31 ... @@ -110,25 +129,28 @@ int main(void) -3. Alternatively, you can use trace output to get the benchmark results in csv format by: - - Setting macro `LV_USE_LOG` to `1` +3. Alternatively, you can use trace output to get the benchmark results in csv + format by: + - Setting macro `LV_USE_LOG` to `1` - Setting trace level `LV_LOG_LEVEL` to `LV_LOG_LEVEL_USER` or higher. - - - ## Result summary In the end, a table is created to display measured FPS values. -On top of the summary screen, the "Weighted FPS" value is shown. -In this, the result of the more common cases are taken into account with a higher weight. +On top of the summary screen, the "Weighted FPS" value is shown. In this, the +result of the more common cases are taken into account with a higher weight. -"Opa. speed" shows the speed of the measurements with opacity compared to full opacity. -E.g. "Opa. speed = 90%" means that rendering with opacity is 10% slower. +"Opa. speed" shows the speed of the measurements with opacity compared to full +opacity. E.g. "Opa. speed = 90%" means that rendering with opacity is 10% +slower. -In the first section of the table, "Slow but common cases", those cases are displayed which are considered common but were slower than 20 FPS. +In the first section of the table, "Slow but common cases", those cases are +displayed which are considered common but were slower than 20 FPS. -Below this in the "All cases section" all the results are shown. The < 10 FPS results are shown with red, the >= 10 but < 20 FPS values are displayed with orange. +Below this in the "All cases section" all the results are shown. The < 10 FPS +results are shown with red, the >= 10 but < 20 FPS values are displayed with +orange. -![LVGL benchmark result summary](https://github.com/lvgl/lvgl/tree/master/demos/benchmark/screenshot2.png?raw=true) \ No newline at end of file +![LVGL benchmark result +summary](https://github.com/lvgl/lvgl/tree/master/demos/benchmark/screenshot2.png?raw=true) diff --git a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/keypad_encoder/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/keypad_encoder/README_EN.md index ad6ea6dcf..1106993f2 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/keypad_encoder/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/keypad_encoder/README_EN.md @@ -1,13 +1,16 @@ # Keypad and Encoder demo +Source path: example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/keypad_encoder ## Overview -LVGL allows you to control the widgets with keypad and/or encoder without touchpad. -This demo shows how to handle buttons, drop-down lists, rollers, sliders, switches and text inputs without touchpad. -Learn more about the touchpad-less usage of LVGL [here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). +LVGL allows you to control the widgets with keypad and/or encoder without +touchpad. This demo shows how to handle buttons, drop-down lists, rollers, +sliders, switches and text inputs without touchpad. Learn more about the +touchpad-less usage of LVGL +[here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). ![Keypad and encoder navigation in LVGL embedded GUI library](screenshot1.gif) ## Run the demo - In `lv_conf.h` or equivalent places set `LV_USE_DEMO_KEYPAD_AND_ENCODER 1` -- After `lv_init()` and initializing the drivers call `lv_demo_keypad_encoder()` \ No newline at end of file +- After `lv_init()` and initializing the drivers call `lv_demo_keypad_encoder()` diff --git a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/music/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/music/README_EN.md index 82ac9c05f..93e91d8ae 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/music/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/music/README_EN.md @@ -1,7 +1,10 @@ # Music player demo +Source path: example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/music ## Overview -The music player demo shows what kind of modern, smartphone-like user interfaces can be created on LVGL. It works the best with display with 480x272 or 272x480 resolution. +The music player demo shows what kind of modern, smartphone-like user interfaces +can be created on LVGL. It works the best with display with 480x272 or 272x480 +resolution. ![Music player demo with LVGL embedded GUI library](screenshot1.gif) @@ -12,16 +15,22 @@ The music player demo shows what kind of modern, smartphone-like user interfaces - After `lv_init()` and initializing the drivers call `lv_demo_music()` ## How the spectrum animation works -- `assets/spectrum.py` creates an array of spectrum values from a music. 4 band are created with 33 samples/sec: bass, bass-mid, mid, mid-treble. +- `assets/spectrum.py` creates an array of spectrum values from a music. 4 band + are created with 33 samples/sec: bass, bass-mid, mid, mid-treble. - The spectrum meter UI does the followings: - - Zoom the album cover proportionality to the current bass value - - Display the 4 bands on the left side of a circle by default at 0°, 45°, 90°, 135° - - Add extra bars next to the "main bars" with a cosine shape. Add more bars for the lower bands. - - If there is a large enough bass, add a random offset to the position of the bars. E.g. start from 63° instead of 0°. (bars greater than 180° start again from 0°) - - If there is no bass, add 1 to the offset of the bars (it creates a "walking" effect) - - Mirror the bars to the right side of the circle - + - Zoom the album cover proportionality to the current bass value + - Display the 4 bands on the left side of a circle by default at 0°, 45°, + 90°, 135° + - Add extra bars next to the "main bars" with a cosine shape. Add more bars + for the lower bands. + - If there is a large enough bass, add a random offset to the position of + the bars. E.g. start from 63° instead of 0°. (bars greater than 180° start + again from 0°) + - If there is no bass, add 1 to the offset of the bars (it creates a + "walking" effect) + - Mirror the bars to the right side of the circle + ## Using spectrum.py -- install `librosa` with `pip3 install librosa` +- install `librosa` with `pip3 install librosa` - run `python spectrum.py my_file.mp3` -- see the result in `spectrum.h` \ No newline at end of file +- see the result in `spectrum.h` diff --git a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/stress/README_EN.md b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/stress/README_EN.md index 20e66b94d..298f778ab 100644 --- a/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/stress/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/stress/README_EN.md @@ -1,13 +1,16 @@ # Stress demo +Source path: example/multimedia/lvgl/lvgl_v8_demos/src/lv_demos/stress ## Overview -A stress test for LVGL. -It contains a lot of object creation, deletion, animations, styles usage, and so on. It can be used if there is any memory corruption during heavy usage or any memory leaks. +A stress test for LVGL. It contains a lot of object creation, deletion, +animations, styles usage, and so on. It can be used if there is any memory +corruption during heavy usage or any memory leaks. ![Stress demo with LVGL embedded GUI library](screenshot1.gif) ## Run the demo - In `lv_conf.h` or equivalent places set `LV_USE_DEMO_STRESS 1` -- In `lv_conf.h` enable all the widgets (`LV_USE_BTN 1`) and the animations (`LV_USE_ANIMATION 1`) -- After `lv_init()` and initializing the drivers call `lv_demo_stress()` \ No newline at end of file +- In `lv_conf.h` enable all the widgets (`LV_USE_BTN 1`) and the animations + (`LV_USE_ANIMATION 1`) +- After `lv_init()` and initializing the drivers call `lv_demo_stress()` diff --git a/example/multimedia/lvgl/lvgl_v8_examples/README_EN.md b/example/multimedia/lvgl/lvgl_v8_examples/README_EN.md index 5a82ba5c1..bd753ff8e 100644 --- a/example/multimedia/lvgl/lvgl_v8_examples/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_examples/README_EN.md @@ -1,18 +1,27 @@ # LVGL v8 Official Example - ## Introduction + This example is used to test LVGL V8 APIs using officially provided examples. -You can replace the lv_example_scroll_1() function in src/main.c (simulator in simulator/applications/application.c) to test other APIs. -Other API functions can be referenced in the src/examples/lv_examples.h header file. +You can replace the lv_example_scroll_1() function in src/main.c (simulator in +simulator/applications/application.c) to test other APIs. Other API functions +can be referenced in the src/examples/lv_examples.h header file. ## Project Compilation and Download: -Board projects in the project directory can be compiled for specific boards by specifying the board parameter: -- To compile a project that can run on HDK 563, execute scons --board=eh-lb563 to generate the project -- Download can be performed through download.bat in the build directory. For example, to flash the 563 project generated in the previous step, execute .\build_eh-lb563\download.bat to download via J-Link -- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. You can execute this script and enter the download UART port number to perform the download -Simulator project is in the simulator directory: -- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to match the local MSVC configuration -- You can also use scons --target=vs2017 to generate the MSVC project project.vcxproj and compile using Visual Studio. +Board projects in the project directory can be compiled for specific boards by +specifying the board parameter: +- To compile a project that can run on HDK 563, execute scons --board=eh-lb563 + to generate the project +- Download can be performed through download.bat in the build directory. For + example, to flash the 563 project generated in the previous step, execute + .\build_eh-lb563\download.bat to download via J-Link +- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat + will be generated. You can execute this script and enter the download UART + port number to perform the download Simulator project is in the simulator + directory: +- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified + accordingly to match the local MSVC configuration +- You can also use scons --target=vs2017 to generate the MSVC project + project.vcxproj and compile using Visual Studio. ```{note} If using VS2022 or other versions besides VS2017, you will be prompted to upgrade the MSVC SDK when loading the project. After upgrading, it can be used normally. @@ -20,7 +29,6 @@ If using VS2022 or other versions besides VS2017, you will be prompted to upgrad ## Supplementary Instructions - How to Use sjpg Source Code Path: SiFli-SDK\example\multimedia\lvgl\lvgl_v8_examples - ### Supported Platforms This example can run on the following development boards: + sf32lb52-lchspi-ulp @@ -28,10 +36,9 @@ This example can run on the following development boards: + sf32lb56-lcd series + sf32lb58-lcd series - - ### Overview -* After inserting an SD card to complete file system mounting, read and display .sjpg and .jpg format images from it +* After inserting an SD card to complete file system mounting, read and display + .sjpg and .jpg format images from it ### Hardware Requirements * Huangshan development board or 52x series development board @@ -39,7 +46,6 @@ This example can run on the following development boards: * A TF card and a TF card reader ### Example Usage - #### Compilation and Flashing The default display image in the demo code is: ``` small_image.sjpg ``` @@ -57,11 +63,13 @@ build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat Select the port as prompted to download: ```none -please input the serial port num:5 +Please enter the serial port number: 5 ``` #### Example Output Result Display: -* After inserting the SD card, mount the file system and read/display images from the file system. The log containing `mount fs on flash to root success` indicates successful file system mounting +* After inserting the SD card, mount the file system and read/display images + from the file system. The log containing `mount fs on flash to root success` + indicates successful file system mounting ![alt text](assets/log1.png) @@ -73,8 +81,10 @@ please input the serial port num:5 ![alt text](assets/demo.jpg) #### Example Configuration Process -* By default, SPI is not enabled for TF file system mounting. If needed, configure as follows: -* First, use a TF card reader to write image files to the TF card, then insert the TF card into the board +* By default, SPI is not enabled for TF file system mounting. If needed, + configure as follows: +* First, use a TF card reader to write image files to the TF card, then insert + the TF card into the board * Configure through `menuconfig` as follows: ``` c menuconfig --board=sf32lb52-lchspi-ulp @@ -93,9 +103,7 @@ menuconfig --board=sf32lb52-lchspi-ulp * Enable LVGL file system interface, configure drive letter, and enable decoder -![alt text](assets/V8_posix.png) - ### Troubleshooting -* Abnormal log -![alt text](assets/log3.png) -If the above situation occurs, the TF card may be loose, unable to communicate properly, or not inserted \ No newline at end of file +* Abnormal log ![alt text](assets/log3.png) If the above situation occurs, the + TF card may be loose, unable to communicate properly, or not inserted + diff --git a/example/multimedia/lvgl/lvgl_v8_lottie/README_EN.md b/example/multimedia/lvgl/lvgl_v8_lottie/README_EN.md index cf32dd96f..5f1b0f5ac 100644 --- a/example/multimedia/lvgl/lvgl_v8_lottie/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_lottie/README_EN.md @@ -10,7 +10,10 @@ This example is used to test the LVGL V8 Lottie API. ## Usage -The following sections provide only essential information. For complete steps on configuring SiFli-SDK and building/running projects, please refer to the [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). +The following sections provide only essential information. For complete steps on +configuring SiFli-SDK and building/running projects, please refer to the +[SiFli-SDK Quick +Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). ### Supported Development Boards @@ -20,14 +23,16 @@ This example can run on the following development boards: - SF32LB56x series ## Project Compilation and Download: -The board project is located in the project directory. You can compile projects adapted to different boards by specifying the board parameter: +The board project is located in the project directory. You can compile projects +adapted to different boards by specifying the board parameter: - To compile for HDK 563 development board, execute: scons --board=eh-lb563 - Download via JLink: Run .\build_\download.bat -- For SF32LB52x/SF32LB56x series, an additional uart_download.bat is generated. Execute this script and enter the UART port number to download - -The simulator project is located in the simulator directory: -- Compile with scons. The SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to match the local MSVC configuration -- You can also generate an MSVC project using scons --target=vs2017 and compile with Visual Studio +- For SF32LB52x/SF32LB56x series, an additional uart_download.bat is generated. + Execute this script and enter the UART port number to download +- Compile with scons. The SiFli-SDK/msvc_setup.bat file needs to be modified + accordingly to match the local MSVC configuration +- You can also generate an MSVC project using scons --target=vs2017 and compile + with Visual Studio ```{note} If you are not using VS2017 (e.g., using VS2022), you will be prompted to upgrade the MSVC SDK when loading the project. After upgrading, it can be used normally. @@ -35,8 +40,11 @@ If you are not using VS2017 (e.g., using VS2022), you will be prompted to upgrad ## Troubleshooting -If you have any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +If you have any technical questions, please submit an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) \ No newline at end of file +- [SiFli-SDK Quick + Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) + diff --git a/example/multimedia/lvgl/lvgl_v8_media/README_EN.md b/example/multimedia/lvgl/lvgl_v8_media/README_EN.md index 6af882db1..c3bd9818b 100644 --- a/example/multimedia/lvgl/lvgl_v8_media/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v8_media/README_EN.md @@ -2,43 +2,55 @@ Source Code Path: example/multimedia/lvgl/lvgl_v8_media + ## Overview -This example demonstrates media playback. Users can overwrite the H264 format MP4 file to disk/video_example.mp4, and it will play after compilation and download. -If the T-card file system is loaded successfully, it will preferentially read video_example.mp4 from the T-card root directory +This example demonstrates media playback. Users can overwrite the H264 format +MP4 file to disk/video_example.mp4, and it will play after compilation and +download. If the T-card file system is loaded successfully, it will +preferentially read video_example.mp4 from the T-card root directory ## Supported Development Boards - + +- eh-lb523 +- sf32lb52-lcd_n16r8 - eh-lb523 - sf32lb52-lcd_n16r8 ## Hardware Requirements Before running this routine, you need to prepare: -- A development board supported by this routine ([Supported Platforms](#supported-development-boards)) -- Screen ++ A development board supported by this routine ([Supported + Platforms](quick_start)) ++ Screen + +### Project Compilation and Programming: +Supported Boards +- Post-55x series boards, such as the 58x, 56x, and 52x series. + +Projects located in the `project` directory can be compiled for a specific +target by specifying the `board` parameter. +- For example, to compile a project for the HDK 563, execute `scons + --board=eh-lb563` to generate the project files. +- Firmware can be programmed using the `download.bat` script located in the + `build` directory. To flash the 563 project generated in the previous step, + run `.\build_eh-lb563\download.bat` to perform the download via J-Link. +- Note: For the SF32LB52x and SF32LB56x series, an additional + `uart_download.bat` script is generated. Run this script and enter the + appropriate COM port number to perform the download via UART. ## Project Compilation and Download Supported boards - Boards after 55x, such as 58x, 56x, 52x - -The board project can be compiled in the project directory by specifying the board to adapt to the relative board project, -- For example, to compile a project that can run on HDK 563, execute scons --board=eh-lb563 to generate the project -- Download can be done through download.bat in the build directory. For example, to burn the 563 project generated in the previous step, you can execute .\build_eh-lb563\download.bat to download via jlink -- In particular, for SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. You can execute this script and enter the download UART port number to download +- For example, to compile a project that can run on HDK 563, execute scons + --board=eh-lb563 to generate the project ## Simulator Configuration The simulator project is in the simulator directory, -- Use scons to compile, the SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to correspond to the local MSVC configuration -- You can also use scons --target=vs2017 to generate the MSVC project project.vcxproj, and compile it with Visual Studio. - Note: If you are not using VS2017, such as VS2022, when loading the project, it will prompt to upgrade the MSVC SDK, and you can use it after the upgrade ## Troubleshooting - -If you have any technical questions, please raise an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub - -## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) \ No newline at end of file +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) diff --git a/example/multimedia/lvgl/lvgl_v9_demos/README_EN.md b/example/multimedia/lvgl/lvgl_v9_demos/README_EN.md index 7e1e66e98..c9bad98c5 100644 --- a/example/multimedia/lvgl/lvgl_v9_demos/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_demos/README_EN.md @@ -1,23 +1,24 @@ -# LVGL v9 Demo +# LVGL v9 Demonstration Source Code Path: example/multimedia/lvgl/lvgl_v9_demos ## Overview -This example demonstrates the official LVGL V9 demo applications. You can use menuconfig to select which demo applications to show. Included applications: +This example demonstrates the official LVGL V9 demo applications. You can use +menuconfig to select which demo applications to show. Included applications: - Show some widget: Demonstrates the usage of lvgl widgets - - Benchmark your system: Demonstrates benchmark (depends on "Show some widget") + - Benchmark your system: Demonstrates benchmark (depends on "Show some + widget") - Demonstrate the usage of encoder and keyboard: Demonstrates keyboard - Stress test for LVGL: Stress test - Music player demo: Demonstrates music playback ## Supported Development Boards - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series - ## Hardware Requirements Before running this example, you need to prepare: @@ -26,19 +27,29 @@ Before running this example, you need to prepare: ## Project Compilation and Download: Board projects can be compiled by specifying the board in the project directory, -- For example, to compile a project that can run on HDK 563, execute scons --board=eh-lb563 to generate the project -- Download can be done through download.bat in the build directory. For example, to flash the 563 project generated in the previous step, execute .\build_eh-lb563\download.bat to download via jlink -- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. You can execute this script and enter the download UART port number to perform the download -Simulator project is in the simulator directory, -- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to match the local MSVC configuration -- You can also use scons --target=vs2017 to generate the MSVC project project.vcxproj and compile using Visual Studio. +- For example, to compile a project that can run on HDK 563, execute scons + --board=eh-lb563 to generate the project +- Download can be done through download.bat in the build directory. For example, + to flash the 563 project generated in the previous step, execute + .\build_eh-lb563\download.bat to download via jlink +- Special note: For SF32LB52x/SF32LB56x series, an additional uart_download.bat + will be generated. You can execute this script and enter the download UART + port number to perform the download Simulator project is in the simulator + directory, +- Compile using scons. The SiFli-SDK/msvc_setup.bat file needs to be modified + accordingly to match the local MSVC configuration +- You can also use scons --target=vs2017 to generate the MSVC project + project.vcxproj and compile using Visual Studio. ```{note} If you are not using VS2017, such as VS2022, you will be prompted to upgrade the MSVC SDK when loading the project. After upgrading, you can use it. ``` ## Troubleshooting -For any technical questions, please raise an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub +For any technical questions, please raise an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub ## Reference Documentation -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) \ No newline at end of file +- [SiFli-SDK Quick + Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) + diff --git a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/README_EN.md b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/README_EN.md index 1381d9bc9..a8aa0d852 100644 --- a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/README_EN.md @@ -1,9 +1,11 @@ # Demos for LVGL +Source path: example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos ## Add the examples to your projects 1. demos can be found in the 'demos' folder once you clone the lvgl. -2. In the ***lv_conf.h*** or equivalent places, you can find demo related macros, change its value to enable or disable specified demos: +2. In the ***lv_conf.h*** or equivalent places, you can find demo related + macros, change its value to enable or disable specified demos: ```c ... @@ -47,8 +49,11 @@ ... ``` -3. If your development environment or toolchain does not add source files inside '***lvgl***' folder automatically, ensure the `demos` folder is included for compilation. -4. Include "***demos/lv_demos.h***" in your application source file, for example: +3. If your development environment or toolchain does not add source files inside + '***lvgl***' folder automatically, ensure the `demos` folder is included for + compilation. +4. Include "***demos/lv_demos.h***" in your application source file, for + example: ```c //! main.c @@ -59,9 +64,12 @@ ## Configure Demos Entry -"demos/lv_demos.c" provides `lv_demos_create` and `lv_demos_show_help` to simplify the creation of demos. +"demos/lv_demos.c" provides `lv_demos_create` and `lv_demos_show_help` to +simplify the creation of demos. -If you build your main program named `lv_demos`, then you can run the widgets demo by running `lv_demos widgets` and the benchmark demo by running `lv_demos benchmark 1`. +If you build your main program named `lv_demos`, then you can run the widgets +demo by running `lv_demos widgets` and the benchmark demo by running `lv_demos +benchmark 1`. For example: @@ -107,19 +115,20 @@ demo_end: lv_deinit(); return 0; } - ``` ## Demos ### Widgets -Shows how the widgets look like out of the box using the built-in material theme. +Shows how the widgets look like out of the box using the built-in material +theme. See in [widgets](https://github.com/lvgl/lvgl/tree/master/demos/widgets) folder. ![Basic demo to show the widgets of LVGL](widgets/screenshot1.png) -For running this demo properly, please make sure **LV_MEM_SIZE** is at least **38KB** (and **48KB** is recommended): +For running this demo properly, please make sure **LV_MEM_SIZE** is at least +**38KB** (and **48KB** is recommended): ```c #define LV_MEM_SIZE (38ul * 1024ul) @@ -128,30 +137,40 @@ For running this demo properly, please make sure **LV_MEM_SIZE** is at least **3 ### Music player -The music player demo shows what kind of modern, smartphone-like user interfaces can be created on LVGL. It works the best with display with 480x272 or 272x480 resolution. +The music player demo shows what kind of modern, smartphone-like user interfaces +can be created on LVGL. It works the best with display with 480x272 or 272x480 +resolution. See in [music](https://github.com/lvgl/lvgl/tree/master/demos/music) folder. ![Music player demo with LVGL](music/screenshot1.gif) ### Keypad and encoder -LVGL allows you to control the widgets with a keypad and/or encoder without a touchpad. This demo shows how to handle buttons, drop-down lists, rollers, sliders, switches, and text inputs without touchpad. -Learn more about the touchpad-less usage of LVGL [here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). +LVGL allows you to control the widgets with a keypad and/or encoder without a +touchpad. This demo shows how to handle buttons, drop-down lists, rollers, +sliders, switches, and text inputs without touchpad. Learn more about the +touchpad-less usage of LVGL +[here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). -See in [keypad_encoder](https://github.com/lvgl/lvgl/tree/master/demos/keypad_encoder) folder. +See in +[keypad_encoder](https://github.com/lvgl/lvgl/tree/master/demos/keypad_encoder) +folder. -![Keypad and encoder navigation in LVGL embedded GUI library](keypad_encoder/screenshot1.png) +![Keypad and encoder navigation in LVGL embedded GUI +library](keypad_encoder/screenshot1.png) ### Benchmark -A demo to measure the performance of LVGL or to compare different settings. -See in [benchmark](https://github.com/lvgl/lvgl/tree/master/demos/benchmark) folder. +A demo to measure the performance of LVGL or to compare different settings. See +in [benchmark](https://github.com/lvgl/lvgl/tree/master/demos/benchmark) folder. ![Benchmark demo with LVGL embedded GUI library](benchmark/screenshot1.png) ### Stress -A stress test for LVGL. It contains a lot of object creation, deletion, animations, style usage, and so on. It can be used if there is any memory corruption during heavy usage or any memory leaks. -See in [stress](https://github.com/lvgl/lvgl/tree/master/demos/stress) folder. -![Stress test for LVGL](stress/screenshot1.png) +A stress test for LVGL. It contains a lot of object creation, deletion, +animations, style usage, and so on. It can be used if there is any memory +corruption during heavy usage or any memory leaks. See in +[stress](https://github.com/lvgl/lvgl/tree/master/demos/stress) folder. ![Stress +test for LVGL](stress/screenshot1.png) ## Contributing -For contribution and coding style guidelines, please refer to the file docs/CONTRIBUTING.md in the main LVGL repo: - https://github.com/lvgl/lvgl \ No newline at end of file +For contribution and coding style guidelines, please refer to the file +docs/CONTRIBUTING.md in the main LVGL repo: https://github.com/lvgl/lvgl diff --git a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/keypad_encoder/README_EN.md b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/keypad_encoder/README_EN.md index ad6ea6dcf..74f8349fd 100644 --- a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/keypad_encoder/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/keypad_encoder/README_EN.md @@ -1,13 +1,16 @@ # Keypad and Encoder demo +Source path: example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/keypad_encoder ## Overview -LVGL allows you to control the widgets with keypad and/or encoder without touchpad. -This demo shows how to handle buttons, drop-down lists, rollers, sliders, switches and text inputs without touchpad. -Learn more about the touchpad-less usage of LVGL [here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). +LVGL allows you to control the widgets with keypad and/or encoder without +touchpad. This demo shows how to handle buttons, drop-down lists, rollers, +sliders, switches and text inputs without touchpad. Learn more about the +touchpad-less usage of LVGL +[here](https://docs.lvgl.io/master/overview/indev.html#keypad-and-encoder). ![Keypad and encoder navigation in LVGL embedded GUI library](screenshot1.gif) ## Run the demo - In `lv_conf.h` or equivalent places set `LV_USE_DEMO_KEYPAD_AND_ENCODER 1` -- After `lv_init()` and initializing the drivers call `lv_demo_keypad_encoder()` \ No newline at end of file +- After `lv_init()` and initializing the drivers call `lv_demo_keypad_encoder()` diff --git a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/music/README_EN.md b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/music/README_EN.md index 511b826b5..a862bc19b 100644 --- a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/music/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/music/README_EN.md @@ -1,8 +1,10 @@ # Music player demo +Source path: example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/music ## Overview -The music player demo shows what kind of modern, smartphone-like user interfaces can be created on LVGL. It works the best with display with 480x272 or 272x480 resolution. - +The music player demo shows what kind of modern, smartphone-like user interfaces +can be created on LVGL. It works the best with display with 480x272 or 272x480 +resolution. ![Music player demo with LVGL embedded GUI library](screenshot1.gif) @@ -12,16 +14,22 @@ The music player demo shows what kind of modern, smartphone-like user interfaces - After `lv_init()` and initializing the drivers call `lv_demo_music()` ## How the spectrum animation works -- `assets/spectrum.py` creates an array of spectrum values from a music. 4 band are created with 33 samples/sec: bass, bass-mid, mid, mid-treble. +- `assets/spectrum.py` creates an array of spectrum values from a music. 4 band + are created with 33 samples/sec: bass, bass-mid, mid, mid-treble. - The spectrum meter UI does the following: - - Zoom the album cover proportionality to the current bass value - - Display the 4 bands on the left side of a circle by default at 0°, 45°, 90°, 135° - - Add extra bars next to the "main bars" with a cosine shape. Add more bars for the lower bands. - - If there is a large enough bass, add a random offset to the position of the bars. E.g. start from 63° instead of 0°. (bars greater than 180° start again from 0°) - - If there is no bass, add 1 to the offset of the bars (it creates a "walking" effect) - - Mirror the bars to the right side of the circle - + - Zoom the album cover proportionality to the current bass value + - Display the 4 bands on the left side of a circle by default at 0°, 45°, + 90°, 135° + - Add extra bars next to the "main bars" with a cosine shape. Add more bars + for the lower bands. + - If there is a large enough bass, add a random offset to the position of + the bars. E.g. start from 63° instead of 0°. (bars greater than 180° start + again from 0°) + - If there is no bass, add 1 to the offset of the bars (it creates a + "walking" effect) + - Mirror the bars to the right side of the circle + ## Using spectrum.py -- install `librosa` with `pip3 install librosa` +- install `librosa` with `pip3 install librosa` - run `python spectrum.py my_file.mp3` -- see the result in `spectrum.h` \ No newline at end of file +- see the result in `spectrum.h` diff --git a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/stress/README_EN.md b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/stress/README_EN.md index 20e66b94d..178fbb15d 100644 --- a/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/stress/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/stress/README_EN.md @@ -1,13 +1,16 @@ # Stress demo +Source path: example/multimedia/lvgl/lvgl_v9_demos/src/lv_demos/stress ## Overview -A stress test for LVGL. -It contains a lot of object creation, deletion, animations, styles usage, and so on. It can be used if there is any memory corruption during heavy usage or any memory leaks. +A stress test for LVGL. It contains a lot of object creation, deletion, +animations, styles usage, and so on. It can be used if there is any memory +corruption during heavy usage or any memory leaks. ![Stress demo with LVGL embedded GUI library](screenshot1.gif) ## Run the demo - In `lv_conf.h` or equivalent places set `LV_USE_DEMO_STRESS 1` -- In `lv_conf.h` enable all the widgets (`LV_USE_BTN 1`) and the animations (`LV_USE_ANIMATION 1`) -- After `lv_init()` and initializing the drivers call `lv_demo_stress()` \ No newline at end of file +- In `lv_conf.h` enable all the widgets (`LV_USE_BTN 1`) and the animations + (`LV_USE_ANIMATION 1`) +- After `lv_init()` and initializing the drivers call `lv_demo_stress()` diff --git a/example/multimedia/lvgl/lvgl_v9_examples/README_EN.md b/example/multimedia/lvgl/lvgl_v9_examples/README_EN.md index 9e33bd04c..e86e3da69 100644 --- a/example/multimedia/lvgl/lvgl_v9_examples/README_EN.md +++ b/example/multimedia/lvgl/lvgl_v9_examples/README_EN.md @@ -1,121 +1,136 @@ -```markdown|CODE_EDIT_BLOCK|d:\SiFli-SDK\SiFli-SDK\example\multimedia\lvgl\lvgl_v9_examples\README_EN.md -# LVGL v9 Official Example +# LVGL v9 Official Examples ## Introduction -This example is used to test LVGL V9 APIs with the official provided examples. -You can replace the lv_example_scroll_1() function in src/main.c (simulator is in simulator/applications/application.c) to test other APIs. -For other API functions, refer to the function definitions in src/examples/lv_examples.h. - -## Project Compilation and Download: -The board project is located in the project directory and can be compiled for a specific board by specifying the board, -- For example, to compile a project that can run on HDK 563, execute scons --board=eh-lb563 to generate the project -- Downloading can be done through the download.bat in the build directory. For example, to flash the 563 project generated in the previous step, you can execute .\build_eh-lb563\download.bat to download via jlink -- It should be noted that for SF32LB52x/SF32LB56x series, an additional uart_download.bat will be generated. You can execute this script and input the download UART port number to perform the download -The simulator project is in the simulator directory, -- Compile using scons, the SiFli-SDK/msvc_setup.bat file needs to be modified accordingly to match the local MSVC configuration -- You can also use scons --target=vs2017 to generate an MSVC project project.vcxproj and compile using Visual Studio. +This example is used to test the LVGL v9 APIs using the official examples +provided. You can replace the `lv_example_scroll_1()` function in `src/main.c` +(or `simulator/applications/application.c` for the simulator) to evaluate other +APIs. For a complete list of available API functions, refer to the definitions +in `src/examples/lv_examples.h`. + +## Project Compilation and Programming: +Projects located in the `project` directory can be compiled for a specific +target by specifying the `board` parameter. +- For example, to compile a project for the HDK 563, execute `scons + --board=eh-lb563` to generate the project files. +- Firmware can be programmed using the `download.bat` script located in the + `build` directory. To flash the 563 project generated in the previous step, + run `.\build_eh-lb563\download.bat` to perform the download via J-Link. +- Note: For the SF32LB52x and SF32LB56x series, an additional + `uart_download.bat` script is generated. Execute this script and enter the + UART port number to perform the download. The simulator project is located in + the `simulator` directory. +- To compile using Scons, ensure that the `SiFli-SDK/msvc_setup.bat` file is + modified to match your local MSVC configuration. +- Alternatively, you can generate an MSVC project (`project.vcxproj`) by running + `scons --target=vs2017` and then compile it using Visual Studio. ```{note} -Note: If you are not using VS2017, for example VS2022, when loading the project, you will be prompted to upgrade the MSVC SDK. After upgrading, it can be used. -``` +Note: If you are using a version other than VS2017 (e.g., VS2022), Visual Studio will prompt you to upgrade the MSVC SDK upon loading the project. The project will be ready for use after the upgrade. +``` -## How to Use Tjpgd -Source path: SiFli-SDK\example\multimedia\lvgl\lvgl_v9_examples +## Using Tjpgd +Source Path: `SiFli-SDK\example\multimedia\lvgl\lvgl_v9_examples` ### Supported Platforms -The example can run on the following development boards +This example is compatible with the following development boards: + sf32lb52-lchspi-ulp -+ sf32lb52-lcd series ++ SF32LB52-LCD Series + sf32lb56-lcd series + sf32lb58-lcd series - ### Overview -* Mount the file system by inserting an SD card, then read .jpg format images from it and display them on the screen +* Mount the file system via an SD card, read a .jpg image from the card, and + display it on the screen. ### Hardware Requirements -* Huangshan development board or 52x series development board -* A USB data cable with data transmission capability +* HS-PI development board or a 52x series development board +* A USB data cable with data transfer capabilities * A TF card and a TF card reader -### Example Usage +### Usage Instructions #### Compilation and Flashing -The demo code displays the image by default: ``` flower.jpg ``` +By default, the demo code displays the image: ``` flower.jpg ``` -Switch to the example project directory and run the scons command to compile: +Navigate to the project directory and run the `scons` command to compile: ``` scons --board=sf32lb52-lchspi-ulp -j8 ``` -Execute the flashing command +Execute the flash command ``` build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat ``` -Follow the prompts to select the port for downloading: +Select the port as prompted to begin the download: ```none -please input the serial port num:5 +Please enter the serial port number: 5 ``` -#### Example Output Results: -* After inserting the SD card, mount the file system and read images from the file system and display image logs. If the log contains `mount fs on flash to root success`, it indicates that the file system was mounted successfully +#### Sample output: +* Upon inserting the SD card, the file system mounts and the image is read. If + the log displays `mount fs on flash to root success `, the file system has + mounted successfully. ![alt text](assets/log1.png) -* You can input ls to view image files in the file system +* Enter the "ls" command to view the image files within the file system. ![alt text](assets/log2.png) -### Example Effect Display +### Demo results ![alt text](assets/demo.jpg) -#### Example Configuration Process -* By default, SPI is not enabled for TF file system mounting. If needed, configure as follows -* First, you can use a TF card reader to write image files to the TF card, then insert the TF card into the board -* Perform the following configuration through menuconfig, the specific operation is as follows +#### Routine Configuration +* By default, the SPI interface for mounting the TF card filesystem is disabled. + If required, follow the configuration steps below. +* First, use a TF card reader to write image files to the TF card, then insert + the card into the board. +* Configure the settings via `menuconfig` as follows: ``` c menuconfig --board=sf32lb52-lchspi-ulp ``` -* Enable SPI bus +* Enable the SPI bus. ![alt text](assets/V9_SPI.png) -* Mount the SD\TF device on the SPI bus +* Mount the SD/TF device on the SPI bus. ![alt text](assets/V9_tf.png) -* Configure file path +* Configure the file path. ![alt text](assets/V9_elm.png) -* Enable LVGL file system interface, configure drive letter, and enable decoder +* Enable the LVGL filesystem interface, configure the drive letter, and enable + the decoder. ![alt text](assets/V9_posix.png) -### tjpgd (Extension) +### TJPGD (Extension) ### Overview -* Decode LV_IMAGE_SRC_VARIABLE type using the tjpgd decoder +* Use the TJPGD decoder to decode `LV_IMAGE_SRC_VARIABLE` types. ### Image Format Conversion -* First, .jpg images need to be converted to RAW data. The conversion tool eez_studio can be used for conversion. Refer to the following for specific operations -![alt text](assets/jpg_awitch_RAW.png) +* First, convert the .jpg images to RAW data. EEZ Studio can be used for this + conversion. Refer to the figure below for the specific procedure: ![alt + text](assets/jpg_awitch_RAW.png) ![alt text](assets/build_raw.png) ![alt text](assets/copy_raw.png) -* Then set the image array, the jpegd decoder will select the corresponding decoding method based on the set type +* Then, set the image array. The JPEGD decoder will select the appropriate + decoding method based on the specified type. ### Configuration Process -* Perform the following configuration through menuconfig, the specific operation is as follows: -Enable LV_USE_FS_MEMFS macro -![alt text](assets/use_fs_memfs.png) +* Perform the following configuration via `menuconfig`: Enable the + LV_USE_FS_MEMFS macro. ![alt text](assets/use_fs_memfs.png) -The example has already converted `img_lvgl_logo.jpg` to RAW data `ui_image_logo.c` +In the example routine, `img_lvgl_logo.jpg` has been converted to RAW data in +`ui_image_logo.c`. ### Troubleshooting -* Abnormal log -![alt text](assets/log3.png) -If the above situation occurs, the TF card may be loose, the TF card cannot communicate normally, or the TF card is not inserted -``` \ No newline at end of file +* Error Log ![alt text](assets/log3.png) If the above error occurs, it may + indicate a loose TF card, a communication failure, or that the TF card is not + inserted. diff --git a/example/multimedia/lvgl/streaming_media/README_EN.md b/example/multimedia/lvgl/streaming_media/README_EN.md index 81c96d680..8d71977cb 100644 --- a/example/multimedia/lvgl/streaming_media/README_EN.md +++ b/example/multimedia/lvgl/streaming_media/README_EN.md @@ -2,16 +2,20 @@ Source Code Path: example/multimedia/lvgl/streaming_media -This example demonstrates how to connect to a mobile phone hotspot via Bluetooth PAN protocol, and then automatically fetch and play online video from the network. The video sources are defined in the `VIDEO_SRC` array in `main.c`. Before the network is connected, the screen remains black. +This example demonstrates how to connect to a mobile phone hotspot via Bluetooth +PAN protocol, and then automatically fetch and play online video from the +network. The video sources are defined in the `VIDEO_SRC` array in `main.c`. +Before the network is connected, the screen remains black. -This example mainly uses SiFli-SDK's Bluetooth Classic (PAN, A2DP), LCD display, lvgl GUI, and FFMPEG decoding features. -Related API references: [Bluetooth](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/api/bluetooth/index.html), [lvgl](https://docs.lvgl.io/latest/en/), [FFMPEG](https://ffmpeg.org/documentation.html). - -Based on this example, you can implement applications such as smart terminal online video playback and Bluetooth hotspot streaming media display. +This example mainly uses SiFli-SDK's Bluetooth Classic (PAN, A2DP), LCD display, +lvgl GUI, and FFMPEG decoding features.\ +Related API references: [Bluetooth]{1}, [lvgl]{2}, [FFMPEG]{3}. ## Usage -For detailed SiFli-SDK configuration and build instructions, please refer to the [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). +For detailed SiFli-SDK configuration and build instructions, please refer to the +[SiFli-SDK Quick +Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). ### Supported Boards @@ -30,21 +34,26 @@ For detailed SiFli-SDK configuration and build instructions, please refer to the ### Connection and Operation Steps -1. **Enable Bluetooth network sharing on your phone** - - iOS: Insert a SIM card and turn on "Personal Hotspot". +1. **Enable Bluetooth network sharing on your phone** + - iOS: Insert a SIM card and turn on "Personal Hotspot".\ ![IOS_ENB](./assets/ios_enable_pan.png) - - Android: In "Personal Hotspot" settings, enable "Bluetooth network sharing". + - Android: In "Personal Hotspot" settings, enable "Bluetooth network + sharing".\ ![ANDRIOD_ENB](./assets/android_enable_pan.png) -2. **After powering on the development board** - - Bluetooth will automatically enter discoverable and pairable mode. Your phone can search for a Bluetooth device named `sifli_streaming` and connect to it. +2. **After powering on the development board** + - Bluetooth will automatically enter discoverable and pairable mode. Your + phone can search for a Bluetooth device named `sifli_streaming` and connect + to it. -3. **After successful connection** - - The serial port will print `pan connect successed`, and the current filename being read will be displayed at the bottom of the screen. - - After the network is connected, the program will automatically fetch and play the video streams in `VIDEO_SRC`. +3. **After successful connection** + - The serial port will print `pan connect successed`, and the current + filename being read will be displayed at the bottom of the screen. + - After the network is connected, the program will automatically fetch and + play the video streams in `VIDEO_SRC`.\ ![PLAY_VIDEO](./assets/play_online_streaming_video.png) -4. **To reconnect PAN** +4. **To reconnect PAN** - You can use the finsh command `pan_cmd conn_pan` to reconnect. ## Project Configuration @@ -82,7 +91,8 @@ Please enable the following options in menuconfig: 7. **Enable lvgl、FFMPEG、MBedTLS libraries** - Path: Third party packages - - Macros: `CONFIG_PKG_USING_LITTLEVGL2RTT`, `CONFIG_PKG_USING_FFMPEG`,`CONFIG_PKG_USING_MBEDTLS` + - Macros: `CONFIG_PKG_USING_LITTLEVGL2RTT`, + `CONFIG_PKG_USING_FFMPEG`,`CONFIG_PKG_USING_MBEDTLS` ## Compilation and Flashing @@ -107,24 +117,29 @@ For detailed steps, please refer to [Quick Start](/quickstart/get-started.md). After Bluetooth connection, the serial port will output: ``` -pan connect successed +PAN connection successful ``` -After the network is connected, the current filename being read will be displayed at the bottom of the screen, and the video will play normally. Before the network is connected, the screen remains black. +After the network is connected, the current filename being read will be +displayed at the bottom of the screen, and the video will play normally. Before +the network is connected, the screen remains black. ## Troubleshooting -- If Bluetooth cannot connect, please check whether Bluetooth network sharing is enabled on your phone. -- If the video cannot play, please confirm that the network is connected and the video source address is accessible. +- If Bluetooth cannot connect, please check whether Bluetooth network sharing is + enabled on your phone. +- If the video cannot play, please confirm that the network is connected and the + video source address is accessible. - To reconnect PAN, you can use the finsh command `pan_cmd conn_pan`. -If you have any technical questions, please submit them via [GitHub issue](https://github.com/OpenSiFli/SiFli-SDK/issues). +If you have any technical questions, please submit them via [GitHub +issue](https://github.com/OpenSiFli/SiFli-SDK/issues). ## Reference Documents ## Update History -| Version | Date | Release Notes | -|:------|:--------|:----------| -| 0.0.1 | 08/2025 | Initial version | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 08/2025 | Initial version | diff --git a/example/multimedia/lvgl/watch/README_EN.md b/example/multimedia/lvgl/watch/README_EN.md index ee7addd42..d031f9a24 100644 --- a/example/multimedia/lvgl/watch/README_EN.md +++ b/example/multimedia/lvgl/watch/README_EN.md @@ -1,61 +1,111 @@ # Watch Interface Using LVGL v8, the included interfaces are: -- Honeycomb main menu -- Watch face -- Cube left-right rotation (not supported on SF32lb55x series chips) -```{note} -- Not supported on 520-hdk -``` - -# Watch Interface -Source Code Path: example/multimedia/lvgl/watch -This is a smartwatch interface example implemented based on LVGL v8, featuring various interactive interfaces and font configuration capabilities. It demonstrates how to use the LVGL graphics library component of SiFli-SDK to build user interfaces for embedded devices. -Developers can use this example as a foundation to build UI interfaces for various smart wearable devices such as sports watches and health monitoring devices. +## Usage ## Supported Boards -This example can run on the following development boards: -+ sf32lb52-lcd series -+ sf32lb56-lcd series -+ sf32lb58-lcd series -+ sf32lb52-lchspi-ulp +This example can be executed on the following development boards: +- SF32LB52-LCD Series +- sf32lb56-lcd series +- sf32lb58-lcd series +- sf32lb52-lchspi-ulp + ```{note} -- Not supported on 520-hdk +- 520-HDK is not supported ``` ### Hardware Requirements -- SiFli development board with LCD display support +- SiFli development boards with LCD support -## Specifying Fonts +## 1. Specifying Fonts -Refer to `src/resource/fonts/SConscript`. By adding the `FREETYPE_FONT_NAME` macro definition in CPPDEFINES, you can register the corresponding TTF font to LVGL -```python -CPPDEFINES += ["FREETYPE_FONT_NAME={}".format(font_name)] -``` -If `font_name` is `DroidSansFallback`, it is equivalent to adding the following macro definition +For example, if `font_name` is set to `DroidSansFallback`, it is equivalent to +adding the following macro definition: ```c #define FREETYPE_FONT_NAME DroidSansFallback ``` -During compilation, it will search for font files with `.ttf` suffix in the `freetype` subdirectory and convert them to C files for compilation + +During compilation, the system searches the `freetype` subdirectory for font +files with the `.ttf` extension and converts them into C files for inclusion in +the build process: ```python objs = Glob('freetype/{}.ttf'.format(font_name)) objs = Env.FontFile(objs) ``` -Macros like `FREETYPE_TINY_FONT_FULL` are defined in `Kconfig.proj` in the project directory, similar to the following: + +Once compilation is complete, the TTF file is converted into a C file located in +the `build_xxx_hcpu/src/resource/fonts/freetype` directory with the filename +`{font_name}.c`. This C file invokes a font registration macro to register the +font with LVGL, making it available for use: +```c +LVSF_FREETYPE_FONT_REGISTER(tiny55_full) +``` + +Macros such as `FREETYPE_TINY_FONT_FULL` are defined in the `Kconfig.proj` file +within the project directory as follows: ```kconfig config FREETYPE_TINY_FONT_FULL bool default y ``` -## Example Output +## 2. Complete `src/resource/fonts/SConscript` Example (supporting multiple custom fonts) + +```python +CPPDEFINES = [] + +font_name = '' # Default font option, defined in [Kconfig.proj] under the project directory. +font_name2 = 'SourceHanSansCN_Normal' # Custom TTF font filename. Place the file in the `src/resource/fonts/freetype` directory. + +if GetDepend('FREETYPE_TINY_FONT_FULL'): + font_name = 'tiny55_full' +elif GetDepend('FREETYPE_TINY_FONT_LITE'): + font_name = 'tiny55_lite' +elif GetDepend('FREETYPE_HANSANS_FONT'): + font_name = 'SourceHanSansCN_Normal' +elif GetDepend('FREETYPE_ARIAL_FONT'): + font_name = 'arial' +else: + font_name = 'DroidSansFallback' + +objs = Glob('freetype/{}.ttf'.format(font_name)) +objs = Env.FontFile(objs) + +objs2 = Glob('freetype/{}.ttf'.format(font_name2)) # Locate the custom font file. +objs += Env.FontFile(objs2) # Convert the custom TTF file to a C source file. +``` + +## Function Usage +```c +// Interface for using the default configured font (font_name) +void lv_ext_set_local_font(lv_obj_t *obj, uint16_t size, lv_color_t color) + +// Interface for using a custom font by specifying the registered font name +void lv_ext_set_font_local_by_name(lv_obj_t *obj, uint16_t size, lv_color_t color, char *fontname) +``` +## Troubleshooting +When multiple fonts are used, the total size of the TTF files may exceed the +pre-allocated memory capacity. If a compilation error such as the one shown +below occurs, you must increase the `max_size` for `"tags": +["HCPU_FLASH2_FONT"]` in `project/xxx_hcpu/ptab.json`. Note that when adjusting +this size, ensure that the addresses of adjacent segments remain contiguous and +consider the maximum memory capacity supported by the specific development +board. +``` +region 'ROM' overflowed by 7880732 bytes +``` +## Sample Output + +Upon successful execution, the development board's screen will display the main +smartwatch interface, including a honeycomb menu and watch face. Users can +navigate between different interfaces via touch or physical buttons. -After successful execution, the development board screen will display the watch main interface, including a honeycomb menu and watch face display. You can switch between different interfaces via touch or buttons. +## References -## Reference Documentation +- [SiFli-SDK Quick Start + Guided](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [LVGL Official Documentation](https://docs.lvgl.io/8.3/) -- [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [LVGL Official Documentation](https://docs.lvgl.io/8.3/) \ No newline at end of file diff --git a/example/multimedia/lvgl/watch_v9/README_EN.md b/example/multimedia/lvgl/watch_v9/README_EN.md index 029f04651..39dc3e073 100644 --- a/example/multimedia/lvgl/watch_v9/README_EN.md +++ b/example/multimedia/lvgl/watch_v9/README_EN.md @@ -1,36 +1,42 @@ # Watch Interface Example -(For a general overview of examples and their usage, please refer to the `README.md` file in the parent "examples" directory.) -Source Code Path: example/multimedia/lvgl/watch_v9 +(For a general overview of examples and their usage, please refer to the +`README.md` file in the parent "examples" directory.) -This example implements a smartwatch interface using LVGL v9, including the following main functional interfaces: +Source Code Path: example/multimedia/lvgl/watch_v9 - Honeycomb main menu - Watch face - Cube rotation (not supported on SF32lb55x series chips) ## Usage -The following sections provide only absolutely necessary information. For complete steps on configuring SiFli-SDK and using it to build and run projects, please refer to the [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). +The following sections provide only absolutely necessary information. For +complete steps on configuring SiFli-SDK and using it to build and run projects, +please refer to the [SiFli-SDK Quick +Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). ### Supported Development Boards + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series + ```{note} - 520-hdk is not supported ``` -### Hardware Requirements -This example does not require special hardware and can run directly on supported development boards. - -### Configure Project - -#### Specify Fonts -Refer to `src/resource/fonts/SConscript`, add font .c files, and use extern declarations where needed - ## Troubleshooting Users may encounter the following compatibility issues when using this example: - Running on 520-hdk development board will fail - SF32lb55x series chips do not support cube rotation function + - `font_file`: Path to the TTF file + - `DroidSansFallback`: C file name + +## Batch convert multiple TTF files to C files -For any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. \ No newline at end of file +Add the following code to the SConscript: + +```python +font_objs1 = Env.ConvertFont(font_file1, 'DroidSansFallback') +font_objs2 = Env.ConvertFont(font_file2, 'DroidSansFallback_other_name') +font_objs = font_objs1 + font_objs2 +``` diff --git a/example/pm/AMOLED/README_EN.md b/example/pm/AMOLED/README_EN.md index be7cc1fc2..df169a36c 100644 --- a/example/pm/AMOLED/README_EN.md +++ b/example/pm/AMOLED/README_EN.md @@ -7,81 +7,103 @@ This example can run on the following development boards: - sf32lb52-core_n16r16 ## Overview -Under the RT-Thread operating system, two modes are set: one is the screen-off mode (screen turns off and enters sleep after 5s of screen refresh); the other is the always-on screen mode (screen remains on and then enters sleep after 5s of screen refresh). Switching between these two modes can be done through finsh commands, where `power_mode 1` (switch from screen-off mode to always-on screen mode), `power_mode 0` (switch from always-on screen mode to screen-off mode). - -> Note: Mode switching can only be successful during the wake-up phase. Mode switching during the sleep phase will not take effect. +Under the RT-Thread operating system, two modes are set: one is the screen-off +mode (screen turns off and enters sleep after 5s of screen refresh); the other +is the always-on screen mode (screen remains on and then enters sleep after 5s +of screen refresh). Switching between these two modes can be done through finsh +commands, where `power_mode 1` (switch from screen-off mode to always-on screen +mode), `power_mode 0` (switch from always-on screen mode to screen-off mode). * Data Summary (using 200mAh battery capacity as an example) +* Data Summary (Based on a 200 mAh Battery Capacity) + **Screen-off Mode** -| |Screen-on during Wake-up |Screen-off Sleep |Daily Consumption |Usable Days | -|:--- |:--- |:--- |:--- |:--- | -|100 times/day|1.73mAh |1.18mAh |2.91mAh |68.7 days | -|300 times/day|5.20mAh |1.17mAh |6.37mAh |31.4 days | -|500 times/day|8.65mAh |1.16mAh |8.65mAh |23.1 days | -|**Average Power Consumption in Two Modes**|**Low Power Mode:** 49.06uA |**Working Mode:** 12.48mA | | | +| | Screen-on during Wake-up | Screen-off Sleep | Daily Consumption | Usable Days | +| ------------------------------------------ | --------------------------- | ------------------------- | ----------------- | ----------- | +| 100 times/day | 1.73 mAh | 1.18 mAh | 2.91 mAh | 68.7 days | +| 300 times/day | 5.20 mAh | 1.17 mAh | 6.37 mAh | 31.4 days | +| 500 times/day | 8.65 mAh | 1.16 mAh | 8.65 mAh | 23.1 days | +| **Average Power Consumption in Two Modes** | **Low Power Mode:** 49.06uA | **Working Mode:** 12.48mA | | | **Always-on Screen Mode** -| |Screen-on during Wake-up |Screen-off Sleep |Daily Consumption |Usable Days | -|:--- |:--- |:--- |:--- |:--- | -|100 times/day|1.73mAh |136mAh |137.73mAh |1.45 days | -|300 times/day|5.20mAh |134.43mAh |139.63mAh |1.43 days | -|500 times/day|8.65mAh |132.85mAh |141.5mAh |1.41 days | -|**Average Power Consumption in Two Modes**|**Low Power Mode:** 5.7mA |**Working Mode:** 12.38mA | | | +| | Screen-on during Wake-up | Screen-off Sleep | Daily Consumption | Usable Days | +| ------------------------------------------ | ------------------------- | ------------------------- | ----------------- | ----------- | +| 100 times/day | 1.73 mAh | 136 mAh | 137.73 mAh | 1.45 days | +| 300 times/day | 5.20 mAh | 134.43 mAh | 139.63 mAh | 1.43 days | +| 500 times/day | 8.65 mAh | 132.85 mAh | 141.5 mAh | 1.41 days | +| **Average Power Consumption in Two Modes** | **Low Power Mode:** 5.7mA | **Working Mode:** 12.38mA | | | ### Mode Introduction * Three screen modes -* 1. Power Off Mode: In this mode, most of the internal circuits of the screen are turned off. The screen will be completely black and will not display any images. Internal power circuits, driver ICs, backlight (for LCD) or pixels (for OLED) will stop working. +* 1. Power Off Mode: In this mode, most of the internal circuits of the screen + are turned off. The screen will be completely black and will not display + any images. Internal power circuits, driver ICs, backlight (for LCD) or + pixels (for OLED) will stop working. -* 2. Idle Mode: The purpose is to minimize power consumption while maintaining basic functions, so as to quickly resume normal operation. The screen usually stops refreshing and maintains the static image of the last frame before entering Idle mode (but some screens may clear the display). Core display drivers and memory (such as GRAM) remain powered, but clocks and scanning circuits may stop or significantly reduce frequency. +* 2. Idle Mode: The purpose is to minimize power consumption while maintaining + basic functions, so as to quickly resume normal operation. The screen + usually stops refreshing and maintains the static image of the last frame + before entering Idle mode (but some screens may clear the display). Core + display drivers and memory (such as GRAM) remain powered, but clocks and + scanning circuits may stop or significantly reduce frequency. -* 3. Normal Mode: This is the full-function working mode of the screen with the highest power consumption. The screen refreshes normally and continuously, dynamically displaying image data sent from the host. All internal circuits, including clock generators, scanning drivers, GRAM, gamma correction circuits, and power circuits, operate at full speed. +* 3. Normal Mode: This is the full-function working mode of the screen with the + highest power consumption. The screen refreshes normally and continuously, + dynamically displaying image data sent from the host. All internal + circuits, including clock generators, scanning drivers, GRAM, gamma + correction circuits, and power circuits, operate at full speed. * Always-on screen mode and screen-off mode in project introduction -1. Always-on screen mode: Refers to the screen's working state being refreshed in Normal Mode. After refreshing, the chip module enters Idle Mode, but the screen does not enter sleep mode. - -2. Screen-off mode: The screen's working state is refreshed in Normal Mode. After refreshing, the screen first enters Power Off Mode, then the chip module enters sleep. +1. Always-on screen mode: Refers to the screen's working state being refreshed + in Normal Mode. After refreshing, the chip module enters Idle Mode, but the + screen does not enter sleep mode. +2. Screen-off mode: The screen's working state is refreshed in Normal Mode. + After refreshing, the screen first enters Power Off Mode, then the chip + module enters sleep. ## Hardware Connection -For low power consumption testing, the board is no longer powered through USB but needs to be powered through a power consumption testing tool to the board's VCC_5V with 5V power supply. Therefore, the following operations need to be performed to conduct power consumption testing. +For low power consumption testing, the board is no longer powered through USB +but needs to be powered through a power consumption testing tool to the board's +VCC_5V with 5V power supply. Therefore, the following operations need to be +performed to conduct power consumption testing. -* Original power supply situation of development board -![alt text](assets/core_board.png) +* Original power supply situation of development board ![alt + text](assets/core_board.png) -* Remove all jumper caps except for ADDIO, PVDD, and AVDD -![alt text](assets/remove_jumper_cap.png) +* Remove all jumper caps except for ADDIO, PVDD, and AVDD ![alt + text](assets/remove_jumper_cap.png) -* Connect the power consumption testing tool's VOUT to the board's VCC_5V, and connect GND to the PPK's GND pin -![alt text](assets/PPK_connect.png) +* Connect the power consumption testing tool's VOUT to the board's VCC_5V, and + connect GND to the PPK's GND pin ![alt text](assets/PPK_connect.png) -* For convenient debugging, the UART converter can be connected to the board's TX and RX -![alt text](assets/uart_connect.png) +* For convenient debugging, the UART converter can be connected to the board's + TX and RX ![alt text](assets/uart_connect.png) -* Final connection -![alt text](assets/final_connect.png) +* Final connection ![alt text](assets/final_connect.png) ## menuconfig Configuration -The required configurations are already enabled by default. +* Enable low power mode ```c menuconfig --board=board_name ``` - -1. Enable low power mode -- Path: Sifli middleware - - Enable: Enable low power support - - Macro switch: `CONFIG_BSP_USING_PM` - - Function: Enable low power - -2. Enable output of low power related logs (disabled by default to reduce power consumption. Can be enabled in menuconfig for debugging and verification) +1. Path: Sifli middleware +- Enable output of low power related logs (disabled by default to reduce power + consumption. Can be enabled in menuconfig for debugging and verification) + - Enabled: Enable Low Power Support + - Macro Switch: `CONFIG_BSP_USING_PM` + - Function: Enables the low power management features. + +2. Path: SiFli Middleware → Enable Low Power Support - Path: SiFli Middleware → Enable Low Power Support - - Enable: Enable PM Debug - - Macro switch: `CONFIG_BSP_PM_DEBUG` - - Function: Output low power related logs + - Enabled: Enable PM Debug + - Macro Switch: `CONFIG_BSP_PM_DEBUG` + - Function: Outputs low power management (PM) debug logs. ### Compilation and Flashing The 52 platform is configured to hibernate in Deep Sleep mode by default.
@@ -93,9 +115,9 @@ Flashing: ``` build_sf32lb52-core_n16r16_hcpu\uart_download.bat - Uart Download + UART Download -please input the serial port num:19 +Please enter serial port number: 19 ``` ## Example Output Results @@ -125,26 +147,26 @@ call par CFG1(3313) fc 9, xtal 2000, pll 2129 call par CFG1(3313) fc 7, xtal 2000, pll 1706 -[2866] I/drv.lcd main: [NONE] -> [OPENING] +[2866] I/drv.lcd main: [NONE] -> [OPENING] [2893] I/drv.lcd lcd_task: open [2908] I/drv.epic lcd_task: drv_gpu opened. [2926] I/drv.lcd lcd_task: HW open [2957] I/drv.lcd lcd_task: Try registered LCD driver... -msh /> +msh /> CO5300_ReadID 0x331100 [5286] I/co5300 lcd_task: LCD module use CO5300 IC [11538] I/drv.lcd lcd_task: Found lcd co5300 id:331100h [11561] I/drv.lcd lcd_task: HW open done. -[11581] I/drv.lcd lcd_task: [OPENING] -> [INITIALIZED] +[11581] I/drv.lcd lcd_task: [OPENING] -> [INITIALIZED] [11601] I/drv.lcd lcd_task: open done. [13554] I/drv.lcd lcd_task: Auto turn on display. [13576] I/drv.lcd lcd_task: set brightness 50 [13599] I/drv.lcd lcd_task: display on -[13615] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] +[13615] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] [184450] I/drv.lcd lcd_task: Power off [184470] I/drv.epic lcd_task: drv_gpu closed. [184488] I/drv.lcd lcd_task: display off -[184508] I/drv.lcd lcd_task: [ON] -> [OFF] +[184508] I/drv.lcd lcd_task: [ON] -> [OFF] [184526] I/drv.lcd lcd_task: HW close [184540] I/drv.lcd lcd_task: HW close done. [184557] I/drv.lcd lcd_task: Power off done @@ -162,88 +184,79 @@ CO5300_ReadID 0x331100 Key interrupt triggered! system_sleeping=0 [356508] I/drv.lcd lcd_task: HW open done. -[356525] I/drv.lcd lcd_task: [OFF] -> [INITIALIZED] +[356525] I/drv.lcd lcd_task: [OFF] -> [INITIALIZED] [356545] I/drv.lcd lcd_task: Power on done. [358540] I/drv.lcd lcd_task: Auto turn on display. [358562] I/drv.lcd lcd_task: set brightness 50 [358583] I/drv.lcd lcd_task: display on -[358600] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] -msh />msh />[529475] I/drv.lcd lcd_task: idle mode on=1 -[529501] I/drv.lcd lcd_task: [ON] -> [IDLEMODE] +[358600] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] +msh />msh />[529475] I/drv.lcd lcd_task: idle mode on=1 +[529501] I/drv.lcd lcd_task: [ON] -> [IDLEMODE] [529523] I/APP.FWK.PM main: gui suspend canel ``` +* Screen-off mode board phenomenon When awakened: ![alt text](assets/lcd_on.png) + When sleeping: ![alt text](assets/lcd_off.png) -* Screen-off mode board phenomenon - When awakened: - ![alt text](assets/lcd_on.png) - When sleeping: - ![alt text](assets/lcd_off.png) - -* Always-on screen mode board phenomenon - When awakened: - ![alt text](assets/lcd_wakeup.png) - When sleeping: - ![alt text](assets/lcd_sleep.png) +* Always-on screen mode board phenomenon When awakened: ![alt + text](assets/lcd_wakeup.png) When sleeping: ![alt text](assets/lcd_sleep.png) ## Power Consumption Test Results -* We use a 200mAh battery capacity as an example to test the above two modes and estimate device usage time. -* Classified into light, medium, and heavy usage scenarios, corresponding to 100, 300, and 500 wake-up times respectively. Each wake-up executes 5 seconds of screen refresh to simulate the time people spend viewing content. - +* We use a 200mAh battery capacity as an example to test the above two modes and + estimate device usage time. +* Classified into light, medium, and heavy usage scenarios, corresponding to + 100, 300, and 500 wake-up times respectively. Each wake-up executes 5 seconds + of screen refresh to simulate the time people spend viewing content. ### Screen-off Mode -1. Key trigger wake-up (used to simulate watching time on a watch) -* Average current during 5s screen refresh after key wake-up: 12.48mA -![alt text](assets/lcd_on_wakeup_ppk.png) +1. Button-triggered wake-up (simulating typical user interaction, such as +checking time on a smartwatch) +* Key trigger wake-up (used to simulate watching time on a watch) -* Power consumption per day - - 100 times: 12.48*100*5/3600 = 1.73 (mAh) - - 300 times: 12.48*300*5/3600 = 5.2 (mAh) - - 500 times: 12.48*500*5/3600 = 8.65 (mAh) - -2. Screen-off sleep (used to simulate standby state) -* Quiescent current in screen-off sleep mode: 49.06uA -![alt text](assets/lcd_off_sleep_ppk.png) +* Average current during 5s screen refresh after key wake-up: 12.48mA ![alt + text]{1} + - 100 cycles: 12.48 * 100 * 5 / 3600 = 1.73 (mAh) + - 300 cycles: 12.48 * 300 * 5 / 3600 = 5.2 (mAh) + - 500 cycles: 12.48 * 500 * 5 / 3600 = 8.65 (mAh) -* Power required for one hour of screen-off sleep - 49.6/1000*1=0.0496 (mAh) - -* Total daily consumption calculated as: - - 100 times: 0.0496 * (24 * 3600 - 100 * 5) + 1.73 = 2.91 (mAh) - - 300 times: 0.0496 * (24 * 3600 - 300 * 5) + 5.20 = 6.37 (mAh) - - 500 times: 0.0496 * (24 * 3600 - 500 * 5) + 8.65 = 9.81 (mAh) +2. Sleep mode with screen off (simulating typical standby state) +* Power consumption per day +* Screen-off sleep (used to simulate standby state) +* Quiescent current in screen-off sleep mode: 49.06uA ![alt text]{1} + - 100 cycles: 0.0496 * (24 * 3600 - 100 * 5) + 1.73 = 2.91 (mAh) + - 300 cycles: 0.0496 * (24 * 3600 - 300 * 5) + 5.20 = 6.37 (mAh) + - 500 cycles: 0.0496 * (24 * 3600 - 500 * 5) + 8.65 = 9.81 (mAh) ### Always-on Screen Mode -1. Key trigger wake-up (used to simulate watch usage) +1.1 Button-triggered wake-up (simulating typical smartwatch usage) +* Key trigger wake-up (used to simulate watch usage) + * Average current required for 5s screen refresh after key wake-up: 12.38mA -![alt text](assets/lcd_wakeup_ppk.png) + ![alt text]{1} + - 100 cycles: 12.48 * 100 * 5 / 3600 = 1.73 (mAh) + - 300 cycles: 12.48 * 300 * 5 / 3600 = 5.2 (mAh) + - 500 cycles: 12.48 * 500 * 5 / 3600 = 8.65 (mAh) +2. Always-on display (AOD) entering sleep mode (simulating typical +wake-on-standby behavior) * Power consumption during usage - - 100 times: 12.48*100*5/3600 = 1.73 (mAh) - - 300 times: 12.48*300*5/3600 = 5.2 (mAh) - - 500 times: 12.48*500*5/3600 = 8.65 (mAh) - -2. Always-on screen sleep (used to simulate always-on screen standby state) -* Quiescent current in always-on screen sleep mode: 5.7mA -![alt text](assets/lcd_sleep_ppk.png) -* Power consumption required for one hour of screen-on sleep - 5.7*1=5.7 (mAh) - -* Daily consumption - - 100 times: 5.7*(24*3600-100*5) + 1.73 = 137.73 (mAh) - - 300 times: 5.7*(24*3600-300*5) + 5.20 = 139.63 (mAh) - - 500 times: 5.7*(24*3600-500*5) + 8.65 = 141.5 (mAh) +* Always-on screen sleep (used to simulate always-on screen standby state) +* Quiescent current in always-on screen sleep mode: 5.7mA ![alt text]{1} + - 100 cycles: 5.7*(24*3600-100*5) + 1.73 = 137.73 (mAh) + - 300 cycles: 5.7*(24*3600-300*5) + 5.20 = 139.63 (mAh) + - 500 cycles: 5.7*(24*3600-500*5) + 8.65 = 141.5 (mAh) ## Abnormal Diagnosis -If the measured results differ significantly from those in the document, there may be abnormalities. Please conduct troubleshooting on your own. -UDDIO: Chip IO power supply -PVDD: Chip main power input -AVDD: Chip audio +If the measured results differ significantly from those in the document, there +may be abnormalities. Please conduct troubleshooting on your own. UDDIO: Chip IO +power supply PVDD: Chip main power input AVDD: Chip audio -1. If there are hardware modifications, it may cause significant deviations in test results -2. Mismatch between power supply voltage and required voltage will also cause significant deviations in test results (using 5V power supply) +1. Hardware modifications may result in significant deviations in test results. +2. Mismatched supply voltage (test conducted with 5V supply) may also lead to +significant deviations. -* Troubleshooting steps: The original 5V power supply can be unplugged, and the jumper caps of UDDIO, PVDD, and AVDD can be removed. The above three paths can be powered individually using the power consumption testing tool, and the remaining two paths can be powered through external VCC. This allows for single-path power consumption testing to identify which power path has abnormalities (note that VCC_3V3 needs to be powered separately as it powers the screen alone). \ No newline at end of file +* If there are hardware modifications, it may cause significant deviations in + test results diff --git a/example/pm/ble/README_EN.md b/example/pm/ble/README_EN.md index d4f19c581..0ede4530f 100644 --- a/example/pm/ble/README_EN.md +++ b/example/pm/ble/README_EN.md @@ -1,35 +1,54 @@ # BLE Broadcast and Connection Power Consumption Test +Source code path: example/pm/ble ## Introduction: -BLE broadcast and connection scenario power consumption test routine (LCPU main frequency at 24MHz). -The wake-up PIN varies on different development boards, with the following corresponding relationships: -- EH-LB551: Uses PA80, corresponding to the INT pin on the external Bluetooth or GPS interface on the HDK board +BLE broadcast and connection scenario power consumption test routine (LCPU main +frequency at 24MHz). The wake-up PIN varies on different development boards, +with the following corresponding relationships: +- EH-LB551: Uses PA80, corresponding to the INT pin on the external Bluetooth or + GPS interface on the HDK board - EH-LB555: Uses PA79, corresponding to TP_INT on the bottom HDK board -When the wake-up PIN is at low level, both HCPU and LCPU cannot enter low power mode. -At this time, commands can be sent to LCPU through Console to modify parameters. When the wake-up PIN is connected to high level (i.e., 1.8V voltage), -HCPU enters low power mode, while LCPU periodically enters and exits low power mode. At this time, Console cannot be used. -After connecting PC and HDK with USB Type-C cable, two serial ports will be enumerated. HCPU uses the second serial port as Console port, and LCPU uses the first serial port as Console port. +When the wake-up PIN is at low level, both HCPU and LCPU cannot enter low power +mode. At this time, commands can be sent to LCPU through Console to modify +parameters. When the wake-up PIN is connected to high level (i.e., 1.8V +voltage), HCPU enters low power mode, while LCPU periodically enters and exits +low power mode. At this time, Console cannot be used. After connecting PC and +HDK with USB Type-C cable, two serial ports will be enumerated. HCPU uses the +second serial port as Console port, and LCPU uses the first serial port as +Console port. ## Related Console Commands - HCPU - 1. Factory reset BLE-related Flash data: nvds reset_all 1 - - To avoid Flash conflicts, it is best to execute this command first when using for the first time. - 2. Set Bluetooth MAC address: `nvds update addr 6 [addr]`. Example: `nvds update addr 6 2345670123C3` + 1. Factory reset BLE-related Flash data: nvds reset_all 1 - To avoid Flash + conflicts, it is best to execute this command first when using for the + first time. + 2. Set Bluetooth MAC address: `nvds update addr 6 [addr]`. Example: `nvds + update addr 6 2345670123C3` - LCPU - - `ble_config adv interval_in_ms`: Modify broadcast period, where `interval_in_ms` is the broadcast interval in milliseconds - - `ble_config conn interval_in_ms`: Modify connection period, where `interval_in_ms` is the connection interval in milliseconds, - command needs to be sent after connecting with phone + - `ble_config adv interval_in_ms`: Modify broadcast period, where + `interval_in_ms` is the broadcast interval in milliseconds + - `ble_config conn interval_in_ms`: Modify connection period, where + `interval_in_ms` is the connection interval in milliseconds, command needs + to be sent after connecting with phone ## Mobile Phone Recommendations: -1. For iPhone, third-party software LightBlue is recommended; for Android, use nRF Connect for BLE testing. +1. For iPhone, third-party software LightBlue is recommended; for Android, use + nRF Connect for BLE testing. ## Project Description - Supported development boards include - eh-lb551 - eh-lb555 -- Compilation method: Enter the hcpu directory and execute the command `scons --board= -j8`, where board_name is the board name. For example, to compile eh-lb551 board, the complete command is `scons --board=eh-lb551 -j8` - The compiled image files are stored in the build_ directory of HCPU. For project usage, refer to <> +- Compilation method: Enter the hcpu directory and execute the command `scons + --board= -j8`, where board_name is the board name. For example, to + compile eh-lb551 board, the complete command is `scons --board=eh-lb551 -j8` + The compiled image files are stored in the build_ directory of + HCPU. For project usage, refer to <{1}> -- LCPU main frequency is 24MHz. You can modify the 'board/bf0_ap_hal_msp.c' file in the LCPU project directory and remove the statement 'HAL_RCC_LCPU_SetDiv(2, 0, 3)' in function HAL_MspInit, - this way it will maintain the 48MHz frequency set by HAL_PreInit. -- 32K crystal default configuration: EH-LB551 does not use it, EH-LB555 uses it. Related configuration modification method: menuconfig -->select board peripherals -->Low power crystal disabled \ No newline at end of file +- LCPU main frequency is 24MHz. You can modify the 'board/bf0_ap_hal_msp.c' file + in the LCPU project directory and remove the statement 'HAL_RCC_LCPU_SetDiv(2, + 0, 3)' in function HAL_MspInit, this way it will maintain the 48MHz frequency + set by HAL_PreInit. +- 32K crystal default configuration: EH-LB551 does not use it, EH-LB555 uses it. + Related configuration modification method: menuconfig -->select board + peripherals -->Low power crystal disabled diff --git a/example/pm/bt/README_EN.md b/example/pm/bt/README_EN.md index 9c9b38785..a6feb6c2e 100644 --- a/example/pm/bt/README_EN.md +++ b/example/pm/bt/README_EN.md @@ -1,33 +1,46 @@ # BLE/BT Power Consumption Test +Source Path: example/pm/bt ## Introduction: -BLE/BT power consumption test routine (LCPU main frequency at 24MHz). BLE can test broadcast and connection mode power consumption, BT can test Scan and Sniff mode power consumption. -The wake-up PIN varies on different development boards, with the following corresponding relationships: - - EC-LB58X: Uses PA64 - - EH-LB561/EH-LB563: Uses PB34, corresponding to HR_INT on HDK - - EH-ss6500/EH-LB523/EH-LB520: Uses PA24, corresponding to GPS_PEN on HDK +BLE/BT power consumption test routine (LCPU main frequency at 24MHz). BLE can +test broadcast and connection mode power consumption, BT can test Scan and Sniff +mode power consumption. The wake-up PIN varies on different development boards, +with the following corresponding relationships: - EC-LB58X: Uses PA64 - +EH-LB561/EH-LB563: Uses PB34, corresponding to HR_INT on HDK - +EH-ss6500/EH-LB523/EH-LB520: Uses PA24, corresponding to GPS_PEN on HDK -When the wake-up PIN is at low level, both HCPU and LCPU cannot enter low power mode. -At this time, commands can be sent through HCPU Console to modify parameters. -When the wake-up PIN is connected to high level, HCPU can enter low power mode, while LCPU periodically enters and exits low power mode. At this time, Console cannot be used. -HCPU uses UART1 as Console port, LCPU uses UART4 as Console port. +When the wake-up PIN is at low level, both HCPU and LCPU cannot enter low power +mode. At this time, commands can be sent through HCPU Console to modify +parameters. When the wake-up PIN is connected to high level, HCPU can enter low +power mode, while LCPU periodically enters and exits low power mode. At this +time, Console cannot be used. HCPU uses UART1 as Console port, LCPU uses UART4 +as Console port. ## Related Console Commands - HCPU 1. Factory reset BLE-related Flash data: `nvds reset_all 1` - - To avoid Flash conflicts, it is best to execute this command first when using for the first time. - 2. Set Bluetooth MAC address: nvds update addr 6 [addr]. Example: nvds update addr 6 2345670123C3 - 3. 'ble_config adv interval_in_ms': Modify broadcast period, where 'interval_in_ms' is the broadcast interval in milliseconds - 4. 'ble_config conn interval_in_ms': Modify connection period, where 'interval_in_ms' is the connection interval in milliseconds, - command needs to be sent after connecting with phone - 5. 'btskey': BTS menu control command, can modify BT parameters. After startup, it defaults to BTS main menu. BTS menu is a multi-level menu. You can send 'btskey s' command to display current menu content, - then send commands according to menu prompts to enter next level menu or execute certain menu functions. For example, in the main menu, sending the following three commands in sequence can turn on Page Scan and turn off Inquiry Scan + - To avoid Flash conflicts, it is best to execute this command first + when using for the first time. + 2. Set Bluetooth MAC address: nvds update addr 6 [addr]. Example: nvds + update addr 6 2345670123C3 + 3. 'ble_config adv interval_in_ms': Modify broadcast period, where + 'interval_in_ms' is the broadcast interval in milliseconds + 4. 'ble_config conn interval_in_ms': Modify connection period, where + 'interval_in_ms' is the connection interval in milliseconds, command + needs to be sent after connecting with phone + 5. 'btskey': BTS menu control command, can modify BT parameters. After + startup, it defaults to BTS main menu. BTS menu is a multi-level menu. + You can send 'btskey s' command to display current menu content, then + send commands according to menu prompts to enter next level menu or + execute certain menu functions. For example, in the main menu, sending + the following three commands in sequence can turn on Page Scan and turn + off Inquiry Scan 1) btskey 1 2) btskey 7 3) btskey 2 Main menu is shown below ``` - ###################################################### +###################################################### ## ## ## BTS2 Demo Main Menu ## ## 1. Generic Command ## @@ -42,10 +55,10 @@ Main menu is shown below ## ## ###################################################### ``` - -After sending 'btskey 1', the Generic Command Menu submenu is displayed + +After sending 'btskey 1', the Generic Command Menu submenu is displayed ``` - ###################################################### +###################################################### ## ## ## Generic Command Menu ## ## 1. Inquiry start ## @@ -65,16 +78,27 @@ After sending 'btskey 1', the Generic Command Menu submenu is displayed ``` ## Mobile Phone Recommendations: -1. For iPhone, third-party software LightBlue is recommended; for Android, use nRF Connect for BLE testing. +1. For iPhone, third-party software LightBlue is recommended; for Android, use + nRF Connect for BLE testing. ## Project Description -- Supported development boards include +- Supported development boards: - ec-lb583 - ec-lb587 - eh-lb561 - eh-lb563 - eh-lb523 -- Compilation method: Enter the hcpu directory and execute the command `scons --board= -j8`, where board_name is the board name. For example, to compile eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8` - The compiled image files are stored in the build_ directory of HCPU. For project usage, refer to <> -For development boards using NAND, such as ec-lb583, ec-lb587 and eh-lb563, when using the development board for the first time, you also need to execute download_fs.bat in the HCPU project development board directory to flash the file system image to Flash, otherwise it will prompt file system mount failure after startup. -The file system image only needs to be flashed once. If the file system is re-flashed, the Bluetooth address will also be lost and needs to be reconfigured. \ No newline at end of file +- Compilation Method: Navigate to the `hcpu` directory and execute the command + `scons --board= -j8`. Replace `` with the name of the + target board. For example, to compile for the `eh-lb561` board, the full + command is `scons --board=eh-lb561 -j8`. The generated image files are stored + in the `build_` directory within `HCPU`. For further details on + usage, refer to the "General Project Build Methodology" guide. For development + boards utilizing NAND Flash (such as `ec-lb583`, `ec-lb587`, and `eh-lb563`), + the first-time setup requires executing the `download_fs.bat` script located + in the board-specific directory under the `HCPU` project to flash the + filesystem image. Failure to do so will result in a filesystem mount error + upon boot. The filesystem image only needs to be flashed once; however, + reflashing the filesystem will erase the Bluetooth address, necessitating + reconfiguration. + diff --git a/example/pm/coremark/README_EN.md b/example/pm/coremark/README_EN.md index c5d639218..d37ab00c4 100644 --- a/example/pm/coremark/README_EN.md +++ b/example/pm/coremark/README_EN.md @@ -1,35 +1,53 @@ # Processor Power Consumption Test +Source Path: example/pm/coremark ## Introduction: Processor power consumption test routine, including the following scenarios: - One core executes CoreMark benchmark program -- One core executes while loop for a period of time, executing nop instructions in the loop +- One core executes while loop for a period of time, executing nop instructions + in the loop - System shutdown, can be woken up by RTC timer -- System shutdown, woken up by button press -The wake-up PIN varies on different development boards, corresponding relationships are as follows: -- EH-LB551: Uses PA80, corresponding to the INT pin on the external Bluetooth or GPS interface on the HDK board +- System shutdown, woken up by button press The wake-up PIN varies on different + development boards, corresponding relationships are as follows: +- EH-LB551: Uses PA80, corresponding to the INT pin on the external Bluetooth or + GPS interface on the HDK board - EH-LB555: Uses PA79, corresponding to TP_INT on the bottom HDK board - EC-LB58X: Uses PA64 - EH-LB561/EH-LB563: Uses PB34, corresponding to HR_INT on the HDK board -- EH-ss6500/EH-LB52x: Uses PA24, corresponding to GPS_PEN on the HDK -When the wake-up PIN is at low level, HCPU cannot enter low power mode. -At this time, commands can be sent to HCPU through console to execute specified tasks. When the wake-up PIN is connected to high level (i.e., 1.8V voltage), HCPU enters low power mode, and at this time HCPU cannot respond to console commands. -LCPU never enters low power mode. If LCPU is started, when not executing tasks, LCPU is in WFI state and can respond to commands from console. -When LCPU is not started, LCPU is considered to be in halt state and cannot process console commands. +- EH-ss6500/EH-LB52x: Uses PA24, corresponding to GPS_PEN on the HDK When the + wake-up PIN is at low level, HCPU cannot enter low power mode. At this time, + commands can be sent to HCPU through console to execute specified tasks. When + the wake-up PIN is connected to high level (i.e., 1.8V voltage), HCPU enters + low power mode, and at this time HCPU cannot respond to console commands. LCPU + never enters low power mode. If LCPU is started, when not executing tasks, + LCPU is in WFI state and can respond to commands from console. When LCPU is + not started, LCPU is considered to be in halt state and cannot process console + commands. -PC and the baseboard are connected using USB Type-C cable, which will enumerate two serial ports. HCPU uses UART1 as Console port, LCPU uses UART4 as Console port. +PC and the baseboard are connected using USB Type-C cable, which will enumerate +two serial ports. HCPU uses UART1 as Console port, LCPU uses UART4 as Console +port. ## Related Console Commands - Both HCPU and LCPU support - - 'run_coremark freq_in_mhz': Modify main frequency and execute CoreMark, 'freq_in_mhz' is the frequency in MHz, for example 'run_coremark 48', execute CoreMark at 48MHz main frequency - - 'run_while_loop freq_in_mhz': Modify main frequency and execute while loop for a period of time, 'freq_in_mhz' is the frequency in MHz, `run_while_loop 48`, execute while loop at 48MHz main frequency + - 'run_coremark freq_in_mhz': Modify main frequency and execute CoreMark, + 'freq_in_mhz' is the frequency in MHz, for example 'run_coremark 48', + execute CoreMark at 48MHz main frequency + - 'run_while_loop freq_in_mhz': Modify main frequency and execute while loop + for a period of time, 'freq_in_mhz' is the frequency in MHz, + `run_while_loop 48`, execute while loop at 48MHz main frequency - HCPU supported main frequencies: 240MHz/192MHz/144MHz/96MHz - LCPU supported main frequencies: 48MHz/24MHz - HCPU supports - - 'lcpu on': Start LCPU, after successful startup, LCPU can receive console commands to execute specified tasks - - 'shutdown [wakeup_time_in_sec]': Shutdown, 'wakeup_time_in_sec' is an optional parameter in seconds, indicating how long after shutdown to automatically power on. If no parameter is provided, after shutdown it can only be woken up by PIN. - On 551 and 555 platforms, PIN is KEY1 button, press to power on. - On 557 platform, PIN corresponds to SPI3_INT pin next to J0804, this pin needs to be connected to high level before shutdown, and connecting to low level after shutdown will trigger power on. - On 58X platform, PIN corresponds to KEY_HOME_RST button, press to power on. + - 'lcpu on': Start LCPU, after successful startup, LCPU can receive console + commands to execute specified tasks + - 'shutdown [wakeup_time_in_sec]': Shutdown, 'wakeup_time_in_sec' is an + optional parameter in seconds, indicating how long after shutdown to + automatically power on. If no parameter is provided, after shutdown it can + only be woken up by PIN. On 551 and 555 platforms, PIN is KEY1 button, + press to power on. On 557 platform, PIN corresponds to SPI3_INT pin next + to J0804, this pin needs to be connected to high level before shutdown, + and connecting to low level after shutdown will trigger power on. On 58X + platform, PIN corresponds to KEY_HOME_RST button, press to power on. ## Project Description - Development boards supported by the project: @@ -40,5 +58,8 @@ PC and the baseboard are connected using USB Type-C cable, which will enumerate - eh-lb561 - eh-lb563 - eh-lb523 -- Compilation method: Enter hcpu directory and execute command `scons --board= -j8`, where board_name is the board name. For example, to compile eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8`. -The compiled image file is stored in HCPU's build_ directory. For project usage, refer to <> \ No newline at end of file +- Compilation method: Enter hcpu directory and execute command `scons + --board= -j8`, where board_name is the board name. For example, to + compile eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8`. + The compiled image file is stored in HCPU's build_ directory. For + project usage, refer to <{1}> diff --git a/example/pm/gui_pm/README_EN.md b/example/pm/gui_pm/README_EN.md index bb5a8ee09..fa12381b0 100644 --- a/example/pm/gui_pm/README_EN.md +++ b/example/pm/gui_pm/README_EN.md @@ -4,36 +4,58 @@ Source code path: example/pm/gui_pm ## Supported Platforms This example runs on the following development board: -- sf32lb52-lchspi-ulp +* sf32lb52-lchspi-ulp ## Background -- After enabling the low-power related macro switches, the host core (HCPU) may fail to enter sleep for a long time. -- A typical scenario occurs when the application keeps refreshing the screen; the LCD refresh thread remains active and breaks the sleep conditions. +- After enabling the low-power related macro switches, the host core (HCPU) may + fail to enter sleep for a long time. +- A typical scenario occurs when the application keeps refreshing the screen; + the LCD refresh thread remains active and breaks the sleep conditions. You can diagnose whether the application currently meets the sleep conditions: -1. No explicit sleep inhibition: There is no logic/flag actively preventing sleep, such as calling `rt_pm_request(PM_SLEEP_MODE_IDLE);`. You can run the `pm_dump` command in the console. If the "Idle Mode Counter" is greater than 0, some module has called `rt_pm_request(PM_SLEEP_MODE_IDLE)` to forbid sleep. If it is 0, sleep is not forbidden. -![alt text](assets/sleep.png) +1. No explicit sleep inhibition: There is no logic/flag actively preventing + sleep, such as calling `rt_pm_request(PM_SLEEP_MODE_IDLE);`. You can run the + `pm_dump` command in the console. If the "Idle Mode Counter" is greater than + 0, some module has called `rt_pm_request(PM_SLEEP_MODE_IDLE)` to forbid + sleep. If it is 0, sleep is not forbidden. ![alt text](assets/sleep.png) -2. OS timeout threshold is satisfied: The remaining time of the soonest-expiring OS timer is greater than the threshold (100 ms by default). -3. No wake-up source is triggered: All configured wake-up sources remain inactive (e.g., key presses, sensor interrupts). -4. The message queue to the LCPU is empty: Data sent by HCPU has been read by the LCPU. +2. OS timeout threshold is satisfied: The remaining time of the soonest-expiring + OS timer is greater than the threshold (100 ms by default). +3. No wake-up source is triggered: All configured wake-up sources remain + inactive (e.g., key presses, sensor interrupts). +4. The message queue to the LCPU is empty: Data sent by HCPU has been read by + the LCPU. -If any of the above is not satisfied, the system will stay active and cannot enter sleep. +If any of the above is not satisfied, the system will stay active and cannot +enter sleep. ## Example Overview -This example is based on the `gui_app_pm` interfaces. When the GUI thread is idle, it proactively yields resources and turns off the display backlight to meet the sleep conditions, achieving the following goals: -- When long inactivity is detected on the display layer, call `gui_pm_fsm(GUI_PM_ACTION_SLEEP)` to trigger the GUI sleep flow. -- In the sleep path, call `gui_suspend()` and `gui_sleep()` to block the current thread so the frequently refreshing display thread is suspended, thereby removing the sleep blocker, and turn off the display output to reduce power. -- When a wake-up source (button) is triggered, `gui_pm_fsm(GUI_PM_ACTION_WAKEUP)` lights the screen again and resumes logic. +This example is based on the `gui_app_pm` interfaces. When the GUI thread is +idle, it proactively yields resources and turns off the display backlight to +meet the sleep conditions, achieving the following goals: +- When long inactivity is detected on the display layer, call + `gui_pm_fsm(GUI_PM_ACTION_SLEEP)` to trigger the GUI sleep flow. + +- In the sleep path, call `gui_suspend()` and `gui_sleep()` to block the current + thread so the frequently refreshing display thread is suspended, thereby + removing the sleep blocker, and turn off the display output to reduce power. + +- When a wake-up source (button) is triggered, + `gui_pm_fsm(GUI_PM_ACTION_WAKEUP)` lights the screen again and resumes logic. ## Key Code -- `lcd_display_task()`: Periodically checks LVGL inactivity time; if it exceeds 5 s, enter the GUI sleep logic. After waking, trigger a redraw to restore the display. -- `gui_suspend()`: After long inactivity, calling `gui_pm_fsm(GUI_PM_ACTION_SLEEP)` changes the state from `GUI_STATE_ACTIVE` to `GUI_STATE_INACTIVE_PENDING` and emits a `GUI_PM_EVT_SUSPEND` event. On the next loop, when `gui_is_force_close()` returns true, the display thread calls `gui_suspend()` to perform the actual suspend. -- `gui_is_force_close()`: Determines whether the GUI needs to be forcibly closed. It checks whether the current state is `GUI_STATE_INACTIVE_PENDING`, which depends on whether `gui_pm_fsm(GUI_PM_ACTION_SLEEP)` has been executed. -- `button_event_handler()`: Button wake-up handler. Calls `gui_pm_fsm(GUI_PM_ACTION_WAKEUP)`; if the current state is `GUI_STATE_INACTIVE` or `GUI_STATE_INACTIVE_PENDING`, it transitions to `GUI_STATE_ACTIVE` and emits `GUI_PM_EVT_RESUME` to resume suspended threads and re-enable the LCD display. +- `lcd_display_task()`: Periodically checks LVGL inactivity time; if it exceeds + 5 s, enter the GUI sleep logic. After waking, trigger a redraw to restore the + display. +- `gui_suspend()`: After long inactivity, calling + `gui_pm_fsm(GUI_PM_ACTION_SLEEP)` changes the state from `GUI_STATE_ACTIVE` to + `GUI_STATE_INACTIVE_PENDING` and emits a `GUI_PM_EVT_SUSPEND` event. On the + next loop, when `gui_is_force_close()` returns true, the display thread calls + `gui_suspend()` to perform the actual suspend. -> Note: The core logic resides in `lcd_display_task`. To reuse the sleep logic from this example, focus on the code blocks in `src/main.c` guarded by `#ifdef GUI_APP_PM`. -The core flow is as follows: +> Note: The core logic resides in `lcd_display_task`. To reuse the sleep logic +> from this example, focus on the code blocks in `src/main.c` guarded by `#ifdef +> GUI_APP_PM`. The core flow is as follows: ```c if (lv_display_get_inactive_time(NULL) > 5000) { @@ -50,29 +72,28 @@ if (gui_is_force_close()) ## Build and Flash ### Build using the sf32lb52-lchspi-ulp_hcpu project as an example -On the 52 platform, Deep Sleep is configured as the default sleep mode. -* Build: - Switch to the example project directory and run scons to build: +On the 52 platform, Deep Sleep is configured as the default sleep mode.
+* Build: Switch to the example project directory and run scons to build: > scons --board=sf32lb52-lchspi-ulp -j8 * Flash: - 1. Switch to the example's `project/build_xx` directory and run `uart_download.bat`. Follow the prompts to select the serial port to download. - 2. Or, from the project directory, run: build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat - + 1. Switch to the example's `project/build_xx` directory and run + `uart_download.bat`. Follow the prompts to select the serial port to + download. + 2. Or, from the project directory, run: + build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat + ```c - build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat +build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat - Uart Download +UART Download - please input the serial port num:5 +Please enter the serial port number: 5 ``` ## Example Output ![alt text](assets/log.png) -* Board status during runtime -![alt text](assets/open.png) -* Board status in sleep -![alt text](assets/off.png) -* Power consumption in sleep -![alt text](assets/sju.png) +* Board status during runtime ![alt text](assets/open.png) +* Board status in sleep ![alt text](assets/off.png) +* Power consumption in sleep ![alt text](assets/sju.png) diff --git a/example/pm/index_EN.md b/example/pm/index_EN.md index a2664336d..ef1a3e352 100644 --- a/example/pm/index_EN.md +++ b/example/pm/index_EN.md @@ -5,4 +5,4 @@ :glob: */* -``` \ No newline at end of file +``` diff --git a/example/pm/jdi/README_EN.md b/example/pm/jdi/README_EN.md index d3c344cc7..170d3e029 100644 --- a/example/pm/jdi/README_EN.md +++ b/example/pm/jdi/README_EN.md @@ -7,55 +7,60 @@ This example can run on the following development boards: - sf32lb52-core_n16r16 ## Overview -After powering on, the screen refreshes for 5 seconds and then enters sleep mode. It can be awakened by pressing Key1. After awakening, the JDI screen refreshes for another 5 seconds. Additionally, a timed wake-up is set to occur every 1 minute to refresh the screen once before entering sleep mode again. This tests power consumption in both sleep and awake states. +After powering on, the screen refreshes for 5 seconds and then enters sleep +mode. It can be awakened by pressing Key1. After awakening, the JDI screen +refreshes for another 5 seconds. Additionally, a timed wake-up is set to occur +every 1 minute to refresh the screen once before entering sleep mode again. This +tests power consumption in both sleep and awake states. * Data Summary (using 200mAh battery capacity as an example) -| |Screen-on during Wake-up |Screen-off Sleep |Daily Consumption |Usable Days | -|:--- |:--- |:--- |:--- |:--- | -|100 times/day|0.64mAh |1.34mAh |1.98mAh |101 days | -|300 times/day|1.93mAh |1.32mAh |3.25mAh |61.5 days | -|500 times/day|3.22mAh |1.31mAh |4.53mAh |44.1 days | -|**Average Current in Two Modes**|**Sleep Power Consumption:** 56uA |**Wake-up Power Consumption:** 4.64mA | | | +| | Screen-on during Wake-up | Screen-off Sleep | Daily Consumption | Usable Days | +| -------------------------------- | --------------------------------- | ------------------------------------- | ----------------- | ----------- | +| 100 times/day | 0.64 mAh | 1.34 mAh | 1.98 mAh | 101 days | +| 300 times/day | 1.93 mAh | 1.32 mAh | 3.25 mAh | 61.5 days | +| 500 times/day | 3.22 mAh | 1.31 mAh | 4.53 mAh | 44.1 days | +| **Average Current in Two Modes** | **Sleep Power Consumption:** 56uA | **Wake-up Power Consumption:** 4.64mA | | | ## Hardware Connections -During low power consumption testing, the board is no longer powered via USB but requires 5V power supply to the board's VCC_5V through a power consumption detection tool. Therefore, the following operations need to be performed for power consumption testing. +During low power consumption testing, the board is no longer powered via USB but +requires 5V power supply to the board's VCC_5V through a power consumption +detection tool. Therefore, the following operations need to be performed for +power consumption testing. ### JDI Screen Pin Connection Configuration -| Pin | JDI Screen Adapter Board Pin | Adapter Board Physical Pin | -|:--- |:--- |:--- | -| PA2 | B2 | 8 | -| PA3 | B1 | 1 | -| PA4 | G1 | 18 | -| PA5 | R1 | 17 | -| PA6 | HST | 16 | -| PA7 | ENB | 14 | -| PA8 | VST | 5 | -| PA39 | VCK | 4 | -| PA40 | XRST | 2 | -| PA41 | HCK | 3 | -| PA42 | R2 | 12 | -| PA43 | G2 | 6 | -| PA24 | FRP | 15 | -| PA25 | XERP | 13 | -| PA24 | VCOM | 7 | - -Note: Physical pin 25 of the JDI screen adapter board needs to be connected to the development board's 3V3 to power the screen. - -* Original power supply situation of the development board -![alt text](assets/core_board.png) - -* Remove all jumper caps except ADDIO, PVDD, AVDD -![alt text](assets/remove_jumper_cap.png) - -* Connect the power consumption test tool's VOUT to the board's VCC_5V, and connect GND to the PPK's GND pin -![alt text](assets/PPK_connect.png) - -* For convenient log viewing, connect the serial adapter board as shown -![alt text](assets/uart_connect.png) - -* Final connections -![alt text](assets/final_connect.png) +| Pin | JDI Screen Adapter Board Pin | Adapter Board Physical Pin | +| ---- | ---------------------------- | -------------------------- | +| PA2 | B2 | 8 | +| PA3 | B1 | 1 | +| PA4 | G1 | 18 | +| PA5 | R1 | 17 | +| PA6 | HST | 16 | +| PA7 | ENB | 14 | +| PA8 | VST | 5 | +| PA39 | VCK | 4 | +| PA40 | XRST | 2 | +| PA41 | HCK | 3 | +| PA42 | R2 | 12 | +| PA43 | G2 | 6 | +| PA24 | FRP | 15 | +| PA25 | XERP | 13 | +| PA24 | VCOM | 7 | +Note: Physical pin 25 of the JDI screen adapter board needs to be connected to +the development board's 3V3 to power the screen. +* Original power supply situation of the development board ![alt + text](assets/core_board.png) + +* Remove all jumper caps except ADDIO, PVDD, AVDD ![alt + text](assets/remove_jumper_cap.png) + +* Connect the power consumption test tool's VOUT to the board's VCC_5V, and + connect GND to the PPK's GND pin ![alt text](assets/PPK_connect.png) + +* For convenient log viewing, connect the serial adapter board as shown ![alt + text](assets/uart_connect.png) + +* Final connections ![alt text](assets/final_connect.png) ## Menuconfig Configuration * The required configurations are enabled by default @@ -63,22 +68,23 @@ Note: Physical pin 25 of the JDI screen adapter board needs to be connected to t ```c menuconfig --board=board_name ``` - 1. Enable low power mode -- Path: Sifli middleware +- Path: Sifli middleware - Enable: Enable low power support - Macro switch: `CONFIG_BSP_USING_PM` - Function: Enable low power -2. Enable logging for low power related information (disabled by default to reduce power consumption; can be enabled in menuconfig for debugging verification) +2. Enable logging for low power related information (disabled by default to + reduce power consumption; can be enabled in menuconfig for debugging + verification) - Path: SiFli Middleware → Enable Low Power Support - Enable: Enable PM Debug - Macro switch: `CONFIG_BSP_PM_DEBUG` - Function: Output low power related logs ### Compilation and Flashing -The 52 platform defaults to Deep Sleep mode for hibernation
-Switch to the project directory of the example and run the scons command to compile: +The 52 platform defaults to Deep Sleep mode for hibernation
Switch to the +project directory of the example and run the scons command to compile: ``` scons --board=sf32lb52-core_n16r16 -j8 ``` @@ -86,43 +92,43 @@ Flashing: ``` build_sf32lb52-core_n16r16_hcpu\uart_download.bat - Uart Download + UART Download -please input the serial port num:19 +Please input the serial port number: 19 ``` - ## Example Output Results + ### Log Printout ``` 09-26 14:19:38:801 SFBL -09-26 14:19:40:858 Serial:c2,Chip:4,Package:6,Rev:f Reason:00000000 -09-26 14:19:40:863 Serial PowerOnMOde:0 rtc_record:00000000 +09-26 14:19:40:858 Serial:c2, Chip:4, Package:6, Rev:f Reason:00000000 +09-26 14:19:40:863 Serial PowerOnMode:0 rtc_record:00000000 09-26 14:19:40:863 \ | / 09-26 14:19:40:865 - SiFli Corporation -09-26 14:19:40:866 / | \ build on Sep 24 2025, 2.4.0 build 81bf05a9 +09-26 14:19:40:866 / | \ Build on Sep 24 2025, 2.4.0 build 81bf05a9 09-26 14:19:40:868 2020 - 2022 Copyright by SiFli team -09-26 14:19:40:870 mount /dev sucess +09-26 14:19:40:870 Mount /dev success 09-26 14:19:40:873 [2484] I/drv.rtc main: PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 09-26 14:19:40:874 [2518] I/drv.rtc main: RTC use LXT RTC_CR=00000001 09-26 14:19:40:875 [2540] I/drv.rtc main: Init RTC, wake = 0 09-26 14:19:40:877 [2731] I/drv.audprc main: init 00 ADC_PATH_CFG0 0x606 09-26 14:19:40:878 [2754] I/drv.audprc main: HAL_AUDPRC_Init res 0 09-26 14:19:40:881 [2778] I/drv.audcodec main: HAL_AUDCODEC_Init res 0 -09-26 14:19:40:885 call par CFG1(3313) +09-26 14:19:40:885 Call par CFG1(3313) 09-26 14:19:40:889 fc 9, xtal 2000, pll 2094 -09-26 14:19:40:892 call par CFG1(3313) +09-26 14:19:40:892 Call par CFG1(3313) 09-26 14:19:40:893 fc 7, xtal 2000, pll 1678 -09-26 14:19:40:895 [3028] I/drv.lcd main: [NONE] -> [OPENING] +09-26 14:19:40:895 [3028] I/drv.lcd main: [NONE] -> [OPENING] 09-26 14:19:40:896 [3055] I/drv.lcd lcd_task: open 09-26 14:19:40:898 [3070] I/drv.epic lcd_task: drv_gpu opened. 09-26 14:19:40:899 [3089] I/drv.lcd lcd_task: HW open 09-26 14:19:40:904 [3128] I/drv.lcd lcd_task: Try registered LCD driver... 09-26 14:19:40:906 [3163] I/drv.lcd lcd_task: Found lcd jdi387a id:1d1h 09-26 14:19:40:912 [3189] I/drv.lcd lcd_task: HW open done. -09-26 14:19:40:913 [3206] I/drv.lcd lcd_task: [OPENING] -> [INITIALIZED] +09-26 14:19:40:913 [3206] I/drv.lcd lcd_task: [OPENING] -> [INITIALIZED] 09-26 14:19:40:914 [3228] I/drv.lcd lcd_task: open done. -09-26 14:19:40:927 msh /> +09-26 14:19:40:927 msh /> 09-26 14:19:40:941 [4959] I/drv.lcd lcd_task: Auto turn on display. 09-26 14:19:40:942 [4981] I/drv.lcd lcd_task: set brightness 50 09-26 14:19:40:943 [5001] I/drv.lcd lcd_task: display on @@ -130,7 +136,7 @@ please input the serial port num:19 09-26 14:19:40:948 [5055] I/drv.pwm lcd_task: 1 Psc 7a1200, Period 16000000, Pulse 8000000 09-26 14:19:40:950 [5086] I/drv.pwm lcd_task: 2 Psc 0, Period 524, Pulse 262 09-26 14:19:40:952 [5108] I/drv.pwm lcd_task: 3 Psc 0, Period 524, Pulse 262 -09-26 14:19:40:953 [5135] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] +09-26 14:19:40:953 [5135] I/drv.lcd lcd_task: [INITIALIZED] -> [ON] 09-26 14:19:40:954 The screen is updated at tick 85. 09-26 14:19:42:000 The screen is updated at tick 1136. 09-26 14:19:43:055 The screen is updated at tick 2188. @@ -138,7 +144,7 @@ please input the serial port num:19 09-26 14:19:45:161 The screen is updated at tick 4291. 09-26 14:19:46:162 The display period has ended, entering sleep mode... 09-26 14:19:46:164 [176105] I/drv.lcd lcd_task: idle mode on=1 -09-26 14:19:46:168 [176126] I/drv.lcd lcd_task: [ON] -> [IDLEMODE] +09-26 14:19:46:168 [176126] I/drv.lcd lcd_task: [ON] -> [IDLEMODE] 09-26 14:19:46:169 The LCD is turned off, entering sleep mode... 09-26 14:19:46:170 [pm]S:3,176182 09-26 14:19:48:754 [pm]W:260994 @@ -156,48 +162,49 @@ please input the serial port num:19 ``` ## Power Consumption Test Results -* We take a 200mAh battery capacity as an example to test in the above two modes and estimate the device usage time. -* Classify into three scenarios: light usage, moderate usage, and heavy usage, corresponding to 100, 300, and 500 wake-ups respectively, with each wake-up executing 5 seconds of screen refresh operation. +* We take a 200mAh battery capacity as an example to test in the above two modes + and estimate the device usage time. +* Classify into three scenarios: light usage, moderate usage, and heavy usage, + corresponding to 100, 300, and 500 wake-ups respectively, with each wake-up + executing 5 seconds of screen refresh operation. ### Wake-up Power Consumption -* The average current when waking up via key press and refreshing the screen for 5s is: 4.64mA -![alt text](assets/wakeup.png) +* The average current when waking up via key press and refreshing the screen for + 5s is: 4.64mA ![alt text](assets/wakeup.png) * Power consumption used in one day - 100 times: 4.64 * 100 * 5 / 3600 = 0.64 (mAh) - - 300 times: 4.64 * 300 * 5 / 3600 = 1.93 (mAh) + - 300 times: 4.64 * 300 * 5 / 3600 = 1.93 (mAh) - 500 times: 4.64 * 500 * 5 / 3600 = 3.22 (mAh) ### Sleep Power Consumption * The average current in sleep mode is: 56uA -* Current breakdown - - Chip module power consumption: around 50uA - - Screen power consumption: around 7uA (VCOM, FRP need to output a 60Hz waveform) -![alt text](assets/enter_sleep.png) +* Current breakdown - Chip module power consumption: around 50uA - Screen power + consumption: around 7uA (VCOM, FRP need to output a 60Hz waveform) ![alt + text](assets/enter_sleep.png) -* Power consumption needed for one hour of sleep - 56 / 1000 * 1 = 0.056 (mAh) +* Power consumption needed for one hour of sleep 56 / 1000 * 1 = 0.056 (mAh) * Total daily consumption calculation as follows: - - 100 times: 0.056 * (24 * 3600 - 100 * 5) / 3600 + 0.64 = 1.98 (mAh) + - 100 times: 0.056 * (24 * 3600 - 100 * 5) / 3600 + 0.64 = 1.98 (mAh) - 300 times: 0.056 * (24 * 3600 - 300 * 5) / 3600 + 1.93 = 3.25 (mAh) - 500 times: 0.056 * (24 * 3600 - 500 * 5) / 3600 + 3.22 = 4.53 (mAh) -3. Data Summary -| |Screen On When Waking Up|Screen Off During Sleep|Daily Consumption|Usable Days| -|:--- |:--- |:--- |:--- |:--- | -|100 times/day|0.64mAh|1.34mAh|1.98mAh|101 days| -|300 times/day|1.93mAh|1.32mAh|3.25mAh|61.5 days| -|500 times/day|3.22mAh|1.31mAh|4.53mAh|44.1 days| - ## Abnormal Diagnosis -If the measured results differ significantly from those in the document, there may be abnormalities that require troubleshooting. -VDDIO: Chip IO power supply -PVDD: Chip main power input -AVDD: Chip audio - -* 1. If there are hardware modifications, it may cause significant deviations in test results -* 2. Mismatched power supply voltage will also cause significant deviations in test results (using 5V power supply) -* 3. If the screen cannot properly refresh, check whether the pins on the screen adapter board are correctly connected to the board - -* Troubleshooting steps: You can remove the original 5V power supply and remove the jumper caps of VDDIO, PVDD, and AVDD. These three paths can be powered individually using the power consumption test tool, while the other two paths are powered through external VCC. This allows single-path power consumption testing to identify which power source has abnormalities (note that VCC_3V3 also needs to be powered separately as it powers the screen). \ No newline at end of file +If the measured results differ significantly from those in the document, there +may be abnormalities that require troubleshooting. VDDIO: Chip IO power supply +PVDD: Chip main power input AVDD: Chip audio + +* 1. Any modifications to the hardware may lead to significant deviations in the + test results. +* 2. Inconsistent supply voltage (e.g., when not using the required 5V supply) + can also result in significant deviations in the test data. +* 3. If the display fails to refresh correctly, verify that the pins on the + display adapter board are properly connected to the main board. + +* Troubleshooting steps: You can remove the original 5V power supply and remove + the jumper caps of VDDIO, PVDD, and AVDD. These three paths can be powered + individually using the power consumption test tool, while the other two paths + are powered through external VCC. This allows single-path power consumption + testing to identify which power source has abnormalities (note that VCC_3V3 + also needs to be powered separately as it powers the screen). diff --git a/example/pm/raise_wrist/README_EN.md b/example/pm/raise_wrist/README_EN.md index 05171ad9c..7145fc66f 100644 --- a/example/pm/raise_wrist/README_EN.md +++ b/example/pm/raise_wrist/README_EN.md @@ -1,85 +1,94 @@ # Raise Wrist to Light Up Screen Example - Source code path: example/pm/raise_wrist ## Supported Platforms - The example can run on the following development boards: * sf32lb52-lchspi-ulp ## Example Overview - -* Time display application: Upon power-on, it displays the default time of 9:30:00 and automatically updates the time display every second. -* Intelligent power management: Automatically enters sleep mode after 10 seconds of inactivity. When the wrist is raised, the sensor detects this gesture to wake up the device and light up the screen to continue displaying time. When the wrist is lowered, the screen turns off and the device enters sleep mode. - Inactivity detection: If a button is pressed or the screen is touched within 10 seconds, it's considered as user activity, and the time will be reset to the default value. -* Sensor data processing: Uses LSM6DSL sensor (accelerometer + gyroscope), continuously reads acceleration data with a 200ms sampling period, and processes the data through algorithms to implement gesture recognition (wrist raise/lower detection). +* Time display application: Upon power-on, it displays the default time of + 9:30:00 and automatically updates the time display every second. +* Intelligent power management: Automatically enters sleep mode after 10 seconds + of inactivity. When the wrist is raised, the sensor detects this gesture to + wake up the device and light up the screen to continue displaying time. When + the wrist is lowered, the screen turns off and the device enters sleep mode. + Inactivity detection: If a button is pressed or the screen is touched within + 10 seconds, it's considered as user activity, and the time will be reset to + the default value. +* Sensor data processing: Uses LSM6DSL sensor (accelerometer + gyroscope), + continuously reads acceleration data with a 200ms sampling period, and + processes the data through algorithms to implement gesture recognition (wrist + raise/lower detection). * Data Summary (using 200mAh battery capacity as an example) -| |Wake-up Work |Screen-off Sleep |Daily Consumption |Usable Days | -|:--- |:--- |:--- |:--- |:--- | -|100 times/day|6.3mAh |9.7mAh |16.0mAh |12.5 days | -|300 times/day|18.8mAh |9.5mAh |28.3mAh |7.1 days | -|500 times/day|31.4mAh |9.3mAh |40.7mAh |4.9 days | -|**Average Power Consumption in Two Modes**|**Screen-off (Low Power Mode):** 410uAh |**Screen-on (Working Mode):** 22.6mAh | + +| | Wake-up Work | Screen-off Sleep | Daily Consumption | Usable Days | +| ------------------------------------------ | --------------------------------------- | ------------------------------------- | ----------------- | ----------- | +| 100 times/day | 6.3 mAh | 9.7 mAh | 16.0 mAh | 12.5 days | +| 300 times/day | 18.8 mAh | 9.5 mAh | 28.3 mAh | 7.1 days | +| 500 times/day | 31.4 mAh | 9.3 mAh | 40.7 mAh | 4.9 days | +| **Average Power Consumption in Two Modes** | **Screen-off (Low Power Mode):** 410uAh | **Screen-on (Working Mode):** 22.6mAh | | | + ## How to Use the Example ### Hardware Connection -Remove the VBAT_S and VBAT jumper caps, and use a power consumption testing tool to supply power through VBAT. Refer to the following diagram for specific hardware connections: -![alt text](assets/connect.png) +Remove the VBAT_S and VBAT jumper caps, and use a power consumption testing tool +to supply power through VBAT. Refer to the following diagram for specific +hardware connections: ![alt text](assets/connect.png) ### Menuconfig Configuration - * Required configurations are enabled by default. ```c menuconfig --board=board_name ``` - 1. Enable 6-axis sensor - - Path: Select board peripherals → Sensor → 6D Sensor for Accelerator and Gyro - - Enable: LSM6DSL - - Macro switch: `CONFIG_ACC_USING_LSM6DSL` - - Purpose: Enable the 6-axis sensor - -2. Enable LVGL - - Path: Third party packages - - Enable: LittlevGL2RTT: The LittlevGl gui lib adapter RT-Thread - - Macro switch: `CONFIG_PKG_USING_LITTLEVGL2RTT` - - Purpose: Use LVGL and select version (default v8) - -3. Enable button - - Path: Sifli middleware - - Enable: Enable button library - - Macro switch: `CONFIG_USING_BUTTON_LIB` - - Purpose: Enable button functionality - -4. Enable low power mode - - Path: Sifli middleware - - Enable: Enable low power support - - Macro switch: `CONFIG_BSP_USING_PM` - - Purpose: Enable low power mode - -5. Enable outputting low power related logs (disabled by default to reduce power consumption. Can be manually enabled in menuconfig for debugging) - - Path: SiFli Middleware → Enable Low Power Support - - Enable: Enable PM Debug - - Macro switch: `CONFIG_BSP_PM_DEBUG` - - Purpose: Output low power related logs +- Enable LVGL + - Path: Third party packages + - Enable: LittlevGL2RTT: The LittlevGl gui lib adapter RT-Thread + - Description: Enables the 6-axis sensor. + +2. Enable button +- Enable low power mode + - Path: Sifli middleware + - Enable: Enable low power support + - Description: Enables LVGL and selects the version (v8 is used by + default). + +3. Enable outputting low power related logs (disabled by default to reduce power + consumption. Can be manually enabled in menuconfig for debugging) +- Path: Sifli middleware + - Enable: Enable button library + - Macro: `CONFIG_USING_BUTTON_LIB` + - Description: Enables the button library. + +4. Enable low-power mode +- Path: Sifli middleware + - Enabled: Enable Low Power Support + - Macro Switch: `CONFIG_BSP_USING_PM` + - Function: Enables the low power management features. + +5. Enable output logs related to low power consumption. (These logs are disabled + by default to minimize power consumption; for debugging and verification, + they can be enabled manually via menuconfig.) +- Path: SiFli Middleware → Enable Low Power Support + - Enabled: Enable PM Debug + - Macro Switch: `CONFIG_BSP_PM_DEBUG` + - Function: Outputs low power management (PM) debug logs. ### Compilation and Flashing - #### Compiling with sf32lb52-lchspi-ulp_hcpu project code as an example - The 52 platform is configured to Deep Sleep mode by default
- -* Compile: - Switch to the example project directory and run the scons command to compile: +* Compile: Switch to the example project directory and run the scons command to + compile: > scons --board=sf32lb52-lchspi-ulp -j8 - * Flash: - 1. Switch to the example `project/build_xx` directory, run `uart_download.bat`, and select the port as prompted to download: - 2. Switch to the example project directory and run: build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat + 1. Switch to the example `project/build_xx` directory, run + `uart_download.bat`, and select the port as prompted to download: + 2. Switch to the example project directory and run: + build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat ```c build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat @@ -88,9 +97,7 @@ Uart Download please input the serial port num:5 ``` - ## Example Output Results - ```c 09-17 19:12:41:285 SFBL 09-17 19:12:43:345 Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000000 @@ -231,45 +238,42 @@ please input the serial port num:5 09-17 19:13:04:487 [pm]WSR:0x4 09-17 19:13:04:564 [pm]S:3,697182 ``` +* Board operation phenomenon ![alt text]{1} -* Board operation phenomenon ![alt text](assets/wakeup_work.jpg) -* Board phenomenon when entering sleep mode +* Board phenomenon when entering sleep mode ![alt text]{1} + ![alt text](assets/enter_pm.jpg) ## Power Consumption Test Results -* Assuming a battery capacity of 200mAh, tests were conducted under various usage scenarios to simulate user behavior of checking time on a smartwatch: - - Light usage: 100 wrist raises per day - - Moderate usage: 300 wrist raises per day - - Heavy usage: 500 wrist raises per day +* Assuming a battery capacity of 200mAh, tests were conducted under various + usage scenarios to simulate user behavior of checking time on a smartwatch: ### When Screen is On - -* Average power consumption during active work or wake-up state: 22.6mA -![alt text](assets/work.png) +* Average power consumption during active work or wake-up state: 22.6mA ![alt + text](assets/work.png) * Daily power consumption for active work: - - Light usage: 22.6 * 100 * 10 / 3600 = 6.3(mAh) - - Moderate usage: 22.6 * 300 * 10 / 3600 = 18.8(mAh) - - Heavy usage: 22.6 * 500 * 10 / 3600 = 31.4(mAh) + - Light usage: 22.6 * 100 * 10 / 3600 = 6.3(mAh) + - Moderate usage: 22.6 * 300 * 10 / 3600 = 18.8(mAh) + - Heavy usage: 22.6 * 500 * 10 / 3600 = 31.4(mAh) ### When Screen is Off - -* Average power consumption in sleep mode: 410uA - Current breakdown: - 1. Base current: 50~60uA - 2. Sensor working current: ~60uA - 3. Charging chip current: ~30uA - 4. Current for data acquisition and wrist detection algorithm every 200ms: ~270uA +* Average power consumption in sleep mode: 410uA Current breakdown: + 1. Base current: 50~60uA + 2. Sensor working current: ~60uA + 3. Charging chip current: ~30uA + 4. Current for data acquisition and wrist detection algorithm every 200ms: + ~270uA ![alt text](assets/pm_mod_sensor.png) ![alt text](assets/pm_all.png) * Daily total power consumption: - - Light usage: 0.410 * (24 * 3600 - 100 * 10) / 3600 + 6.3 = 16.0(mAh) - - Moderate usage: 0.410 * (24 * 3600 - 300 * 10) / 3600 + 18.8 = 28.3(mAh) - - Heavy usage: 0.410 * (24 * 3600 - 500 * 10) / 3600 + 31.4 = 40.7(mAh) + - Light usage: 0.410 * (24 * 3600 - 100 * 10) / 3600 + 6.3 = 16.0(mAh) + - Moderate usage: 0.410 * (24 * 3600 - 300 * 10) / 3600 + 18.8 = 28.3(mAh) + - Heavy usage: 0.410 * (24 * 3600 - 500 * 10) / 3600 + 31.4 = 40.7(mAh) diff --git a/example/rt_device/adc/adc_battery/README_EN.md b/example/rt_device/adc/adc_battery/README_EN.md index b9ad64d31..1f4b344d0 100644 --- a/example/rt_device/adc/adc_battery/README_EN.md +++ b/example/rt_device/adc/adc_battery/README_EN.md @@ -5,11 +5,15 @@ The example can run on the following development boards. * sf32lb52-lcd_n16r8 ## Overview -* Under RT-Thread operating system, ADC single-channel sampling to read vbat battery voltage +* Under RT-Thread operating system, ADC single-channel sampling to read vbat + battery voltage ## Example Usage ### Compilation and Flashing -* This example uses ADC. Under RT-Thread operating system, ADC peripheral is virtualized as an rt_device for read/write operations. At this time, you need to confirm whether the `rtconfig.h` file in the current path contains the following 2 macros: +* This example uses ADC. Under RT-Thread operating system, ADC peripheral is + virtualized as an rt_device for read/write operations. At this time, you need + to confirm whether the `rtconfig.h` file in the current path contains the + following 2 macros: ```c #define BSP_USING_ADC 1 @@ -17,58 +21,69 @@ The example can run on the following development boards. #define RT_USING_ADC 1 ``` -Only when the above three macros are included, the `sifli_adc_init` function will register the `"bat1"` rt_device through the `rt_hw_adc_register` function, and then the device can be successfully found with `rt_device_find` and controlled with `rt_device_control`.
-**Note**
-SiFli series MCUs support timer interrupt to trigger multi-channel simultaneous sampling. You can refer to the definition within macro `BSP_GPADC_SUPPORT_MULTI_CH_SAMPLING` and the chip user manual -* If the above three macros are missing, you need to enable them through `menuconfig` with the following command +Only when the above three macros are included, the `sifli_adc_init` function +will register the `"bat1"` rt_device through the `rt_hw_adc_register` function, +and then the device can be successfully found with `rt_device_find` and +controlled with `rt_device_control`.
**Note**
SiFli series MCUs support +timer interrupt to trigger multi-channel simultaneous sampling. You can refer to +the definition within macro `BSP_GPADC_SUPPORT_MULTI_CH_SAMPLING` and the chip +user manual +* If the above three macros are missing, you need to enable them through + `menuconfig` with the following command -> menuconfig --board=sf32lb52-lcd_n16r8 525 development board +> menuconfig --board=sf32lb52-lcd_n16r8 525 development board -> menuconfig --board=sf32lb52-lcd_52d 52d development board +> menuconfig --board=sf32lb52-lcd_52d 52d development board -As shown in the figure below, select GPADC1, save and exit menuconfig, check if the `rtconfig.h` macro is generated -![alt text](assets/MENUCONFIG_ADC.png) +As shown in the figure below, select GPADC1, save and exit menuconfig, check if +the `rtconfig.h` macro is generated ![alt text](assets/MENUCONFIG_ADC.png) * Switch to the example project directory and run the scons command to compile: ``` scons --board=em_lb525 -j8 ``` -* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as + prompted to download: ``` build_sf32lb52-lcd_52d_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` #### Example Output Results Display: -* Voltage reading log before connecting battery -![alt text](assets/beffer.png) +* Voltage reading log before connecting battery ![alt text](assets/beffer.png) -* Voltage reading log after connecting battery -![alt text](assets/last.png) +* Voltage reading log after connecting battery ![alt text](assets/last.png) -The value printed in the log is the original register value, Voltage is the converted mV voltage +The value printed in the log is the original register value, Voltage is the +converted mV voltage #### ADC Configuration Process -* Set channel 7 corresponding to battery Vbat interface -![alt text](assets/1.png) +* Set channel 7 corresponding to battery Vbat interface ![alt + text](assets/1.png) -**Note** -1. ADC input ports are fixed IO ports, as shown in the figure below:
52 chip ADC CH1-7 distribution, corresponding to software configured Channel0-6, the last channel CH8(Channel 7) is internally connected to battery Vbat detection and is not mapped to external IO
-![alt text](assets/ADC_MAP.png) -1. `HAL_PIN_Set` `HAL_PIN_Set_Analog` the last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu
+**Note** +1. ADC input ports are fixed IO ports, as shown in the figure below:
52 chip + ADC CH1-7 distribution, corresponding to software configured Channel0-6, the + last channel CH8(Channel 7) is internally connected to battery Vbat detection + and is not mapped to external IO
![alt text](assets/ADC_MAP.png) +1. `HAL_PIN_Set` `HAL_PIN_Set_Analog` the last parameter is for hcpu/lcpu + selection, 1: select hcpu, 0: select lcpu
-* Use `rt_device_find` and `rt_device_control` sequentially to find and configure the `bat1` device interface function. -`rt_adc_ops` does not define `rt_device_open`, so not executing `rt_device_open` will not affect ADC functionality, it will only affect whether `bat1` shows open status in `list_device` +* Use `rt_device_find` and `rt_device_control` sequentially to find and + configure the `bat1` device interface function. `rt_adc_ops` does not define + `rt_device_open`, so not executing `rt_device_open` will not affect ADC + functionality, it will only affect whether `bat1` shows open status in + `list_device` ```c #define ADC_DEV_NAME "bat1" /* ADC1 device, already registered in rt_hw_adc_register function, cannot be modified arbitrarily */ #define ADC_DEV_CHANNEL 7 /* ADC channel selection vbat fixed to CH8(Channel 7) */ @@ -90,7 +105,7 @@ void adc_example(void) read_arg.channel = ADC_DEV_CHANNEL; r = rt_adc_enable((rt_adc_device_t)s_adc_dev, read_arg.channel); - + /* This interface will call sifli_adc_control function, read only once, users can process data themselves */ r = rt_device_control(s_adc_dev, RT_ADC_CMD_READ, &read_arg.channel); /* Log printed value is in 0.1mV units, 20846 equals 2084.6mV or 2.0846V */ @@ -111,12 +126,14 @@ void adc_example(void) ## Exception Diagnosis * Program crashes with the following log ```c - Start adc demo! - Assertion failed at function:rt_adc_enable, line number:144 ,(dev) - Previous ISR enable 0 +Starting ADC demo... +Assertion failed at function: rt_adc_enable, line: 144, (dev) +Previous ISR enable: 0 ``` -Reason: -`BSP_USING_ADC1` is not defined, causing `rt_hw_adc_register` function to not register `"bat1"`, and Assert crashes when `rt_device_find` searches for this device +Reason:\ +`BSP_USING_ADC1` is not defined, causing `rt_hw_adc_register` function to not +register `"bat1"`, and Assert crashes when `rt_device_find` searches for this +device\ Ensure the `rtconfig.h` file contains the following 3 macros: ```c #define BSP_USING_ADC 1 @@ -125,10 +142,12 @@ Ensure the `rtconfig.h` file contains the following 3 macros: ``` * ADC sampled voltage value is incorrect -1. Use `list_device` command to check if `bat1` device exists. ADC driver does not affect ADC functionality when `bat1` device is not opened with `rt_device_open` +1. Use `list_device` command to check if `bat1` device exists. ADC driver does + not affect ADC functionality when `bat1` device is not opened with + `rt_device_open` ``` - msh /> - TX:list_device +msh /> + TX: list_device list_device device type ref count -------- -------------------- ---------- @@ -150,23 +169,27 @@ Ensure the `rtconfig.h` file contains the following 3 macros: uart2 Character Device 0 uart1 Character Device 2 pin Miscellaneous Device 0 - msh /> + msh /> ``` -2. Check if ADC hardware is connected correctly. ADC sampling channels are fixed IO ports and cannot be specified arbitrarily. For specific CH0-7 IO assignments, refer to the chip manual -3. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), cannot exceed input range +2. Check if ADC hardware is connected correctly. ADC sampling channels are fixed + IO ports and cannot be specified arbitrarily. For specific CH0-7 IO + assignments, refer to the chip manual +3. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), + cannot exceed input range * ADC accuracy is insufficient 1. Whether ADC calibration parameters are obtained and used 2. Whether the accuracy of voltage divider resistors meets requirements -3. Whether ADC reference voltage is stable and has excessive ripple (refer to ADC voltage reference chip manual for details) - +3. Whether ADC reference voltage is stable and has excessive ripple (refer to + ADC voltage reference chip manual for details) ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf -* [RT-Thread Official Website](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc)
-https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc +* DS0052-SF32LB52x-Datasheet V0p3.pdf +* [RT-Thread Official + Website](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc)
+ https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |11/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | -------- | --------------- | +| 0.0.1 | Nov 2024 | Initial version | +| | | | diff --git a/example/rt_device/adc/channel/README_EN.md b/example/rt_device/adc/channel/README_EN.md index 252c855ca..2ee5dd709 100644 --- a/example/rt_device/adc/channel/README_EN.md +++ b/example/rt_device/adc/channel/README_EN.md @@ -16,97 +16,110 @@ The example can run on the following development boards. ## Example Usage ### Compilation and Flashing -* This example uses ADC. Under RT-Thread operating system, ADC peripheral is virtualized as an rt_device for read/write operations. At this time, you need to confirm whether the `rtconfig.h` file in the current path contains the following 2 macros: - -> #define BSP_USING_ADC 1 -> #define BSP_USING_ADC1 1 -> #define RT_USING_ADC 1 - -Only when the above three macros are included, the `sifli_adc_init` function will register the `"bat1"` rt_device through the `rt_hw_adc_register` function, and then the device can be successfully found with `rt_device_find` and controlled with `rt_device_control`.
-**Note**
-SiFli series MCUs support timer interrupt to trigger multi-channel simultaneous sampling. You can refer to the definition within macro `BSP_GPADC_SUPPORT_MULTI_CH_SAMPLING` and the chip user manual -* If the above three macros are missing, you need to enable them through `menuconfig` with the following command - -> menuconfig --board=sf32lb52-lcd_n16r8 525 development board -> menuconfig --board=sf32lb52-lcd_52d 52d development board -> menuconfig --board=sf32lb58-lcd_n16r64n4 587 development board - -As shown in the figure below, select GPADC1, save and exit menuconfig, check if the `rtconfig.h` macro is generated -![alt text](assets/MENUCONFIG_ADC.png) +* This example uses ADC. Under RT-Thread operating system, ADC peripheral is + virtualized as an rt_device for read/write operations. At this time, you need + to confirm whether the `rtconfig.h` file in the current path contains the + following 2 macros: + +> #define BSP_USING_ADC 1 #define BSP_USING_ADC1 1 #define RT_USING_ADC 1 + +Only when the above three macros are included, the `sifli_adc_init` function +will register the `"bat1"` rt_device through the `rt_hw_adc_register` function, +and then the device can be successfully found with `rt_device_find` and +controlled with `rt_device_control`.
**Note**
SiFli series MCUs support +timer interrupt to trigger multi-channel simultaneous sampling. You can refer to +the definition within macro `BSP_GPADC_SUPPORT_MULTI_CH_SAMPLING` and the chip +user manual +* If the above three macros are missing, you need to enable them through + `menuconfig` with the following command + +> menuconfig --board=sf32lb52-lcd_n16r8 525 development board menuconfig +> --board=sf32lb52-lcd_52d 52d development board menuconfig +> --board=sf32lb58-lcd_n16r64n4 587 development board + +As shown in the figure below, select GPADC1, save and exit menuconfig, check if +the `rtconfig.h` macro is generated ![alt text](assets/MENUCONFIG_ADC.png) * Switch to the example project directory and run the scons command to compile: > scons --board=em-'bread nmae' -j8 -* Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +* Switch to the example `project/build_xx` directory and run + `uart_download.bat`, select the port as prompted to download: > build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ->Uart Download +> UART Download ->please input the serial port num:5 +> Please enter the serial port number: 5 ### sf32lb58-lcd_n16r64n4 Flashing -sf32lb58-lcd_n16r64n4 flashing is different from 52 series flashing and requires J-link for flashing. Connect J-link with development board and PC -![alt text](assets/connect.png) -In J-Link Commander, input 'connect' and '?' commands to select the corresponding model to complete connection. Successful connection is shown below: - -![alt text](assets/J-link.png) -After successful connection, return to ConEmu and input 'build_sf32lb58-lcd_n16r64n4_hcpu\download.bat' for flashing +sf32lb58-lcd_n16r64n4 flashing is different from 52 series flashing and requires +J-link for flashing. Connect J-link with development board and PC ![alt +text](assets/connect.png) In J-Link Commander, input 'connect' and '?' commands +to select the corresponding model to complete connection. Successful connection +is shown below: + +![alt text](assets/J-link.png) After successful connection, return to ConEmu and +input 'build_sf32lb58-lcd_n16r64n4_hcpu\download.bat' for flashing ### Hardware Connection (52 Series) -* PA28 is the fixed output IO for ADC1 Channel 0 -![alt text](assets/SF32LB52_DevKit_ADC.png) +* PA28 is the fixed output IO for ADC1 Channel 0\ + ![alt text](assets/SF32LB52_DevKit_ADC.png) ### Hardware Connection (587) -* PB34 is the fixed output IO for ADC1 Channel 2 -![alt text](assets/5872.png) +* PB34 is the fixed output IO for ADC1 Channel 2\ + ![alt text](assets/5872.png) #### Example Output Results Display: * Log output: ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000080 \ | / - SiFli Corporation / | \ build on Nov 5 2024, 2.2.0 build 00000000 2020 - 2022 Copyright by SiFli team - mount /dev sucess + mount /dev success [32m][490] I/drv.rtc: PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [0m][32m][516] I/drv.rtc: RTC use LXT RTC_CR=00000001 [0m][32m][538] I/drv.rtc: Init RTC, wake = 1 [0m][32m][565] I/drv.audprc: init 00 ADC_PATH_CFG0 0x606 [0m][32m][587] I/drv.audprc: HAL_AUDPRC_Init res 0 [0m][32m][608] I/drv.audcodec: HAL_AUDCODEC_Init res 0 - [0m][32m][630] I/TOUCH: Regist touch screen driver, probe=1203bf69 + [0m][32m][630] I/TOUCH: Registered touch screen driver, probe=1203bf69 [0mcall par CFG1](35bb) fc 9, xtal 2000, pll 2051 call par CFG1(35bb) fc 9, xtal 2000, pll 2051 - Start adc demo! - adc control origin data 2783, Voltage 20846 - [32m][828] I/adc: adc channel:0,value:20846 - [0m]msh />[32m][1567] I/adc: rt_adc_read:0,value:20700 - [0m]spi adc end! + Start ADC demo! + ADC raw data: 2783, Voltage: 20846 + [32m][828] I/adc: ADC channel: 0, value: 20846 + [0m]msh />[32m][1567] I/adc: rt_adc_read: 0, value: 20700 + [0m]SPI ADC end! ``` -The log printed value is in 0.1mV units, 20846 equals 2084.6mV or 2.0846V +The log printed value is in 0.1mV units, 20846 equals 2084.6mV or 2.0846V #### ADC Configuration Process * Ensure the `rtconfig.h` file contains the following 4 macros: ->#define BSP_USING_ADC 1 ->#define BSP_USING_ADC1 1 ->#define RT_USING_ADC 1 +> #define BSP_USING_ADC 1 #define BSP_USING_ADC1 1 #define RT_USING_ADC 1 * Configure PA28 port corresponding to ADC1 Channel 0 ``` - \* set pinmux of channel 0 to analog input *\ +\* Set the pinmux of Channel 0 to analog input *\ HAL_PIN_Set_Analog(PAD_PA28, 1); ``` -**Note** -1. ADC input ports are fixed IO ports, as shown in the figure below:
52 chip ADC CH1-7 distribution, corresponding to software configured Channel0-6, the last channel CH8(Channel 7) is internally connected to battery Vbat detection and is not mapped to external IO
-![alt text](assets/ADC_MAP.png) -1. `HAL_PIN_Set` `HAL_PIN_Set_Analog` the last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu
- - -* Use `rt_device_find` and `rt_device_control` sequentially to find and configure the `bat1` device interface function. -`rt_adc_ops` does not define `rt_device_open`, so not executing `rt_device_open` will not affect ADC functionality, it will only affect whether `bat1` shows open status in `list_device` +**Note** +1. ADC input ports are fixed IO ports, as shown in the figure below:
52 chip + ADC CH1-7 distribution, corresponding to software configured Channel0-6, the + last channel CH8(Channel 7) is internally connected to battery Vbat detection + and is not mapped to external IO
![alt text](assets/ADC_MAP.png) +1. `HAL_PIN_Set` `HAL_PIN_Set_Analog` the last parameter is for hcpu/lcpu + selection, 1: select hcpu, 0: select lcpu
+ + +* Use `rt_device_find` and `rt_device_control` sequentially to find and + configure the `bat1` device interface function. `rt_adc_ops` does not define + `rt_device_open`, so not executing `rt_device_open` will not affect ADC + functionality, it will only affect whether `bat1` shows open status in + `list_device` ```c #define ADC_DEV_NAME "bat1" /* ADC1 device, already registered in rt_hw_adc_register function, cannot be modified arbitrarily */ #define ADC_DEV_CHANNEL 0 /* ADC channel selection PA28 fixed to CH1(Channel 0) */ @@ -128,7 +141,7 @@ void adc_example(void) read_arg.channel = ADC_DEV_CHANNEL; r = rt_adc_enable((rt_adc_device_t)s_adc_dev, read_arg.channel); - + /* This interface will call sifli_adc_control function, read only once, users can process data themselves */ r = rt_device_control(s_adc_dev, RT_ADC_CMD_READ, &read_arg.channel); /* Log printed value is in 0.1mV units, 20846 equals 2084.6mV or 2.0846V */ @@ -149,12 +162,14 @@ void adc_example(void) ## Exception Diagnosis * Program crashes with the following log ```c - Start adc demo! - Assertion failed at function:rt_adc_enable, line number:144 ,(dev) - Previous ISR enable 0 +Starting ADC demo... +Assertion failed at function: rt_adc_enable, line: 144, (dev) +Previous ISR enable: 0 ``` -Reason: -`BSP_USING_ADC1` is not defined, causing `rt_hw_adc_register` function to not register `"bat1"`, and Assert crashes when `rt_device_find` searches for this device +Reason:\ +`BSP_USING_ADC1` is not defined, causing `rt_hw_adc_register` function to not +register `"bat1"`, and Assert crashes when `rt_device_find` searches for this +device\ Ensure the `rtconfig.h` file contains the following 3 macros: ```c #define BSP_USING_ADC 1 @@ -162,18 +177,21 @@ Ensure the `rtconfig.h` file contains the following 3 macros: #define RT_USING_ADC 1 ``` * ADC sampled voltage value is incorrect -1. Use `pin status 28` command to check the corresponding PA28 IO status, whether it matches the following +1. Use `pin status 28` command to check the corresponding PA28 IO status, + whether it matches the following ``` - msh /> +msh /> TX:pin status 28 pin status 28 [32m][372862432] I/TEST.GPIO: PIN 28, FUNC=15, VAL=0, ANA_IN, GPIO_MODE_INPUT, irqhdr=/, arg=/ - [0m]msh /> + [0m]msh /> ``` -2. Use `list_device` command to check if `bat1` device exists. ADC driver does not affect ADC functionality when `bat1` device is not opened with `rt_device_open` +2. Use `list_device` command to check if `bat1` device exists. ADC driver does + not affect ADC functionality when `bat1` device is not opened with + `rt_device_open` ``` - msh /> - TX:list_device +msh /> + TX: list_device list_device device type ref count -------- -------------------- ---------- @@ -195,23 +213,27 @@ Ensure the `rtconfig.h` file contains the following 3 macros: uart2 Character Device 0 uart1 Character Device 2 pin Miscellaneous Device 0 - msh /> + msh /> ``` -3. Check if ADC hardware is connected correctly. ADC sampling channels are fixed IO ports and cannot be specified arbitrarily. For specific CH0-7 IO assignments, refer to the chip manual -4. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), cannot exceed input range +3. Check if ADC hardware is connected correctly. ADC sampling channels are fixed + IO ports and cannot be specified arbitrarily. For specific CH0-7 IO + assignments, refer to the chip manual +4. ADC input voltage range is 0V - reference voltage (52 defaults to 3v3), + cannot exceed input range * ADC accuracy is insufficient 1. Whether ADC calibration parameters are obtained and used 2. Whether the accuracy of voltage divider resistors meets requirements -3. Whether ADC reference voltage is stable and has excessive ripple (refer to ADC voltage reference chip manual for details) - +3. Whether ADC reference voltage is stable and has excessive ripple (refer to + ADC voltage reference chip manual for details) ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf -* [RT-Thread Official Website](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc)
-https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc +* DS0052-SF32LB52x-Datasheet V0p3.pdf +* [RT-Thread Official + Website](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc)
+ https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |11/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | -------- | --------------- | +| 0.0.1 | Nov 2024 | Initial version | +| | | | diff --git a/example/rt_device/adc/index_EN.md b/example/rt_device/adc/index_EN.md index 87087c7f9..7dcbcccd0 100644 --- a/example/rt_device/adc/index_EN.md +++ b/example/rt_device/adc/index_EN.md @@ -1,9 +1,8 @@ -# ADC Example +# ADC Example ```{toctree} :titlesonly: :glob: */* - -``` \ No newline at end of file +``` diff --git a/example/rt_device/audprc/README_EN.md b/example/rt_device/audprc/README_EN.md index 3f89a124e..505b0d7ac 100644 --- a/example/rt_device/audprc/README_EN.md +++ b/example/rt_device/audprc/README_EN.md @@ -3,7 +3,7 @@ Source code path: example/rt_device/audprc ## Supported Platforms - + + eh-lb525 + sf32lb52-lcd series + sf32lb56-lcd series @@ -11,54 +11,56 @@ Source code path: example/rt_device/audprc + ec-lb587 ## Overview - + In this example, Audprc is used together with Audcodec, including: + Mic recording. + Playing recordings through speaker. + Loopback (simultaneous recording and playback). - ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ A development board supported by this example ([Supported Platforms](quick_start)). ++ A development board supported by this example ([Supported + Platforms](quick_start)). + Speaker. ### menuconfig Configuration -1. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) +1. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) 2. This example uses FINSH functionality, need to enable `RT_USING_FINSH`. -3. Enable peripherals (PA, select according to actual board model) -![PA AW8155](./assets/peripherals.png) +3. Enable peripherals (PA, select according to actual board model) ![PA + AW8155](./assets/peripherals.png) ### Compilation and Flashing Switch to the example project directory and run scons command to compile: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results of Example - + In this example, recording and playback are operated through FINSH commands: -Purpose | Command | Example |Notes -|---|--|--|--| -Recording|audprc rx [channels:1/2] [sample rate] [sample bits]|`audprc rx 1 16000 16` |Recording stored in ram buffer (recording automatically stops after 1M) -Play recording|audprc tx [channels:1/2] [sample rate] [sample bits]|`audprc tx 1 16000 16`| Playback data from ram buffer (need to record first) -Loopback|audprc txrx [rx channels:1/2] [rx sample rate] [rx sample bits] [tx channels:1/2] [tx sample rate] [tx sample bits]|`audprc rxtx 1 16000 16 1 16000 16`|Simultaneous recording (mic) and playback (speaker) (Before executing recording and playback commands, if Loopback is running, need to stop first.) -Stop Loopback|audprc txrxstop|`audprc txrxstop`|Stop Loopback +| Purpose | Command | Example | Notes | +| -------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| Recording | audprc rx [channels:1/2] [sample rate] [sample bits] | `audprc rx 1 16000 16` | Recording stored in ram buffer (recording automatically stops after 1M) | +| Play recording | audprc tx [channels:1/2] [sample rate] [sample bits] | `audprc tx 1 16000 16` | Playback data from ram buffer (need to record first) | +| Loopback | audprc txrx [rx channels:1/2] [rx sample rate] [rx sample bits] [tx channels:1/2] [tx sample rate] [tx sample bits] | `audprc rxtx 1 16000 16 1 16000 16` | Simultaneous recording (mic) and playback (speaker) (Before executing recording and playback commands, if Loopback is running, need to stop first.) | +| Stop Loopback | audprc txrxstop | `audprc txrxstop` | Stop Loopback | Serial port output as follows: ``` @@ -139,19 +141,18 @@ Serial port output as follows: 01-23 11:06:21:150 [I/drv.audprc] bf0_audio_stop 0x1102 01-23 11:06:21:152 [I/drv.audprc] audprc close adc/dac 01-23 11:06:21:153 [I/drv.audprc] bf0_audio_stop 0x1102 done -01-23 11:06:21:156 sifli_aw8155_stop - +01-23 11:06:21:156 sifli_aw8155_stop ``` ## Exception Diagnosis ## Reference Documents - + ## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |12/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | +| | | | diff --git a/example/rt_device/emmc/README_EN.md b/example/rt_device/emmc/README_EN.md index 2b50b0c52..23188a270 100644 --- a/example/rt_device/emmc/README_EN.md +++ b/example/rt_device/emmc/README_EN.md @@ -1,7 +1,8 @@ # eMMC/SD Card Example Source code path: example/rt_device/emmc ## Overview -The example demonstrates creating partitions on eMMC or SD card, mounting elm file system on partitions, and performing various file system operations +The example demonstrates creating partitions on eMMC or SD card, mounting elm +file system on partitions, and performing various file system operations ## Supported Platforms * sf32lb56-lcd_a128r12n1 * sf32lb56-lcd_n16r12n1 @@ -27,15 +28,13 @@ ls - List information about the FILEs.//List all file information ``` menuconfig --board=56devkit_lcd(board= followed by board name) ``` -1. Enable SDIO -![alt text](assets/sdio.png) +1. Enable SDIO ![alt text](assets/sdio.png) -2. Note that SF32LB56X has two SDMMC controller IPs: SDMMC1 (SDHCI IP) and SDMMC2 (SDIO IP). If eMMC is connected to SDMMC2, the configuration needs to be changed to BSP_USING_SD_LINE. -![alt text](assets/image1.png) - -3. Enable and configure SD device -![alt text](assets/sd.png) +2. Note that SF32LB56X has two SDMMC controller IPs: SDMMC1 (SDHCI IP) and + SDMMC2 (SDIO IP). If eMMC is connected to SDMMC2, the configuration needs to + be changed to BSP_USING_SD_LINE. ![alt text](assets/image1.png) +3. Enable and configure SD device ![alt text](assets/sd.png) ### Compilation and Flashing Follow these steps to complete compilation and flashing. @@ -46,29 +45,37 @@ build_56_board_lcd_hcpu\download.bat(uart_download.bat)//Can flash through jlink ## Experimental Results -1. Successful mount log (If you see the output log contains the items framed in the picture, it means mount is successful) -![alt text](assets/log2.png) +1. Successful mount log (the presence of the highlighted text in the output log +indicates a successful mount). ![alt text](assets/log2.png) -2. Perform file creation operations. First input ls to view existing files or directories in the file system, then use mkdir XXX to create, cd to the created directory, use echo command to create text and write content, then use cat command to view the created file content, finally use pwd command to view the current working path -![alt text](assets/log1.png) +2. Creating a file: First, execute `ls` to view existing files or directories in +the filesystem. Use `mkdir ` to create a new directory, then `cd` into it. Use +the `echo` command to create a text file and write content to it. Verify the +content using `cat`, and finally, use `pwd` to check the current working +directory. ![alt text](assets/log1.png) ## Results that could not be completed as expected (log) ![alt text](assets/log3.png) ## Failure reasons and solutions -1. If the log shows the following, first check if TF card is inserted, then check if SD in the above menuconfig is enabled, you can refer to the above menuconfig operation configuration +If the expected log does not appear, you can troubleshoot from the following +aspects: ``` rt_mmcsd_blk_device_create find [sd0] fail !!! ``` -2. If the log shows the following, please check if TF card is inserted +2. If the log displays the following, please check whether the TF card is +properly inserted: ``` [E/DFS] Device (root) was not found [E/DFS] Device (misc) was not found ``` -If the expected log does not appear, you can troubleshoot from the following aspects: +If the expected log output does not appear, troubleshoot using the following +steps: +* If the log shows the following, first check if TF card is inserted, then check + if SD in the above menuconfig is enabled, you can refer to the above + menuconfig operation configuration +* If the log shows the following, please check if TF card is inserted * Whether hardware connection is normal * Check if USB interface is loose -* Check if USB cable has data transmission capability -* Whether TF card is usable \ No newline at end of file diff --git a/example/rt_device/gpio/README_EN.md b/example/rt_device/gpio/README_EN.md index 1c5e00a47..d321aed20 100644 --- a/example/rt_device/gpio/README_EN.md +++ b/example/rt_device/gpio/README_EN.md @@ -6,27 +6,32 @@ The example can run on the following development boards. * sf32lb52-lcd series * sf32lb56-lcd series * sf32lb58-lcd series +* sf32lb58-lcd series ## Example Overview -* Configure GPIO output, input interrupt operation, demonstrate GPIO HAL functions -* Toggle GPIO_out level value every second, input GPIO triggers interrupt on rising and falling edges, serial port prints interrupt information - +* Configure GPIO output, input interrupt operation, demonstrate GPIO HAL + functions +* Toggle GPIO_out level value every second, input GPIO triggers interrupt on + rising and falling edges, serial port prints interrupt information ## Example Usage ### Hardware Connection -* Note: Connect input GPIO and output GPIO through jumper wire, so that GPIO_out level transition can be assigned to GPIO_in to achieve entering interrupt and printing information +* Note: Connect input GPIO and output GPIO through jumper wire, so that GPIO_out + level transition can be assigned to GPIO_in to achieve entering interrupt and + printing information -|Development Board |OUT Pin |OUT Pin Name|IN Pin |IN Pin Name | -|:--- |:--- |:--- |:--- |:--- | -|sf32lb52-lcd_n16r8 |5 |PA41 |3 |PA42 | -|sf32lb56-lcd_n16r12n1 |5 |PA20 |3 |PA12 | -|sf32lb58-lcd_n16r64n4 |5 |PB28 |3 |PB29 | +| Development Board | OUT Pin | OUT Pin Name | IN Pin | IN Pin Name | +| --------------------- | ------- | ------------ | ------ | ----------- | +| sf32lb52-lcd_n16r8 | 5 | PA41 | 3 | PA42 | +| sf32lb56-lcd_n16r12n1 | 5 | PA41 | 3 | PA42 | +| sf32lb58-lcd_n16r64n4 | 5 | PB28 | 3 | PB29 | +| sf32lb58-lcd | 5 | PB28 | 3 | PB29 | * For more detailed pin definitions please refer to\ -`[sf32lb52-lcd_n16r8]()`\ -`[sf32lb56-lcd_n16r12n1]()`\ -`[sf32lb58-lcd_n16r64n4]()` + `[sf32lb52-lcd_n16r8]()`\ + `[sf32lb56-lcd_n16r12n1]()`\ + `[sf32lb58-lcd_n16r64n4]()` ### Compilation and Flashing #### Compiled using the SF32LB52-LCD engineering code as an example @@ -34,29 +39,31 @@ Switch to the example project directory and run scons command to compile: > scons --board=sf32lb52-lcd_n16r8 -j8 -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: > build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -> Uart Download +> UART Download + +> Please enter the serial port number: 5 -> please input the serial port num:5 ### Example Output Results Display: * Log output: ``` - SFBL - Serial:c2,Chip:4,Package:4,Rev:7 Reason:00000000 - [I/drv.adc] Get ADC configure fail +SFBL + Serial:c2, Chip:4, Package:4, Rev:7 Reason:00000000 + [I/drv.adc] Failed to get ADC configuration \ | / - SiFli Corporation / | \ build on Jan 23 2025, 2.1.7 build bef6b3d8 2020 - 2022 Copyright by SiFli team - mount /dev sucess - [D/USBD] No class register on usb device + mount /dev success + [D/USBD] No class registered on USB device [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 - [I/drv.rtc] RTC use LXT RTC_CR=00000001 + [I/drv.rtc] RTC using LXT RTC_CR=00000001 [I/drv.rtc] Init RTC, wake = 0 [I/drv.audprc] init 00 ADC_PATH_CFG0 0x606 [I/drv.audprc] HAL_AUDPRC_Init res 0 @@ -66,18 +73,18 @@ Switch to the example `project/build_xx` directory and run `uart_download.bat`, call par CFG1(3313) fc 7, xtal 2000, pll 1657 Start gpio rtt demo! - msh /> + msh /> ``` When GPIO_out level toggles every second: ``` Interrupt occurred! -Pin_Out 41 has been toggle, value = 1 +Pin_Out 41 has been toggled, value = 1 Pin_In 42, value = 1 ``` Toggle after 1 second: ``` Interrupt occurred! -Pin_Out 41 has been toggle, value = 0 +Pin_Out 41 has been toggled, value = 0 Pin_In 42, value = 0 ``` ## Example Description @@ -120,21 +127,22 @@ Configure `GPIO1 pin41` (i.e., GPIO_A41) as output mode struct rt_device_pin_mode m; m.pin = Pin_Out; m.mode = PIN_MODE_OUTPUT; -rt_device_control(device, 0, &m); +rt_device_control(device, 0, &m); ``` ### Input Mode (with Interrupt) #### GPIO Initialization -Configure `GPIO1 pin42` (i.e., GPIO_A42) as input mode with rising and falling edge detection +Configure `GPIO1 pin42` (i.e., GPIO_A42) as input mode with rising and falling +edge detection ```C -//set pin to PIN_MODE_INPUT +// Set pin to PIN_MODE_INPUT m.pin = Pin_In; m.mode = PIN_MODE_INPUT; -rt_device_control(device, 0, &m); +rt_device_control(device, 0, &m); -//set irq mode +// Configure IRQ mode rt_pin_attach_irq(m.pin, PIN_IRQ_MODE_RISING_FALLING, irq_handler, (void *)(rt_uint32_t)m.pin); rt_pin_irq_enable(m.pin, 1); ``` @@ -143,27 +151,27 @@ rt_pin_irq_enable(m.pin, 1); ```C void irq_handler(void *args) { - //set your own irq handle + // Define custom IRQ handler logic here rt_kprintf("Interrupt occurred!\n"); - - //read Pin_Out + + // Read Pin_Out status struct rt_device_pin_status st; st.pin = Pin_Out; - rt_device_read(device, 0, &st, sizeof(struct rt_device_pin_status)); - rt_kprintf("Pin_Out %d has been toggle, value = %d\n", Pin_Out, st.status); + rt_device_read(device, 0, &st, sizeof(struct rt_device_pin_status)); + rt_kprintf("Pin_Out %d has been toggled, value = %d\n", Pin_Out, st.status); - //read Pin_In + // Read Pin_In status st.pin = Pin_In; - rt_device_read(device, 0, &st, sizeof(struct rt_device_pin_status)); + rt_device_read(device, 0, &st, sizeof(struct rt_device_pin_status)); rt_kprintf("Pin_In %d, value = %d\n", Pin_In, st.status); rt_kprintf(" \n"); } ``` ## API Reference -[](#hal-gpio) +[] ## Update History -|Version |Date |Release Notes | -|:--- |:--- |:--- | -|0.0.1 |12/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | diff --git a/example/rt_device/gpu/index_EN.md b/example/rt_device/gpu/index_EN.md index 3c2c29b45..ea581e515 100644 --- a/example/rt_device/gpu/index_EN.md +++ b/example/rt_device/gpu/index_EN.md @@ -1,9 +1,7 @@ # GPU Example - ```{toctree} :titlesonly: :glob: */* - ``` diff --git a/example/rt_device/gpu/render_list_mode/README_EN.md b/example/rt_device/gpu/render_list_mode/README_EN.md index cb17dbb8e..147b3fa6c 100644 --- a/example/rt_device/gpu/render_list_mode/README_EN.md +++ b/example/rt_device/gpu/render_list_mode/README_EN.md @@ -1,9 +1,10 @@ # GPU Render List Mode Example Program +Source path: example/rt_device/gpu/render_list_mode ```{warning} Not verified ``` ## Introduction This example program uses drv_epic's render list mode to create some rendering operations including fill, draw, rectangle, polygon, border, arc, line, bitmap font and other operations, and uses 2 framebuffers of 1/16 screen size (`render_buffer`) to render and send the results to the screen for display. - After one rendering operation is completed, it will continue to repeat the previous rendering operations and send the display results to the screen. + After one rendering operation is completed, it will continue to repeat the previous rendering operations and send the display results to the screen. ## Project Description - - This example can work on 52x, 56x with PSRAM packaging tests. \ No newline at end of file + - This example can work on 52x, 56x with PSRAM packaging tests. diff --git a/example/rt_device/gpu/single_mode/README_EN.md b/example/rt_device/gpu/single_mode/README_EN.md index f296ec8fd..0233949d4 100644 --- a/example/rt_device/gpu/single_mode/README_EN.md +++ b/example/rt_device/gpu/single_mode/README_EN.md @@ -1,15 +1,17 @@ # EPIC Example Program - -EPIC (ePicasso) is our self-developed graphics engine, a hardware acceleration module specifically designed for 2D/2.5D image processing, mainly used to offload CPU load in image operations and improve image processing efficiency. +EPIC (ePicasso) is our self-developed graphics engine, a hardware acceleration +module specifically designed for 2D/2.5D image processing, mainly used to +offload CPU load in image operations and improve image processing efficiency. ## Overview -This program is a graphics blending example based on RT-Thread operating system and EPIC. The implemented functions are as follows: -* 1. Fill rectangles and crop rectangles for blending display +This program is a graphics blending example based on RT-Thread operating system +and EPIC. The implemented functions are as follows: +* 1. Rectangular filling and clipping for alpha blending * 2. Gradient color filling -* 3. Scale an ezip image -* 4. Rotate a normal rgb565 format image + mask function -* 5. Single font display -* 6. Multi-font blending display +* 3. Rescaling an EZIP image +* 4. RGB565 image rotation with masking +* 5. Single-font rendering +* 6. Multi-font composite rendering ## Supported Development Boards The example can run on the following development boards: @@ -29,74 +31,110 @@ build_sf32lb52-lchspi-ulp_hcpu\uart_download.bat ``` Select the port as prompted for download: ```none -please input the serial port num:6 +Please input the serial port number: 6 ``` #### Example Output Result Display: The LCD screen will cyclically display the following functions: -* Fill rectangles and crop rectangles for blending display -* Gradient color filling -* Scale an ezip image -* Rotate a normal rgb565 format image + mask function -* Single font display -* Multi-font blending display +* 1. Rectangular filling and clipping for alpha blending +* 2. Gradient color filling +* 3. Rescaling an EZIP image +* 4. RGB565 image rotation with masking +* 5. Single-font rendering +* 6. Multi-font composite rendering --- ## Example Explanation ### Main program flow includes: -Initialize GPU and LCD devices ---> Use EPIC corresponding interfaces to process image data --> Output the processed image data to screen display. - +Initialize GPU and LCD devices ---> Use EPIC corresponding interfaces to process +image data --> Output the processed image data to screen display. ### Key interfaces used: #### 1. GPU/EPIC interfaces: -| Interface Name | Function Description | -|-----------------------------|------------------------------| -| drv_gpu_open() | Initialize GPU resources, including interrupts | -| drv_epic_fill() | Fill rectangular area with specified color | -| HAL_EPIC_LayerConfigInit()| Initialize layer configuration structure | -| HAL_EPIC_LayerSetDataOffset() | Set layer data offset (for cropping) | -| HAL_EPIC_GetColorDepth() |Get the pixel depth of the color mode | -| drv_epic_blend() | Execute multi-layer blending operation | -| drv_epic_wait_done() | Wait for blending operation to complete | -| drv_epic_fill_grad() | Execute gradient fill operation | -| drv_epic_cont_blend_reset() | Reset continuous blending state | -| drv_epic_cont_blend() |Execute continuous blending operation | +| Interface Name | Function Description | +| ----------------------------- | ---------------------------------------------- | +| drv_gpu_open() | Initialize GPU resources, including interrupts | +| drv_epic_fill() | Fill rectangular area with specified color | +| HAL_EPIC_LayerConfigInit() | Initialize layer configuration structure | +| HAL_EPIC_LayerSetDataOffset() | Set layer data offset (for cropping) | +| HAL_EPIC_GetColorDepth() | Get the pixel depth of the color mode | +| drv_epic_blend() | Execute multi-layer blending operation | +| drv_epic_wait_done() | Wait for blending operation to complete | +| drv_epic_fill_grad() | Execute gradient fill operation | +| drv_epic_cont_blend_reset() | Reset continuous blending state | +| drv_epic_cont_blend() | Execute continuous blending operation | + #### 2. LCD display interfaces: -| Interface Name | Function Description | -|-------------------------------------------|----------------------------------| -| rt_device_find("lcd") | Find LCD device | -| rt_device_open() | Open LCD device | -| rt_device_control(..., RTGRAPHIC_CTRL_SET_BUF_FORMAT) | Set display memory format | -| rt_device_control(..., RTGRAPHIC_CTRL_GET_INFO) | Get LCD screen information | -| rt_graphix_ops()->draw_rect_async() | Asynchronously draw rectangle and refresh screen | +| Interface Name | Function Description | +| ----------------------------------------------------- | ------------------------------------------------ | +| rt_device_find("lcd") | Find LCD device | +| rt_device_open() | Open LCD device | +| rt_device_control(..., RTGRAPHIC_CTRL_SET_BUF_FORMAT) | Set display memory format | +| rt_device_control(..., RTGRAPHIC_CTRL_GET_INFO) | Get LCD screen information | +| rt_graphix_ops()->draw_rect_async() | Asynchronously draw rectangle and refresh screen | --- ## Important Notes!!! -When the screen doesn't display, check if the fill color is in ARGB8888 format, because the drv_epic_fill interface requires the fill color format to be ARGB8888 -![alt text](assets/image1.png) -When the image effect doesn't meet expectations or the screen doesn't display (as shown in the example): it may be due to improper cropping. -![alt text](assets/fail_show.png) +When the screen doesn't display, check if the fill color is in ARGB8888 format, +because the drv_epic_fill interface requires the fill color format to be +ARGB8888 ![alt text](assets/image1.png) When the image effect doesn't meet +expectations or the screen doesn't display (as shown in the example): it may be +due to improper cropping. ![alt text](assets/fail_show.png) --- #### About Cropping -* The blending principle of this example is to crop 'extract' the fill areas from the fg_layer and bg_layer layers, then place them in an output_layer. -* However, it should be noted that when cropping interfaces like HAL_EPIC_LayerSetDataOffset() are not called, the default cropping start position is the first address pointed to by the layer.data pointer, which is the top-left corner (0,0) in this example. Then the cropped area will be (layer.width - 0, layer.height - 0). -At this time, if the fill areas we set for the fg_layer and bg_layer layers are not within the cropped area, then our valid data will not be 'extracted'. -* As shown in the code of this example, the fill area is set to (100 ~ 250, 100 ~ 200), and the cropped area is (0 ~ 150, 0 ~ 100). Our fill area perfectly avoids the cropped area, so the data 'extracted' by cropping will be empty, only cropping the background. -![alt text](assets/image2.png) -![alt text](assets/image4.png) -![alt text](assets/image3.png) +* The blending principle of this example is to crop 'extract' the fill areas + from the fg_layer and bg_layer layers, then place them in an output_layer. +* However, it should be noted that when cropping interfaces like + HAL_EPIC_LayerSetDataOffset() are not called, the default cropping start + position is the first address pointed to by the layer.data pointer, which is + the top-left corner (0,0) in this example. Then the cropped area will be + (layer.width - 0, layer.height - 0). At this time, if the fill areas we set + for the fg_layer and bg_layer layers are not within the cropped area, then our + valid data will not be 'extracted'. +* As shown in the code of this example, the fill area is set to (100 ~ 250, 100 + ~ 200), and the cropped area is (0 ~ 150, 0 ~ 100). Our fill area perfectly + avoids the cropped area, so the data 'extracted' by cropping will be empty, + only cropping the background. ![alt text](assets/image2.png) ![alt + text](assets/image4.png) ![alt text](assets/image3.png) --- -So how do we both want to set the fill area position and accurately crop 'extract' our fill area? -* The first and simplest method is to keep the starting position of the fill area consistent with the position of the first address pointed to by the layer.data pointer (that is, put the fill area in the cropped area) without calling any cropping functions. -* The second method is to call the cropping interface, such as HAL_EPIC_LayerSetDataOffset(EPIC_BlendingDataType *layer, int16_t x, int16_t y), where the parameter layer is the layer to be cropped, x is the x coordinate of the starting position you want to crop, and y is the y coordinate of the starting position you want to crop. This way we can crop wherever we want. It should be noted that the values of x and y need to be added to the values of layer.x_offset and layer.y_offset on the basis of the starting position you want to crop. As shown in this example, the starting position to be cropped is (100,100), and the values of layer.x_offset and layer.y_offset are 50, 50, then our x and y values are 100 + 50 = 150, 100 + 50 = 150. -![alt text](assets/image5.png) +So how do we both want to set the fill area position and accurately crop +'extract' our fill area? +* The first and simplest method is to keep the starting position of the fill + area consistent with the position of the first address pointed to by the + layer.data pointer (that is, put the fill area in the cropped area) without + calling any cropping functions. +* The second method is to call the cropping interface, such as + HAL_EPIC_LayerSetDataOffset(EPIC_BlendingDataType *layer, int16_t x, int16_t + y), where the parameter layer is the layer to be cropped, x is the x + coordinate of the starting position you want to crop, and y is the y + coordinate of the starting position you want to crop. This way we can crop + wherever we want. It should be noted that the values of x and y need to be + added to the values of layer.x_offset and layer.y_offset on the basis of the + starting position you want to crop. As shown in this example, the starting + position to be cropped is (100,100), and the values of layer.x_offset and + layer.y_offset are 50, 50, then our x and y values are 100 + 50 = 150, 100 + + 50 = 150. ![alt text](assets/image5.png) ## Important Notes about Mask!!! -* When creating a mask layer, the ax_mode format should be selected as ALPHA_BLEND_MASK, and the color_mode value should be consistent with your image data format -* On 52x, there are only 2 normal layers + 1 mask layer, and the number of configured normal layers cannot be too many -* The pixel alignment standard is: A2 format 4-pixel alignment, A4 format 2-pixel alignment, A8 format no alignment operation required. When the displayed effect does not meet expectations, check whether total_width meets the alignment requirements -* If the image display is incorrect and found to be skewed, you can check whether the passed width is consistent with the actual image width. If it's smaller than the actual width, the vertical lines will skew to the right, and if it's larger than the actual width, they will skew to the left \ No newline at end of file +* When creating a mask layer, the ax_mode format should be selected as + ALPHA_BLEND_MASK, and the color_mode value should be consistent with your + image data format +* On 52x, there are only 2 normal layers + 1 mask layer, and the number of + configured normal layers cannot be too many +* The pixel alignment standard is: A2 format 4-pixel alignment, A4 format + 2-pixel alignment, A8 format no alignment operation required. When the + displayed effect does not meet expectations, check whether total_width meets + the alignment requirements +* If the image display is incorrect and found to be skewed, you can check + whether the passed width is consistent with the actual image width. If it's + smaller than the actual width, the vertical lines will skew to the right, and + if it's larger than the actual width, they will skew to the left +* If the image appears skewed during display, verify that the transmitted width + matches the actual image width. If the transmitted width is smaller than the + actual width, vertical lines will tilt to the right; if larger, they will tilt + to the left. + diff --git a/example/rt_device/i2c/eeprom/README_EN.md b/example/rt_device/i2c/eeprom/README_EN.md index 102f35a8f..8bf14a91e 100644 --- a/example/rt_device/i2c/eeprom/README_EN.md +++ b/example/rt_device/i2c/eeprom/README_EN.md @@ -6,72 +6,85 @@ The example can run on the following development boards: * sf32lb52-lcd series * sf32lb56-lcd series * sf32lb58-lcd series + ## Overview -* Under RT-Thread operating system, demonstrate the usage of I2C through read and write operations on EEPROM chip AT24CO8SC module +* Under RT-Thread operating system, demonstrate the usage of I2C through read + and write operations on EEPROM chip AT24CO8SC module ## Example Usage ### Hardware Connection Connect VCC and GND of AT24CO8SC to 5v and GND respectively for power supply\ -Connect SDA and SCK of AT24CO8SC according to the following table based on the development board model +Connect SDA and SCK of AT24CO8SC according to the following table based on the +development board model -|Development Board |SDA Pin|SDA Pin Name|SCL Pin|SCL Pin Name| -|:--- |:--- |:--- |:--- |:--- | -|sf32lb52-nano |3 |PA42 |5 |PA41 | -|sf32lb52-lcd |3 |PA42 |5 |PA41 | -|sf32lb56-lcd |3 |PA12 |5 |PA20 | -|sf32lb58-lcd |3 |PB29 | |PB28 | +| Development Board | SDA Pin | SDA Pin Name | SCL Pin | SCL Pin Name | +| ----------------- | ------- | ------------ | ------- | ------------ | +| sf32lb52-nano | 3 | PA42 | 5 | PA41 | +| sf32lb52-lcd | 3 | PA42 | 5 | PA41 | +| sf32lb56-lcd | 3 | PA12 | 5 | PA20 | +| sf32lb58-lcd | 3 | PB29 | | PB28 | * For more detailed pin definitions, please refer to\ -[sf32lb52-nano](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-Nano.html) -[sf32lb52-lcd](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) -[sf32lb56-lcd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) -[sf32lb58-lcd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) - -* AT24C08SC -![alt text](assets/at24c08sc.png) + [sf32lb52-nano](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-Nano.html) + [sf32lb52-lcd](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) + [sf32lb56-lcd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) + [sf32lb58-lcd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) +* AT24C08SC ![alt text](assets/at24c08sc.png) ### Compilation and Programming -* This example uses I2C2. When using RT-Thread operating system, I2C2 peripheral will be virtualized as an rt_device for read and write operations. At this time, you need to confirm whether the `rtconfig.h` file in the project path contains the following 3 macros: +* This example uses I2C2. When using RT-Thread operating system, I2C2 peripheral + will be virtualized as an rt_device for read and write operations. At this + time, you need to confirm whether the `rtconfig.h` file in the project path + contains the following 3 macros: ```c #define RT_USING_I2C 1 #define BSP_USING_I2C 1 #define BSP_USING_I2C2 1 ``` -Only when the above three macros are included, the `rt_i2c_bus_device_register` function will register the `"i2c2"` `rt_device` in the `rt_hw_i2c_init2` function, and then this device can be successfully found and opened with `rt_device_find` and `rt_device_open`. +Only when the above three macros are included, the `rt_i2c_bus_device_register` +function will register the `"i2c2"` `rt_device` in the `rt_hw_i2c_init2` +function, and then this device can be successfully found and opened with +`rt_device_find` and `rt_device_open`. -If the above three macros are missing, you need to enable them through the following `menuconfig` command: +If the above three macros are missing, you need to enable them through the +following `menuconfig` command: ```c menuconfig --board=sf32lb52-lcd_n16r8 ``` -As shown in the figure below, select I2C2, save and exit menuconfig, check whether the `rtconfig.h` macro is generated -![alt text](assets/i2c2_menuconfig.png) +As shown in the figure below, select I2C2, save and exit menuconfig, check +whether the `rtconfig.h` macro is generated ![alt +text](assets/i2c2_menuconfig.png) #### SF525 Project Code Compilation -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` #### SF587 Project Code Compilation -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -Switch to the example `project/build_xx` directory and run `download.bat`, the program will be automatically downloaded through JLink: +Switch to the example `project/build_xx` directory and run `download.bat`, the +program will be automatically downloaded through JLink: > build_sf32lb58-lcd_n16r64n4_hcpu\download.bat @@ -79,7 +92,7 @@ Switch to the example `project/build_xx` directory and run `download.bat`, the p ### Example Output Results Display: * Log output: ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000000 \ | / - SiFli Corporation @@ -110,19 +123,16 @@ Switch to the example `project/build_xx` directory and run `download.bat`, the p [3298] D/eeprom_i2c: i2c read reg:0x3,pdata:0x33,ret:1 [3323] D/eeprom_i2c: i2c read reg:0x4,pdata:0x44,ret:1 [3345] D/eeprom_i2c: i2c end! - msh /> + msh /> ``` #### I2C read/write waveforms required by AT24C08SC chip manual * I2C write waveform\ -![alt text](assets/i2c_byte_write.png) + ![alt text](assets/i2c_byte_write.png) * I2C read waveform\ -![alt text](assets/i2c_random_read.png) + ![alt text](assets/i2c_random_read.png) #### Partial waveforms captured by logic analyzer -* I2C write waveform -![alt text](assets/i2c_w.png) -* I2C read waveform -![alt text](assets/i2c_r.png) - +* I2C write waveform ![alt text](assets/i2c_w.png) +* I2C read waveform ![alt text](assets/i2c_r.png) #### I2C Parameter Modification * See comments in EEPROM_init function @@ -130,65 +140,67 @@ Switch to the example `project/build_xx` directory and run `download.bat`, the p unsigned char EEPROM_init(void) { - uint8_t slaveAddr = EEPROM_I2C_ADDRESS; // 7bit address of device + uint8_t slaveAddr = EEPROM_I2C_ADDRESS; // 7-bit device address HAL_StatusTypeDef ret; - //1. pin mux + // 1. Pin Multiplexing (Pin Mux) #ifdef SF32LB52X - HAL_PIN_Set(PAD_PA41, I2C2_SCL, PIN_PULLUP, 1); // i2c io select + HAL_PIN_Set(PAD_PA41, I2C2_SCL, PIN_PULLUP, 1); // Select I2C IO HAL_PIN_Set(PAD_PA42, I2C2_SDA, PIN_PULLUP, 1); #elif defined(SF32LB58X) - HAL_PIN_Set(PAD_PB28, I2C6_SCL, PIN_PULLUP, 1); // i2c io select + HAL_PIN_Set(PAD_PB28, I2C6_SCL, PIN_PULLUP, 1); // Select I2C IO HAL_PIN_Set(PAD_PB29, I2C6_SDA, PIN_PULLUP, 1); #endif - // 2. i2c init - // find i2c2 + // 2. I2C Initialization + // Locate I2C bus #ifdef SF32LB52X i2c_bus = rt_i2c_bus_device_find("i2c2"); #elif defined(SF32LB58X) i2c_bus = rt_i2c_bus_device_find("i2c6"); #endif - rt_kprintf("i2c_bus:0x%x\n", i2c_bus); + rt_kprintf("i2c_bus: 0x%x\n", i2c_bus); if (i2c_bus) { #ifdef SF32LB52X - rt_kprintf("Find i2c bus device I2C2\n"); + rt_kprintf("Found I2C bus device: I2C2\n"); #elif defined(SF32LB58X) - rt_kprintf("Find i2c bus device I2C6\n"); + rt_kprintf("Found I2C bus device: I2C6\n"); #endif - // open rt_device i2c2 + // Open I2C device with read/write access rt_device_open((rt_device_t)i2c_bus, RT_DEVICE_FLAG_RDWR); //rt_i2c_open(i2c_bus, RT_DEVICE_FLAG_RDWR); struct rt_i2c_configuration configuration = { .mode = 0, .addr = 0, - .timeout = 500, //Waiting for timeout period (ms) - .max_hz = 400000, //I2C rate (hz) + .timeout = 500, // Timeout period in ms + .max_hz = 400000, // I2C clock frequency in Hz }; - // config I2C parameter - rt_i2c_configure(i2c_bus, &configuration); + // Configure I2C parameters + rt_i2c_configure(i2c_bus, &configuration); } else { #ifdef SF32LB52X - LOG_E("Can not found i2c bus I2C2, init fail\n"); + LOG_E("Failed to find I2C bus: I2C2. Initialization failed.\n"); #elif defined(SF32LB58X) - LOG_E("Can not found i2c bus I2C6, init fail\n"); + LOG_E("Failed to find I2C bus: I2C6. Initialization failed.\n"); #endif return -1; } return 0; } ``` -* When opening rt_device device, if using rt_i2c_open function, no functional issues are found, but when using `list_device`, `i2c2` will not show open status: +* When opening rt_device device, if using rt_i2c_open function, no functional + issues are found, but when using `list_device`, `i2c2` will not show open + status: ```c rt_i2c_open(i2c_bus, RT_DEVICE_FLAG_RDWR); ``` ```c - msh /> +msh /> TX:list_device list_device device type ref count @@ -207,14 +219,14 @@ rt_i2c_open(i2c_bus, RT_DEVICE_FLAG_RDWR); btim1 Timer Device 0 uart1 Character Device 2 pin Miscellaneous Device 0 - msh /> + msh /> ``` When using `rt_device_open`: ```c rt_device_open((rt_device_t)i2c_bus, RT_DEVICE_FLAG_RDWR); ``` ```c - msh /> +msh /> TX:list_device list_device device type ref count @@ -232,58 +244,65 @@ rt_device_open((rt_device_t)i2c_bus, RT_DEVICE_FLAG_RDWR); lptim1 Timer Device 0 btim1 Timer Device 0 uart1 Character Device 2 - pin Miscellaneous Device 0 + pin Miscellaneous Device 0 ``` -* This only demonstrates one usage of I2C. When the waveform required by I2C peripheral is inconsistent with the example, you can refer to the usage of rt_i2c_transfer function. +* This only demonstrates one usage of I2C. When the waveform required by I2C + peripheral is inconsistent with the example, you can refer to the usage of + rt_i2c_transfer function. -**Note**: -1. Except for SF32LB55x chips, all PA ports support HCPU I2C SDA and SCL functions, all PB ports support LCPU I2C SDA and SCL functions -2. HCPU PA ports cannot be configured for LCPU I2C instances, and LCPU PB ports cannot be configured for HCPU I2C usage. -For example, I2C5 is an LCPU I2C instance, its SCL and SDA pins cannot be mapped to PA ports -3. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +**Note**: +1. Except for SF32LB55x chips, all PA ports support HCPU I2C SDA and SCL + functions, all PB ports support LCPU I2C SDA and SCL functions +2. HCPU PA ports cannot be configured for LCPU I2C instances, and LCPU PB ports + cannot be configured for HCPU I2C usage. For example, I2C5 is an LCPU I2C + instance, its SCL and SDA pins cannot be mapped to PA ports +3. The last parameter of HAL_PIN_Set is for hcpu/lcpu selection, 1: select hcpu, + 0: select lcpu ## Exception Diagnosis * No I2C waveform output -1. Use `pin status 39` command to check the corresponding PA39, PA40 IO status FUNC is correct, VAL level should be 1 +1. Use `pin status 39` command to check the corresponding PA39, PA40 IO status + FUNC is correct, VAL level should be 1 ``` - msh /> +msh /> TX:pin status 39 pin status 39 [32m][215653658] I/TEST.GPIO: PIN 39, FUNC=4, VAL=1, DIG_IO_PU, GPIO_MODE_INPUT, irqhdr=/, arg=/ [0m] - msh /> - msh /> + msh /> + msh /> TX:pin status 40 pin status 40 [32m][215753678] I/TEST.GPIO: PIN 40, FUNC=4, VAL=1, DIG_IO_PU, GPIO_MODE_INPUT, irqhdr=/, arg=/ [0m] - msh /> - msh /> + msh /> + msh /> ``` 2. Use 'list_device' command to check if 'i2c2' device exists and is opened 3. Check if IO configuration and connection are correct * Continuous write failure, I2C waveform normal, no acknowledgment signal -1. AT24C08SC write input requires up to 5ms Write Cycle Time waiting for data programming +1. AT24C08SC write input requires up to 5ms Write Cycle Time waiting for data + programming ```c void EEPROM_test(void) { unsigned char i = 0; - for ( i = 0; i < 4; i++) + for ( i = 0; i < 4; i++) { EEPROM_write_data(TEST_ADDR[i], TEST_DATA[i]); - delayms(5); //5ms delay for AT240C8SC write time cycle + delayms(5); // 5ms delay to satisfy AT24C08SC write cycle duration } - for ( i = 0; i < 4; i++) + for ( i = 0; i < 4; i++) { - EEPROM_read_data(TEST_ADDR[i], &RECEIVED); + EEPROM_read_data(TEST_ADDR[i], &RECEIVED); } } ``` ## Reference Documents * [AT24C08SC](./assets/at24c02sc.pdf) ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | diff --git a/example/rt_device/i2c/index_EN.md b/example/rt_device/i2c/index_EN.md index 7fd865d3f..bee0ebc66 100644 --- a/example/rt_device/i2c/index_EN.md +++ b/example/rt_device/i2c/index_EN.md @@ -4,7 +4,4 @@ :glob: */* - - - ``` diff --git a/example/rt_device/i2s/README_EN.md b/example/rt_device/i2s/README_EN.md index 7c3abc867..ff79113e0 100644 --- a/example/rt_device/i2s/README_EN.md +++ b/example/rt_device/i2s/README_EN.md @@ -3,55 +3,62 @@ Source path: example/rt_device/i2s ## Supported Platforms - + + sf32lb52-nano + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -In this example, two development boards are used to demonstrate I2S transmission and reception (one development board A as tx, one development board B as rx), including: + +In this example, two development boards are used to demonstrate I2S transmission +and reception (one development board A as tx, one development board B as rx), +including: + Development board A: - mic recording. - Send to development board B via i2s. -+ Development board B: ++ Development board A: - Receive data from development board A via i2s. - speaker playback. -* Due to the special nature of the sf32lb58-lcd board, it can only function as a master when using I2S. Therefore, the sf32lb52-lcd and sf32lb56-lcd boards need to be used as slaves for testing. The master device records audio and sends it to the slaves via I2S for playback. + +* Due to the special nature of the sf32lb58-lcd board, it can only function as a + master when using I2S. Therefore, the sf32lb52-lcd and sf32lb56-lcd boards + need to be used as slaves for testing. The master device records audio and + sends it to the slaves via I2S for playback. ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ Two development boards supported by this example ([Supported platforms](quick_start)). ++ Two development boards supported by this example ([Supported + platforms](quick_start)). + Speaker. + Two data cables (used for program flashing of the two boards respectively). ### menuconfig Configuration -1. Enable I2S -![AUDIO CODEC & PROC](./assets/mc_i2s.png) -![AUDIO CODEC & PROC](./assets/mc_i2s_codec.png) +1. Enable I2S ![AUDIO CODEC & PROC](./assets/mc_i2s.png) ![AUDIO CODEC & + PROC](./assets/mc_i2s_codec.png) ```{tip} If the chip supports multiple I2S, configure according to actual usage. ``` -2. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) +2. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) -3. This example uses FINSH functionality, need to enable `RT_USING_FINSH`. +3. This example uses FINSH functionality, need to enable `RT_USING_FINSH`. ```{tip} Configurations 2 and 3 are used for auxiliary function demonstration in this example, not necessary for I2S configuration. -``` +``` ### Hardware Connection\PIN CONFIG -Taking `SF32LB52_DevKit-LCD` as an example, this example uses `PA02 ~ PA06` as I2S pins, pin configuration is as follows: +Taking `SF32LB52_DevKit-LCD` as an example, this example uses `PA02 ~ PA06` as +I2S pins, pin configuration is as follows: ```c - /* PIN CONFIG */ +/* PIN CONFIG */ #ifdef BSP_ENABLE_I2S_CODEC #ifdef SOC_SF32LB52X HAL_PIN_Set(PAD_PA06, I2S1_LRCK, PIN_NOPULL, 1); @@ -63,7 +70,8 @@ Taking `SF32LB52_DevKit-LCD` as an example, this example uses `PA02 ~ PA06` as I #endif ``` -If you need to use other development board models, you need to change the pinmux configuration. Here is an example for 56x and 58x models: +If you need to use other development board models, you need to change the pinmux +configuration. Here is an example for 56x and 58x models: ```c #ifdef SOC_SF32LB56X HAL_PIN_Set(PAD_PA71, I2S1_LRCK, PIN_NOPULL, 1); @@ -82,22 +90,25 @@ If you need to use other development board models, you need to change the pinmux ``` Wiring: -Development board A | -- | Development board B ---|--|-- -I2S1_LRCK|--|I2S1_LRCK -I2S1_BCK|--|I2S1_BCK -I2S1_SDI|--|I2S1_SDO -I2S1_SDO|--|I2S1_SDI -I2S1_MCLK|--|I2S1_MCLK - -Since `sf32lb58-lcd` is rather special, when connecting the wires here, 58 should be used as A (master), and `sf32lb52-lcd` should be used as B (slave) for the connection. -If you are unsure about pin positioning, you can refer to the following figures: -SF32LB52x_DevKit_40p diagram: -![AUDIO CODEC & PROC](./assets/52x.png) -SF32LB56x_DevKit_40p diagram: -![AUDIO CODEC & PROC](./assets/56x.png) - -[SF32LB58x_DevKitPin Definition Diagram](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) +| Development board A | -- | Development board B | +| ------------------- | --- | ------------------- | +| I2S1_LRCK | -- | I2S1_LRCK | +| I2S1_BCK | -- | I2S1_BCK | +| I2S1_SDI | -- | I2S1_SDO | +| I2S1_SDO | -- | I2S1_SDI | +| I2S1_MCLK | -- | I2S1_MCLK | + +Since `sf32lb58-lcd` is rather special, when connecting the wires here, 58 +should be used as A (master), and `sf32lb52-lcd` should be used as B (slave) for +the connection. If you are unsure about pin positioning, you can refer to the +following figures: SF32LB52x_DevKit_40p diagram: ![AUDIO CODEC & PROC]{1} +SF32LB56x_DevKit_40p diagram: ![AUDIO CODEC & PROC]{2} + +[SF32LB58x_DevKitPin Definition Diagram](./assets/52x.png) + +[SF32LB58x_DevKit Pin Definition +Diagram](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) + ```{warning} On `SF32LB52_DevKit-LCD`: + `PA02 ~ PA06` will be used when LCD is configured, pay attention to conflicts (need to disable LCD: `BSP_USING_LCD = n BSP_USING_LCDC = n`). @@ -106,11 +117,13 @@ For other form factors, you need to refer to the specification to select pins. ``` ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```shell -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```shell $ ./uart_download.bat @@ -118,24 +131,24 @@ $ ./uart_download.bat please input the serial port num:5 (Board A port number) ``` -Flash board B again -$ ./uart_download.bat +Flash board B again $ ./uart_download.bat - Uart Download + UART Download please input the serial port num:6 (Board B port number) -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - + This example operates through FINSH commands: -Purpose | Command | Example |Notes -|---|--|--|--| -Recording|audprc rx [channels:1/2] [sampling rate] [sampling bits]|`audprc rx 1 16000 16` |Recording is saved to ram buffer (recording automatically stops after reaching 1M) -I2S transmission|i2s tx [tx channels:1/2] [tx sampling rate] [tx sampling bits]|`i2s tx 1 16000 16`|Send recorded data in ram buffer via i2s. `The example is configured in master mode by default.` Configuration method can be seen in `i2s_config_tx`. -I2S reception|i2s rx [rx channels:1/2] [rx sampling rate] [rx sampling bits]|`i2s rx 1 16000 16`|Received data is saved to ram buffer (stops receiving after reaching 1M). `The example is configured in slave mode by default.` Configuration method can be seen in `i2s_config_rx`. -Playback recording|audprc tx [channels:1/2] [sampling rate] [sampling bits]|`audprc tx 1 16000 16`| Playback data from ram buffer +| Purpose | Command | Example | Notes | +| ------------------ | -------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Recording | audprc rx [channels:1/2] [sampling rate] [sampling bits] | `audprc rx 1 16000 16` | Recording is saved to ram buffer (recording automatically stops after reaching 1M) | +| I2S transmission | i2s tx [tx channels:1/2] [tx sampling rate] [tx sampling bits] | `i2s tx 1 16000 16` | Send recorded data in ram buffer via i2s. `The example is configured in master mode by default.` Configuration method can be seen in `i2s_config_tx`. | +| I2S reception | i2s rx [rx channels:1/2] [rx sampling rate] [rx sampling bits] | `i2s rx 1 16000 16` | Received data is saved to ram buffer (stops receiving after reaching 1M). `The example is configured in slave mode by default.` Configuration method can be seen in `i2s_config_rx`. | +| Playback recording | audprc tx [channels:1/2] [sampling rate] [sampling bits] | `audprc tx 1 16000 16` | Playback data from ram buffer | Operations are as follows: 1. Development board A, record an audio clip. @@ -172,9 +185,9 @@ Operations are as follows: 01-03 00:51:03:854 [I/drv.audprc] bf0_audio_stop 0x1001 ``` -2. I2S transmission and reception +2. I2S transmission and reception - Development board A starts I2S transmission + Development board A starts I2S transmission ```c 01-03 00:51:44:552 TX:i2s tx 1 16000 16 01-03 00:51:44:577 [EX_I2S]I2S TX: @@ -189,7 +202,7 @@ Operations are as follows: 01-03 00:52:00:957 [EX_I2S]I2S TX finished. 01-03 00:52:00:962 [EX_I2S]i2s_stop_tx ``` - `At the same time`, development board B starts I2S reception + `At the same time`, development board B starts I2S reception ```c 01-03 00:51:43:833 TX:i2s rx 1 16000 16 01-03 00:51:43:865 [EX_I2S]I2S RX. @@ -210,7 +223,7 @@ Operations are as follows: 3. Development board B plays the received data ``` - 01-03 00:52:13:543 TX:audprc tx 1 16000 16 +01-03 00:52:13:543 TX:audprc tx 1 16000 16 01-03 00:52:13:591 [EX_I2S]audprc_tx_entry 01-03 00:52:13:600 [EX_I2S]prc_codec : sub_type=1 channel 1, samplerate 16000, bits 16 01-03 00:52:13:604 [EX_I2S]speaker OUTPUTSRC channel=1 in_rate=16000 out_rate=16000 @@ -258,4 +271,5 @@ Operations are as follows: |:---|:---|:---| |0.0.1 |12/2024 |Initial version | | | | | -| | | | \ No newline at end of file +| | | | +``` diff --git a/example/rt_device/index_EN.md b/example/rt_device/index_EN.md index e1a52e1ce..322b95c06 100644 --- a/example/rt_device/index_EN.md +++ b/example/rt_device/index_EN.md @@ -1,11 +1,11 @@ # RT-Thread Device Driver -This example demonstrates how to access hardware modules using RT-Thread device driver interfaces. +This example demonstrates how to access hardware modules using RT-Thread device +driver interfaces. ```{toctree} :titlesonly: :glob: */* - ``` diff --git a/example/rt_device/motor/README_EN.md b/example/rt_device/motor/README_EN.md index 2140a29a9..0901d4ef1 100644 --- a/example/rt_device/motor/README_EN.md +++ b/example/rt_device/motor/README_EN.md @@ -1,77 +1,102 @@ # Motor Encoder Drive Example (RT-Thread) -[English](README_EN.md) | [中文](README.md) +[English](README_EN.md) | [Simplified Chinese](README.md) Source path: example/motor ## Overview -This example demonstrates the complete flow to drive and control a pair of DC gear motors on RT-Thread. It includes: +This example demonstrates the complete flow to drive and control a pair of DC +gear motors on RT-Thread. It includes: - Reading motor speed/position using pulse encoders. - Controlling motor duty cycle and direction using PWM outputs. -- Implementing PID control for speed and position loops (including an anti-windup variant). +- Implementing PID control for speed and position loops (including an + anti-windup variant). - Providing a finsh Finsh command (`motor`) for real-time control and debugging. ### Brief on the PID algorithm -This example uses classic PID controllers for both the speed and position loops. The PID controller produces a control signal based on the error between the setpoint and the measured value to drive the PWM duty. The continuous-time PID expression is: +This example uses classic PID controllers for both the speed and position loops. +The PID controller produces a control signal based on the error between the +setpoint and the measured value to drive the PWM duty. The continuous-time PID +expression is: -$$ -u(t)=K_P e(t) + K_I \int_0^{t} e(\tau)\,d\tau + K_D \frac{d e(t)}{d t} -$$ +$$ u(t)=K_P e(t) + K_I \int_0^{t} e(\tau)\,d\tau + K_D \frac{d e(t)}{d t} $$ -where $e(t)=r(t)-y(t)$ is the error between setpoint $r(t)$ and process variable $y(t)$, and $K_P,K_I,K_D$ are the proportional, integral and derivative gains respectively. +where $e(t)=r(t)-y(t)$ is the error between setpoint $r(t)$ and process variable +$y(t)$, and $K_P,K_I,K_D$ are the proportional, integral and derivative gains +respectively. -In embedded sampled implementations, a discrete form is commonly used (with sampling period $T_s$ and sample index $k$): +In embedded sampled implementations, a discrete form is commonly used (with +sampling period $T_s$ and sample index $k$): -$$ -u[k]=K_P e[k] + K_I T_s \sum_{i=0}^{k} e[i] + K_D \frac{e[k]-e[k-1]}{T_s} -$$ +$$ u[k]=K_P e[k] + K_I T_s \sum_{i=0}^{k} e[i] + K_D \frac{e[k]-e[k-1]}{T_s} $$ or in recursive form: -$$ -u[k]=K_P e[k] + I[k] + K_D \frac{e[k]-e[k-1]}{T_s},\qquad I[k]=I[k-1]+K_I T_s e[k] -$$ +$$ u[k]=K_P e[k] + I[k] + K_D \frac{e[k]-e[k-1]}{T_s},\qquad I[k]=I[k-1]+K_I T_s +e[k] $$ -Anti-windup strategy: when the drive signal $u[k]$ exceeds the actuator limits (e.g. PWM duty range 0~100%), the output should be saturated and the integral accumulation stopped or adjusted to prevent further growth of the integral term which could cause overshoot. A common simple method is integral clamping: +Anti-windup strategy: when the drive signal $u[k]$ exceeds the actuator limits +(e.g. PWM duty range 0~100%), the output should be saturated and the integral +accumulation stopped or adjusted to prevent further growth of the integral term +which could cause overshoot. A common simple method is integral clamping: 1) Compute the unsaturated control (including all terms); 2) Clip the control to the allowed range; -3) If clipping occurred, do not update or conditionally update the integral term (only accumulate when not saturated or when the error direction helps reduce saturation). +3) If clipping occurred, do not update or conditionally update the integral term + (only accumulate when not saturated or when the error direction helps reduce + saturation). -Tuning tips: start with $K_I=0, K_D=0$ and increase $K_P$ until acceptable response speed; then add $K_I$ to eliminate steady-state error; finally tune $K_D$ to reduce overshoot and oscillation. Speed loop sampling is typically higher (tens to hundreds of Hz), while position loop sampling can be lower; the position loop usually acts as an outer loop around the speed loop. +Tuning tips: start with $K_I=0, K_D=0$ and increase $K_P$ until acceptable +response speed; then add $K_I$ to eliminate steady-state error; finally tune +$K_D$ to reduce overshoot and oscillation. Speed loop sampling is typically +higher (tens to hundreds of Hz), while position loop sampling can be lower; the +position loop usually acts as an outer loop around the speed loop. ### Quadrature encoder -This example uses incremental quadrature encoders (A/B two channels) for measuring motor speed and position. The encoder outputs two square waves approximately 90° out of phase; counters count A/B pulses to obtain incremental counts. +This example uses incremental quadrature encoders (A/B two channels) for +measuring motor speed and position. The encoder outputs two square waves +approximately 90° out of phase; counters count A/B pulses to obtain incremental +counts. Wiring -- Use `ENC1A_PIN` / `ENC1B_PIN` for encoder 1 A/B channels; use `ENC2A_PIN` / `ENC2B_PIN` for encoder 2 (see the hardware connections table below). +- Use `ENC1A_PIN` / `ENC1B_PIN` for encoder 1 A/B channels; use `ENC2A_PIN` / + `ENC2B_PIN` for encoder 2 (see the hardware connections table below). Sampling window and counting -- The code reads and resets the encoder counters in the main loop at a fixed window (the main loop uses wake_time += 20), the window is about 20 ms (0.02 s). -- Therefore the input `pulse` to `pulse_to_rpm(int32_t pulse)` is the pulse increment measured during this 20 ms window. +- The code reads and resets the encoder counters in the main loop at a fixed + window (the main loop uses wake_time += 20), the window is about 20 ms (0.02 + s). +- Therefore the input `pulse` to `pulse_to_rpm(int32_t pulse)` is the pulse + increment measured during this 20 ms window. Pulse to RPM conversion -- Convert pulses in the window to pulses per second: pulses_per_second = pulse / 0.02 = pulse * 50 -- Convert pulses per second to rotational speed using pulses per revolution (PPR, accounting for encoder resolution, gearbox ratio and quadrature x4 counting): +- Convert pulses in the window to pulses per second: pulses_per_second = pulse / + 0.02 = pulse * 50 +- Convert pulses per second to rotational speed using pulses per revolution + (PPR, accounting for encoder resolution, gearbox ratio and quadrature x4 + counting): rpm = pulses_per_second / PPR * 60 = pulse * 50 / PPR * 60 -- The inverse conversion (converting a target RPM to pulses within the time window, used for mapping) is: +- The inverse conversion (converting a target RPM to pulses within the time + window, used for mapping) is: pulse = (int)(rpm / 60 * PPR / 50) PPR origin -- In this example, total PPR is determined by three parts: encoder's PPR, gearbox ratio and quadrature x4 counting. The formula is: +- In this example, total PPR is determined by three parts: encoder's PPR, + gearbox ratio and quadrature x4 counting. The formula is: total_ppr = encoder_ppr * gearbox_ratio * 4 -- With example hardware parameters: encoder_ppr = 13, gearbox_ratio = 20.409, we get: +- With example hardware parameters: encoder_ppr = 13, gearbox_ratio = 20.409, we + get: total_ppr = 13 * 20.409 * 4 = 1061.268 @@ -87,18 +112,21 @@ Example Notes -- Pulse direction: the code uses signed pulse values to represent direction (positive/negative). The command interface accepts a `dir` parameter to set the target direction (sign). -- Replace the PPR values according to your encoder and gearbox. For precision, consult the encoder datasheet or measure it practically. -- If the signal is noisy or bouncy, consider hardware filtering or software debouncing, moving average or low-pass filtering to improve speed calculation stability. +- Pulse direction: the code uses signed pulse values to represent direction + (positive/negative). The command interface accepts a `dir` parameter to set + the target direction (sign). +- Replace the PPR values according to your encoder and gearbox. For precision, + consult the encoder datasheet or measure it practically. +- If the signal is noisy or bouncy, consider hardware filtering or software + debouncing, moving average or low-pass filtering to improve speed calculation + stability. ## Usage -After the program starts, control the motors via the serial console. -The finsh command format is: motor dir spd num -Parameters: direction, speed, number of rotations. -Direction (dir): 0 = forward, 1 = reverse -Speed (spd): in rpm (revolutions per minute) -Number of rotations (num): total rotations; set to 0 for continuous run -Examples: +After the program starts, control the motors via the serial console. The finsh +command format is: motor dir spd num Parameters: direction, speed, number of +rotations. Direction (dir): 0 = forward, 1 = reverse Speed (spd): in rpm +(revolutions per minute) Number of rotations (num): total rotations; set to 0 +for continuous run Examples: - `motor 0 120 10` means forward, 120 rpm, 10 rotations - `motor 1 180 12` means reverse, 180 rpm, 12 rotations @@ -108,46 +136,66 @@ This example can run on the following development boards: ### Hardware reference -- Motor: MG310 with gearbox; gearbox ratio 1:20.409; no-load speed ≈ 300 rpm; rated voltage 7.4V. +- Motor: MG310 with gearbox; gearbox ratio 1:20.409; no-load speed ≈ 300 rpm; + rated voltage 7.4V. - Encoder: Hall-effect quadrature encoder, PPR = 13. -- Driver: TB6612FNG (dual low-voltage driver, common TB6612 modules) — small size and simple drive; rated continuous current typically ≤ 1~2 A (higher peak), suitable for small gear motors. -- Others: jumper wires (Dupont), regulator/power module capable of supplying sufficient stall current, oscilloscope/multimeter for debugging when needed. +- Driver: TB6612FNG (dual low-voltage driver, common TB6612 modules) — small + size and simple drive; rated continuous current typically ≤ 1~2 A (higher + peak), suitable for small gear motors. +- Others: jumper wires (Dupont), regulator/power module capable of supplying + sufficient stall current, oscilloscope/multimeter for debugging when needed. ### Hardware connections Development board to driver: -| Function | Macro | Pin # | Pin name | -|:---|:---:|:---:|:---:| -| PWM A output | `PWMA_PIN` | 36 | PA36 | -| PWM B output | `PWMB_PIN` | 41 | PA41 | -| AIN1 (left motor direction) | `AIN1_PIN` | 44 | PA44 | -| AIN2 (left motor direction) | `AIN2_PIN` | 35 | PA35 | -| STBY (enable) | `STBY_PIN` | 43 | PA43 | -| BIN1 (right motor direction) | `BIN1_PIN` | 42 | PA42 | -| BIN2 (right motor direction) | `BIN2_PIN` | 40 | PA40 | +| Function | Macro | Pin # | Pin name | +| ---------------------------- | :--------: | :---: | :------: | +| PWM A output | `PWMA_PIN` | 36 | PA36 | +| PWM B output | `PWMB_PIN` | 41 | PA41 | +| AIN1 (left motor direction) | `AIN1_PIN` | 44 | PA44 | +| AIN2 (left motor direction) | `AIN2_PIN` | 35 | PA35 | +| STBY (enable) | `STBY_PIN` | 43 | PA43 | +| BIN1 (right motor direction) | `BIN1_PIN` | 42 | PA42 | +| BIN2 (right motor direction) | `BIN2_PIN` | 40 | PA40 | Development board to encoders: -| Function | Macro | Pin # | Pin name | -|:---|:---:|:---:|:---:| -| Encoder1 A | `ENC1A_PIN` | 38 | PA38 | -| Encoder1 B | `ENC1B_PIN` | 37 | PA37 | -| Encoder2 A | `ENC2A_PIN` | 39 | PA39 | -| Encoder2 B | `ENC2B_PIN` | 30 | PA30 | +| Function | Macro | Pin # | Pin name | +| ---------- | :---------: | :---: | :------: | +| Encoder1 A | `ENC1A_PIN` | 38 | PA38 | +| Encoder1 B | `ENC1B_PIN` | 37 | PA37 | +| Encoder2 A | `ENC2A_PIN` | 39 | PA39 | +| Encoder2 B | `ENC2B_PIN` | 30 | PA30 | Driver to motors: - Left motor: M+ to driver AO1, M- to AO2 - Right motor: M+ to driver BO2, M- to BO1 -**Note**: adjust wiring and the pin macros in the code to match your actual hardware (for example, pin macros, PWM polarity, enable/direction mapping, power requirements, etc.). - -**Note (configuration and migration guide)**: if you use different motor/driver models, check and modify the code following these points: - -- Pins and macros: update the pin macros at the top of the file (e.g. `PWMA_PIN`, `PWMB_PIN`, `AIN1_PIN`, `AIN2_PIN`, `STBY_PIN`, `ENC1A_PIN`, `ENC1B_PIN`, `ENC2A_PIN`, `ENC2B_PIN`) to match your wiring. -- PWM polarity and frequency: some drivers require specific PWM polarity (active-high or active-low) or frequency. If the output direction is reversed from expected, invert duty logic or swap high/low mappings; adjust timer PWM frequency if needed. -- Enable/standby and direction signals: confirm the polarity (active-high/active-low) of the driver enable and direction signals. If different, invert the corresponding control logic or pin outputs in the driver code. -- Power and grounding: ensure motor/driver power can supply sufficient stall current and share ground with the MCU. Incorrect power or missing common ground may cause drive failures or incorrect encoder readings. -- Hall encoder interface: Hall sensors may need pull-ups or filtering; verify encoder supply and MCU logic levels (3.3V vs 5V); use level shifting or isolation if necessary. -- Protection and cooling: check driver current rating and heat dissipation; add heatsinks or current-limiting protection (fuses, current sensing) if needed. +**Note**: adjust wiring and the pin macros in the code to match your actual +hardware (for example, pin macros, PWM polarity, enable/direction mapping, power +requirements, etc.). + +**Note (configuration and migration guide)**: if you use different motor/driver +models, check and modify the code following these points: + +- Pins and macros: update the pin macros at the top of the file (e.g. + `PWMA_PIN`, `PWMB_PIN`, `AIN1_PIN`, `AIN2_PIN`, `STBY_PIN`, `ENC1A_PIN`, + `ENC1B_PIN`, `ENC2A_PIN`, `ENC2B_PIN`) to match your wiring. +- PWM polarity and frequency: some drivers require specific PWM polarity + (active-high or active-low) or frequency. If the output direction is reversed + from expected, invert duty logic or swap high/low mappings; adjust timer PWM + frequency if needed. +- Enable/standby and direction signals: confirm the polarity + (active-high/active-low) of the driver enable and direction signals. If + different, invert the corresponding control logic or pin outputs in the driver + code. +- Power and grounding: ensure motor/driver power can supply sufficient stall + current and share ground with the MCU. Incorrect power or missing common + ground may cause drive failures or incorrect encoder readings. +- Hall encoder interface: Hall sensors may need pull-ups or filtering; verify + encoder supply and MCU logic levels (3.3V vs 5V); use level shifting or + isolation if necessary. +- Protection and cooling: check driver current rating and heat dissipation; add + heatsinks or current-limiting protection (fuses, current sensing) if needed. Suggested modification order: 1) Update pin macros and build to confirm no syntax errors; @@ -158,58 +206,51 @@ Suggested modification order: ### Build and flash Switch to the example `project` directory and run scons to build: - -```powershell +``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run the uart download batch in the matching build folder and follow the prompts to select the port: +Run the uart download batch in the matching build folder and follow the prompts +to select the port: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ## Example output - -motor 0 120 10 -Motor command set: - Direction: Forward - Speed: 120 rpm - Rotations: 10 -msh />left speed: 113.072289 rpm, right speed: 113.072289 rpm. -left speed: 118.725899 rpm, right speed: 118.725899 rpm. -left speed: 118.725899 rpm, right speed: 121.552711 rpm. -left speed: 115.899094 rpm, right speed: 115.899094 rpm. -left speed: 118.725899 rpm, right speed: 115.899094 rpm. -left speed: -5.653615 rpm, right speed: 0.000000 rpm. -left speed: 0.000000 rpm, right speed: 0.000000 rpm. - -motor 1 180 12 -Motor command set: - Direction: Reverse - Speed: 180 rpm - Rotations: 12 -msh />left speed: -172.435242 rpm, right speed: -175.262039 rpm. -left speed: -178.088852 rpm, right speed: -178.088852 rpm. -left speed: -175.262039 rpm, right speed: -175.262039 rpm. -left speed: -178.088852 rpm, right speed: -180.915665 rpm. -left speed: 0.000000 rpm, right speed: 0.000000 rpm. -left speed: 0.000000 rpm, right speed: 0.000000 rpm. +motor 0 120 10 Motor command set: Direction: Forward Speed: 120 rpm Rotations: +10 msh />left speed: 113.072289 rpm, right speed: 113.072289 rpm. left speed: +118.725899 rpm, right speed: 118.725899 rpm. left speed: 118.725899 rpm, right +speed: 121.552711 rpm. left speed: 115.899094 rpm, right speed: 115.899094 rpm. +left speed: 118.725899 rpm, right speed: 115.899094 rpm. left speed: -5.653615 +rpm, right speed: 0.000000 rpm. left speed: 0.000000 rpm, right speed: 0.000000 +rpm. + +motor 1 180 12 Motor command set: Direction: Reverse Speed: 180 rpm Rotations: +12 msh />left speed: -172.435242 rpm, right speed: -175.262039 rpm. left speed: +-178.088852 rpm, right speed: -178.088852 rpm. left speed: -175.262039 rpm, +right speed: -175.262039 rpm. left speed: -178.088852 rpm, right speed: +-180.915665 rpm. left speed: 0.000000 rpm, right speed: 0.000000 rpm. left +speed: 0.000000 rpm, right speed: 0.000000 rpm. ## Troubleshooting If the motor does not spin or the speed is abnormal, check the following: 1. Verify power connections, voltage and current meet the motor requirements. 2. Check motor wiring, especially PWM and direction control pins. -3. Confirm encoder wiring and that A/B channels are connected to the correct pins. +3. Confirm encoder wiring and that A/B channels are connected to the correct + pins. -If the problem persists after these checks, please open an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +If the problem persists after these checks, please open an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## References -- [SiFli-SDK Quickstart](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) -- [SiFli-SDK Development Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) +- [SiFli-SDK + Quickstart](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html) +- [SiFli-SDK Development + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/development/index.html) diff --git a/example/rt_device/nand_flash/README_EN.md b/example/rt_device/nand_flash/README_EN.md index f0e3a375b..0506900a1 100644 --- a/example/rt_device/nand_flash/README_EN.md +++ b/example/rt_device/nand_flash/README_EN.md @@ -5,25 +5,35 @@ Source path: SiFli-SDK\example\rt_device\nand_flash * sf32lb58-lcd_a128r32n1 ## Overview -The nand_flash example is used to demonstrate the RT-Thread layer's NAND read, write, and erase function interfaces. +The nand_flash example is used to demonstrate the RT-Thread layer's NAND read, +write, and erase function interfaces. -Before compilation, you need to configure the corresponding controller as a NAND interface. When the system starts, it will initialize NAND and perform bad block management information initialization (applications do not need to pay attention to this part). +Before compilation, you need to configure the corresponding controller as a NAND +interface. When the system starts, it will initialize NAND and perform bad block +management information initialization (applications do not need to pay attention +to this part). -NAND erase operations must be performed with block alignment (including address and length). The block size can be obtained through the interface. +NAND erase operations must be performed with block alignment (including address +and length). The block size can be obtained through the interface. + +NAND write operations must be performed with page alignment (including address +and length). The page size can be obtained through the interface. Read +operations are recommended to be page-aligned. -NAND write operations must be performed with page alignment (including address and length). The page size can be obtained through the interface. Read operations are recommended to be page-aligned. - ## Example Usage Taking sf32lb56-lcd_a128r12n1 as an example ### Compilation and Programming -* Compilation method: Switch to the project example project directory and run the scons command to compile the code: +* Compilation method: Switch to the project example project directory and run + the scons command to compile the code: ``` scons --board=board_name -j8 For example: scons --board=sf32lb56-lcd_a128r12n1 -j8 ``` -If the following error occurs during compilation, it means that the board participating in compilation is not a nand flash type board. -![alt text](assets/nand1.png) -* Download method: Enter the project directory and execute the build command to flash the compiled program +If the following error occurs during compilation, it means that the board +participating in compilation is not a nand flash type board. ![alt +text](assets/nand1.png) +* Download method: Enter the project directory and execute the build command to + flash the compiled program ``` build__hcpu\download.bat(uart_download.bat) : board name @@ -32,25 +42,38 @@ uart_download.bat: used for serial port programming For example: build_sf32lb56-lcd_a128r12n1_hcpu\download.bat ``` ### Example Output Display -First, get the NAND device handle based on the address and confirm whether the address is valid -If invalid, the log will print: ```Address 0x%x is not for NAND FLASH``` +First, get the NAND device handle based on the address and confirm whether the +address is valid If invalid, the log will print: ```Address 0x%x is not for NAND +FLASH``` + +Then get the NAND ID, total capacity (total size), page size (page size), block +size (block size) -Then get the NAND ID, total capacity (total size), page size (page size), block size (block size) +Then perform erase processing If erase fails, the log will print: ```Erase fail +at address 0x%x, res %d ``` -Then perform erase processing -If erase fails, the log will print: ```Erase fail at address 0x%x, res %d ``` +Check if erase is successful If the check is not all 1s, the log will print: +```"Data not 0xffffffff after erase at pos 0x%x ``` -Check if erase is successful -If the check is not all 1s, the log will print: ```"Data not 0xffffffff after erase at pos 0x%x ``` +Then generate random numbers and write them to all pages in the entire block If +it fails, the log will print: ```write page fail at pos 0x%x ``` -Then generate random numbers and write them to all pages in the entire block -If it fails, the log will print: ```write page fail at pos 0x%x ``` +Finally read and verify If the read data is inconsistent with the written data, +the log will print: ```"Read page fail at pos 0x ``` ```Read data not same to +source at pos 0x ``` ![alt text](assets/nand2.png) -Finally read and verify -If the read data is inconsistent with the written data, the log will print: ```"Read page fail at pos 0x ``` ```Read data not same to source at pos 0x ``` -![alt text](assets/nand2.png) ### Troubleshooting -If the log does not show the expected log and phenomena, you can troubleshoot from the following aspects: -* Whether the hardware connection is normal -* Check if the USB cable has data transmission capability -* Troubleshoot based on the information in the above log \ No newline at end of file +If the log does not show the expected log and phenomena, you can troubleshoot +from the following aspects: +```c +Write speed: 3121.95 KB/s (time: 41 ticks, pages: 64) +Write Ops: 64 pages, 1560.98 ops/sec +Read speed: 10666.67 KB/s (time: 12 ticks, pages: 128) +Read Ops: 128 pages, 10666.67 ops/sec +``` +### Troubleshooting +If the expected logs or behavior do not appear, troubleshoot the following +areas: +* Verify that hardware connections are secure. +* Ensure the USB cable supports data transmission. +* Troubleshoot based on the information provided in the logs above. diff --git a/example/rt_device/nnacc/README_EN.md b/example/rt_device/nnacc/README_EN.md index 1d53e64a3..35b9872ae 100644 --- a/example/rt_device/nnacc/README_EN.md +++ b/example/rt_device/nnacc/README_EN.md @@ -1,20 +1,23 @@ # NNACC Example - Source code path: example/hal/nnacc - ## Supported Platforms The example can run on the following development boards: * sf32lb58-lcd_a128r32n1_dsi ## Overview -NNACC (Neural Network Accelerator) is an abbreviation for a dedicated hardware module provided in Sifli chips, specifically designed to accelerate the following tasks: +NNACC (Neural Network Accelerator) is an abbreviation for a dedicated hardware +module provided in Sifli chips, specifically designed to accelerate the +following tasks: + Convolutional computation (Conv2D) + Depthwise separable convolution (Depthwise Conv2D) + Gaussian filtering + Other AI inference related operations -This example demonstrates: verifying whether the hardware accelerator on the chip can correctly execute depthwise separable convolution (Depthwise Convolution) operations. +This example demonstrates: verifying whether the hardware accelerator on the +chip can correctly execute depthwise separable convolution (Depthwise +Convolution) operations. + ## Example Usage ``` @@ -31,34 +34,37 @@ main() ``` ### Compilation and Flashing -Switch to the example project directory and run the scons command to compile (board=board type): +Switch to the example project directory and run the scons command to compile +(board=board type): ``` scons --board=sf32lb58-lcd_a128r32n1_dsi -j8 ``` -`build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat`, select the port as prompted for download: +`build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat`, select the port as +prompted for download: ``` build_sf32lb58-lcd_a128r32n1_dsi_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please enter the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and download, please refer to the relevant +introduction in [](/quickstart/get-started.md). ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example (supports nnacc) +Before running this example, you need to prepare a development board supported +by this example (supports nnacc) ``` **Note**: 1. In sf32lb58x, the large core defaults to using hwp_nnacc1, and the small core defaults to using hwp_nnacc2. For specific chip configuration, please check the corresponding register.h file 2. sf32lb56x only has one hwp_nnacc1 on the large core, and the small core has no nnacc. For specific chip configuration, please check the corresponding register.h file - ``` ### menuconfig Configuration -Enable NN_ACC switch -![](./assets/image.png) +Enable NN_ACC switch ![](./assets/image.png) + ### Verification Results #### Example output result display: @@ -76,15 +82,3 @@ HAL_NNACC_Start. Test passed: NNACC result is correct. msh /> ``` - -## Exception Diagnosis -If the expected log does not appear, you can troubleshoot from the following aspects: -* Whether the hardware supports nnacc -* Whether the corresponding switch is enabled in menuconfig - -## Reference Documentation - -## Update History -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |7/2025 |Initial version | \ No newline at end of file diff --git a/example/rt_device/nor_flash/README_EN.md b/example/rt_device/nor_flash/README_EN.md index 923ace9e4..47db59555 100644 --- a/example/rt_device/nor_flash/README_EN.md +++ b/example/rt_device/nor_flash/README_EN.md @@ -1,10 +1,16 @@ # nor_flash +Source path: example/rt_device/nor_flash ## Overview -nor_flash is used to demonstrate the RT-Thread layer's NOR FLASH read, write, and erase function interfaces. +nor_flash is used to demonstrate the RT-Thread layer's NOR FLASH read, write, +and erase function interfaces. -Before compilation, you need to configure the corresponding controller as a Nor interface. When the system starts, it will initialize Nor and perform bad block management information initialization. Applications do not need to pay attention to this part. +Before compilation, you need to configure the corresponding controller as a Nor +interface. When the system starts, it will initialize Nor and perform bad block +management information initialization. Applications do not need to pay attention +to this part. -NOR FLASH erase operations need to be 4KB aligned (including address and length). There are no requirements for read and write operations. +NOR FLASH erase operations need to be 4KB aligned (including address and +length). There are no requirements for read and write operations. ## Supported Platforms * sf32lb52-lcd_n16r8 @@ -14,13 +20,15 @@ NOR FLASH erase operations need to be 4KB aligned (including address and length) ## Example Usage Taking sf32lb56-lcd_n16r12n1 as an example ### Compilation and Programming -* Compilation method: Switch to the project example project directory and run the scons command to compile the code: +* Compilation method: Switch to the project example project directory and run + the scons command to compile the code: ``` scons --board=board_name -j8 For example: scons --board=sf32lb56-lcd_n16r12n1 -j8 ``` -* Download method: Enter the project directory and execute the build command to flash the compiled program +* Download method: Enter the project directory and execute the build command to + flash the compiled program ``` build__hcpu\download.bat(uart_download.bat) : board name @@ -29,24 +37,37 @@ uart_download.bat: used for serial port programming For example: build_sf32lb56-lcd_n16r12n1_hcpu\download.bat ``` ### Example Output Display -First, get the NOR device handle based on the address and confirm whether the address is valid -If invalid, the log will print: ```Address 0x%x not NOR FLASH``` +First, get the NOR device handle based on the address and confirm whether the +address is valid If invalid, the log will print: ```Address 0x%x not NOR +FLASH``` -Then get the NOR ID, total capacity (length) -Then perform erase processing -If erase fails, the log will print: ```FLASH ERASE fail %d ``` +Then get the NOR ID, total capacity (length) Then perform erase processing If +erase fails, the log will print: ```FLASH ERASE fail %d ``` -Check if erase is successful -If the check is not all 1s, the log will print: ```"Data not 0xffffffff but 0x%08x after erase at pos 0x%x ``` +Check if erase is successful If the check is not all 1s, the log will print: +```"Data not 0xffffffff but 0x%08x after erase at pos 0x%x ``` + +Then generate random numbers and write them to all pages in the entire block If +it fails, the log will print: ```Write flash fail ``` + +Finally read and verify If the read data is inconsistent with the written data, +the log will print: ```compare flash fail ``` ![alt text](assets/nor1.png) + + +### Troubleshooting +If the log does not show the expected log and phenomena, you can troubleshoot +from the following aspects: +```c +Write speed: 420.71 KB/s (time: 2434 ticks, sectors: 256) +Write Ops: 256 sectors, 105.18 ops/sec +Read speed: 31030.30 KB/s (time: 33 ticks, sectors: 256) +Read Ops: 256 sectors, 7757.58 ops/sec +``` -Then generate random numbers and write them to all pages in the entire block -If it fails, the log will print: ```Write flash fail ``` -Finally read and verify -If the read data is inconsistent with the written data, the log will print: ```compare flash fail ``` -![alt text](assets/nor1.png) ### Troubleshooting -If the log does not show the expected log and phenomena, you can troubleshoot from the following aspects: -* Whether the hardware connection is normal -* Check if the USB cable has data transmission capability -* Troubleshoot based on the information in the above log \ No newline at end of file +If the expected logs or behavior do not appear, please troubleshoot the +following areas: +* Verify that the hardware connections are secure and correct. +* Ensure the USB cable supports data transfer. +* Analyze the log information provided above to identify the issue. diff --git a/example/rt_device/pdm/README_EN.md b/example/rt_device/pdm/README_EN.md index 3578dd68d..1b60a5d50 100644 --- a/example/rt_device/pdm/README_EN.md +++ b/example/rt_device/pdm/README_EN.md @@ -3,66 +3,72 @@ Source path: example/rt_device/pdm ## Supported Platforms - -+ sf32lb52-nano -+ sf32lb52-lcd series -+ sf32lb56-lcd series -+ sf32lb58-lcd series -* eh-lb525 + +* sf32lb52-nano +* sf32lb52-lcd series +* sf32lb56-lcd series +* sf32lb58-lcd series ## Overview - + This example demonstrates PDM recording, including: + Recording via PDM, PCM data saved to Flash (raw write). + Read recorded data and playback. - ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported platforms](quick_start)). ++ One development board supported by this example ([Supported + platforms](quick_start)). + PDM + Speaker. ### menuconfig Configuration -1. Enable PDM (using PDM1 here) -![PDM](./assets/mc_pdm_enable.png) -![PDM1](./assets/mc_pdm1_enable.png) -2. Enable AUDIO CODEC and AUDIO PROC: -![AUDIO CODEC & PROC](./assets/mc_audcodec_audprc.png) -3. Enable AUDIO(`AUDIO`): -![AUDIO](./assets/mc_audio.png) +1. Enable PDM (using PDM1 here) ![PDM](./assets/mc_pdm_enable.png) + ![PDM1](./assets/mc_pdm1_enable.png) +2. Enable AUDIO CODEC and AUDIO PROC: ![AUDIO CODEC & + PROC](./assets/mc_audcodec_audprc.png) +3. Enable AUDIO(`AUDIO`): ![AUDIO](./assets/mc_audio.png) 4. Enable AUDIO MANAGER.(`AUDIO_USING_MANAGER`) -![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) + ![AUDIO_USING_MANAGER](./assets/mc_audio_manager.png) ```{tip} Configurations 3 and 4 are for playing recorded files. In this example, recording playback uses Audio manager interface. -``` +``` ### Hardware Connection\PIN CONFIG -|Development Board | PDM | PDM1_CLK | PDM1_DATA | Power Supply | GND | SEL(left/right channel selection) | -|--------|------------|---------------|-------------------|---|---|---| -|SF32LB52_DevKit-LCD | PDM1 | PAD_PA22/PAD_PA07 | PAD_PA23/PAD_PA08 | 3.3V | GND | GND/3.3V | +| Development Board | PDM | PDM1_CLK | PDM1_DATA | Power Supply | GND | SEL(left/right channel selection) | +| ------------------- | ---- | ----------------- | ----------------- | ------------ | --- | --------------------------------- | +| SF32LB52_DevKit-LCD | PDM1 | PAD_PA22/PAD_PA07 | PAD_PA23/PAD_PA08 | 3.3V | GND | GND/3.3V | +| SF32LB52_LCD | PDM1 | PAD_PA22/PAD_PA07 | PAD_PA23/PAD_PA08 | 3.3V | GND | GND/3.3V | +| SF32LB56-LCD | PDM1 | PAD_PA69 | PAD_PA20 | 3.3V | GND | GND/3.3V | +| SF32LB58-LCD | PDM2 | PAD_PA23 | PAD_PA18 | 3.3V | GND | GND/3.3V | +* For detailed pin definitions, refer to + [sf32lb52-nano](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-Nano.html) + [sf32lb52-lcd](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) + [sf32lb56-lcd](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) + [sf32lb58-lcd](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html). ```{tip} + When there are two PDM channels, SEL is used to distinguish left and right channels. + When there is one PDM channel, SEL can be left floating. ``` -Taking `SF32LB52_DevKit-LCD` as an example, using `PA07/PA08` as `PDM1_CLK/PDM1_DATA`, pin configuration is as follows: +Taking `SF32LB52_DevKit-LCD` as an example, using `PA07/PA08` as +`PDM1_CLK/PDM1_DATA`, pin configuration is as follows: ```C - /* PIN CONFIG */ +/* * PIN CONFIG * */ #ifdef SOC_SF32LB52X -#if !defined(BSP_USING_LCD) && defined(BSP_USING_PDM1) +#if !defined(BSP_USING_LCD) && defined(BSP_USING_PDM1) HAL_PIN_Set(PAD_PA07, PDM1_CLK, PIN_NOPULL, 1); HAL_PIN_Set(PAD_PA08, PDM1_DATA, PIN_PULLDOWN, 1); #endif #endif -```` +``` ![SF32LB52_DevKit-LCD PDM connection](./assets/pdm_hw.png) ```{warning} @@ -75,42 +81,49 @@ For other form factors, you need to refer to the specification to select pins. ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```c -> scons --board=sf32lb52-lcd_n16r8 -j32 +> scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - + This example operates recording and playback through FINSH commands: -1. Start recording command: `pdm open [channel selection] [depth] [sampling rate]` -For example: -+ `pdm open 1 16 16000` -Means configure for left channel, 16-bit, 16k sampling rate recording. -+ `pdm open 2 16 16000` -Means configure for dual channel (stereo), 16-bit, 16k sampling rate recording. +1. Start recording command: `pdm open [channel selection] [depth] [sampling + rate]`\ + For example: ++ `pdm open 1 16 16000`\ + Means configure for left channel, 16-bit, 16k sampling rate recording. ++ `pdm open 2 16 16000`\ + Means configure for dual channel (stereo), 16-bit, 16k sampling rate + recording. 2. End recording command: `pdm stop` -+ `pdm stop` -Means end recording. ++ `pdm stop`\ + Means end recording. -3. Playback recording command: `pdm play [channel count] [depth] [sampling rate]` -For example: -+ `pdm play 1 16 16000` -Means playback mono, 16k sampling rate, 16-bit recorded data. -+ `pdm play 2 16 16000` -Means playback dual channel, 16k sampling rate, 16-bit recorded data. +3. Playback recording command: `pdm play [channel count] [depth] [sampling + rate]`\ + For example: ++ `pdm play 1 16 16000`\ + Means playback mono, 16k sampling rate, 16-bit recorded data. ++ `pdm play 2 16 16000`\ + Means playback dual channel, 16k sampling rate, 16-bit recorded data. -After executing recording and then playback, normal recording and playback can be achieved. +After executing recording and then playback, normal recording and playback can +be achieved. Serial port log output reference: ```c @@ -188,11 +201,11 @@ Serial port log output reference: ## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |12/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | +| | | | diff --git a/example/rt_device/pulse_encoder/README_EN.md b/example/rt_device/pulse_encoder/README_EN.md index bc6f9a87c..0d522ed5f 100644 --- a/example/rt_device/pulse_encoder/README_EN.md +++ b/example/rt_device/pulse_encoder/README_EN.md @@ -5,21 +5,27 @@ Source path: example\rt_device\pulse_encoder The example can run on the following development boards. * sf32lb58-lcd_n16r64n4 ## Overview -* Pulse encoders can accurately measure the position of rotating shafts. Each rotation by a certain angle generates a pulse signal from the encoder. By counting these pulses, the current position of the rotating shaft can be determined. -* GPtimer encoder mode example where external pulse encoder controls timer CNT increment/decrement +* Pulse encoders can accurately measure the position of rotating shafts. Each + rotation by a certain angle generates a pulse signal from the encoder. By + counting these pulses, the current position of the rotating shaft can be + determined. +* GPtimer encoder mode example where external pulse encoder controls timer CNT + increment/decrement +* Supports multiple encoders ## Example Usage ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration -![Enable timer:](./assets/image2.png) -![Enable timer:](./assets/image1.png) +![Enable timer:](./assets/image2.png) ![Enable timer:](./assets/image1.png) ## Example Usage ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: > scons --board=sf32lb58-lcd_n16r64n4 -j8 @@ -30,7 +36,8 @@ Switch to the example `project/build_xx` directory and run `download.bat` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ### Read GPtimer cnt value controlled by external device increment/decrement every second #### Example Output Results Display: * log output: @@ -46,21 +53,21 @@ msh /> ``` * This example uses polling method to read cnt value every second - #### encoder channel selection parameter modification -|Form Factor Name | GPTIMx_CHx | Pin (Physical Position) | -|--------|---------------|-------------------| -|525 | | | -| | GPTIM1_CH1 | PAD_PA24 (19) | -| | GPTIM1_CH2 | PAD_PA25 (21) | -|587: | | | -| | GPTIM1_CH1 |PAD_PA82 (CONN2 22) | -| | GPTIM1_CH2 |PAD_PA51 (CONN2 28) | +| Form Factor Name | GPTIMx_CHx | Pin (Physical Position) | +| ---------------- | ---------- | ----------------------- | +| 525 | | | +| | GPTIM1_CH1 | PAD_PA24 (19) | +| | GPTIM1_CH2 | PAD_PA25 (21) | +| | GPTIM2_CH1 | PAD_PA37 | +| | GPTIM1_CH1 | PAD_PA82 (CONN2 22) | +| 587: | | | +| | GPTIM1_CH1 | PAD_PA82 (CONN2 22) | +| | GPTIM1_CH2 | PAD_PA51 (CONN2 28) | ```c - #ifdef SF32LB52X HAL_PIN_Set(PAD_PA24, GPTIM1_CH1, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA25, GPTIM1_CH2, PIN_PULLUP, 1); @@ -68,30 +75,31 @@ msh /> HAL_PIN_Set(PAD_PA82, GPTIM1_CH1, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA51, GPTIM1_CH2, PIN_PULLUP, 1); #endif - - ``` -**Note**: -1. For 52x chips, can be configured to any IO with PA_TIM function as encoder channel -2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: select lcpu - - - - - +**Note**: +1. For 52x chips, can be configured to any IO with PA_TIM function as encoder + channel +2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: + select lcpu ## Exception Diagnosis -If the expected log doesn't appear and rotation cannot increment/decrement cnt, you can troubleshoot from the following aspects: +If the expected log doesn't appear and rotation cannot increment/decrement cnt, +you can troubleshoot from the following aspects: * Whether hardware connection is normal -* Whether pin configuration is correct - +* Whether pin configuration is correct ## Reference Documentation -- For rt_device examples, the RT-Thread official website documentation provides more detailed explanations, you can add webpage links here, for example, refer to RT-Thread's [RTC documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) +- For rt_device examples, the RT-Thread official website documentation provides + more detailed explanations, you can add webpage links here, for example, refer + to RT-Thread's [RTC + documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 | 12/2024| 2.0| -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +| | | | +``` + +``` diff --git a/example/rt_device/pwm/index_EN.md b/example/rt_device/pwm/index_EN.md index d7cb58029..a4aad8909 100644 --- a/example/rt_device/pwm/index_EN.md +++ b/example/rt_device/pwm/index_EN.md @@ -4,7 +4,4 @@ :glob: */* - - - ``` diff --git a/example/rt_device/pwm/pwm/README_EN.md b/example/rt_device/pwm/pwm/README_EN.md index 2e357d48b..fcb76b966 100644 --- a/example/rt_device/pwm/pwm/README_EN.md +++ b/example/rt_device/pwm/pwm/README_EN.md @@ -11,37 +11,38 @@ The example can run on the following development boards. ## Overview * Includes examples of GPtimer outputting PWM via IO ports - - ## Example Usage ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ### GPtimer Output PWM #### Example Output Results Display: * log output: ``` Start gtimer pwm demo! -[32m][2821] I/pwm: pwm_set:percentage:20,period:1000000,freq:1000hz +[32m][2821] I/pwm: pwm_set: percentage: 20, period: 1000000, freq: 1000Hz [0m][32m][2848] I/drv.pwm: psc 2, Period 60000, [0m][32m][2866] I/drv.pwm: Pulse 12000 [0m]gtimer pwm demo end! -msh /> +msh /> ``` * PA09 outputs PWM waveform (default 200Hz, 20% duty cycle) @@ -50,47 +51,48 @@ msh /> #### PWM Parameter Modification * IO Output Modification -Physical position refers to the pin header position corresponding to the pin on the board - -|Form Factor Name | PWM | CHX | Pin (Physical Position) | -|--------|------------|---------------|-------------------| -|sf32lb52-nano | GPTIM1 | CH2 | PA20 (Physical pin is on the back of the board, requires manual flying wire to bring out) | -|sf32lb52-lcd | GPTIM1 | CH2 | PA20 (10) | -|sf32lb58-lcd | GPTIM1 | CH2 |PA51 (CONN2 28) | -|sf32lb56-lcd | GPTIM1 | CH2 |PA36 (40) | +Physical position refers to the pin header position corresponding to the pin on +the board +| Form Factor Name | PWM | CHX | Pin (Physical Position) | +| ---------------- | ------ | --- | ----------------------------------------------------------------------------------------- | +| sf32lb52-nano | GPTIM1 | CH2 | PA20 (Physical pin is on the back of the board, requires manual flying wire to bring out) | +| sf32lb52-lcd | GPTIM1 | CH2 | PA20 (10) | +| sf32lb58-lcd | GPTIM1 | CH2 | PA51 (CONN2 28) | +| sf32lb56-lcd | GPTIM1 | CH2 | PA36 (40) | ```c - - #if defined(BSP_USING_BOARD_EM_LB525XXX)/* 52 series default PA20 (physical position 10) output */ +#if defined(BSP_USING_BOARD_EM_LB525XXX)/* 52 series default PA20 (physical position 10) output */ HAL_PIN_Set(PAD_PA20, GPTIM1_CH2, PIN_NOPULL, 1);/*GPTIM1_CH1 function*/ #elif defined (BSP_USING_BOARD_EM_LB587XXX)/* 587 series default PA51 output */ HAL_PIN_Set(PAD_PA51, GPTIM1_CH2, PIN_NOPULL, 1);/*GPTIM1_CH2 function*/ #endif - - ``` -**Note**: -1. Except for 55x chips, can be configured to any IO with PA_TIM function to output PWM waveform -2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +**Note**: +1. Except for 55x chips, can be configured to any IO with PA_TIM function to + output PWM waveform +2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: + select lcpu * PWM period, pulse width modification - - - - ## Exception Diagnosis -If the expected log and PWM waveform output don't appear, you can troubleshoot from the following aspects: +If the expected log and PWM waveform output don't appear, you can troubleshoot +from the following aspects: * Whether hardware connection is normal -* Whether pin configuration is correct - +* Whether pin configuration is correct ## Reference Documentation -- For rt_device examples, the RT-Thread official website documentation provides more detailed explanations, you can add webpage links here, for example, refer to RT-Thread's [RTC documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) +- For rt_device examples, the RT-Thread official website documentation provides + more detailed explanations, you can add webpage links here, for example, refer + to RT-Thread's [RTC + documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 | 12/2024| 2.0| -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +| | | | +``` + +``` diff --git a/example/rt_device/pwm/pwm_dma/README_EN.md b/example/rt_device/pwm/pwm_dma/README_EN.md index 1340d6d4b..e51f9f2df 100644 --- a/example/rt_device/pwm/pwm_dma/README_EN.md +++ b/example/rt_device/pwm/pwm_dma/README_EN.md @@ -6,43 +6,46 @@ The example can run on the following development boards. * sf32lb52-lcd series * sf32lb56-lcd series * sf32lb58-lcd series -## Overview -* Includes examples of Gtime, Atime using pwm+dma functionality to output PWM waveforms via IO ports +## Overview +* Includes examples of Gtime, Atime using pwm+dma functionality to output PWM + waveforms via IO ports ## Example Usage ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration -sf32lb52-lcd_n16r8 menuconfig configuration -![Enable timer:](./assets/menuconfig_52x.png) -sf32lb58-lcd_n16r64n4 menuconfig configuration -![Enable timer:](./assets/menuconfig_58x.png) -**Note**: pwm setting already sets TIM configuration, check if Enable timer configuration causes conflicts -![Enable timer:](./assets/menuconfig_rgb3.png) +sf32lb52-lcd_n16r8 menuconfig configuration ![Enable +timer:](./assets/menuconfig_52x.png) sf32lb58-lcd_n16r64n4 menuconfig +configuration ![Enable timer:](./assets/menuconfig_58x.png) **Note**: pwm +setting already sets TIM configuration, check if Enable timer configuration +causes conflicts ![Enable timer:](./assets/menuconfig_rgb3.png) -Similar conflict error: -![Enable timer:](./assets/Possible_error1.png) +Similar conflict error: ![Enable timer:](./assets/Possible_error1.png) ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please enter the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ### Atime Output Waveform ![Enable timer:](./assets/atim_waveform.png) ### Gtime Output Waveform @@ -53,36 +56,37 @@ For detailed steps on compilation and downloading, please refer to the relevant #### Example Output Results Display: * 52x log output: ``` -Start atimer pwm demo! -[32m][2692] I/NO_TAG: pwm_set:percentage:90,period:1000000,freq:1000hz -[0m][32m][2721] I/NO_TAG: hwp_atim1_ccr1:107999 -[0m][32m][2739] I/NO_TAG: hwp_atim1_arr:119999 +Starting ATIMER PWM demo... +[32m][2692] I/NO_TAG: pwm_set: percentage: 90, period: 1000000, freq: 1000Hz +[0m][32m][2721] I/NO_TAG: hwp_atim1_ccr1: 107999 +[0m][32m][2739] I/NO_TAG: hwp_atim1_arr: 119999 [0m]DMA data before transfer: pulse_dma_data[0]: 59999 pulse_dma_data[1]: 71999 pulse_dma_data[2]: 83999 -atimer pwm demo end! -msh />Start gtimer pwm demo! -[32m][3471] I/NO_TAG: pwm_set:percentage:10,period:1000000,freq:1000hz -[0m][32m][3500] I/NO_TAG: hwp_gptim2_ccr1:2399 -[0m][32m][3518] I/NO_TAG: hwp_gptim2_arr:23999 +ATIMER PWM demo completed. +msh />Starting GTIMER PWM demo... +[32m][3471] I/NO_TAG: pwm_set: percentage: 10, period: 1000000, freq: 1000Hz +[0m][32m][3500] I/NO_TAG: hwp_gptim2_ccr1: 2399 +[0m][32m][3518] I/NO_TAG: hwp_gptim2_arr: 23999 [0m]DMA data before transfer: dma_data[0]: 4799 dma_data[1]: 7199 dma_data[2]: 9599 -gtimer pwm demo end! -msh /> -``` +GTIMER PWM demo completed. +msh /> +``` #### Pin Parameter Modification * IO Output Modification -Physical position refers to the pin header position corresponding to the pin on the board +Physical position refers to the pin header position corresponding to the pin on +the board -|Form Factor Name | PWM | Pin (Physical Position) | -|--------|---------------------------|-------------------| -|525 | GPTIM2_CH1/ATIM1_CH1 | PA20 (10) | -|587 | GPTIM1_CH2/ATIM2_CH4 |PA51 (CONN2 28) | +| Form Factor Name | PWM | Pin (Physical Position) | +| ---------------- | -------------------- | ----------------------- | +| 525 | GPTIM2_CH1/ATIM1_CH1 | PA20 (10) | +| 587 | GPTIM1_CH2/ATIM2_CH4 | PA51 (CONN2 28) | @@ -90,76 +94,82 @@ Physical position refers to the pin header position corresponding to the pin on void pwm_dma_atim_set_example() { #ifdef SF32LB52X - HAL_PIN_Set(PAD_PA20, ATIM1_CH1, PIN_NOPULL, 1);//52x ATIM1_CH1 corresponds to pwma1_cc1 + HAL_PIN_Set(PAD_PA20, ATIM1_CH1, PIN_NOPULL, 1); // 52x ATIM1_CH1 maps to pwma1_cc1 #elif defined SF32LB58X - HAL_PIN_Set(PAD_PA51, ATIM2_CH4, PIN_NOPULL, 1);//58X ATIM2_CH4 corresponds to pwma2_cc4 + HAL_PIN_Set(PAD_PA51, ATIM2_CH4, PIN_NOPULL, 1); // 58X ATIM2_CH4 maps to pwma2_cc4 #endif #ifdef SF32LB52X - config_atim.channel = 1;//pwm config + config_atim.channel = 1; // PWM configuration #elif defined SF32LB58X - config_atim.channel = 4;//58 pwm config + config_atim.channel = 4; // 58 PWM configuration #endif - //Set basic data(ARR,CRR) and calculate pulse - rt_device_control((struct rt_device *)device,PWM_CMD_SET,(void *)&config_atim); - //dma_transfer - rt_device_control((struct rt_device *)device,PWM_CMD_ENABLE,(void *)&config_atim); + // Initialize basic parameters (ARR, CCR) and calculate pulse width + rt_device_control((struct rt_device *)device, PWM_CMD_SET, (void *)&config_atim); + // Enable DMA transfer + rt_device_control((struct rt_device *)device, PWM_CMD_ENABLE, (void *)&config_atim); } void pwm_dma_gptim_set_example() { #ifdef SF32LB52X - HAL_PIN_Set(PAD_PA20, GPTIM2_CH1, PIN_NOPULL, 1);//52x gtime2_ch1 corresponds to pwm3_cc1 + HAL_PIN_Set(PAD_PA20, GPTIM2_CH1, PIN_NOPULL, 1); // 52x GPTIM2_CH1 maps to pwm3_cc1 #elif defined SF32LB58X - HAL_PIN_Set(PAD_PA51, GPTIM1_CH2, PIN_NOPULL, 1);//58X gtime1_ch2 corresponds to pwm2_cc2 + HAL_PIN_Set(PAD_PA51, GPTIM1_CH2, PIN_NOPULL, 1); // 58X GPTIM1_CH2 maps to pwm2_cc2 #endif #ifdef SF32LB52X - config_gtim.channel = 1;//pwm config + config_gtim.channel = 1; // PWM configuration #elif defined SF32LB58X - config_gtim.channel = 2;//58 pwm config + config_gtim.channel = 2; // 58 PWM configuration #endif - rt_device_control((struct rt_device *)device,PWM_CMD_SET,(void *)&config_gtim); - //dma_transfer - rt_device_control((struct rt_device *)device,PWM_CMD_ENABLE,(void *)&config_gtim); + rt_device_control((struct rt_device *)device, PWM_CMD_SET, (void *)&config_gtim); + // Enable DMA transfer + rt_device_control((struct rt_device *)device, PWM_CMD_ENABLE, (void *)&config_gtim); } - - ``` -**Note**: -1. Except for 55x chips, can be configured to any IO with PA_TIM function to output PWM waveform -2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +**Note**: +1. Except for 55x chips, can be configured to any IO with PA_TIM function to + output PWM waveform +2. The last parameter of HAL_PIN_Set is hcpu/lcpu selection, 1: select hcpu, 0: + select lcpu * PWM period, pulse width modification ```c - uint32_t period = PWM_PERIOD; +uint32_t period = PWM_PERIOD; uint8_t percentage = 10; rt_uint32_t pulse = (percentage % 100) * period / 100; config_gtim.period = period; config_gtim.pulse = pulse; - config_gtim.use_percentage = 1;//Enables the percentage calculation of pulse - config_gtim.data_len = 3;//dma_data_len + config_gtim.use_percentage = 1; // Enable pulse width calculation based on percentage + config_gtim.data_len = 3; // DMA data length ``` ## Exception Diagnosis -If the expected log and PWM waveform output don't appear, you can troubleshoot from the following aspects: +If the expected log and PWM waveform output don't appear, you can troubleshoot +from the following aspects: * Whether hardware connection is normal -* Whether pin configuration is correct +* Whether pin configuration is correct * Whether the selected pin mode conflicts or mismatches - ## Reference Documentation -- For rt_device examples, the RT-Thread official website documentation provides more detailed explanations, you can add webpage links here, for example, refer to RT-Thread's [RTC documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) +- For rt_device examples, the RT-Thread official website documentation provides + more detailed explanations, you can add webpage links here, for example, refer + to RT-Thread's [RTC + documentation](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 | 12/2024| 2.0| -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | +| | | | +``` + +``` diff --git a/example/rt_device/rgb_led/README_EN.md b/example/rt_device/rgb_led/README_EN.md index 209a9c50e..45e41d254 100644 --- a/example/rt_device/rgb_led/README_EN.md +++ b/example/rt_device/rgb_led/README_EN.md @@ -3,13 +3,15 @@ Source path: example/rt_device/rgbled ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ++ sf32lb58-lcd series ## Overview - -This example demonstrates rgbled driver based on rt-device (using rt-thread), including: + +This example demonstrates rgbled driver based on rt-device (using rt-thread), +including: + rgb_ cycling RGB light display; ```{tip} @@ -17,11 +19,12 @@ This example is based on HCPU and uses PWM DMA driver. ``` ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration @@ -29,53 +32,49 @@ Run the following command ```c menuconfig --board=sf32lb52-lcd_n16r8 ``` -Enable PWM, 52x use PWM3 CHANNLE1, 58x use PWM4 CHANNLE4
-![Enable rgbled:](./assets/menuconfig_pwm_52x.png)
-![Enable rgbled:](./assets/menuconfig_pwm_58x.png)
- -Enable RGBLED peripheral and corresponding peripheral pwm, Channel
-![Enable rgbled:](./assets/menuconfig_rgb_52x.png)
-![Enable rgbled:](./assets/menuconfig_rgb_58x.png)
+Enable PWM, 52x use PWM3 CHANNLE1, 58x use PWM4 CHANNLE4
\ +![Enable rgbled:](./assets/menuconfig_pwm_52x.png)
![Enable +rgbled:](./assets/menuconfig_pwm_58x.png)
-**Note**: pwm setting already sets TIM configuration, check if Enable timer configuration causes conflicts -![Enable timer:](./assets/menuconfig_rgb3.png) +Enable RGBLED peripheral and corresponding peripheral pwm, Channel
![Enable +rgbled:](./assets/Possible_error1.png) ![Enable rgbled:]{3} -Similar conflict error: -![Enable timer:](./assets/Possible_error1.png) - -Error from different pwm channel and rgb configuration: -![Enable timer:](./assets/Possible_error2.png) +**Note**: pwm setting already sets TIM configuration, check if Enable timer +configuration causes conflicts ![Enable timer:]
### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` -scons -j8 --board=sf32lb52-lcd_n16r8 +scons -j8 --board=sf32lb52-lcd_n16r8 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - -After the example starts, the serial port cyclically outputs color characters, and the hardware rgbled also displays corresponding colors: + +After the example starts, the serial port cyclically outputs color characters, +and the hardware rgbled also displays corresponding colors: ``` -12-25 11:51:46:770 start display color! -12-25 11:51:47:266 -> black -12-25 11:51:49:261 -> blue -12-25 11:51:50:257 -> green -12-25 11:51:51:264 -> cyan -12-25 11:51:51:283 -> red -12-25 11:51:52:262 -> purple -12-25 11:51:54:278 -> yellow -12-25 11:51:55:275 -> white - +12-25 11:51:46:770 Start display color sequence! +12-25 11:51:47:266 -> Black +12-25 11:51:49:261 -> Blue +12-25 11:51:50:257 -> Green +12-25 11:51:51:264 -> Cyan +12-25 11:51:51:283 -> Red +12-25 11:51:52:262 -> Purple +12-25 11:51:54:278 -> Yellow +12-25 11:51:55:275 -> White ``` @@ -85,17 +84,15 @@ After the example starts, the serial port cyclically outputs color characters, a 1. Confirm PWM/DMA configuration status through PWM/DMA registers: 2. Enable rgb configuration error -GTIM2 register status: -![PWM_DMA](./assets/reg_rgled_gtim.png) -DMAC1 register status: -![PWM_DMA](./assets/reg_rgled_dma.png) +GTIM2 register status: ![PWM_DMA]
DMAC1 register status: +![PWM_DMA](./assets/reg_rgled_gtim.png)
## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |12/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | +| | | | diff --git a/example/rt_device/rtc/README_EN.md b/example/rt_device/rtc/README_EN.md index bffdedda1..dd742c351 100644 --- a/example/rt_device/rtc/README_EN.md +++ b/example/rt_device/rtc/README_EN.md @@ -1,95 +1,107 @@ # RTC Example Source path: example/rt_device/rtc ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -This example demonstrates system time setting, system time reading, and alarm usage based on the RT device framework: + +This example demonstrates system time setting, system time reading, and alarm +usage based on the RT device framework: + Set date and time, read date and time. + Set Alarm. ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration The following configuration has been set up OK for this example. -1. This example is based on external 32k crystal, need to configure LXT enable (LXT_DISABLE not checked): -![LXT ENABLE](./assets/mc_lxt_enable.png) -2. Enable RTC (`BSP_USING_ONCHIP_RTC` configuration automatically configures `RT_USING_RTC`): -![RTC_USING_ONCHIP_RTC](./assets/mc_onchip_rtc_enable.png) -3. Enable RTC Alarm: -![RTC_USING_ALARM](./assets/mc_rtc_using_alarm.png) +1. This example is based on external 32k crystal, need to configure LXT enable + (LXT_DISABLE not checked):\ + ![LXT ENABLE](./assets/mc_lxt_enable.png) +2. Enable RTC (`BSP_USING_ONCHIP_RTC` configuration automatically configures + `RT_USING_RTC`):\ + ![RTC_USING_ONCHIP_RTC](./assets/mc_onchip_rtc_enable.png) +3. Enable RTC Alarm:\ + ![RTC_USING_ALARM](./assets/mc_rtc_using_alarm.png) ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select the port as +prompted to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [](/quickstart/get-started.md). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [](/quickstart/get-started.md). ## Expected Results - + After the example starts, the serial port outputs as follows: 1. Set system time to 2024/01/01 08:30:00 ```c -10-09 11:01:46:350 set system time (by RT DEVICE): 2024 01 01 08:30:00 -10-09 11:01:46:352 current system time: 2024 01 01 08:30:00 +10-09 11:01:46:350 Set system time (via RT DEVICE): 2024 01 01 08:30:00 +10-09 11:01:46:352 Current system time: 2024 01 01 08:30:00 ``` 2. Set system time to 2024/02/01 08:30:00 ```c -10-09 11:01:46:354 set system time (by RTT API): 2024 02 01 08:30:00 -10-09 11:01:46:356 current system time: 2024 02 01 08:30:00 +10-09 11:01:46:354 Set system time (via RTT API): 2024 02 01 08:30:00 +10-09 11:01:46:356 Current system time: 2024 02 01 08:30:00 ``` 3. Set one-shot alarm, alarm time is 08:32:00 ```c -10-09 11:01:46:358 SET ONESHOT ALARM : [08:32:00] +10-09 11:01:46:358 Set one-shot alarm: [08:32:00] ``` 4. Alarm triggered ```c -10-09 11:03:46:301 Alarm triggered at 2024 02 01 08:32:00 +10-09 11:03:46:301 Alarm triggered at 2024 02 01 08:32:00 ``` 5. Periodically get system time (every second) ```c -10-09 11:03:56:885 current system time: 2024 02 01 08:32:11 -10-09 11:03:57:852 current system time: 2024 02 01 08:32:12 -10-09 11:03:58:880 current system time: 2024 02 01 08:32:13 -10-09 11:03:59:847 current system time: 2024 02 01 08:32:14 -10-09 11:04:00:861 current system time: 2024 02 01 08:32:15 +10-09 11:03:56:885 Current system time: 2024 02 01 08:32:11 +10-09 11:03:57:852 Current system time: 2024 02 01 08:32:12 +10-09 11:03:58:880 Current system time: 2024 02 01 08:32:13 +10-09 11:03:59:847 Current system time: 2024 02 01 08:32:14 +10-09 11:04:00:861 Current system time: 2024 02 01 08:32:15 ``` ## Exception Diagnosis -1. RTC timing is not accurate: -1.1 Confirm if the crystal configuration is correct: -For example, if there is no external 32k, you need to configure 'LXT_Disable'. -1.2 Confirm that RTC has been enabled ([menuconfig configuration](#menuconfig-configuration)). -1.3 After RTC initialization, it will be recorded in the RTC ACKUP register: -`HAL_Set_backup(RTC_BACKUP_INITIALIZED, 1)` -When it is not a cold start, RTC will not reinitialize, so when RTC configuration changes, it is necessary to perform a cold start (or manually clear this flag). +1. RTC timing is not accurate:\ + 1.1 Confirm if the crystal configuration is correct:\ + For example, if there is no external 32k, you need to configure + 'LXT_Disable'.\ + 1.2 Confirm that RTC has been enabled ([menuconfig + configuration](#menuconfig配置)).\ + 1.3 After RTC initialization, it will be recorded in the RTC ACKUP register:\ + `HAL_Set_backup(RTC_BACKUP_INITIALIZED, 1)`\ + When it is not a cold start, RTC will not reinitialize, so when RTC + configuration changes, it is necessary to perform a cold start (or manually + clear this flag). ## Reference Documentation - -[RTC Device](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) + +[RTC +Device](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/rtc/rtc) ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -|0.0.2 |08/2025 |Supplement `Exception Diagnosis`| -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | -------------------------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 08/2025 | Supplement `Exception Diagnosis` | +| | | | diff --git a/example/rt_device/sensor/README_EN.md b/example/rt_device/sensor/README_EN.md index 347fb615b..abe89d694 100644 --- a/example/rt_device/sensor/README_EN.md +++ b/example/rt_device/sensor/README_EN.md @@ -1,5 +1,9 @@ # Sensor Example -Sensors are an important part of the Internet of Things. "Sensors to IoT" is equivalent to "eyes to humans". If humans lose their eyes, they cannot see this vast and colorful world, and the same is true for IoT. A large number of sensors have been developed for developers to choose from, such as: Accelerometer, Magnetometer, Gyroscope, Barometer/pressure, Humidometer, etc. +Sensors are an important part of the Internet of Things. "Sensors to IoT" is +equivalent to "eyes to humans". If humans lose their eyes, they cannot see this +vast and colorful world, and the same is true for IoT. A large number of sensors +have been developed for developers to choose from, such as: Accelerometer, +Magnetometer, Gyroscope, Barometer/pressure, Humidometer, etc. Source code path: SiFli-SDK\example\rt_device\sensor @@ -8,11 +12,17 @@ Source code path: SiFli-SDK\example\rt_device\sensor ## Sensor Types and Introduction * LTR303 sensor, MMC56X3 sensor, LSM6DS sensor -* SiFli-SDK is currently based on RT-Thread, so peripheral APIs are consistent with RT-Thread. For detailed API usage instructions, please refer to [RT-Thread sensor API](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/sensor/sensor) documentation. In the following examples, we will gradually explain the usage of each API and how to add new sensors. +* SiFli-SDK is currently based on RT-Thread, so peripheral APIs are consistent + with RT-Thread. For detailed API usage instructions, please refer to + [RT-Thread sensor + API](https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/sensor/sensor) + documentation. In the following examples, we will gradually explain the usage + of each API and how to add new sensors. ## Example Usage ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ``` scons --board=sf32lb52-lchspi-ulp -j8 ``` @@ -26,27 +36,33 @@ please input the serial port num:6 ``` #### Example Output Results Display: -* After programming completion, serial port prints data from each sensor -![alt text](assets/sensor.png) +* After programming completion, serial port prints data from each sensor ![alt + text](assets/sensor.png) #### Sensor Configuration Process * Default configuration has been done, users do not need to modify it themselves * Enable corresponding sensors and `I2C3` in menuconfig ``` -menuconfig --board=sf32lb52-lchspi-ulp +menuconfig --board=sf32lb52-lchspi-ulp ``` -![alt text](assets/menuconfig_sensor.png) -![alt text](assets/I2C3.png) +![alt text](assets/menuconfig_sensor.png) ![alt text](assets/I2C3.png) ## Hardware Connection -Looking at the schematic of Lichee Huangshan Pi, we find that all sensors use `PA_39_I2C3_SDA` and `PA_40_I2C3_SLC` for data reception and transmission, with peripheral bus using `I2C3`. -![alt text](assets/sensor_1.png) +Looking at the schematic of Lichee Huangshan Pi, we find that all sensors use +`PA_39_I2C3_SDA` and `PA_40_I2C3_SLC` for data reception and transmission, with +peripheral bus using `I2C3`. ![alt text](assets/sensor_1.png) ## Hardware Configuration -* For sf32lb52-lchspi-ulp development board, it can be configured to any IO with PA*_I2C_UART functionality to output I2C SDA, SCLK waveforms. I2C name is not mandatory and can be configured as needed (I2C1~I2C4), here using I2C3 as example. -* Sensors communicate through I2C protocol, with specific connection pins being PA40 (SCL clock line) and PA39 (SDA data line) -* Configure IO pins to I2C mode through HAL_PIN_Set() function, set to pull-up mode. The last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu +* For sf32lb52-lchspi-ulp development board, it can be configured to any IO with + PA*_I2C_UART functionality to output I2C SDA, SCLK waveforms. I2C name is not + mandatory and can be configured as needed (I2C1~I2C4), here using I2C3 as + example. +* Sensors communicate through I2C protocol, with specific connection pins being + PA40 (SCL clock line) and PA39 (SDA data line) +* Configure IO pins to I2C mode through HAL_PIN_Set() function, set to pull-up + mode. The last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select + lcpu ```c static void board_io_init(void) { @@ -57,18 +73,33 @@ static void board_io_init(void) ## How to Add a New Sensor ### Add a Sensor Driver -* In SiFli-SDK\customer\peripherals\sensor folder, create a folder with the sensor name for the sensor driver code (e.g., magnetometer SiFli-SDK\customer\peripherals\sensor\MMC56x3) -* Create corresponding .c and .h files for sensor_name and sensor_memsic_(sensor_name) in the folder (e.g., magnetometer MMC56x3) -* Write the required driver code for the sensor in sensor_name.c file, including: sensor initialization code, I2C communication interface management, sensor register configuration, sensor data collection and processing, sensor working mode control (written according to sensor manual) -* Write sensor interface definitions in sensor_memsic_(sensor_name).c file, including: sensor initialization interface, sensor data acquisition interface, sensor working mode interface -* For specific operation steps, refer to [Sensor Addition Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/app_note/sensor.html) +* In SiFli-SDK\customer\peripherals\sensor folder, create a folder with the + sensor name for the sensor driver code (e.g., magnetometer + SiFli-SDK\customer\peripherals\sensor\MMC56x3) +* Create corresponding .c and .h files for sensor_name and + sensor_memsic_(sensor_name) in the folder (e.g., magnetometer MMC56x3) +* Write the required driver code for the sensor in sensor_name.c file, + including: sensor initialization code, I2C communication interface management, + sensor register configuration, sensor data collection and processing, sensor + working mode control (written according to sensor manual) +* Write sensor interface definitions in sensor_memsic_(sensor_name).c file, + including: sensor initialization interface, sensor data acquisition interface, + sensor working mode interface +* For specific operation steps, refer to [Sensor Addition + Guide](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/app_note/sensor.html) ### App Function Code -* 1. First confirm the connection pins between sensor and board, perform IO pin initialization through board_io_init function. -* 2. Add sensor initialization function, for example, MMC5603 sensor initialization function is rt_hw_mmc56x3_init. -* 3. Open and configure sensor device, first find the device (enable corresponding sensor in menuconfig for whichever sensor is added), then open sensor device for configuration. -* 4. Add sensor data acquisition function, for example, MMC5603 sensor data acquisition function uses rt_device_read interface function for data reading. -* 5. Finally print the read data +* 1. Identify the connection pins between the sensor and the board, then + initialize the IO pins using the `board_io_init` function. +* 2. Register the sensor initialization function. For example, the + initialization function for the MMC5603 sensor is `rt_hw_mmc56x3_init`. +* 3. Open and configure the sensor device. First, locate the device (ensure the + corresponding sensor is enabled in `menuconfig`), and then open the sensor + device to configure its parameters. +* 4. Implement the sensor data acquisition logic. For instance, the + `rt_device_read` interface can be used to read data from the MMC5603 sensor. +* 5. Finally, output the retrieved data via the console. ## Exception Diagnosis -* If data reading is abnormal or has abnormal jumps, check if rt_device_control correctly sets power mode, if there is electromagnetic interference \ No newline at end of file +* If data reading is abnormal or has abnormal jumps, check if rt_device_control + correctly sets power mode, if there is electromagnetic interference diff --git a/example/rt_device/spi/circular_rx/README_EN.md b/example/rt_device/spi/circular_rx/README_EN.md index 8b222203c..b42555377 100644 --- a/example/rt_device/spi/circular_rx/README_EN.md +++ b/example/rt_device/spi/circular_rx/README_EN.md @@ -6,22 +6,23 @@ Source path: `example/rt_device/spi/circular_rx` - `sf32lb58-lcd_n16r64n4` ## Overview -This example validates DMA circular mode in the RT-Thread SPI driver and supports three modes: +This example validates DMA circular mode in the RT-Thread SPI driver and +supports three modes: - **Master TRX mode**: full-duplex TX/RX, suitable for loopback testing - **Slave RX mode**: receive only, requires an external Master to provide clock - **Slave TX mode**: transmit only, requires an external Master to provide clock ## API Reference -| API | Description | -|------|------| -| `rt_device_control(..., RT_SPI_CTRL_CONFIG_DMA_CIRCULAR, ...)` | Configure circular DMA direction | -| `rt_device_set_rx_indicate()` | Register RX half-buffer / full-buffer callback | -| `rt_device_set_tx_complete()` | Register TX half-buffer / full-buffer callback | -| `rt_spi_transfer()` | Start TX+RX full-duplex circular DMA | -| `rt_device_read()` | Start RX only circular DMA | -| `rt_device_write()` | Start TX only circular DMA | -| `rt_device_control(..., RT_SPI_CTRL_STOP_DMA_CIRCULAR, ...)` | Stop circular DMA | +| API | Description | +| -------------------------------------------------------------- | ---------------------------------------------- | +| `rt_device_control(..., RT_SPI_CTRL_CONFIG_DMA_CIRCULAR, ...)` | Configure circular DMA direction | +| `rt_device_set_rx_indicate()` | Register RX half-buffer / full-buffer callback | +| `rt_device_set_tx_complete()` | Register TX half-buffer / full-buffer callback | +| `rt_spi_transfer()` | Start TX+RX full-duplex circular DMA | +| `rt_device_read()` | Start RX only circular DMA | +| `rt_device_write()` | Start TX only circular DMA | +| `rt_device_control(..., RT_SPI_CTRL_STOP_DMA_CIRCULAR, ...)` | Stop circular DMA | ## Required Configuration `project/proj.conf` should include: @@ -45,7 +46,8 @@ Select by the `SPI_CIRCULAR_DEMO_MODE` macro: 2. Attach/open the `spi_circular` device 3. Configure SPI (Master, Mode0, 8bit, 20MHz) 4. Call `rt_spi_take_bus()/rt_spi_release_bus()` to trigger DMA handle linking -5. Call `rt_device_control(..., RT_SPI_CTRL_CONFIG_DMA_CIRCULAR, ...)` with `TXRX` +5. Call `rt_device_control(..., RT_SPI_CTRL_CONFIG_DMA_CIRCULAR, ...)` with + `TXRX` 6. Call `rt_spi_transfer()` to start circular DMA 7. Short MOSI and MISO for loopback verification @@ -67,16 +69,16 @@ Select by the `SPI_CIRCULAR_DEMO_MODE` macro: ### Pin Mapping Table -| Board | Function Pin | Local Device Pin | Remote Device Pin | Physical Pin (CONN2) | -|--------|----------|--------------|--------------|-------------------| -| sf32lb52-lcd | PA_24 | dio | SPI_MOSI | 19 | -| | PA_25 | di | SPI_MISO | 21 | -| | PA_28 | clk | SPI_CLK | 23 | -| | PA_29 | cs | SPI_CS | 24 | -| sf32lb58-lcd | PA_21 | dio | SPI_MOSI | 8 | -| | PA_20 | di | SPI_MISO | 10 | -| | PA_28 | clk | SPI_CLK | 5 | -| | PA_29 | cs | SPI_CS | 3 | +| Board | Function Pin | Local Device Pin | Remote Device Pin | Physical Pin (CONN2) | +| ------------ | ------------ | ---------------- | ----------------- | -------------------- | +| sf32lb52-lcd | PA_24 | dio | SPI_MOSI | 19 | +| | PA_25 | di | SPI_MISO | 21 | +| | PA_28 | clk | SPI_CLK | 23 | +| | PA_29 | cs | SPI_CS | 24 | +| sf32lb58-lcd | PA_21 | dio | SPI_MOSI | 8 | +| | PA_20 | di | SPI_MISO | 10 | +| | PA_28 | clk | SPI_CLK | 5 | +| | PA_29 | cs | SPI_CS | 3 | The hardware schematic of `sf32lb52-lcd_n16r8` is shown below: @@ -97,29 +99,29 @@ Connect with standard 4-wire SPI. An external Master must provide clock. ### Master TRX Mode ```text -Start SPI circular DMA demo! +Starting SPI circular DMA demo. Mode: Master TRX (loopback) -Circular DMA started on spi1 -Tip: Short MOSI(DO) to MISO(DI) for loopback verification. -RX: half=1 full=0 rx[0..7]: 00 01 02 03 04 05 06 07, rx[mid..mid+7]: 80 81 82 83 84 85 86 87, mismatch=0 +Circular DMA initialized on spi1. +Note: Short MOSI(DO) to MISO(DI) for loopback verification. +RX: half=1 full=0, rx[0..7]: 00 01 02 03 04 05 06 07, rx[mid..mid+7]: 80 81 82 83 84 85 86 87, mismatch=0 ``` ### Slave RX Mode ```text -Start SPI circular DMA demo! +Starting SPI circular DMA demo. Mode: Slave RX only -Tip: Connect external SPI Master to provide clock. -Circular DMA started on spi1 +Note: Connect an external SPI Master to provide the clock signal. +Circular DMA initialized on spi1. RX: half=1 full=0 ``` ### Slave TX Mode ```text -Start SPI circular DMA demo! +Starting SPI circular DMA demo. Mode: Slave TX only -Tip: Connect external SPI Master to provide clock. -Circular DMA started on spi1 -TX: half=1 full=0 tx[0..7]: 00 01 02 03 04 05 06 07, tx[mid..mid+7]: 80 81 82 83 84 85 86 87 +Note: Connect an external SPI Master to provide the clock signal. +Circular DMA initialized on spi1. +TX: half=1 full=0, tx[0..7]: 00 01 02 03 04 05 06 07, tx[mid..mid+7]: 80 81 82 83 84 85 86 87 ``` ## Callback Functions @@ -164,6 +166,6 @@ Check: - Header: `rtos/rtthread/bsp/sifli/drivers/drv_spi.h` ## Changelog -| Version | Date | Description | -|:---|:---|:---| -| 1.0.0 | 03/2026 | Initial release, supporting Master TRX / Slave RX / Slave TX modes | +| Version | Date | Description | +| ------- | ------- | ------------------------------------------------------------------ | +| 1.0.0 | 03/2026 | Initial release, supporting Master TRX / Slave RX / Slave TX modes | diff --git a/example/rt_device/spi/index_EN.md b/example/rt_device/spi/index_EN.md index b95e36d66..740cf116e 100644 --- a/example/rt_device/spi/index_EN.md +++ b/example/rt_device/spi/index_EN.md @@ -4,7 +4,4 @@ :glob: */* - - - ``` diff --git a/example/rt_device/spi_tf/README_EN.md b/example/rt_device/spi_tf/README_EN.md index 015e77a8a..ef97eecf7 100644 --- a/example/rt_device/spi_tf/README_EN.md +++ b/example/rt_device/spi_tf/README_EN.md @@ -1,16 +1,21 @@ # SD Card File System Performance Test Example - -(For an overall overview of the examples and their usage, please refer to the `README.md` file in the parent "examples" directory.) - -This example demonstrates how to perform file system performance testing on SD cards via SPI interface on the SF32LB52x platform. The example implements real-time speed monitoring, buffer optimization, and detailed performance analysis functionality. - -This example utilizes the following features of SiFli-SDK: -- **RT-Thread File System**: Using DFS (Device File System) framework for file operations - [API Reference](https://www.rt-thread.org/document/site/programming-manual/filesystem/filesystem/) -- **SPI Driver**: Communication with SD card through SPI bus - [API Reference](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/drivers/spi.html) +(For an overall overview of the examples and their usage, please refer to the +`README.md` file in the parent "examples" directory.) + +This example demonstrates how to perform file system performance testing on SD +cards via SPI interface on the SF32LB52x platform. The example implements +real-time speed monitoring, buffer optimization, and detailed performance +analysis functionality. +- **RT-Thread File System**: Using DFS (Device File System) framework for file + operations - [API + Reference](https://www.rt-thread.org/document/site/programming-manual/filesystem/filesystem/) +- **SPI Driver**: Communication with SD card through SPI bus - [API + Reference](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/drivers/spi.html) - **FAT File System**: Using ELM FAT file system for data storage -- **HAL Layer Interface**: Using Hardware Abstraction Layer for low-level hardware control +- **HAL Layer Interface**: Using Hardware Abstraction Layer for low-level + hardware control -Based on this example, the following applications can be created: +This example utilizes the following features of SiFli-SDK: - Data logger applications (such as sensor data storage) - Multimedia file storage systems - Embedded database applications @@ -19,7 +24,10 @@ Based on this example, the following applications can be created: ## Usage -The following subsections provide only absolutely necessary information. For complete steps on configuring SiFli-SDK and using it to build and run projects, please refer to [SiFli-SDK Quick Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). +The following subsections provide only absolutely necessary information. For +complete steps on configuring SiFli-SDK and using it to build and run projects, +please refer to [SiFli-SDK Quick +Start](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/quickstart/index.html). ## Supported Development Boards @@ -39,116 +47,118 @@ This example has been verified to run on the following development boards: - Uses SPI1 bus (already connected on board) **Hardware Connection Description**: -| SD Card Pin | Function | Dev Board Pin | -|-------------|----------|---------------| +| SD Card Pin | Function | Dev Board Pin | +| ----------- | ----------- | --------------- | | CS | Chip Select | Auto-configured | -| MOSI | Data Input | SPI1_MOSI | -| MISO | Data Output | SPI1_MISO | -| CLK | Clock | SPI1_CLK | -| VDD | Power | 3.3V | -| GND | Ground | GND | +| MOSI | Data Input | SPI1_MOSI | +| MISO | Data Output | SPI1_MISO | +| CLK | Clock | SPI1_CLK | +| VDD | Power | 3.3V | +| GND | Ground | GND | ### Software Requirements - RT-Thread operating system (integrated in SDK) -- Serial terminal software (such as PuTTY, SecureCRT, etc., for viewing output and inputting commands) +- Serial terminal software (such as PuTTY, SecureCRT, etc., for viewing output + and inputting commands) ## Example Output -If you see the following console output, the example should be running correctly: +If you see the following console output, the example should be running +correctly: ``` SFBL -Serial:c2,Chip:4,Package:4,Rev:7 Reason:00000000 +Serial: c2, Chip: 4, Package: 4, Rev: 7 Reason: 00000000 -[I/drv.adc] Get ADC configure fail +[I/drv.adc] ADC configuration failed \ | / - SiFli Corporation / | \ build on Jul 18 2025, 2.4.0 build 00000000 2020 - 2022 Copyright by SiFli team -mount /dev sucess -[BUS]spi1 probe sdcard... -[MSD] 1006 [err] wait ready timeout! +/dev mounted successfully +[BUS] SPI1 probing SD card... +[MSD] 1006 [err] Wait ready timeout! -[MSD] 1006 [info] SD card goto IDLE mode OK! +[MSD] 1006 [info] SD card entered IDLE mode successfully! -[MSD] 1007 [info] CMD8 response : 0x01 0xF0 0x00 0x01 0xAA +[MSD] 1007 [info] CMD8 response: 0x01 0xF0 0x00 0x01 0xAA -[MSD] 1008 [info] Ver2.00 or later or SDHC or SDXC memory card! +[MSD] 1008 [info] Ver 2.00+ or SDHC/SDXC memory card detected [MSD] 1009 SD_V2: READ_OCR -[MSD] 1009 response:1,0,ff,80 -[MSD] 1010 [info] OCR is 0x00FF8000 +[MSD] 1009 response: 1, 0, ff, 80 +[MSD] 1010 [info] OCR: 0x00FF8000 -[MSD] 1041 SD_V2 again: READ_OCR -[MSD] 1041 [info] OCR 2nd read is 0xC0FF8000 +[MSD] 1041 SD_V2 retry: READ_OCR +[MSD] 1041 [info] OCR 2nd read: 0xC0FF8000 -[MSD] 1042 [info] It is SD2.0 SDHC Card!!! +[MSD] 1042 [info] SD 2.0 SDHC card detected [MSD] 1044 [info] CSD Version 2.0 -[MSD] 1044 [info] TRAN_SPEED: 0x32, 10Mbit/s. +[MSD] 1044 [info] TRAN_SPEED: 0x32, 10 Mbit/s -[MSD] 1045 [info] CSD : C_SIZE : 60719 +[MSD] 1045 [info] CSD: C_SIZE: 60719 -[MSD] 1045 [info] card capacity : 29.64 Gbyte +[MSD] 1045 [info] Card capacity: 29.64 GB -[MSD] 1046 [info] sector_count : 62177280 +[MSD] 1046 [info] Sector count: 62177280 -[SD]msd init ok -find sd0 ok ! 2000d1ac +[SD] MSD initialization successful +Found sd0: 2000d1ac [I/drv.rtc] PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 -[I/drv.rtc] RTC use LXT RTC_CR=00000001 +[I/drv.rtc] RTC using LXT, RTC_CR=00000001 -[I/drv.rtc] Init RTC, wake = 0 +[I/drv.rtc] Initializing RTC, wake = 0 -[I/drv.audprc] init 00 ADC_PATH_CFG0 0x606 +[I/drv.audprc] Init 00 ADC_PATH_CFG0 0x606 -[I/drv.audprc] HAL_AUDPRC_Init res 0 +[I/drv.audprc] HAL_AUDPRC_Init result: 0 -[I/drv.audcodec] HAL_AUDCODEC_Init res 0 +[I/drv.audcodec] HAL_AUDCODEC_Init result: 0 -[I/TOUCH] Regist touch screen driver, probe=120260f5 -call par CFG1(3313) +[I/TOUCH] Registering touch screen driver, probe=120260f5 +Calling par CFG1 (3313) fc 9, xtal 2000, pll 2095 -call par CFG1(3313) +Calling par CFG1 (3313) fc 7, xtal 2000, pll 1676 -fal_mtd_msd_device_create dev:sd0 part:root offset:0x0, size:0xfa000 -fal_mtd_msd_device_create dev:sd0 part:misc offset:0xfa000, size:0xfa000 -mount fs on flash to root success -mount fs on flash to FS_MSIC success +fal_mtd_msd_device_create dev: sd0, part: root, offset: 0x0, size: 0xfa000 +fal_mtd_msd_device_create dev: sd0, part: misc, offset: 0xfa000, size: 0xfa000 +Flash filesystem mounted to root successfully +Flash filesystem mounted to FS_MSIC successfully ========== SD Card File System Performance Test ========== -SF32LB52x SD Card Test Program -Tick Per Second: 1000 +SF32LB52x SD Card Test Utility +Ticks Per Second: 1000 Optimal Buffer Size: 64 KB SD Operation Interval: 5 ms -Use 'help' to see available commands +Type 'help' for a list of available commands Quick commands: - fs_write /test.dat 16 - Test write speed (16MB) - fs_read /test.dat 16 - Test read speed (16MB) - sd_optimize - Check SD configuration - buffer_optimize - Test different buffer sizes - fs_speed_test 32 - Complete speed test (32MB) + fs_write /test.dat 16 - Test write speed (16 MB) + fs_read /test.dat 16 - Test read speed (16 MB) + sd_optimize - Verify SD configuration + buffer_optimize - Evaluate different buffer sizes + fs_speed_test 32 - Comprehensive speed test (32 MB) ========================================================= -msh /> +msh /> ``` -At this point, users need to input commands through the serial terminal to interact with the example. For example, input `fs_write /test.dat 16` to test the speed of writing a 16MB file. - +At this point, users need to input commands through the serial terminal to +interact with the example. For example, input `fs_write /test.dat 16` to test +the speed of writing a 16MB file. ### Usage of Commands in Quick Commands - #### fs_write /test.dat <...> -Enter a number in the <...> position to test the speed of writing a file of that size (in MB). For example: -`fs_write /test.dat 32` +Enter a number in the <...> position to test the speed of writing a file of that +size (in MB). For example: `fs_write /test.dat 32` ``` ========== Write Speed Test ========== File: /test.dat @@ -170,12 +180,10 @@ Total bytes: 33554432 (32 MB) Total time: 28.16 seconds Average speed: 1.14 MB/s ------------------------------ - ``` - #### fs_read /test.dat <...> -Enter a number in the <...> position to test the speed of reading a file of that size (in MB). For example: -`fs_read /test.dat 8` +Enter a number in the <...> position to test the speed of reading a file of that +size (in MB). For example: `fs_read /test.dat 8` ``` ========== Read Speed Test ========== File: /test.dat @@ -191,14 +199,14 @@ Buffer: 64 KB [00:06] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 7.5/8.0 MB (93.8%) ----- Read Test Results ----- -Total bytes: 8388608 (8 MB) -Total time: 6.67 seconds -Average speed: 1.20 MB/s +Total data: 8,388,608 bytes (8 MB) +Elapsed time: 6.67 seconds +Average throughput: 1.20 MB/s ----------------------------- ``` - #### sd_optimize -This is a command to check SD configuration. It will list the main parameters of the environment where this example is running, with the following effect: +This is a command to check SD configuration. It will list the main parameters of +the environment where this example is running, with the following effect: ``` ========== SD Card Configuration ========== SD Card Type: SDHC @@ -221,18 +229,18 @@ SPI Configuration: Buffer Address: 0x60000000 Buffer Size: 64 KB =========================================== - ``` - #### buffer_optimize -This is an option to test different buffer sizes. It can test read and write speeds at 4KB-512KB respectively, display the optimal results, and provide parameter modification suggestions, with the following effect: +This is an option to test different buffer sizes. It can test read and write +speeds at 4KB-512KB respectively, display the optimal results, and provide +parameter modification suggestions, with the following effect: ``` ========== Buffer Size Optimization Test ========== -Testing with proper SD card rest intervals... -Each test uses isolated files and adequate rest time. +Executing tests with standardized SD card cooldown periods... +Each iteration utilizes isolated files and adequate idle time. ==================================================== [1/8] Testing 4 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_4k_0.dat)... Write: 0.92 MB/s [NEW BEST] Read test... @@ -240,7 +248,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 0.92 MB/s, Read 1.13 MB/s [2/8] Testing 8 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_8k_1.dat)... Write: 1.04 MB/s [NEW BEST] Read test... @@ -248,7 +256,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.04 MB/s, Read 1.16 MB/s [3/8] Testing 16 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_16k_2.dat)... Write: 1.10 MB/s [NEW BEST] Read test... @@ -256,7 +264,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.10 MB/s, Read 1.19 MB/s [4/8] Testing 32 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_32k_3.dat)... Write: 1.14 MB/s [NEW BEST] Read test... @@ -264,7 +272,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.14 MB/s, Read 1.20 MB/s [5/8] Testing 64 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_64k_4.dat)... Write: 1.14 MB/s Read test... @@ -272,7 +280,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.14 MB/s, Read 1.20 MB/s [6/8] Testing 128 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_128k_5.dat)... Write: 1.14 MB/s [NEW BEST] Read test... @@ -280,7 +288,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.14 MB/s, Read 1.20 MB/s [7/8] Testing 256 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_256k_6.dat)... Write: 1.14 MB/s Read test... @@ -288,7 +296,7 @@ Each test uses isolated files and adequate rest time. Summary: Write 1.14 MB/s, Read 1.20 MB/s [8/8] Testing 512 KB buffer: - SD card resting (3 seconds)... + SD card cooldown (3 seconds)... Write test (/buftest_512k_7.dat)... Write: 1.15 MB/s [NEW BEST] Read test... @@ -297,18 +305,18 @@ Each test uses isolated files and adequate rest time. ========== Optimization Results ========== -Best Write: 512 KB buffer -> 1.15 MB/s -Best Read: 512 KB buffer -> 1.21 MB/s +Optimal Write: 512 KB buffer -> 1.15 MB/s +Optimal Read: 512 KB buffer -> 1.21 MB/s Current buffer: 64 KB Recommendations: -Recommended buffer size: 512 KB -Consider updating OPTIMAL_BUFFER_SIZE to 512 KB +Suggested buffer size: 512 KB +Consider updating 'OPTIMAL_BUFFER_SIZE' to 512 KB. ========================================== ``` - #### fs_speed_test <...> -Comprehensive test command. Enter a number in the <...> position to determine the test file size (MB) and perform a complete speed test. For example: +Comprehensive test command. Enter a number in the <...> position to determine +the test file size (MB) and perform a complete speed test. For example: ``` ========== Enhanced Speed Test ========== File: /speed_test.dat, Size: 8 MB @@ -345,7 +353,7 @@ Buffer: 64 KB ==================================== [00:01] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 1.3/8.0 MB (15.6%) -[00:02] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 2.5/8.0 MB (31.3%) +[00:02] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 2.5/31.3 MB (31.3%) [00:03] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 3.8/8.0 MB (46.9%) [00:04] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 5.0/8.0 MB (62.5%) [00:05] Read: 1.20 MB/s (Avg: 1.20 MB/s) - 6.3/8.0 MB (78.1%) @@ -360,6 +368,21 @@ Average speed: 1.20 MB/s ========== Test Complete ========== ``` +### Performance test for U-disk mounting via USB transmission + +The performance of this example, with USB transmission enabled and the file +system mounted as a U-disk in the test environment, is as follows: + +#### Write Performance +- Test Conditions: Write 200 MB (204,800 KB) of data +- Duration: 6 min 53 sec (413 sec) +- Average Write Speed: Approx. 495 KB/s + +#### Read Performance +- Test Conditions: Read 200 MB (204,800 KB) of data +- Duration: 6 min 01 sec (361 sec) +- Average Read Speed: Approx. 567 KB/s + ## Example Analysis ### Code Structure @@ -428,7 +451,7 @@ Error: the flash device name (sd0) is not found. #### 2. File System Mount Failure **Error Message**: ``` -mount fs on flash to root fail +Failed to mount flash file system to root. ``` **Solution**: - Check if SD card format is FAT32 @@ -443,11 +466,11 @@ mount fs on flash to root fail **Solution**: 1. Run buffer optimization: ``` - msh />buffer_optimize + msh />buffer_optimize ``` 2. Check SD card configuration: ``` - msh />sd_optimize + msh />sd_optimize ``` 3. Replace with higher speed class SD card (recommend Class 10 or UHS-I) @@ -460,30 +483,33 @@ mount fs on flash to root fail ### Debugging Tips -1. **Enable Verbose Logging** - Define in `spi_msd.c`: +1. **Enable Verbose Logging** Define in `spi_msd.c`: ```c #define MSD_TRACE ``` 2. **Monitor Memory Usage** ``` - msh />free + msh />free ``` 3. **View Thread Status** ``` - msh />list_thread + msh />list_thread ``` -If you have any technical questions, please submit an [issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. +If you have any technical questions, please submit an +[issue](https://github.com/OpenSiFli/SiFli-SDK/issues) on GitHub. ## Reference Documentation -- [RT-Thread File System Documentation](https://www.rt-thread.org/document/site/programming-manual/filesystem/filesystem/) -- [SiFli SDK SPI Driver Documentation](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/drivers/spi.html) +- [RT-Thread File System + Documentation](https://www.rt-thread.org/document/site/programming-manual/filesystem/filesystem/) +- [SiFli SDK SPI Driver + Documentation](https://docs.sifli.com/projects/sdk/latest/sf32lb52x/drivers/spi.html) - [FAT File System Specification](http://elm-chan.org/fsw/ff/00index_e.html) -- [SD Card SPI Mode Protocol Specification](https://www.sdcard.org/downloads/pls/) +- [SD Card SPI Mode Protocol + Specification](https://www.sdcard.org/downloads/pls/) ## SD Card Performance Test - Quick Command Reference @@ -576,6 +602,7 @@ rm /speed_test.dat ls / ``` + ### Tips - Use `help` to see all commands @@ -584,10 +611,13 @@ ls / ### Quick Troubleshooting -| Issue | Solution | -|-------|----------| -| SD not found | Re-insert SD card | -| Mount failed | Execute `dfs_mkfs elm root` | -| Low speed | Run `buffer_optimize` | -| Test hangs | Restart system | - +| Issue | Solution | +| ------------------ | --------------------------- | +| SD not found | Re-insert SD card | +| Mount failed | Execute `dfs_mkfs elm root` | +| Low speed | Run `buffer_optimize` | +| Test hangs | Restart system | +| Throughput too low | Execute `buffer_optimize` | +| Low speed | Run `buffer_optimize` | +| Test hangs | Restart system | +| Test hangs | Restart system | diff --git a/example/rt_device/uart/README_EN.md b/example/rt_device/uart/README_EN.md index acc6a576f..926d44cb1 100644 --- a/example/rt_device/uart/README_EN.md +++ b/example/rt_device/uart/README_EN.md @@ -7,78 +7,102 @@ The example can run on the following development boards: * sf32lb56-lcd series * sf32lb58-lcd series ## Overview -* Under RT-Thread operating system, use RX DMA mode to operate UART2 to verify its serial port transmission and reception capabilities -* Note that after development board reset, if uart2 prints log consistent with the image below, it indicates successful transmission. To verify uart2 reception capability, the default serial port print log is used to verify the accuracy of received content +* Under RT-Thread operating system, use RX DMA mode to operate UART2 to verify + its serial port transmission and reception capabilities +* Note that after development board reset, if uart2 prints log consistent with + the image below, it indicates successful transmission. To verify uart2 + reception capability, the default serial port print log is used to verify the + accuracy of received content ## Example Usage ### Compilation and Programming -For detailed steps on compilation and downloading, please refer to [](/quickstart/get-started.md) related introduction. -* This example uses uart2. When using RT-Thread operating system, uart2 peripheral will be virtualized as an rt_device for read and write operations. At this time, you need to confirm whether the `rtconfig.h` file in the project compilation path contains the following 3 macros: +For detailed steps on compilation and downloading, please refer to +[](/quickstart/get-started.md) related introduction. +* This example uses uart2. When using RT-Thread operating system, uart2 + peripheral will be virtualized as an rt_device for read and write operations. + At this time, you need to confirm whether the `rtconfig.h` file in the project + compilation path contains the following 3 macros: ```c #define BSP_USING_UART 1 #define BSP_USING_UART2 1 #define BSP_UART2_RX_USING_DMA 1 ``` -Only when the above three macros are included, the `rt_hw_serial_register` function will register the `"uart2"` `rt_device` in the `rt_hw_usart_init` function, and then this device can be successfully found and opened with `rt_device_find` and `rt_device_open`. +Only when the above three macros are included, the `rt_hw_serial_register` +function will register the `"uart2"` `rt_device` in the `rt_hw_usart_init` +function, and then this device can be successfully found and opened with +`rt_device_find` and `rt_device_open`. -If the above three macros are missing, you need to enable them through the following `menuconfig` command (Note: missing macros may not cause errors, if configured serial port has no information printed, please check if it's enabled in time): +If the above three macros are missing, you need to enable them through the +following `menuconfig` command (Note: missing macros may not cause errors, if +configured serial port has no information printed, please check if it's enabled +in time): ```c menuconfig --board=sf32lb52-lcd_n16r8 ``` -As shown in the figure below, select uart2 and rx dma, save and exit menuconfig, check if `rtconfig.h` macro is generated -![alt text](assets/menuconfig.png) -* Switch to example project directory and run scons command to execute compilation: +As shown in the figure below, select uart2 and rx dma, save and exit menuconfig, +check if `rtconfig.h` macro is generated ![alt text](assets/menuconfig.png) +* Switch to example project directory and run scons command to execute + compilation: ``` scons --board=sf32lb52-lcd_n16r8 -j8 ``` -* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select port as prompted to download: +* Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select port as prompted + to download: ``` build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat -Uart Download +UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` ### Hardware Connection -Here is the document link, in which the pin definitions have the actual pin mapping relationships: +Here is the document link, in which the pin definitions have the actual pin +mapping relationships: [SF32LB52-DevKit-LCD](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-LCD.html) [SF32LB52-DevKit-Nano](https://wiki.sifli.com/board/sf32lb52x/SF32LB52-DevKit-Nano.html) [SF32LB56-DevKit-LCD](https://wiki.sifli.com/board/sf32lb56x/SF32LB56-DevKit-LCD.html) [SF32LB58-DevKit-LCD](https://wiki.sifli.com/board/sf32lb58x/SF32LB58-DevKit-LCD.html) -|Board Name | UART | TX(Physical Position) | RX(Physical Position) | -|--------|------------|---------------|-------------------| -|525/56 | UART2 | PAD_PA27(8) | PAD_PA20(10) | -|587 | UART2 | PAD_PA28 (CONN2 5) |PAD_PA29 (CONN2 3) | -|52nano | UART2 | PAD_PA28 |PAD_PA25 | +| Board Name | UART | TX(Physical Position) | RX(Physical Position) | +| ---------- | ----- | --------------------- | --------------------- | +| 525/56 | UART2 | PAD_PA27(8) | PAD_PA20(10) | +| 587 | UART2 | PAD_PA28 (CONN2 5) | PAD_PA29 (CONN2 3) | +| 52nano | UART2 | PAD_PA28 | PAD_PA25 | Here is an example diagram of the 525 connection: -* PA27 configured in software as UART2 TX, connected to computer USB-to-serial RX -* PA20 configured in software as UART2 RX, connected to computer USB-to-serial TX +* PA27 configured in software as UART2 TX, connected to computer USB-to-serial + RX +* PA20 configured in software as UART2 RX, connected to computer USB-to-serial + TX * GND connected to USB-to-serial GND, as shown below: ![alt text](assets/52-DevKit-lcd-V1.0.png) #### Example Output Results Display: -* Log output: left side shows machine log, right side shows computer USB-to-serial data transmission and reception: -![alt text](assets/uart_log.png) +* Log output: left side shows machine log, right side shows computer + USB-to-serial data transmission and reception: ![alt + text](assets/uart_log.png) -* Note: There are two serial ports when serial port is opened, one is the uart2 configured by code for computer USB-to-serial, and one is the built-in debug port uart1 +* Note: There are two serial ports when serial port is opened, one is the uart2 + configured by code for computer USB-to-serial, and one is the built-in debug + port uart1 +The `rev: ` at the end of the log is the character received from computer +USB-to-serial TX -The `rev: ` at the end of the log is the character received from computer USB-to-serial TX - -* Note: Here the received data is printed using the default serial port instead of uart2, because uart2's data transmission function is also one of the example features +* Note: Here the received data is printed using the default serial port instead + of uart2, because uart2's data transmission function is also one of the + example features ``` - SFBL +SFBL Serial:c2,Chip:4,Package:3,Rev:3 Reason:00000080 \ | / - SiFli Corporation / | \ build on Oct 23 2024, 2.2.0 build 00000000 2020 - 2022 Copyright by SiFli team - mount /dev sucess + mount /dev success [32m][490] I/drv.rtc: PSCLR=0x80000100 DivAI=128 DivAF=0 B=256 [0m][32m][517] I/drv.rtc: RTC use LXT RTC_CR=00000001 [0m][32m][538] I/drv.rtc: Init RTC, wake = 1 @@ -94,30 +118,37 @@ The `rev: ` at the end of the log is the character received from computer USB-to [796] D/uart2: uart device config 0 send:uart2 demo uart demo end! - msh /> + msh /> uart_rec: cnt = 5,count = 5 uart_rec: cnt = 0,count = 5 rev:abc ``` -Below is the data `uart2 demo` characters sent by computer USB-to-serial after development board reset, and the data sent manually to verify if uart2 can receive serial port data +Below is the data `uart2 demo` characters sent by computer USB-to-serial after +development board reset, and the data sent manually to verify if uart2 can +receive serial port data ```c - uart2 demo +uart2 demo TX:abc ``` -Function to verify uart2 reception content accuracy: After sending abc in uart2 log window, it will receive `abc` characters, line feed, and carriage return in corresponding uart2 interrupt, total 5 character ASCII codes, printing the following content -* Note: Always printing one extra log considers that continuous reception may exceed maximum receivable value and require multiple receptions, e.g., if maximum reception is 256 but received is 260, it will print\ -uart_rec: cnt = 256,count = 256\ -uart_rec: cnt = 4,count = 260\ -uart_rec: cnt = 0,count = 260 +Function to verify uart2 reception content accuracy: After sending abc in uart2 +log window, it will receive `abc` characters, line feed, and carriage return in +corresponding uart2 interrupt, total 5 character ASCII codes, printing the +following content +* Note: Always printing one extra log considers that continuous reception may + exceed maximum receivable value and require multiple receptions, e.g., if + maximum reception is 256 but received is 260, it will print\ + uart_rec: cnt = 256,count = 256\ + uart_rec: cnt = 4,count = 260\ + uart_rec: cnt = 0,count = 260 ```c - uart_rec: cnt = 5,count = 5 +uart_rec: cnt = 5,count = 5 uart_rec: cnt = 0,count = 5 rev:abc ``` #### uart2 Configuration Process -* Ensure `rtconfig.h` file contains the following 3 macros: -Input command in compilation window to check board=(board type) +* Ensure `rtconfig.h` file contains the following 3 macros: Input command in + compilation window to check board=(board type) ```c #define BSP_USING_UART 1 #define BSP_USING_UART2 1 @@ -130,20 +161,26 @@ menuconfig --board=sf32lb52-lcd_n16r8 * Set corresponding Uart2 IO ports ```c - #if defined(BSP_USING_BOARD_EM_LB525XXX) +#if defined(BSP_USING_BOARD_EM_LB525XXX) HAL_PIN_Set(PAD_PA20, USART2_RXD, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA27, USART2_TXD, PIN_PULLUP, 1); - #elif defined (BSP_USING_BOARD_EM_LB587XXX) + #elif defined (BSP_USING_BOARD_EM_LB525XXX) HAL_PIN_Set(PAD_PA29, USART2_RXD, PIN_PULLUP, 1); HAL_PIN_Set(PAD_PA28, USART2_TXD, PIN_PULLUP, 1); #endif ``` -**Note**: -1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART functionality to output UART2 waveform (to query pin multiplexing table, search in project path files such as: bf0_pin_const.c) -2. HAL_PIN_Set last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: select lcpu -3. Hcpu PA ports cannot be configured for Lcpu uart peripherals, such as uart5, uart6 output -* Explanation of partial content in serial port initialization function int uart2_init(void):\ -Use `rt_device_find`, `rt_device_control`, `rt_device_open` sequentially to find, configure, and open `uart2` device +**Note**: +1. Except for 55x chips, can be configured to any IO with PA*_I2C_UART + functionality to output UART2 waveform (to query pin multiplexing table, + search in project path files such as: bf0_pin_const.c) +2. HAL_PIN_Set last parameter is for hcpu/lcpu selection, 1: select hcpu, 0: + select lcpu +3. Hcpu PA ports cannot be configured for Lcpu uart peripherals, such as uart5, + uart6 output +* Explanation of partial content in serial port initialization function int + uart2_init(void):\ + Use `rt_device_find`, `rt_device_control`, `rt_device_open` sequentially to + find, configure, and open `uart2` device ```c #define UART_DEMO_NAME "uart2" @@ -176,11 +213,13 @@ Use `rt_device_find`, `rt_device_control`, `rt_device_open` sequentially to find } /* set the callback function of recieving */ ``` -* Configure uart2 interrupt callback function `uart_rx_ind`, and create and start thread `serial_rx_thread_entry` to receive and process data received by RX DMA +* Configure uart2 interrupt callback function `uart_rx_ind`, and create and + start thread `serial_rx_thread_entry` to receive and process data received by + RX DMA ```c - /* Set uart_rx_ind as uart2 interrupt callback function */ +/* Set uart_rx_ind as uart2 interrupt callback function */ rt_device_set_rx_indicate(g_uart_device, uart_rx_ind); - + /* creat the thread of g_uart_device */ rt_thread_t thread = rt_thread_create("g_uart_device", serial_rx_thread_entry, RT_NULL, 3 * 1024, 12, 10); @@ -194,23 +233,27 @@ Use `rt_device_find`, `rt_device_control`, `rt_device_open` sequentially to find ret = RT_ERROR; } ``` -* static void serial_rx_thread_entry(void parameter) receives and processes data received by RX DMA: uses default serial port print function `rt_kprintf` to verify data received by uart2, continuously loops using `cnt = rt_device_read()` to check if data is currently received, so log printing will always print one extra case when cnt=0 +* static void serial_rx_thread_entry(void parameter) receives and processes data + received by RX DMA: uses default serial port print function `rt_kprintf` to + verify data received by uart2, continuously loops using `cnt = + rt_device_read()` to check if data is currently received, so log printing will + always print one extra case when cnt=0 ```c uint16_t count = 0; uint8_t cnt = 0; while (1) { - rt_sem_take(&rx_sem, RT_WAITING_FOREVER); + rt_sem_take(&rx_sem, RT_WAITING_FOREVER); while (1) { - cnt = rt_device_read(g_uart_device, -1, &data[count], ONE_DATA_MAXLEN); + cnt = rt_device_read(g_uart_device, -1, &data[count], ONE_DATA_MAXLEN); count += cnt; rt_kprintf("uart_rec: cnt = %d,count = %d\n", cnt, count); if (0 == cnt) break; } rt_kprintf("rev:"); - for (uint16_t i = 0; i < count; i++) + for (uint16_t i = 0; i < count; i++) { rt_kprintf("%c", data[i]); } @@ -220,13 +263,15 @@ uint16_t count = 0; ``` * uart2 sends data through uart_send_data function ```c - uint8_t tx_data[ONE_DATA_MAXLEN] = {'u','a','r','t','2',' ','d','e','m','o','\n'}; +uint8_t tx_data[ONE_DATA_MAXLEN] = {'u','a','r','t','2',' ','d','e','m','o','\n'}; uart_send_data(tx_data,12); ``` -* After enabling `finsh` functionality, you can input `list_device` in log serial terminal to check if `uart2` is in open status. 0 means device is registered, 1,2 means number of times device is opened +* After enabling `finsh` functionality, you can input `list_device` in log + serial terminal to check if `uart2` is in open status. 0 means device is + registered, 1,2 means number of times device is opened ```c - TX:list_device +TX:list_device list_device device type ref count -------- -------------------- ---------- @@ -244,34 +289,40 @@ uint16_t count = 0; uart2 Character Device 1 uart1 Character Device 2 pin Miscellaneous Device 0 - msh /> + msh /> ``` -* This only demonstrates one recommended usage of uart. For other operations under rt-thread operating system, refer to rt-thread official website user manual - +* This only demonstrates one recommended usage of uart. For other operations + under rt-thread operating system, refer to rt-thread official website user + manual ## Exception Diagnosis * No uart2 waveform output -1. Use `pin status 20/27` command to check corresponding PA20, PA27 IO status FUNC. VAL level should be 1 +1. Use `pin status 20/27` command to check corresponding PA20, PA27 IO status + FUNC. VAL level should be 1 ```c - msh /> +msh /> TX:pin status 20 pin status 20 [I/TEST.GPIO] PIN 20, FUNC=4, VAL=1, DIG_IO_PU, GPIO_MODE_INPUT, irqhdr=/, arg=/ - msh /> - msh /> + msh /> + msh /> TX:pin status 27 pin status 27 [I/TEST.GPIO] PIN 27, FUNC=4, VAL=1, DIG_IO_PU, GPIO_MODE_INPUT, irqhdr=/, arg=/ - msh /> - msh /> + msh /> + msh /> ``` 2. Use `list_device` command to check if `uart2` device exists and is opened 3. Check if uart2 configuration process is all effective * uart2 waveform normal, computer serial port cannot receive data -1. Check if uart2 output and computer serial port connection are normal, need TX to connect RX, RX to connect TX, if baud rate is consistent, and if corresponding TX, RX pins are correct -2. Check hardware connection, including if uart2 output level and computer uart level are consistent +1. Check if uart2 output and computer serial port connection are normal, need TX + to connect RX, RX to connect TX, if baud rate is consistent, and if + corresponding TX, RX pins are correct +2. Check hardware connection, including if uart2 output level and computer uart + level are consistent * Computer serial port sends data, uart2 has data reception loss phenomenon -1. Confirm if serial port DMA buffer length is sufficient `#define RT_SERIAL_RB_BUFSZ 256` +1. Confirm if serial port DMA buffer length is sufficient `#define + RT_SERIAL_RB_BUFSZ 256` ```c /* &data[count]: memory address for received data; @@ -279,15 +330,16 @@ ONE_DATA_MAXLEN: prepared reception length, can be larger than DMA buffer length Return value: actual received length, 0 means reception completed; */ rt_device_read(g_uart_device, -1, &data[count], ONE_DATA_MAXLEN); -``` +``` ## Reference Documents * EH-SF32LB52X_Pin_config_V1.3.0_20231110.xlsx -* DS0052-SF32LB52x-芯片技术规格书 V0p3.pdf -* DS0058-SF32LB58x-芯片技术规格书 V1p8.pdf -* RT-Thread Official Website https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README +* DS0052-SF32LB52x-Datasheet V0p3.pdf +* DS0058-SF32LB58x-Datasheet V1p8.pdf +* RT-Thread Official Website + https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/README ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| 0.0.2| 12/2024|2.0 | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| 0.0.2 | 12/2024 | 2.0 | diff --git a/example/rt_device/usb/index_EN.md b/example/rt_device/usb/index_EN.md index 570f96de5..0c67f72b2 100644 --- a/example/rt_device/usb/index_EN.md +++ b/example/rt_device/usb/index_EN.md @@ -4,7 +4,4 @@ :glob: */* - - - ``` diff --git a/example/rt_device/usb/usb_mstorage/README_EN.md b/example/rt_device/usb/usb_mstorage/README_EN.md index 87982c9eb..e02c0db6e 100644 --- a/example/rt_device/usb/usb_mstorage/README_EN.md +++ b/example/rt_device/usb/usb_mstorage/README_EN.md @@ -1,6 +1,8 @@ # USB_MSTORAGE Example +Source Path: example/rt_device/usb/usb_mstorage ## Overview -The example demonstrates USB as a device functioning as a USB flash drive, which can mount local file system on PC. +The example demonstrates USB as a device functioning as a USB flash drive, which +can mount local file system on PC. ## Supported Development Boards The example can run on the following development boards: @@ -9,11 +11,14 @@ The example can run on the following development boards: * sf32lb56-lcd series * sf32lb58-lcd series - -**Note:** Generally, examples run on the chip's HCPU. "eh-lb563_v2" is equivalent to "eh-lb563_v2_hcpu". If you want to run the example on LCPU, you can use "eh-lb563_v2_lcpu". Currently USB functionality temporarily only supports running on HCPU. +**Note:** Generally, examples run on the chip's HCPU. "eh-lb563_v2" is +equivalent to "eh-lb563_v2_hcpu". If you want to run the example on LCPU, you +can use "eh-lb563_v2_lcpu". Currently USB functionality temporarily only +supports running on HCPU. ## Example Directory Structure -USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows other files in the project directory. +USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows +other files in the project directory. ``` |--Readme.md |--src @@ -29,59 +34,68 @@ USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows ``` ## Example Usage ### Hardware Requirements -1. To run the example, you need to have a development board that supports this example. -2. A USB data cable capable of data transmission. -3. HDK52X V1.2 version hardware needs the following changes: +1. To run this example, a compatible development board is required. 2. A USB +data cable with data transfer capability is required. 3. For HDK52X V1.2 +hardware, the following modifications are necessary: | R0105 | R0710 | R0706 | -|-------|-------|-------| -| NF | NF | NF | +| ----- | ----- | ----- | +| NF | NF | NF | -4. HDK56X V1.1 version hardware needs the following changes: +4. For HDK56X V1.1 hardware, the following modifications are necessary: | R0210 | R0211 | R0202 | R0204 | R0634 | R0633 | R0132 | R0107 | R0103 | R0106 | -|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------| -| NF | NF | NF | NF | NF | NF | NF | NF | 220K | 390K | +| ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | +| NF | NF | NF | NF | NF | NF | NF | NF | 220K | 390K | ### Pin Configuration -**Note:** The table below shows pin configurations for VBUS control on each development board. -1. In HDK52X V1.2 version, USB insertion/removal pin uses NTC function pin multiplexing. -2. In HDK56X V1.1 version, USB DP and DM pins are multiplexed with UART1, so you need to change LOG print uart1 to uart4 and disable uart1. -| | vbus pin | DP | DM | -|---------------|-------------|------|------| -|eh-lb523 | PA32 | PA35 | PA36 | -|eh-lb520 | PA32 | PA35 | PA36 | -|eh-lb525 | PA32 | PA35 | PA36 | -|eh-lb561 | PA51 | PA17 | PA18 | -|eh-lb563 | PAXX | PA17 | PA18 | +**Note:** The table below shows pin configurations for VBUS control on each +development board. +| | VBUS pin | DP | DM | +| -------- | -------- | ---- | ---- | +| eh-lb523 | PA32 | PA35 | PA36 | +| eh-lb520 | PA32 | PA35 | PA36 | +| eh-lb525 | PA32 | PA35 | PA36 | +| eh-lb561 | PA51 | PA17 | PA18 | +| eh-lb563 | PAXX | PA17 | PA18 | ### menuconfig Configuration ``` //Execute command menuconfig --board=sf32lb52-lcd_n16r8 ``` -**Note:** USB pins in HDK52X are not multiplexed with UART, so steps 1 and 2 can be skipped. +**Note:** USB pins in HDK52X are not multiplexed with UART, so steps 1 and 2 can +be skipped. -1. Configure log print serial port number "the device name for console" +If there is DHARA functionality (like 525, 563 using external NAND flash chip +series), due to DHARA mapping existence, "msc class disk name" is the DHARA name +after mapping: for example, currently 563HDK has only one partition with DHARA +name dhara0. -2. Enable log print serial port uart4, disable uart1; "Enable UART4" -![alt text](assets/1.png) +2. Enable UART4 for log output and disable UART1; "Enable UART4" ![alt +text](assets/1.png) -3. Enable USB device functionality; "Enable USB Device" -![alt text](assets/2.png) +3. Enable the USB device functionality. Select "Enable USB Device" as shown in +![alt text](assets/2.png). -4. Configure USB insertion detection pin; "usb Insertion detetion PIN", configure it to corresponding pin number +4. Configure the USB insertion detection pin. Set "usb Insertion detection PIN" +to the corresponding pin number. -5. Enable USB storage functionality; "Enable to usb device as Mass Storage device" -![alt text](assets/3.png) +5. Enable the USB storage functionality. Select "Enable to usb device as Mass +Storage device" as shown in ![alt text](assets/3.png). -6. Configure USB mount file system partition; -If there is no DHARA functionality (used for NAND management and optimization) like HDK523, HDK561, you only need to modify "msc class disk name" to the file system partition name to be loaded for USB recognition. -![alt text](assets/4.png) +6. Configure the USB mount partition. For systems without DHARA functionality +(used for NAND management and optimization), such as the HDK523 and HDK561, +simply set the "msc class disk name" to the name of the file system partition to +be exported via USB. ![alt text](assets/4.png) -If there is DHARA functionality (like 525, 563 using external NAND flash chip series), due to DHARA mapping existence, "msc class disk name" is the DHARA name after mapping: for example, currently 563HDK has only one partition with DHARA name dhara0. +For systems with DHARA functionality (such as the 525 and 563 series using +external NAND flash), the "msc class disk name" must be set to the mapped DHARA +device name due to the DHARA translation layer. For example, on the current +563HDK, a single partition is mapped as "dhara0". ### Compilation and Programming -Follow these steps to complete compilation and programming. -The project's NAND or NOR needs to be selected for compilation and burning based on the flash chip model mounted on the board. +Follow these steps to complete compilation and programming. The project's NAND +or NOR needs to be selected for compilation and burning based on the flash chip +model mounted on the board. ``` scons --board=sf32lb52-lcd_n16r8 @@ -89,14 +103,15 @@ scons --board=sf32lb52-lcd_n16r8 ``` ## Example Output Results Display -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and requires troubleshooting. -System startup +The following results show the log after the example runs on the development +board. If you cannot see these logs, it means the example did not run +successfully as expected and requires troubleshooting. System startup ``` mount fs on flash to root success usb_init Use help to check USB mstorage file system command! -msh />usb_thread_entry +msh />usb_thread_entry ``` Log when USB is inserted and USB flash drive device is detected @@ -104,7 +119,8 @@ Log when USB is inserted and USB flash drive device is detected ![alt text](assets/log1.png) ## Troubleshooting -If expected log does not appear, troubleshooting can be done from the following aspects: +If expected log does not appear, troubleshooting can be done from the following +aspects: * Whether hardware connection is normal * Whether pin configuration is correct * Check if USB interface is loose @@ -112,23 +128,29 @@ If expected log does not appear, troubleshooting can be done from the following * Check if USB clock is 60MHz frequency ## Example Extension - + If you want to modify VBUS detection pin number, you can modify as follows: -1. Modify configuration menuconfig --board=eh-lb525 and re-modify the parameter in "usb Insertion detection PIN" to the desired detection pin -D:\MyWork\code_sdk\siflisdk\customer\boards\ec-lb555xxx -2. Modify pinmux configuration file **"\siflisdk\customer\boards\ec-lb corresponding model directory\bsp_pinmux.c"**, configure this pin to GPIO mode; +1. Modify configuration menuconfig --board=eh-lb525 and re-modify the parameter + in "usb Insertion detection PIN" to the desired detection pin + D:\MyWork\code_sdk\siflisdk\customer\boards\ec-lb555xxx +2. Modify pinmux configuration file **"\siflisdk\customer\boards\ec-lb + corresponding model directory\bsp_pinmux.c"**, configure this pin to GPIO + mode; ```c -HAL_PIN_Set(PAD_PA32, GPIO_A32, PIN_NOPULL, 1);//USB VBUS +HAL_PIN_Set(PAD_PA32, GPIO_A32, PIN_NOPULL, 1); // USB VBUS ``` ## Example Instance sf32lb52-lcd_52d -The following are instance steps for implementing USB flash drive functionality using sf32lb52-lcd_52d +The following are instance steps for implementing USB flash drive functionality +using sf32lb52-lcd_52d ### Hardware Requirements -* To run the example, you need to have a development board that supports this example. +* To run the example, you need to have a development board that supports this + example. * Two USB data cables capable of data transmission. -Insert two data cables into 52d interfaces and connect to PC. If PC shows "Unrecognized USB device", it may be due to: +Insert two data cables into 52d interfaces and connect to PC. If PC shows +"Unrecognized USB device", it may be due to: * USB Device not enabled * Hardware device not connected correctly @@ -136,7 +158,8 @@ Insert two data cables into 52d interfaces and connect to PC. If PC shows "Unrec * Connected data cable is damaged and cannot perform data transmission Here are some solutions: -* Enter menu page through menuconfig --board=sf32lb52-lcd_52d command, enable Enable USB Device, then check register data for self-diagnosis +* Enter menu page through menuconfig --board=sf32lb52-lcd_52d command, enable + Enable USB Device, then check register data for self-diagnosis ![alt text](assets/code4.png) @@ -144,40 +167,46 @@ Here are some solutions: * Replace with a normally functioning data cable -When USB insertion can be recognized normally, you can proceed with file writing and programming +When USB insertion can be recognized normally, you can proceed with file writing +and programming ### Compilation and Programming -Execute the following commands to complete compilation and programming for -emlb52d. +Execute the following commands to complete compilation and programming for +-emlb52d. ``` scons --board=sf32lb52-lcd_52d -j8 build_sf32lb52-lcd_52d_hcpu\uart_download.bat - ``` ## Example Instance -emlb587 -The following are instance steps for implementing USB flash drive functionality using -emlb587 +The following are instance steps for implementing USB flash drive functionality +using -emlb587 ### Hardware Requirements -* To run the example, you need to have a development board that supports this example. +* To run the example, you need to have a development board that supports this + example. * Two USB data cables capable of data transmission. * A j-link for programming -After connecting link with development board and PC, proceed with file compilation and programming +After connecting link with development board and PC, proceed with file +compilation and programming ### Compilation and Programming Execute the following commands to complete compilation for -emlb587. ``` -scons --board=sf32lb58-lcd_n16r64n4 -j8 +scons --board=sf32lb58-lcd_n16r64n4 -j8 ``` -After compilation, open J-LINK connection tool, execute connect command to connect. If connection fails, check if serial port is occupied or other issues. After successful J-LINK connection, proceed with file programming +After compilation, open J-LINK connection tool, execute connect command to +connect. If connection fails, check if serial port is occupied or other issues. +After successful J-LINK connection, proceed with file programming Execute the following commands to complete programming for -emlb587. ``` -build_sf32lb58-lcd_n16r64n4_hcpu\download.bat +build_sf32lb58-lcd_n16r64n4_hcpu\download.bat ``` @@ -186,4 +215,5 @@ build_sf32lb58-lcd_n16r64n4_hcpu\download.bat USB flash drive device appears in PC device list -![alt text](assets/6_LI.png) \ No newline at end of file +![alt text](assets/6_LI.png) + diff --git a/example/rt_device/usb/usb_vcom/README_EN.md b/example/rt_device/usb/usb_vcom/README_EN.md index ec9ea732c..00e2ab070 100644 --- a/example/rt_device/usb/usb_vcom/README_EN.md +++ b/example/rt_device/usb/usb_vcom/README_EN.md @@ -1,6 +1,8 @@ # USB_VCOM Example +Source path: example/rt_device/usb/usb_vcom ## Overview -The example demonstrates USB as a device functioning as virtual serial port, which can access USB device through serial port on PC. +The example demonstrates USB as a device functioning as virtual serial port, +which can access USB device through serial port on PC. ## Supported Development Boards The example can run on the following development boards:
@@ -8,10 +10,14 @@ The example can run on the following development boards:
* sf32lb56-lcd series * sf32lb58-lcd series -**Note:** Generally, examples run on the chip's HCPU. "eh-lb563" is equivalent to "eh-lb563_hcpu". If you want to run the example on LCPU, you can use "eh-lb563_lcpu". Currently USB functionality temporarily only supports running on HCPU. +**Note:** Generally, examples run on the chip's HCPU. "eh-lb563" is equivalent +to "eh-lb563_hcpu". If you want to run the example on LCPU, you can use +"eh-lb563_lcpu". Currently USB functionality temporarily only supports running +on HCPU. ## Example Directory Structure -USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows other files in the project directory. +USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows +other files in the project directory. ``` |--Readme.md |--src @@ -27,49 +33,48 @@ USB_MSTORAGE project contains 1 .c file (main.c). The tree structure below shows ``` ## Example Usage ### Hardware Requirements -1. To run the example, you need to have a development board that supports this example. -2. A USB data cable capable of data transmission. -3. HDK52X V1.2 version hardware needs the following changes: +1. To run this example, a compatible development board is required. 2. A USB +data cable with data transfer capability is required. 3. For HDK52X V1.2 +hardware, the following modifications are necessary: | R0105 | R0710 | R0706 | -|-------|-------|-------| -| NF | NF | NF | +| ----- | ----- | ----- | +| NF | NF | NF | -4. HDK56X V1.1 version hardware needs the following changes: +4. For HDK56X V1.1 hardware, the following modifications are necessary: | R0210 | R0211 | R0202 | R0204 | R0634 | R0633 | R0132 | R0107 | R0103 | R0106 | -|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------| -| NF | NF | NF | NF | NF | NF | NF | NF | 220K | 390K | +| ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | +| NF | NF | NF | NF | NF | NF | NF | NF | 220K | 390K | ### Pin Configuration -**Note:** The table below shows pin configurations for VBUS control on each development board. -1. In HDK52X V1.2 version, USB insertion/removal pin uses NTC function pin multiplexing. -2. In HDK56X V1.1 version, USB DP and DM pins are multiplexed with UART1, so you need to change LOG print uart1 to uart4 and disable uart1. -| | vbus pin | DP | DM | -|---------------|-------------|------|------| -|eh-lb523 | PA32 | PA35 | PA36 | -|eh-lb520 | PA32 | PA35 | PA36 | -|eh-lb525 | PA32 | PA35 | PA36 | -|eh-lb561 | PA51 | PA17 | PA18 | -|eh-lb563 | PAXX | PA17 | PA18 | +**Note:** The table below shows pin configurations for VBUS control on each +development board. +| | VBUS pin | DP | DM | +| -------- | -------- | ---- | ---- | +| eh-lb523 | PA32 | PA35 | PA36 | +| eh-lb520 | PA32 | PA35 | PA36 | +| eh-lb525 | PA32 | PA35 | PA36 | +| eh-lb561 | PA51 | PA17 | PA18 | +| eh-lb563 | PAXX | PA17 | PA18 | ### menuconfig Configuration ``` //Execute command menuconfig --board=sf32lb52-lcd_n16r8 ``` -**Note:** USB pins in HDK52X are not multiplexed with UART, so steps 1 and 2 can be skipped. +**Note:** USB pins in HDK52X are not multiplexed with UART, so steps 1 and 2 can +be skipped. -1. Configure log print serial port number "the device name for console" +1. Set "the device name for console" to configure the UART port for log output. ![alt text](assets/usb_1.jpg) -2. Enable log print serial port uart4, disable uart1; "Enable UART4" -![alt text](assets/usb_2.jpg) +2. Enable UART4 for log output and disable UART1; "Enable UART4" ![alt +text](assets/usb_2.jpg) 3. Enable USB device functionality; "Enable USB Device" -* In compilation interface, input `menuconfig --board=sf32lb52-lcd_52d` to enter menu, configure as follows under `(Top) → On-chip Peripheral RTOS Drivers` -![alt text](assets/usb_3.jpg) -* Under `(Top) → Device Drivers → Using USB`, enable CDC device, set virtual serial port character size, enable virtual serial port DMA functionality. -![alt text](assets/enable.png) -* Under `(Top) → Device Drivers → Using USB → Device type`, select CDC device -![alt text](assets/CDC.png) +* Configure log print serial port number "the device name for console" ![alt + text](assets/usb_3.jpg) +* Enable log print serial port uart4, disable uart1; "Enable UART4" ![alt + text](assets/enable.png) +* Enable USB device functionality; "Enable USB Device" ### Compilation and Programming Follow these steps to complete compilation and programming. @@ -79,59 +84,64 @@ scons --board=sf32lb52-lcd_n16r8 -j8 build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat ``` -(For operating different chip boards, just change the chip name, for example 587 board, just replace 'eh-lb525' with 'sf32lb58-lcd_n16r64n4') +(For operating different chip boards, just change the chip name, for example 587 +board, just replace 'eh-lb525' with 'sf32lb58-lcd_n16r64n4') ## Example Output Results Display -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and requires troubleshooting. -System startup +The following results show the log after the example runs on the development +board. If you cannot see these logs, it means the example did not run +successfully as expected and requires troubleshooting. System startup ```c - usb_init - Use help to check USB cdc vcom command! - msh /> +usb_init +Use 'help' to view the USB CDC VCOM commands. +msh /> ``` -1. Serial port data transmission; input finsh command "vcom_write 123456" (using serial port tool SifliTrace) ![alt text](./assets/vcom_write.png) ```c -void vcom_write(int avgc, char **argv) +void vcom_write(int argc, char **argv) { - rt_size_t len = rt_device_write(usb_vcom, 0, argv[1], strlen(argv[1])); - if (len != strlen(argv[1])) rt_kprintf("write fail!\n"); - else rt_kprintf("write succ!\n"); + rt_size_t len = rt_device_write(usb_vcom, 0, argv[1], strlen(argv[1])); + if (len != strlen(argv[1])) rt_kprintf("Write failed!\n"); + else rt_kprintf("Write successful!\n"); } -MSH_CMD_EXPORT(vcom_write, vcom write); +MSH_CMD_EXPORT(vcom_write, write to vcom); ``` -2. On corresponding PC serial port assistant, you can see received "123456" -![alt text](assets/123456.png) -3. Serial port data reception; send string on PC serial port assistant. HDK will print as follows: abcdefg +2. The string "123456" should be visible in the corresponding PC serial terminal +emulator. ![alt text](assets/123456.png) 3. For serial data reception, transmit +a string from the PC serial terminal. The HDK will print the following: abcdefg ```c - serial_thread_entry cdc_rx_buf=abcdefg +serial_thread_entry cdc_rx_buf=abcdefg ``` ![alt text](assets/abcdefg.png) - ## Troubleshooting -If expected log does not appear, troubleshooting can be done from the following aspects: +## Troubleshooting +If expected log does not appear, troubleshooting can be done from the following +aspects: * Whether hardware connection is normal * Whether pin configuration is correct * Check if USB interface is loose * Check if USB cable has data transmission capability * Check if USB clock is 60MHz frequency -If virtual serial port number cannot be recognized, troubleshooting can be done from the following aspects: +If virtual serial port number cannot be recognized, troubleshooting can be done +from the following aspects: * Whether USB clock is enabled, refer to the following * Whether USB data transmission line has data capability ### Check if USB Clock is Enabled -You can open Ozone, select chip to connect, then check -![alt text](assets/image.jpg) -![alt text](assets/image-1.jpg) -* If clock is not enabled, you can enter menuconfig –board=sf32lb52-lcd_52d menu to enable it (specific operation as follows) -![alt text](assets/image2.jpg) -Then connect virtual serial port USB - ## Example Extension - - If you want to modify VBUS detection pin number, you can modify as follows: - 1. Modify configuration menuconfig --board=sf32lb52-lcd_n16r8 and re-modify the parameter in "usb Insertion detection PIN" to the desired detection pin - D:\MyWork\code_sdk\siflisdk\customer\boards\ec-lb555xxx - 2. Modify pinmux configuration file **"\siflisdk\customer\boards\ec-lb corresponding model directory\bsp_pinmux.c"**, configure this pin to GPIO mode; +You can open Ozone, select chip to connect, then check ![alt +text](assets/image.jpg) ![alt text](assets/image-1.jpg) +* If clock is not enabled, you can enter menuconfig –board=sf32lb52-lcd_52d menu + to enable it (specific operation as follows) ![alt text](assets/image2.jpg) + Then connect virtual serial port USB +## Example Extension + +If you want to modify VBUS detection pin number, you can modify as follows: + 1. Modify configuration menuconfig --board=sf32lb52-lcd_n16r8 and re-modify + the parameter in "usb Insertion detection PIN" to the desired detection pin + D:\MyWork\code_sdk\siflisdk\customer\boards\ec-lb555xxx + 2. Modify pinmux configuration file **"\siflisdk\customer\boards\ec-lb + corresponding model directory\bsp_pinmux.c"**, configure this pin to GPIO + mode; ```c -HAL_PIN_Set(PAD_PA32, GPIO_A32, PIN_NOPULL, 1);//USB VBUS -``` \ No newline at end of file + HAL_PIN_Set(PAD_PA32, GPIO_A32, PIN_NOPULL, 1); // USB VBUS + ``` diff --git a/example/rt_device/wdt/README_EN.md b/example/rt_device/wdt/README_EN.md index 850f7bb69..51ed92693 100644 --- a/example/rt_device/wdt/README_EN.md +++ b/example/rt_device/wdt/README_EN.md @@ -3,14 +3,15 @@ Source code path: example/rt_device/wdt/wdt ## Supported Platforms - + + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -This example demonstrates WDT usage based on rt-device (using rt-thread), including: + +This example demonstrates WDT usage based on rt-device (using rt-thread), +including: + WDT on/off. + WDT feeding. + WDT timeout response. @@ -19,36 +20,40 @@ This example is based on HCPU, using IWDT and WDT1. ``` ## Example Usage - + ### Hardware Requirements -Before running this example, you need to prepare a development board supported by this example +Before running this example, you need to prepare a development board supported +by this example ### menuconfig Configuration 1. BSP enable WDT (automatically configures `RT_USING_WDT`): -![BSP_USING_WDT](./assets/mc_bsp_using_wdt.png) + ![BSP_USING_WDT](./assets/mc_bsp_using_wdt.png) 2. Configure WDT timeout time (`WDT_TIMEOUT`): -![BSP_USING_WDT](./assets/mc_wdt_timeout.png) + ![BSP_USING_WDT](./assets/mc_wdt_timeout.png) ### Compilation and Programming -Switch to example project directory and run scons command to execute compilation: +Switch to example project directory and run scons command to execute +compilation: ``` scons --board=eh-lb525 -j32 ``` -Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select port as prompted to download: +Run `build_sf32lb52-lcd_n16r8_hcpu\uart_download.bat`, select port as prompted +to download: ``` $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to [](/quickstart/get-started.md) related introduction. +For detailed steps on compilation and downloading, please refer to +[](/quickstart/get-started.md) related introduction. ## Expected Results of Example - + After example startup, serial port outputs as follows: 1. WDT off then on: ```c @@ -68,24 +73,26 @@ rt_hw_watchdog_init registers idle hook for feeding. Cancel here to demonstrate ``` 3. Feeding (every 5 seconds): ```c -11-01 11:05:29:709 watchdog feeding. -11-01 11:05:34:699 watchdog feeding. -11-01 11:05:39:668 watchdog feeding. -11-01 11:05:44:660 watchdog feeding. -11-01 11:05:49:629 watchdog feeding. -11-01 11:05:54:600 watchdog feeding. -11-01 11:05:59:594 watchdog feeding. -11-01 11:06:04:575 watchdog feeding. -11-01 11:06:09:558 watchdog feeding. -11-01 11:06:14:553 watchdog feeding. +11-01 11:05:29:709 Watchdog feeding. +11-01 11:05:34:699 Watchdog feeding. +11-01 11:05:39:668 Watchdog feeding. +11-01 11:05:44:660 Watchdog feeding. +11-01 11:05:49:629 Watchdog feeding. +11-01 11:05:54:600 Watchdog feeding. +11-01 11:05:59:594 Watchdog feeding. +11-01 11:06:04:575 Watchdog feeding. +11-01 11:06:09:558 Watchdog feeding. +11-01 11:06:14:553 Watchdog feeding. ``` -3. After stopping feeding, WDT1 timeout (`WDT_TIMEOUT`, configured in menuconfig), generating interrupt. In interrupt (`WDT_IRQHandler`) WDT1/WDT2 will be disabled, IWDT refreshed, IWDT timeout time updated (`WDT_TIMEOUT`): +3. After stopping feeding, WDT1 timeout (`WDT_TIMEOUT`, configured in + menuconfig), generating interrupt. In interrupt (`WDT_IRQHandler`) WDT1/WDT2 + will be disabled, IWDT refreshed, IWDT timeout time updated (`WDT_TIMEOUT`): ```c 11-01 11:06:14:557 Stop watchdog feeding. -11-01 11:06:51:813 WDT1 timeout occurs. -11-01 11:06:51:817 WDT reconfig: -11-01 11:06:51:821 WDT1 and WDT2 has been stopped. -11-01 11:06:51:825 IWDT refreshed and set timeout time to WDT_TIMEOUT. +11-01 11:06:51:813 WDT1 timeout occurred. +11-01 11:06:51:817 WDT reconfiguration: +11-01 11:06:51:821 WDT1 and WDT2 have been stopped. +11-01 11:06:51:825 IWDT refreshed; timeout set to WDT_TIMEOUT. ``` ```{tip} Provides overridable function: wdt_store_exception_information, called by WDT_IRQHandler. Can be used to save scene, reboot system, etc. @@ -93,22 +100,21 @@ Provides overridable function: wdt_store_exception_information, called by WDT_IR 4. IWDT timeout resets system: ```c 11-01 11:07:35:237 SFBL -11-01 11:07:37:445 Serial:c2,Chip:4,Package:3,Rev:2 Reason:00000000 +11-01 11:07:37:445 Serial:c2, Chip:4, Package:3, Rev:2, Reason:00000000 ``` ## Exception Diagnosis -1. Confirm WDT configuration status (enable status, count configuration, working mode) through WDT registers: -![WDT regmap](./assets/wdt_regmap.png) - +1. Confirm WDT configuration status (enable status, count configuration, working + mode) through WDT registers: ![WDT regmap](./assets/wdt_regmap.png) ## Reference Documents - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/rt_driver/README_EN.md b/example/rt_driver/README_EN.md index 1b6a1cba5..7ee52448a 100644 --- a/example/rt_driver/README_EN.md +++ b/example/rt_driver/README_EN.md @@ -1,26 +1,27 @@ # Screen Module Debug Program +Source code path: example/rt_driver ## Overview -This is a screen refresh display and touch data reading and printing program based on rt-thread's rt driver framework. +This is a screen refresh display and touch data reading and printing program +based on rt-thread's rt driver framework. Suitable for debugging and testing screen drivers and touch drivers. The screen can display content that changes every 3 seconds: -- Color bar with 8 gradient colors (white, gray, red, green, blue, cyan, purple, yellow), each gradient color transitions from black. +- Color bar with 8 gradient colors (white, gray, red, green, blue, cyan, purple, + yellow), each gradient color transitions from black. - Vertical grayscale gradient (cycles every 256 lines) - Solid colors (red, green, blue, white, black) - - ## main Function The main function creates 2 threads: - LCD screen refresh thread - Touch reading thread - ### 1. LCD Screen Refresh Thread 1. Open lcd rt device -2. Get and search screen information, print its width, height, set color depth, screen refresh pixel alignment requirement information +2. Get and search screen information, print its width, height, set color depth, + screen refresh pixel alignment requirement information 3. Fill framebuffer (see overview description) 4. Refresh framebuffer to screen 5. After refresh completion, set backlight brightness @@ -29,12 +30,15 @@ The main function creates 2 threads: 8. Jump to step 3 #### framebuffer Related -Color format definition FB_COLOR_FORMAT defaults to 24bit -Bytes per pixel for color format FB_PIXEL_BYTES defaults to 3 +Color format definition FB_COLOR_FORMAT defaults to 24bit Bytes per pixel for +color format FB_PIXEL_BYTES defaults to 3 -For ramless screens, to prevent framebuffer from being refreshed during filling, framebuffer2 is defined. During display, they are used alternately to prevent filling and refresh conflicts. +For ramless screens, to prevent framebuffer from being refreshed during filling, +framebuffer2 is defined. During display, they are used alternately to prevent +filling and refresh conflicts. ### 2. Touch Reading Thread 1. Open touch rt device 2. Set touch interrupt trigger function tp_rx_indicate to release semaphore -3. In while loop, if semaphore is acquired, read touch data and print it on serial port. \ No newline at end of file +3. In while loop, if semaphore is acquired, read touch data and print it on + serial port. diff --git a/example/storage/fatfs/index_EN.md b/example/storage/fatfs/index_EN.md index eb09cc5e3..ef3964f38 100644 --- a/example/storage/fatfs/index_EN.md +++ b/example/storage/fatfs/index_EN.md @@ -1,6 +1,10 @@ # FatFs Example -According to the different storage media, FatFs routines are divided into NAND and NOR routines, both use the same file system API, the difference lies in the partition configuration parameters are different, you can compare the `proj.conf` of the two projects to understand the differences. +According to the different storage media, FatFs routines are divided into NAND +and NOR routines, both use the same file system API, the difference lies in the +partition configuration parameters are different, you can compare the +`proj.conf` of the two projects to understand the differences. + ```{toctree} :titlesonly: @@ -8,7 +12,4 @@ According to the different storage media, FatFs routines are divided into NAND a */* - - - ``` diff --git a/example/storage/fatfs/nand/README_EN.md b/example/storage/fatfs/nand/README_EN.md index 89087caa7..221d9e931 100644 --- a/example/storage/fatfs/nand/README_EN.md +++ b/example/storage/fatfs/nand/README_EN.md @@ -1,68 +1,124 @@ # FatFs NAND Example +Source path: example/storage/fatfs/nand + ## Usage Guide -This example demonstrates FatFs file system functionality using FAT format. Common file commands can be called in UART console, such as: +- sf32lb52-lcd_a128r16 +- sf32lb56-lcd_a128r12n1 +- sf32lb58-lcd_a128r32n1 + +## Example Usage Instructions +This example demonstrates the file system capabilities of FatFs using the FAT +format. Standard file system commands can be executed via the UART console, +including: ``` -df - Disk free -mountfs - Mount device to file system -mkfs - Format disk with file system -mkdir - Create the DIRECTORY. -pwd - Print the name of the current working directory. -cd - Change the shell working directory. -rm - Remove(unlink) the FILE(s). -cat - Concatenate FILE(s) -mv - Rename SOURCE to DEST. -cp - Copy SOURCE to DEST. -ls - List information about the FILEs. +df - Display free disk space +mountfs - Mount a device to the file system +mkfs - Format a disk with a file system +mkdir - Create a directory +pwd - Print the name of the current working directory +cd - Change the shell working directory +rm - Remove (unlink) files +cat - Concatenate and display file content +mv - Rename SOURCE to DEST +cp - Copy SOURCE to DEST +ls - List information about files +``` +### Hardware Requirements +The example includes a file system performance benchmark, which can be initiated +using the `fs_test` command: +- To run the example, you need to have a development board that supports this + example +- A USB data cable capable of data transmission +- The benchmark evaluates both write and read speeds. +Expected test results: +```c +TX:fs_test +Creating test file with 1024 KB data... +Written 0 KB... +Written 100 KB... +Written 200 KB... +Written 300 KB... +Written 400 KB... +Written 500 KB... +Written 600 KB... +Written 700 KB... +Written 800 KB... +Written 900 KB... +Written 1000 KB... +Write test completed +Write Speed: 1721799 bytes/sec (1681.44 KB/s) +Write Ops/sec: 1681 ops/sec +Reading test file... +Read 0 KB... +Read 100 KB... +Read 200 KB... +Read 300 KB... +Read 400 KB... +Read 500 KB... +Read 600 KB... +Read 700 KB... +Read 800 KB... +Read 900 KB... +Read 1000 KB... +Read test completed +Read Speed: 5518821 bytes/sec (5389.47 KB/s) +Read Ops/sec: 5389 ops/sec ``` - -### File System Packaging -The default compilation script does not download file system partition image files, so if the mount fails during the first program run, it will automatically format the partition. For specific implementation, see the `mnt_init` function in `main.c`. The SDK also provides functionality to package files in specified directories and generate file system image files. You can uncomment the following code in `SConstruct`. This code packages files in the disk directory during compilation and generates the `fs_root.bin` file in the build directory. If the partition table in `ptab.json` defines a partition with `img` attribute as `fs_root`, the download script will simultaneously download that bin file. - +### menuconfig Configuration + +![alt text]{1} 2. Use device virtual file system + ``` -# fs_bin=FileSystemBuild( "../disk", env) -# AddCustomImg("fs_root",bin=[fs_bin]) +//Execute command + menuconfig --board=em-lb561 ``` -## Example Usage Instructions +## Project Description ### Hardware Requirements -1. To run the example, you need to have a development board that supports this example -2. A USB data cable capable of data transmission +1. Prerequisites for running the routine include a supported development board +and 2. a USB data cable capable of data transmission. ### menuconfig Configuration ``` - //Execute command +// Execute command menuconfig --board=em-lb561 -``` -1. First, you need to enable MTD Dhara Nand Flash device in menuconfig +``` +1. Enable the MTD Dhara Nand Flash device in menuconfig. -![alt text](assets/file_system_1.png) -2. Use device virtual file system +![alt text](assets/file_system_1.png) 2. Enable the Device Virtual File System +(DFS). -![alt text](assets/file_system_2.png) -3. Select HAL Assert type +![alt text](assets/file_system_2.png) 3. Select the HAL Assert type. ![alt text](assets/file_system_3.png) -## Project Description -- Compilation method: Enter project directory and execute command `scons --board= -j8`, where board_name is the board name. For example, to compile eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8`. The compiled image file is stored in HCPU's build_ directory. For common project usage, refer to <> -- Download method: Enter project directory and execute command `build__hcpu\download.bat(uart_download.bat)`, where board_name is the board name. If download has uart prefix, it uses serial port for program burning; without it, it uses jlink burning (depending on whether the board model supports jlink burning). For example, compiling eh-lb561 board, the complete command is `build_en-lb561_hcpu\download.bat` - ## Example Output Results Display -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and requires troubleshooting. +- Send ls through serial port to view files in root directory. +- Input mkdir test1 to create test1 folder (directory). + +## Example Output Results +The following log shows the output of the example running on the development +board. If these logs do not appear, the example failed to run as expected and +troubleshooting is required. ``` -mount fs on flash root success//Indicates successful file system mounting +Filesystem successfully mounted on flash root. ``` -1. Send ls through serial port to view files in root directory. +1. Execute `ls` via the serial terminal to list the files in the root directory. -2. Input mkdir test1 to create test1 folder (directory). +2. Enter `mkdir test1` to create a new directory named `test1`. -3. Input cd+directory name to go to XXX directory, input pwd to check if current working path is in the cd directory. +3. Use `cd` followed by the directory name to navigate to the specified path. +Execute `pwd` to verify that the current working directory has updated +correctly. -4. You can create mkdir test2 again in this working directory, use ls to check if creation was successful in this directory. -![alt text](assets/file_system_log_1.png) +4. You may create another directory within this path using `mkdir test2`. Run +`ls` to confirm the directory was created successfully. ![alt +text](assets/file_system_log_1.png) ### Troubleshooting -If the log does not show expected log and phenomena, troubleshooting can be done from the following aspects: -* Whether hardware connection is normal -* Check if USB cable has data transmission capability -* Whether the above menu is configured correctly (especially board flash model) \ No newline at end of file +If the expected logs or behavior do not appear, please troubleshoot the +following areas: +* Verify that the hardware connections are secure and correct. +* Ensure the USB cable supports data transfer. +* Verify that the menu configuration is correct (specifically the Flash model + for the board). diff --git a/example/storage/fatfs/nor/README_EN.md b/example/storage/fatfs/nor/README_EN.md index 30c949030..86d4ee8f3 100644 --- a/example/storage/fatfs/nor/README_EN.md +++ b/example/storage/fatfs/nor/README_EN.md @@ -1,68 +1,140 @@ # FatFs NOR Example +Source path: example/storage/fatfs/nor + ## Usage Guide -This example demonstrates FatFs file system functionality using FAT format. Common file commands can be called in UART console, such as: +- sf32lb52-lcd_n16r8 +- sf32lb56-lcd_n16r12n1 +- sf32lb58-lcd_n16r32n1 + +## Example Usage Instructions +This example demonstrates the FatFs file system functionality using the FAT +format. Standard file system commands can be invoked via the UART console, such +as: ``` -df - Disk free -mountfs - Mount device to file system -mkfs - Format disk with file system -mkdir - Create the DIRECTORY. -pwd - Print the name of the current working directory. -cd - Change the shell working directory. -rm - Remove(unlink) the FILE(s). -cat - Concatenate FILE(s) +df - Display free disk space. +mountfs - Mount a device to the file system. +mkfs - Format a disk with a file system. +mkdir - Create a directory. +pwd - Print the current working directory. +cd - Change the working directory. +rm - Remove (unlink) files. +cat - Concatenate and display file content. mv - Rename SOURCE to DEST. cp - Copy SOURCE to DEST. -ls - List information about the FILEs. +ls - List information about files. +``` +### Hardware Requirements +This example includes a file system performance testing feature, which can be +executed using the `fs_test` command: +- To run the example, you need to have a development board that supports this + example +- A USB data cable capable of data transmission +- The test evaluates both write and read speeds. +Expected test results are as follows: +```c +TX:fs_test 2048 4 + Creating test file with 2048 KB data using 4K buffer... + Written 100 KB... + Written 200 KB... + Written 300 KB... + Written 400 KB... + Written 500 KB... + Written 600 KB... + Written 700 KB... + Written 800 KB... + Written 900 KB... + Written 1000 KB... + Written 1100 KB... + Written 1200 KB... + Written 1300 KB... + Written 1400 KB... + Written 1500 KB... + Written 1600 KB... + Written 1700 KB... + Written 1800 KB... + Written 1900 KB... + Written 2000 KB... + Written 2048 KB... + Write test completed + Write Speed: 385505 bytes/sec (376.47 KB/s) + Reading test file... + Read 100 KB... + Read 200 KB... + Read 300 KB... + Read 400 KB... + Read 500 KB... + Read 600 KB... + Read 700 KB... + Read 800 KB... + Read 900 KB... + Read 1000 KB... + Read 1100 KB... + Read 1200 KB... + Read 1300 KB... + Read 1400 KB... + Read 1500 KB... + Read 1600 KB... + Read 1700 KB... + Read 1800 KB... + Read 1900 KB... + Read 2000 KB... + Read 2048 KB... + Read test completed + Read Speed: 27962026 bytes/sec (27306.67 KB/s) + msh />msh /> ``` - -### File System Packaging +### menuconfig Configuration + +![alt text]{1} 2. Use device virtual file system -The default compilation script does not download file system partition image files, so if the mount fails during the first program run, it will automatically format the partition. For specific implementation, see the `mnt_init` function in `main.c`. The SDK also provides functionality to package files in specified directories and generate file system image files. You can uncomment the following code in `SConstruct`. This code packages files in the disk directory during compilation and generates the `fs_root.bin` file in the build directory. If the partition table in `ptab.json` defines a partition with `img` attribute as `fs_root`, the download script will simultaneously download that bin file. - ``` -# fs_bin=FileSystemBuild( "../disk", env) -# AddCustomImg("fs_root",bin=[fs_bin]) +//Execute command + menuconfig --board=em-lb561 ``` -## Example Usage Instructions +## Project Description ### Hardware Requirements -1. To run the example, you need to have a development board that supports this example -2. A USB data cable capable of data transmission +1. Prerequisites: A development board supported by this routine. 2. A USB data +cable capable of data transmission. ### menuconfig Configuration ``` - //Execute command +// Execute command menuconfig --board=em-lb561 -``` -1. First, you need to enable MTD Nor Flash device in menuconfig +``` +1. First, enable the MTD Nor Flash device in menuconfig. -![alt text](assets/file_system_1.png) -2. Use device virtual file system +![alt text](assets/file_system_1.png) 2. Enable the Device Virtual File System +(VFS). -![alt text](assets/file_system_2.png) -3. Select HAL Assert type +![alt text](assets/file_system_2.png) 3. Select the HAL Assert type. ![alt text](assets/file_system_3.png) -## Project Description -- Compilation method: Enter project directory and execute command `scons --board= -j8`, where board_name is the board name. For example, to compile eh-lb561 board, the complete command is `scons --board=eh-lb561 -j8`. The compiled image file is stored in HCPU's build_ directory. For common project usage, refer to <> -- Download method: Enter project directory and execute command `build__hcpu\download.bat(uart_download.bat)`, where board_name is the board name. If download has uart prefix, it uses serial port for program burning; without it, it uses jlink burning (depending on whether the board model supports jlink burning). For example, compiling eh-lb561 board, the complete command is `build_en-lb561_hcpu\download.bat` - ## Example Output Results Display -The following results show the log after the example runs on the development board. If you cannot see these logs, it means the example did not run successfully as expected and requires troubleshooting. +- Send ls through serial port to view files in root directory +- Input mkdir test2 to create test2 folder (directory) + +## Example Output +The following log shows the output of the example running on the development +board. If these logs are not visible, the example is not running as expected and +requires troubleshooting. ``` -mount fs on flash root success//Indicates successful file system mounting +Filesystem successfully mounted on flash root. ``` -1. Send ls through serial port to view files in root directory +1. Execute the `ls` command via the serial port to view the files in the root +directory. -2. Input mkdir test2 to create test2 folder (directory) +2. Enter `mkdir test2` to create a folder (directory) named "test2". -3. Input ls again to see if test2 folder (directory) was created successfully +3. Enter `ls` again to verify if the "test2" folder (directory) was successfully +created. -4. Input pwd to view current working path -![alt text](assets/file_system_log_1.png) +4. Enter `pwd` to check the current working directory path. ![alt +text](assets/file_system_log_1.png) ### Troubleshooting -If the log does not show expected log and phenomena, troubleshooting can be done from the following aspects: -* Whether hardware connection is normal -* Check if USB cable has data transmission capability -* Whether the above menuconfig is configured correctly \ No newline at end of file +If the expected logs or behavior do not appear, please troubleshoot the +following areas: +* Verify that the hardware connections are secure and correct. +* Ensure the USB cable supports data transfer. +* Is the menuconfig configured correctly? diff --git a/example/storage/flashdb/README_EN.md b/example/storage/flashdb/README_EN.md index 88761ffb1..db0f862ab 100644 --- a/example/storage/flashdb/README_EN.md +++ b/example/storage/flashdb/README_EN.md @@ -3,35 +3,37 @@ Source path: example/storage/flashdb ## Supported Platforms - + + sf32lb52-nano series + sf32lb52-lcd series + sf32lb56-lcd series + sf32lb58-lcd series ## Overview - -FlashDB is an ultra-lightweight embedded database that focuses on providing data storage solutions for embedded products. FlashDB provides two database modes: -+ Key-value database(KVDB): It is a non-relational database that stores data as a collection of key-value pairs, where the key is used as a unique identifier. -+ Time Series Database(TSDB): Time Series Database. + +FlashDB is an ultra-lightweight embedded database that focuses on providing data +storage solutions for embedded products. FlashDB provides two database modes: ++ Key-value database(KVDB): It is a non-relational database that stores data as + a collection of key-value pairs, where the key is used as a unique identifier. ++ Time Series Database(TSDB): Time Series Database. This example demonstrates the configuration and usage of FlashDB, including: + project/nand: KVDB/TSDB configuration and usage on Nand flash. + project/nor: KVDB/TSDB configuration and usage on Nor flash. - ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported platforms](quick_start)). ++ One development board supported by this example ([Supported + platforms](quick_start)). ### menuconfig Configuration -1. Enable FlashDB: -![FLASHDB](./assets/mc_flashdb.png) +1. Enable FlashDB:\ + ![FLASHDB](./assets/mc_flashdb.png) ```{tip} FDB Mode: + `Use FAL Mode` : Using FAL storage mode @@ -42,16 +44,16 @@ Before running this example, you need to prepare: + Nand uses `FILE MODE`, operates through file system, `FDB Mode` configured as `PKG_FDB_USING_FILE_POSIX_MODE`. + Nor uses `FAL MODE`, operates flash directly, `FDB Mode` configured as `PKG_FDB_USING_FAL_MODE`. ``` -2. Configure `FAT` file system (when using `FILE MODE`) -![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) +2. Configure `FAT` file system (when using `FILE MODE`)\ + ![RT_USING_DFS_ELMFAT](./assets/mc_fat.png) ```{tip} Mount file system partition in mnt_init. FDB initialization requires specifying a storage path (directory in the file system). ``` -3. FAL partition configuration (when using `FAL MODE`) +3. FAL partition configuration (when using `FAL MODE`) + `project/nor/ptab.json`: ```c - { + { "offset": "0x00620000", "max_size": "0x00004000", "tags": [ @@ -64,8 +66,8 @@ Before running this example, you need to prepare: "tags": [ "TSDB_TST_REGION" ] - }, - ``` + }, + ``` + `project/nor/custom_mem_map.h` ```c #define FAL_PART_TABLE \ @@ -74,41 +76,44 @@ Before running this example, you need to prepare: {FAL_PART_MAGIC_WORD, "tsdb_tst", NOR_FLASH2_DEV_NAME, TSDB_TST_REGION_OFFSET, TSDB_TST_REGION_SIZE, 0}, \ ... ... } - ``` + ``` ```{tip} FDB initialization requires specifying flash partition name (for example, in this example it is "kvd_tst"/"tsd_tst"). ``` ### Compilation and Programming -Switch to the example project/nand directory and run the scons command to execute compilation: +Switch to the example project/nand directory and run the scons command to +execute compilation: ```c -> scons --board=eh-lb525 -j32 +> scons --board=eh-lb525 -j32 ``` -Switch to the example `project/nand/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/nand/build_xx` directory and run +`uart_download.bat`, select the port as prompted to download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ```{tip} project/nor is the corresponding nor solution, compilation and download methods are the same, the difference is the corresponding board. ``` ## Expected Results - -This example operates FlashDB through FINSH commands: + +This example operates FlashDB through FINSH commands:\ KVDB: -Purpose | Command | Example -|---|--|--| -Set kvdb|kvdb set [key] [data type:int\|str] [value]|`kvdb set "kv1" int 100` -Read kvdb|kvdb get [key] [data type:int\|str]|`kvdb get "kv1" int` -Delete kvdb|kvdb del [key]|`kvdb del "kv1"` +| Purpose | Command | Example | +| ----------- | ------------------------------------------ | ------------------------ | +| Set kvdb | kvdb set [key] [data type:int|str] [value] | `kvdb set "kv1" int 100` | +| Read kvdb | kvdb get [key] [data type:int|str] | `kvdb get "kv1" int` | +| Delete kvdb | kvdb del [key] | `kvdb del "kv1"` | -Serial port output as follows: +Serial port output as follows: ```c // Set, read integer data @@ -138,16 +143,16 @@ Serial port output as follows: 12-23 00:53:20:116 kvdb get "key1" int 12-23 00:53:20:120 [key1] int 12-23 00:53:20:147 get the key1 failed -``` +``` TSDB: -Purpose | Command | Example -|---|--|--| -Add tsdb|tsdb append [value]|`tsdb append 1` -Query all tsdb|tsdb query_all|`tsdb query_all` -Query tsdb by time|tsdb query_by_time [from timestamp] [to timestamp]|`tsdb query_by_time 0 946686530` -Clear tsdb|tsdb clear|`tsdb clear` - -Serial port output as follows: +| Purpose | Command | Example | +| ------------------ | -------------------------------------------------- | -------------------------------- | +| Add tsdb | tsdb append [value] | `tsdb append 1` | +| Query all tsdb | tsdb query_all | `tsdb query_all` | +| Query tsdb by time | tsdb query_by_time [from timestamp] [to timestamp] | `tsdb query_by_time 0 946686530` | +| Clear tsdb | tsdb clear | `tsdb clear` | + +Serial port output as follows: ```c // clear tsdb 12-23 00:55:21:376 TX:tsdb clear @@ -189,14 +194,14 @@ Serial port output as follows: ## Reference Documentation - + + siflisdk\external\FlashDB\README.md + siflisdk\external\FlashDB\README_zh.md ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |10/2024 |Initial version | -| | | | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 10/2024 | Initial version | +| | | | +| | | | diff --git a/example/storage/index_EN.md b/example/storage/index_EN.md index 8e57d2049..da67a4da8 100644 --- a/example/storage/index_EN.md +++ b/example/storage/index_EN.md @@ -4,5 +4,4 @@ :glob: */* - ``` diff --git a/example/storage/littlefs/nor/README_EN.md b/example/storage/littlefs/nor/README_EN.md index 88a424c0b..5d7079c37 100644 --- a/example/storage/littlefs/nor/README_EN.md +++ b/example/storage/littlefs/nor/README_EN.md @@ -3,92 +3,108 @@ Source code path: example/storage/littlefs ## Supported Platforms - + + sf32lb52-lcd_n16r8 ## Overview - -LittleFS is a lightweight, power-loss safe file system designed for embedded systems, especially suitable for non-volatile storage devices such as NOR Flash. + +LittleFS is a lightweight, power-loss safe file system designed for embedded +systems, especially suitable for non-volatile storage devices such as NOR Flash. + + ## Usage Guide -This example demonstrates the file system functionality of LittleFs. You can call common file commands in the UART console, such as: +This example demonstrates the file system functionality of LittleFs. You can +call common file commands in the UART console, such as: ``` -df - Disk free -mountfs - Mount device to file system -mkfs - Format disk with file system -mkdir - Create the DIRECTORY. -pwd - Print the name of the current working directory. -cd - Change the shell working directory. -rm - Remove(unlink) the FILE(s). -cat - Concatenate FILE(s) -mv - Rename SOURCE to DEST. -cp - Copy SOURCE to DEST. -ls - List information about the FILEs. - +df - Display free disk space +mountfs - Mount a device to the file system +mkfs - Format a disk with a file system +mkdir - Create a directory +pwd - Print the name of the current working directory +cd - Change the shell working directory +rm - Remove (unlink) files +cat - Concatenate and display file content +mv - Rename SOURCE to DEST +cp - Copy SOURCE to DEST +ls - List information about files ``` - + ### File System Packaging -The default compilation script does not download the file system partition image file, so the first time the program runs, if the mount fails, it will automatically format the partition. The specific implementation can be found in the `mnt_init` function in `main.c`. The SDK also provides the functionality to package files under a specified directory and generate a file system image file. You can uncomment the following code in `SConstruct`. This code's function is to package files under the disk directory during compilation and generate a `fs_root.bin` file in the build directory. If the partition table in `ptab.json` defines a partition with the `img` attribute as `fs_root`, the download script will also download the bin file. - +The default compilation script does not download the file system partition image +file, so the first time the program runs, if the mount fails, it will +automatically format the partition. The specific implementation can be found in +the `mnt_init` function in `main.c`. The SDK also provides the functionality to +package files under a specified directory and generate a file system image file. +You can uncomment the following code in `SConstruct`. This code's function is to +package files under the disk directory during compilation and generate a +`fs_root.bin` file in the build directory. If the partition table in `ptab.json` +defines a partition with the `img` attribute as `fs_root`, the download script +will also download the bin file. + ``` -# fs_bin=FileSystemBuild( "../disk", env) -# AddCustomImg("fs_root",bin=[fs_bin]) +# fs_bin=FileSystemBuild("../disk", env) +# AddCustomImg("fs_root", bin=[fs_bin]) ``` - ## Example Usage Instructions ### Hardware Requirements -1. Before running the example, you need to have a development board that supports this example -2. A USB data cable with data transmission capability - +1. Prerequisites for running the routine include a supported development board +and 2. a USB data cable capable of data transmission. ### menuconfig Configuration ``` - //Execute command +//Execute command menuconfig --board=em-lb561 -``` -1. First, you need to enable MTD Nor Flash device in menuconfig +``` +![alt text]{1} 2. Use device virtual file system and enable LittleFs file system -![alt text](assets/file_system_1.png) -2. Use device virtual file system and enable LittleFs file system +![alt text](assets/file_system_1.png) 3. Select HAL Assert type ![alt text](assets/file_system_2.png) -3. Select HAL Assert type ![alt text](assets/file_system_3.png) + ### Compilation and Flashing Switch to the example project directory and run the scons command to compile: ```c -> scons --board=sf32lb52-lcd_n16r8 -j32 +> scons --board=sf32lb52-lcd_n16r8 -j32 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted for download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted for download: ```c $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and download, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and download, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results -The following results show the log after the example runs on the development board. If you don't see these logs, it means the example didn't run as expected and you need to investigate the cause. +The following results show the log after the example runs on the development +board. If you don't see these logs, it means the example didn't run as expected +and you need to investigate the cause. ``` mount fs on flash root success//indicates successful file system mounting ``` -1. Send ls via serial port to view files in the root directory +1. Execute the `ls` command via the serial port to view the files in the root +directory. -2. Enter mkdir test2 to create a test2 folder (directory) +2. Enter `mkdir test2` to create a folder (directory) named "test2". -3. Enter ls again to see if the test2 folder (directory) was created successfully +3. Enter `ls` again to verify if the "test2" folder (directory) was successfully +created. -4. Enter pwd to view the current working path -![alt text](assets/file_system_log_1.png) +4. Enter `pwd` to check the current working directory path. ![alt +text](assets/file_system_log_1.png) ## Exception Diagnosis -If the expected log and phenomena do not appear, you can troubleshoot from the following aspects: +If the expected log and phenomena do not appear, you can troubleshoot from the +following aspects: * Whether the hardware connection is normal * Check if the USB cable has data transmission capability -* Whether the above menuconfig is configured correctly \ No newline at end of file +* Whether the above menuconfig is configured correctly diff --git a/example/system/coredump/README_EN.md b/example/system/coredump/README_EN.md index 3727fa69a..ee5a889d5 100644 --- a/example/system/coredump/README_EN.md +++ b/example/system/coredump/README_EN.md @@ -2,7 +2,10 @@ Source path: `example/system/coredump` ## Overview -- This example demonstrates how to save crash information. It also supports connecting to a mobile phone over BLE and transferring crash context data. After power-on, the device broadcasts with a name like `COREDUMP-xx-xx-xx-xx-xx-xx`. +- This example demonstrates how to save crash information. It also supports + connecting to a mobile phone over BLE and transferring crash context data. + After power-on, the device broadcasts with a name like + `COREDUMP-xx-xx-xx-xx-xx-xx`. ## Supported Platforms Verified on the following platforms: @@ -15,20 +18,12 @@ This example supports four mode combinations: 2) Partition mode, minidump enabled 3) File mode, minidump disabled 4) File mode, minidump enabled - -The default is mode 1 (Partition mode, minidump disabled). You can switch modes using the following settings. - -2) Partition mode, minidump enabled -![alt text](asserts/partition.png) -![alt text](asserts/mini_enable.png) - -3) File mode, minidump disabled -![alt text](asserts/file_mode.png) -![alt text](asserts/mini_disable.png) - -4) File mode, minidump enabled -![alt text](asserts/file_mode.png) -![alt text](asserts/mini_enable.png) +2. Partition mode, minidump enabled ![alt text](asserts/partition.png) ![alt + text](asserts/mini_enable.png) +3. File mode, minidump disabled ![alt text](asserts/file_mode.png) ![alt + text](asserts/mini_disable.png) +4. File mode, minidump enabled ![alt text](asserts/file_mode.png) ![alt + text](asserts/mini_enable.png) ### Build and Flash Using `sf32lb52-lcd_n16r8` as an example, follow these steps to build and flash: @@ -39,15 +34,7 @@ scons --board=sf32lb52-lcd_n16r8 ``` ## How to Use -After power-on, when a crash occurs (you can manually trigger a crash with `assert`), logs like the following indicate that crash context data has been saved: -![alt text](asserts/assert.png) - -Reset the board, then open the SiFli BLE app on your phone. Find and connect to the Bluetooth device named like `COREDUMP-xx-xx-xx-xx-xx-xx`, then export the crash context data in the app: -![alt text](asserts/ble.png) - -During export, a large amount of corresponding logs will appear: -![alt text](asserts/dump.png) - -Finally, a `.bin` file is generated on the phone. Send this file to your PC and use `Context2Mem.exe` to convert the `.bin` file into a dump file: -http://docs.sifli.cc/test_doc/methods/%E6%95%B4%E6%9C%BAlog%E5%AF%BC%E5%87%BA%E4%B8%8E%E8%BD%AC%E6%8D%A2.html +After power-on, when a crash occurs (you can manually trigger a crash with +`assert`), logs like the following indicate that crash context data has been +saved: ![alt text](asserts/assert.png) diff --git a/example/system/finsh/README_EN.md b/example/system/finsh/README_EN.md index 84ccde83b..b030bd8e6 100644 --- a/example/system/finsh/README_EN.md +++ b/example/system/finsh/README_EN.md @@ -1,4 +1,5 @@ # FinSH +Source path: example/system/finsh ## Supported Platforms The example can run on the following development boards. @@ -6,29 +7,36 @@ The example can run on the following development boards. * sf32lb56-lcd series * sf32lb58-lcd series - ## Overview -* FinSH is RT-Thread's command line component (shell), providing a set of operational interfaces for users to call from the command line, mainly used for debugging or viewing system information. In addition to FinSH's built-in commands, FinSH also provides multiple macro interfaces to export custom commands, and exported commands can be executed directly in FinSH. +* FinSH is RT-Thread's command line component (shell), providing a set of + operational interfaces for users to call from the command line, mainly used + for debugging or viewing system information. In addition to FinSH's built-in + commands, FinSH also provides multiple macro interfaces to export custom + commands, and exported commands can be executed directly in FinSH. ## FinSH Function Configuration -* FinSH functionality can be trimmed, with macro configuration options defined in the _rtconfig.h_ file. The specific configuration items are shown in the table below. - -|Macro Definition |Value Type |Description |Default Value| -|:--- |:--- |:--- |:---| -|#define RT_USING_FINSH |None |Enable FinSH |Enabled| -|#define FINSH_THREAD_NAME |String |FinSH thread name |"tshell"| -|define FINSH_USING_HISTORY |None |Enable history recall function |Enabled| -|#define FINSH_HISTORY_LINES |Integer |Number of history command lines that can be recalled |5| -|#define FINSH_USING_SYMTAB |None |Enable symbol table usage in FinSH |Enabled| -|#define FINSH_USING_DESCRIPTION |None |Add a description to each FinSH symbol |Enabled| -|#define FINSH_USING_MSH |None |Enable msh mode |Enabled| -|#define FINSH_ARG_MAX |Integer |Maximum number of input parameters |10| -|#define FINSH_USING_AUTH |None |Enable permission verification |Disabled| -|#define FINSH_DEFAULT_PASSWORD |String |Permission verification password |Disabled | - - -* The reference configuration example in _rtconfig.h_ is shown below, and can be configured according to actual functional requirements. Enter `menuconfig` in the compilation interface and configure under `RTOS → RT-Thread Components → Command shell`. -![Figure 1: FinSH Configuration Menu](assets/finsh_menu.png) +* FinSH functionality can be trimmed, with macro configuration options defined + in the _rtconfig.h_ file. The specific configuration items are shown in the + table below. + +| Macro Definition | Value Type | Description | Default Value | +| ------------------------------- | ---------- | ---------------------------------------------------- | ------------- | +| #define RT_USING_FINSH | None | Enable FinSH | On | +| #define FINSH_THREAD_NAME | String | FinSH thread name | "tshell" | +| define FINSH_USING_HISTORY | None | Enable history recall function | On | +| #define FINSH_HISTORY_LINES | Integer | Number of history command lines that can be recalled | 5 | +| #define FINSH_USING_SYMTAB | None | Enable symbol table usage in FinSH | On | +| #define FINSH_USING_DESCRIPTION | None | Add a description to each FinSH symbol | On | +| #define FINSH_USING_MSH | None | Enable msh mode | On | +| #define FINSH_ARG_MAX | Integer | Maximum number of input parameters | 10 | +| #define FINSH_USING_AUTH | None | Enable permission verification | Off | +| #define FINSH_DEFAULT_PASSWORD | String | Permission verification password | Off | + + +* The reference configuration example in _rtconfig.h_ is shown below, and can be + configured according to actual functional requirements. Enter `menuconfig` in + the compilation interface and configure under `RTOS → RT-Thread Components → + Command shell`. ![Figure 1: FinSH Configuration Menu](assets/finsh_menu.png) ```c /* Enable FinSH */ #define RT_USING_FINSH @@ -60,7 +68,9 @@ The example can run on the following development boards. ``` ## FinSH Custom Command Application Examples ### msh Command Example without Parameters -* Export a custom command to msh, example code is shown below. The code creates a `myhello` function, then uses the `MSH_CMD_EXPORT` command to export the `myhello` function to the FinSH command list. +* Export a custom command to msh, example code is shown below. The code creates + a `myhello` function, then uses the `MSH_CMD_EXPORT` command to export the + `myhello` function to the FinSH command list. ```c #include @@ -69,7 +79,7 @@ void myhello(void) rt_kprintf("hello RT-Thread!\n"); } -MSH_CMD_EXPORT(myhello , say hello to RT-Thread); +MSH_CMD_EXPORT(myhello , say hello to RT-Thread); ``` Run the myhello command, the result is as follows: ``` @@ -78,15 +88,17 @@ hello RT_Thread! msh /> ``` ### msh Command Example with Parameters -* Export a custom command with parameters to FinSH, example code is shown below. The code creates an `atcmd()` function, then uses the `MSH_CMD_EXPORT` command to export the `atcmd()` function to the msh command list. +* Export a custom command with parameters to FinSH, example code is shown below. + The code creates an `atcmd()` function, then uses the `MSH_CMD_EXPORT` command + to export the `atcmd()` function to the msh command list. ```c #include static void atcmd(int argc, char**argv) { - if (argc < 2) + if (argc < 2) { - rt_kprintf("Please input'atcmd '\n"); + rt_kprintf("Please input 'atcmd '\n"); return; } @@ -100,37 +112,33 @@ static void atcmd(int argc, char**argv) } else { - rt_kprintf("Please input'atcmd '\n"); + rt_kprintf("Please input 'atcmd '\n"); } } -MSH_CMD_EXPORT(atcmd, atcmd sample: atcmd ); - +MSH_CMD_EXPORT(atcmd, atcmd sample: atcmd ); ``` Run the `atcmd` command, the result is as follows: ``` -msh />atcmd +msh />atcmd Please input 'atcmd ' -msh /> - +msh /> ``` Run the `atcmd server` command, the result is as follows: ``` -msh />atcmd server +msh />atcmd server AT server! -msh /> - +msh /> ``` Run the `atcmd client` command, the result is as follows: ``` -msh />atcmd client +msh />atcmd client AT client! -msh /> - +msh /> ``` -**Note**: -An infinite loop must be added in the main function to enter the msh command. +**Note**: An infinite loop must be added in the main function to enter the msh +command. ```c int main(void) { @@ -140,13 +148,12 @@ int main(void) } return 0; } - ``` ## Reference Documentation * ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |12/2024 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------- | --------------- | +| 0.0.1 | 12/2024 | Initial version | +| | | | diff --git a/example/system/index_EN.md b/example/system/index_EN.md index 762572139..26b5471fd 100644 --- a/example/system/index_EN.md +++ b/example/system/index_EN.md @@ -4,5 +4,4 @@ :glob: */* - -``` \ No newline at end of file +``` diff --git a/example/system/ulog/README_EN.md b/example/system/ulog/README_EN.md index 282fe8eee..1628c28c8 100644 --- a/example/system/ulog/README_EN.md +++ b/example/system/ulog/README_EN.md @@ -1,4 +1,5 @@ # Log Usage Example +Source path: example/system/ulog ## Supported Platforms The example can run on the following development boards. @@ -7,10 +8,17 @@ The example can run on the following development boards. - sf32lb58-lcd series ## Overview -- Logging is the output of software runtime status, process, and other information to different media (such as: files, console, display, etc.) for display and storage. It provides reference basis for problem tracing, performance analysis, system monitoring, fault warning, and other functions during software debugging and maintenance. +- Logging is the output of software runtime status, process, and other + information to different media (such as: files, console, display, etc.) for + display and storage. It provides reference basis for problem tracing, + performance analysis, system monitoring, fault warning, and other functions + during software debugging and maintenance. ## ulog Function Configuration -- ulog configuration options are described below. You can configure according to actual functional requirements; generally, the default configuration can be used. Enter `menuconfig` in the compilation interface and configure under `RTOS→ RT-Thread Components→ Utilities`. +- ulog configuration options are described below. You can configure according to + actual functional requirements; generally, the default configuration can be + used. Enter `menuconfig` in the compilation interface and configure under + `RTOS→ RT-Thread Components→ Utilities`. ``` [*] Enable ulog /* Enable ulog */ The static output log level./* Select static log output level. After selection, logs lower than the set level (specifically referring to logs using LOG_X API) will not be compiled into ROM */ @@ -24,7 +32,9 @@ The example can run on the following development boards. [ ] Enable runtime log filter. /* Enable runtime log filter, i.e., dynamic filtering. After enabling, logs will support dynamic filtering by tags, keywords, etc. during system runtime. */ [*] Enable syslog format log and API. /* Enable syslog format log and API */ ``` -* Enter `menuconfig` in the compilation interface and configure log format options under `TOS → RT-Thread Components → Utilities → Enable ulog → log format` as described below: +* Enter `menuconfig` in the compilation interface and configure log format + options under `TOS → RT-Thread Components → Utilities → Enable ulog → log + format` as described below: ``` [ ] Enable float number support. It will using more thread stack. /* Floating point number support (traditional rtdbg/rt_kprintf do not support floating point logs) */ [*] Enable color log. /* Colored logs */ @@ -33,7 +43,6 @@ The example can run on the following development boards. [*] Enable level information. /* Level information */ [*] Enable tag information. /* Tag information */ [ ] Enable thread information. /* Thread information */ - ``` @@ -46,28 +55,38 @@ The example can run on the following development boards. ``` The `int ulog_test()` function uses `LOG_X API`, roughly as follows: ```c -/* output different level log by LOG_X API */ +/* Output logs at different levels using the LOG_X API */ LOG_D("LOG_D(%d): RT-Thread is an open source IoT operating system from China.", count); LOG_I("LOG_I(%d): RT-Thread is an open source IoT operating system from China.", count); LOG_W("LOG_W(%d): RT-Thread is an open source IoT operating system from China.", count); LOG_E("LOG_E(%d): RT-Thread is an open source IoT operating system from China.", count); ``` -Enter `ulog_test` and the serial port output result is shown below: -![alt text](assets/ulog1.png) +Enter `ulog_test` and the serial port output result is shown below:\ +![alt text](assets/ulog1.png) ## Usage in Interrupt ISR -- Often logs need to be output in interrupt ISR, but interrupt ISR may interrupt threads that are outputting logs. To ensure interrupt logs and thread logs do not interfere with each other, special handling for interrupt situations is needed. -ulog has integrated interrupt log functionality, but it is not enabled by default. When using, simply enable the `Enable ISR log` option, and the log API usage is consistent with thread usage. +- Often logs need to be output in interrupt ISR, but interrupt ISR may interrupt + threads that are outputting logs. To ensure interrupt logs and thread logs do + not interfere with each other, special handling for interrupt situations is + needed. ulog has integrated interrupt log functionality, but it is not enabled + by default. When using, simply enable the `Enable ISR log` option, and the log + API usage is consistent with thread usage. ## Setting Log Format -- ulog supported log formats can be configured in `menuconfig`, located at `RTOS → RT-Thread Components → Utilities → Enable ulog → log format`, specific configuration as follows -![alt text](assets/menuconfig.png) +- ulog supported log formats can be configured in `menuconfig`, located at `RTOS + → RT-Thread Components → Utilities → Enable ulog → log format`, specific + configuration as follows ![alt text](assets/menuconfig.png) -- You can configure: floating point number support, colored logs, time information (including timestamp), level information, tag information, thread information. Let's select all these options, save, recompile, and run the ulog example again to see the actual effect: -![alt text](assets/ulog2.png) +- You can configure: floating point number support, colored logs, time + information (including timestamp), level information, tag information, thread + information. Let's select all these options, save, recompile, and run the ulog + example again to see the actual effect:\ + ![alt text](assets/ulog2.png) ## hexdump Output Usage -- `hexdump` is also a commonly used function for log output. Through `hexdump`, you can output a section of data in hex format. See the specific usage and runtime effect below: +- `hexdump` is also a commonly used function for log output. Through `hexdump`, + you can output a section of data in hex format. See the specific usage and + runtime effect below: ```c /* Define an array of 128 bytes length */ uint8_t i, buf[128]; @@ -79,55 +98,67 @@ for (i = 0; i < sizeof(buf); i++) /* Dump the data in the array in hex format, width 16 */ ulog_hexdump("buf_dump_test", 16, buf, sizeof(buf)); ``` -- Run the ulog example again to see the actual effect: -![alt text](assets/ulog3.png) +- Run the ulog example again to see the actual effect:\ + ![alt text](assets/ulog3.png) ## Dynamic Log Filter -- Static filtering has advantages such as resource saving, but often users need to dynamically adjust log filtering methods during software runtime. This is where ulog's dynamic filter functionality can be used. Using dynamic filter functionality requires enabling the `Enable runtime log filter` option in `menuconfig`. This option is disabled by default. -ulog supports the following four dynamic filtering methods. -- Filter by module level - -|Parameter |Description | -|:---|:---| -|tag |Log tag | -| level|Set log level | -|Return |-- | -|>=0| Success | -|-5 |Failure, insufficient memory | - - Command format: `ulog_tag_lvl `. -The module here refers to a class of log code with the same tag attributes. Sometimes it's necessary to dynamically modify a module's log output level during runtime. -Parameter level log levels can take the following values: - - |Level |Name |Value | - |:---|:---|:---| - |LOG-LVL_ASSERT |Assert |0 | - |LOG_LVL_ERROR |Error |3 | - |LOG_LVL_WARNING |Warning |4 | - |LOG_LVL_INFO|Info|6| - |LOG_LVL_DBG |Debug |7| - |LOG_FILTER_LVL_SILENT |Silent |0| - |LOG_FILTER_LVL_ALL |All | 7| - -- Global filter by tag - - Command format: `ulog_tag [tag]`, when tag is empty, tag filtering is cancelled. -This filtering method can perform tag filtering on all logs, only logs containing tag information are allowed to output. -For example: with logs of tags `wifi.driveer`, `wifi.mgnt`, `aydio.driver`, when filter tag is set to `wifi`, only logs with tags `wifi.driver` and `wifi.mgnt` will output. -- Global filter by level - - Command format: `ulog_lvl `, level values refer to above. -After setting the global filter level through function or command, logs below the set level will stop outputting. +- Static filtering has advantages such as resource saving, but often users need + to dynamically adjust log filtering methods during software runtime. This is + where ulog's dynamic filter functionality can be used. Using dynamic filter + functionality requires enabling the `Enable runtime log filter` option in + `menuconfig`. This option is disabled by default. ulog supports the following + four dynamic filtering methods. +- Filter by module level + +| Parameter | Description | +| --------- | ---------------------------- | +| tag | Log tag | +| level | Set log level | +| Return | -- | +| >=0 | Success | +| -5 | Failure, insufficient memory | + - Command format: `ulog_tag_lvl `.\ + The module here refers to a class of log code with the same tag attributes. + Sometimes it's necessary to dynamically modify a module's log output level + during runtime.\ + Parameter level log levels can take the following values: + + | Level | Name | Value | + | --------------------- | ------- | ----- | + | LOG_LVL_ASSERT | Assert | 0 | + | LOG_LVL_ERROR | Error | 3 | + | LOG_LVL_WARNING | Warning | 4 | + | LOG_LVL_INFO | Info | 6 | + | LOG_LVL_DBG | Debug | 7 | + | LOG_FILTER_LVL_SILENT | Silent | 0 | + | LOG_FILTER_LVL_ALL | All | 7 | + +- Global filter by tag + - Command format: `ulog_tag [tag]`, when tag is empty, tag filtering is + cancelled.\ + This filtering method can perform tag filtering on all logs, only logs + containing tag information are allowed to output.\ + For example: with logs of tags `wifi.driveer`, `wifi.mgnt`, `aydio.driver`, + when filter tag is set to `wifi`, only logs with tags `wifi.driver` and + `wifi.mgnt` will output. +- Global filter by level + - Command format: `ulog_lvl `, level values refer to above.\ + After setting the global filter level through function or command, logs + below the set level will stop outputting. - Global filter by keyword - - Command format: `ulog_kw [keyword]`, when keyword is empty, keyword filtering is cancelled. -This filtering method can perform keyword filtering on all logs, only logs containing keyword information are allowed to output. -- View filter information -After setting filter parameters, if you want to view current filter information, you can enter the `ulog_filter` command, roughly as shown below: -![alt text](assets/ulog_filter.png) - - + - Command format: `ulog_kw [keyword]`, when keyword is empty, keyword + filtering is cancelled.\ + This filtering method can perform keyword filtering on all logs, only logs + containing keyword information are allowed to output. +- View filter information\ + After setting filter parameters, if you want to view current filter + information, you can enter the `ulog_filter` command, roughly as shown below:\ + ![alt text](assets/ulog_filter.png) ## Reference Documentation * ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |1/2025 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | ------------ | --------------- | +| 0.0.1 | January 2025 | Initial version | +| | | | diff --git a/example/vglite/README_EN.md b/example/vglite/README_EN.md index 9f92b2100..2db72175a 100644 --- a/example/vglite/README_EN.md +++ b/example/vglite/README_EN.md @@ -1,21 +1,20 @@ # VGLite Demo Program +Source Path: example/vglite ## Linear Gradient + Mask -Fixed display of linear gradient inside a path, executes 10 frames with 2-second intervals. -Open console and run command `utest_run tc_vglite_0_0 1` -Code is in tc_vg_linear_grad.c +Fixed display of linear gradient inside a path, executes 10 frames with 2-second +intervals. Open console and run command `utest_run tc_vglite_0_0 1` Code is in +tc_vg_linear_grad.c ## Font Rendering -Displays 2 frames, one small font and one large font, executes once. -Open console and run command `utest_run tc_vglite_0_1 1` -Code is in tc_vg_glyphs.c +Displays 2 frames, one small font and one large font, executes once. Open +console and run command `utest_run tc_vglite_0_1 1` Code is in tc_vg_glyphs.c ## Rotating Image -Rotates a pointer image, executes 3600 frames with 160ms intervals. -Open console and run command `utest_run tc_vglite_0_2 1` -Code is in tc_vg_rotate.c +Rotates a pointer image, executes 3600 frames with 160ms intervals. Open console +and run command `utest_run tc_vglite_0_2 1` Code is in tc_vg_rotate.c + ## Album Flip Effect -Executes 3D flip effect of album cover, runs continuously. -Open console and run command `utest_run tc_vglite_1_2 1` -Code is in tc_vg_coverflow.c \ No newline at end of file +Executes 3D flip effect of album cover, runs continuously. Open console and run +command `utest_run tc_vglite_1_2 1` Code is in tc_vg_coverflow.c diff --git a/example/zbt/bap_broadcast_sink/README_EN.md b/example/zbt/bap_broadcast_sink/README_EN.md index dde9c8c9e..ca162b3e7 100644 --- a/example/zbt/bap_broadcast_sink/README_EN.md +++ b/example/zbt/bap_broadcast_sink/README_EN.md @@ -3,21 +3,25 @@ Source path: example/zbt/bap_broadcast_sink ## Supported Platforms - -+ sf32lb52x + ++ SF32LB52X ## Overview - + This example demonstrates the BLE Audio Sink side, flashed to sf32lb52x boards. -It requires example/zbt/bap_broadcast_src or example/zbt/bap_broadcast_src_with_classic_bt project as the source side. The source side can only use 52j or 52d series (those ending with letters), and cannot use 525 as the source side. +It requires example/zbt/bap_broadcast_src or +example/zbt/bap_broadcast_src_with_classic_bt project as the source side. The +source side can only use 52j or 52d series (those ending with letters), and +cannot use 525 as the source side. ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported platforms](quick_start)). ++ One development board supported by this example ([Supported + platforms](quick_start)). + Speaker. ```{warning} @@ -28,37 +32,41 @@ Before running this example, you need to prepare: ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```bash scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```bash $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example runs, it will connect to the BLE Audio source device and receive audio data for playback. + +After the example runs, it will connect to the BLE Audio source device and +receive audio data for playback. ## Exception Diagnosis ## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |6/2025 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | --------- | --------------- | +| 0.0.1 | June 2025 | Initial version | +| | | | diff --git a/example/zbt/bap_broadcast_src/README_EN.md b/example/zbt/bap_broadcast_src/README_EN.md index eaa45bbc2..0550f99eb 100644 --- a/example/zbt/bap_broadcast_src/README_EN.md +++ b/example/zbt/bap_broadcast_src/README_EN.md @@ -3,23 +3,27 @@ Source path: example/zbt/bap_broadcast_src ## Supported Platforms - + + sf32lb52 letter series ## Overview - -This example demonstrates the BLE Audio Source side, flashed to sf32lb52 letter series boards, such as 52j or 52D. It cannot be flashed to 525 boards. -This example will play mp3 files from the disk directory. The local speaker will not sound, but will transmit audio to another sink device board for playback. -Another sink device can be found at example/zbt/bap_broadcast_sink. You need to compile the sink project and flash it to another device. + +This example demonstrates the BLE Audio Source side, flashed to sf32lb52 letter +series boards, such as 52j or 52D. It cannot be flashed to 525 boards. This +example will play mp3 files from the disk directory. The local speaker will not +sound, but will transmit audio to another sink device board for playback. +Another sink device can be found at example/zbt/bap_broadcast_sink. You need to +compile the sink project and flash it to another device. ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported platforms](quick_start)). ++ One development board supported by this example ([Supported + platforms](quick_start)). + Speaker. ```{warning} @@ -30,37 +34,42 @@ Before running this example, you need to prepare: ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```bash scons --board=sf32lb52-nano_52j -j8 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```bash $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example runs, it will decode mp3 files from the disk directory and transmit them via BLE to connected BLE Audio sink devices for playback. The local source device speaker will not play. + +After the example runs, it will decode mp3 files from the disk directory and +transmit them via BLE to connected BLE Audio sink devices for playback. The +local source device speaker will not play. ## Exception Diagnosis ## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |6/2025 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | --------- | --------------- | +| 0.0.1 | June 2025 | Initial version | +| | | | diff --git a/example/zbt/bap_broadcast_src_with_classic_bt/README_EN.md b/example/zbt/bap_broadcast_src_with_classic_bt/README_EN.md index 488615b2c..981560cb1 100644 --- a/example/zbt/bap_broadcast_src_with_classic_bt/README_EN.md +++ b/example/zbt/bap_broadcast_src_with_classic_bt/README_EN.md @@ -1,23 +1,26 @@ # BLE Audio Player (Source) - Source path: example/zbt/bap_broadcast_sink ## Supported Platforms - + + sf32lb52x ## Overview - + This example demonstrates the BLE Audio Sink side, flashed to sf32lb52x boards. -It requires example/zbt/bap_broadcast_src or example/zbt/bap_broadcast_src_with_classic_bt project as the source side. The source side can only use 52j or 52d series (those ending with letters), and cannot use 525 as the source side. +It requires example/zbt/bap_broadcast_src or +example/zbt/bap_broadcast_src_with_classic_bt project as the source side. The +source side can only use 52j or 52d series (those ending with letters), and +cannot use 525 as the source side. ## Example Usage - + ### Hardware Requirements Before running this example, you need to prepare: -+ One development board supported by this example ([Supported platforms](quick_start)). ++ One development board supported by this example ([Supported + platforms](quick_start)). + Speaker. ```{warning} @@ -28,37 +31,41 @@ Before running this example, you need to prepare: ### Compilation and Programming -Switch to the example project directory and run the scons command to execute compilation: +Switch to the example project directory and run the scons command to execute +compilation: ```bash scons --board=sf32lb52-lcd_n16r8 -j8 ``` -Switch to the example `project/build_xx` directory and run `uart_download.bat`, select the port as prompted to download: +Switch to the example `project/build_xx` directory and run `uart_download.bat`, +select the port as prompted to download: ```bash $ ./uart_download.bat - Uart Download + UART Download -please input the serial port num:5 +Please input the serial port number: 5 ``` -For detailed steps on compilation and downloading, please refer to the relevant introduction in [Quick Start](quick_start). +For detailed steps on compilation and downloading, please refer to the relevant +introduction in [Quick Start](quick_start). ## Expected Results - -After the example runs, it will connect to the BLE Audio source device and receive audio data for playback. + +After the example runs, it will connect to the BLE Audio source device and +receive audio data for playback. ## Exception Diagnosis ## Reference Documentation - + ## Update Log -|Version |Date |Release Notes | -|:---|:---|:---| -|0.0.1 |6/2025 |Initial version | -| | | | \ No newline at end of file +| Version | Date | Release Notes | +| ------- | --------- | --------------- | +| 0.0.1 | June 2025 | Initial version | +| | | | diff --git a/example/zbt/index_EN.md b/example/zbt/index_EN.md index a57f35cb0..7a3b0f67d 100644 --- a/example/zbt/index_EN.md +++ b/example/zbt/index_EN.md @@ -7,5 +7,4 @@ bap_broadcast_sink/README.md bap_broadcast_src/README.md bap_broadcast_src_with_classic_bt/README.md - -``` \ No newline at end of file +```