From e4ff88f3640458f820838efd047a3831333446d8 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 22 Sep 2025 23:31:13 +0200 Subject: WIP improved docs (feat. LLM) --- docs/conf.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'docs/conf.py') diff --git a/docs/conf.py b/docs/conf.py index 4249d41f7..be9aeaaf9 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -24,9 +24,29 @@ extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon', 'sphinx_autodoc_typehints', ] +# Autodoc configuration +autodoc_default_options = { + 'members': True, + 'undoc-members': True, + 'show-inheritance': True, +} + +# Napoleon configuration for Google/NumPy style docstrings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_init_with_doc = False +napoleon_include_private_with_doc = False + +# Intersphinx mapping for cross-references +intersphinx_mapping = { + 'python': ('https://docs.python.org/3', None), +} + templates_path = ['_templates'] exclude_patterns = ['_build'] -- cgit v1.3.1 From 9dd67b19e207edd17917296a5c7c185c86507fa8 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 20 Oct 2025 20:19:40 +0200 Subject: revert unnecessary Sphinx config changes --- docs/conf.py | 20 -------------------- 1 file changed, 20 deletions(-) (limited to 'docs/conf.py') diff --git a/docs/conf.py b/docs/conf.py index be9aeaaf9..4249d41f7 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -24,29 +24,9 @@ extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', - 'sphinx.ext.viewcode', - 'sphinx.ext.napoleon', 'sphinx_autodoc_typehints', ] -# Autodoc configuration -autodoc_default_options = { - 'members': True, - 'undoc-members': True, - 'show-inheritance': True, -} - -# Napoleon configuration for Google/NumPy style docstrings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_init_with_doc = False -napoleon_include_private_with_doc = False - -# Intersphinx mapping for cross-references -intersphinx_mapping = { - 'python': ('https://docs.python.org/3', None), -} - templates_path = ['_templates'] exclude_patterns = ['_build'] -- cgit v1.3.1 From a1ae5b20ccf760282538dd81b9290527757fa9c7 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 11 Nov 2025 10:27:47 +0700 Subject: update doc --- .github/workflows/static_analysis.yml | 9 +- README.rst | 56 ++++++-- docs/_static/custom.css | 3 + docs/conf.py | 8 +- docs/contributing/code_of_conduct.rst | 1 - docs/contributing/index.rst | 22 --- docs/contributing/porting.rst | 243 ---------------------------------- docs/faq.rst | 32 +---- docs/getting_started.rst | 159 ++++++++++++---------- docs/index.rst | 37 +----- docs/info/changelog.rst | 48 +++++++ docs/info/code_of_conduct.rst | 1 + docs/info/index.rst | 1 + docs/integration.rst | 93 +++++++++++++ docs/porting.rst | 243 ++++++++++++++++++++++++++++++++++ docs/reference/architecture.rst | 39 ++---- docs/reference/boards.rst | 31 +++-- docs/reference/dependencies.rst | 12 +- docs/reference/glossary.rst | 2 +- docs/troubleshooting.rst | 43 ++++-- hw/bsp/family_support.cmake | 49 +++++-- tools/gen_doc.py | 2 +- 22 files changed, 640 insertions(+), 494 deletions(-) create mode 100644 docs/_static/custom.css delete mode 100644 docs/contributing/code_of_conduct.rst delete mode 100644 docs/contributing/index.rst delete mode 100644 docs/contributing/porting.rst create mode 100644 docs/info/code_of_conduct.rst create mode 100644 docs/integration.rst create mode 100644 docs/porting.rst (limited to 'docs/conf.py') diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index a89cdc279..4db267517 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -90,7 +90,8 @@ jobs: path: ${{ steps.analyze.outputs.sarif-output }} PVS-Studio: - if: github.repository_owner == 'hathach' + # Only run on non-forked PR since secrets token is required + if: github.repository_owner == 'hathach' && github.event.pull_request.head.repo.fork == false runs-on: ubuntu-latest strategy: fail-fast: false @@ -141,7 +142,8 @@ jobs: path: pvs-studio-${{ matrix.board }}.sarif SonarQube: - if: github.repository_owner == 'hathach' + # Only run on non-forked PR since secrets token is required + if: github.repository_owner == 'hathach' && github.event.pull_request.head.repo.fork == false runs-on: ubuntu-latest env: BUILD_WRAPPER_OUT_DIR: build_wrapper_output_directory @@ -184,7 +186,8 @@ jobs: --define sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json IAR-CStat: - #if: github.repository_owner == 'hathach' + # Only run on non-forked PR since secrets token is required + #if: github.repository_owner == 'hathach' && github.event.pull_request.head.repo.fork == false if: false runs-on: ubuntu-latest strategy: diff --git a/README.rst b/README.rst index 2d84a2f6c..d0586f55a 100644 --- a/README.rst +++ b/README.rst @@ -1,26 +1,55 @@ +TinyUSB +======= + |Build Status| |CircleCI Status| |Documentation Status| |Static Analysis| |Fuzzing Status| |License| Sponsors -======== +-------- TinyUSB is funded by: Adafruit. Purchasing products from them helps to support this project. .. figure:: docs/assets/adafruit_logo.svg :alt: Adafruit Logo + :align: left :target: https://www.adafruit.com -TinyUSB Project -=============== +.. raw:: html + +
+ +Overview +-------- .. figure:: docs/assets/logo.svg :alt: TinyUSB + :align: left + +.. raw:: html + +
+ +TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems. It’s designed for memory safety +(no dynamic allocation) and thread safety (all interrupts deferred to non-ISR task functions). The stack emphasizes portability, +small footprint, and real-time performance across 50+ MCU families. -TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. Check out the online `documentation `__ for more details. +Key Features +------------ + +* **Thread-safe:** USB interrupts deferred to task context +* **Memory-safe:** No dynamic allocation, all buffers static +* **Portable:** Supports 50+ MCU families +* **Comprehensive:** Includes CDC, HID, MSC, Audio, and Host support +* **RTOS-friendly:** Works with bare metal, FreeRTOS, RT-Thread, and Mynewt .. figure:: docs/assets/stack.svg :width: 500px + :align: left :alt: stackup +.. raw:: html + +
+ :: . @@ -36,7 +65,7 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst Getting started -=============== +--------------- See the `online documentation `_ for information about using TinyUSB and how it is implemented. @@ -49,7 +78,7 @@ For bugs and feature requests, please `raise an issue `_ Host Stack -========== +---------- - Human Interface Device (HID): Keyboard, Mouse, Generic - Mass Storage Class (MSC) @@ -81,14 +110,14 @@ Host Stack Similar to the Device Stack, if you have a special requirement, ``usbh_app_driver_get_cb()`` can be used to write your own class driver without modifying the stack. Power Delivery Stack -==================== +-------------------- - Power Delivery 3.0 (PD3.0) with USB Type-C support (WIP) - Super early stage, only for testing purpose - Only support STM32 G4 OS Abstraction layer -==================== +-------------------- TinyUSB is completely thread-safe by pushing all Interrupt Service Request (ISR) events into a central queue, then processing them later in the non-ISR context task function. It also uses semaphore/mutex to access shared resources such as Communication Device Class (CDC) FIFO. Therefore the stack needs to use some of the OS's basic APIs. Following OSes are already supported out of the box. @@ -98,7 +127,7 @@ TinyUSB is completely thread-safe by pushing all Interrupt Service Request (ISR) - **Mynewt** Due to the newt package build system, Mynewt examples are better to be on its `own repo `_ Supported CPUs -============== +-------------- +--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ | Manufacturer | Family | Device | Host | Highspeed | Driver | Note | @@ -234,7 +263,7 @@ Supported CPUs +--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ Table Legend ------------- +^^^^^^^^^^^^ ========= ========================= βœ” Supported @@ -244,7 +273,7 @@ Table Legend ========= ========================= Development Tools -================= +----------------- The following tools are provided freely to support the development of the TinyUSB project: @@ -273,6 +302,5 @@ The following tools are provided freely to support the development of the TinyUS .. _Supported Boards: docs/reference/boards.rst .. _Dependencies: docs/reference/dependencies.rst .. _Concurrency: docs/reference/concurrency.rst -.. _Contributing: docs/contributing/index.rst .. _Code of Conduct: CODE_OF_CONDUCT.rst -.. _Porting: docs/contributing/porting.rst +.. _Porting: docs/porting.rst diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 000000000..d64d26047 --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,3 @@ +.clear-both { + clear: both; +} diff --git a/docs/conf.py b/docs/conf.py index 4249d41f7..cd0338413 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ from pathlib import Path # -- Project information ----------------------------------------------------- project = 'TinyUSB' -copyright = '2024, Ha Thach' +copyright = '2025, Ha Thach' author = 'Ha Thach' @@ -41,6 +41,8 @@ html_favicon = 'assets/logo.svg' html_theme_options = { 'sidebar_hide_name': True, } +html_static_path = ['_static'] +html_css_files = ['custom.css'] todo_include_todos = True @@ -52,7 +54,9 @@ def preprocess_readme(): if src.exists(): content = src.read_text() content = re.sub(r"docs/", r"", content) - content = re.sub(r".rst", r".html", content) + content = re.sub(r"\.rst\b", r".html", content) + if not content.endswith("\n"): + content += "\n" tgt.write_text(content) preprocess_readme() diff --git a/docs/contributing/code_of_conduct.rst b/docs/contributing/code_of_conduct.rst deleted file mode 100644 index fb1859c75..000000000 --- a/docs/contributing/code_of_conduct.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../../CODE_OF_CONDUCT.rst \ No newline at end of file diff --git a/docs/contributing/index.rst b/docs/contributing/index.rst deleted file mode 100644 index 78933a3ca..000000000 --- a/docs/contributing/index.rst +++ /dev/null @@ -1,22 +0,0 @@ -************ -Contributing -************ - -Contributing can be highly rewarding, but it can also be frustrating at times. -It takes time to review patches, and as this is an open source project, that -sometimes can take a while. The reviewing process depends on the availability -of the maintainers, who may not be always available. Please try to be -understanding through the process. - -There a few guidelines you need to keep in mind when contributing. Please have -a look at them as that will make the contribution process easier for all -parties. - -Index -===== - -.. toctree:: - :maxdepth: 2 - - code_of_conduct - porting diff --git a/docs/contributing/porting.rst b/docs/contributing/porting.rst deleted file mode 100644 index c3076354c..000000000 --- a/docs/contributing/porting.rst +++ /dev/null @@ -1,243 +0,0 @@ - -******* -Porting -******* - -TinyUSB is designed to be a universal USB protocol stack for microcontrollers. It -handles most of the high level USB protocol and relies on the microcontroller's USB peripheral for -data transactions on different endpoints. Porting is the process of adding low-level support for -the rest of the common stack. Once the low-level is implemented, it is very easy to add USB support -for the microcontroller to other projects, especially those already using TinyUSB such as CircuitPython. - -Below are instructions on how to get the cdc_msc device example running on a new microcontroller. Doing so includes adding the common code necessary for other uses while minimizing other extra code. Whenever you see a phrase or word in ``<>`` it should be replaced. - -Register defs -------------- - -The first step to adding support is including the register definitions and startup code for the -microcontroller in TinyUSB. We write the TinyUSB implementation against these structs instead of higher level functions to keep the code small and to prevent function name collisions in linking of larger projects. For ARM microcontrollers this is the CMSIS definitions. They should be -placed in the ``hw/mcu//`` directory. - -Once this is done, create a directory in ``hw/bsp/`` for the specific board you are using to test the code (duplicating an existing board's directory is the best way to get started). The board should be a readily available development board so that others can also test. - -Build ------ - -Now that those directories are in place, we can start our iteration process to get the example building successfully. To build, run from the root of TinyUSB: - -.. code-block:: bash - - make -C examples/device/cdc_msc BOARD= - -Unless you've read ahead, this will fail miserably. Now, lets get it to fail less by updating the files in the board directory. The code in the board's directory is responsible for setting up the microcontroller's clocks and pins so that USB works. TinyUSB itself only operates on the USB peripheral. The board directory also includes information what files are needed to build the example. - -One of the first things to change is the ``-DCFG_TUSB_MCU`` C flag in the ``board.mk`` file. This is used to tell TinyUSB what platform is being built. So, add an entry to ``src/tusb_option.h`` and update the ``CFLAGS`` to match. - -Update ``board.mk``'s VENDOR and CHIP_FAMILY values when creating the directory for the struct files. Duplicate one of the other sources from ``src/portable`` into ``src/portable//`` and delete all of the implementation internals. We'll cover what everything there does later. For now, get it compiling. - -Implementation --------------- - -At this point you should get an error due to an implementation issue and hopefully the build is setup for the new MCU. You will still need to modify the ``board.mk`` to include specific ``CFLAGS``, the linker script, linker flags, source files, include directories. All file paths are relative to the top of the TinyUSB repo. - -Board Support (BSP) -^^^^^^^^^^^^^^^^^^^ - -The board support code is only used for self-contained examples and testing. It is not used when TinyUSB is part of a larger project. Its responsible for getting the MCU started and the USB peripheral clocked. It also optionally provides LED definitions that are used to blink an LED to show that the code is running. - -It is located in ``hw/bsp//board_.c``. - -``board_init()`` -~~~~~~~~~~~~~~~~ - -``board_init()`` is responsible for starting the MCU, setting up the USB clock and USB pins. It is also responsible for initializing LED pins. - -One useful clock debugging technique is to set up a PWM output at a known value such as 500hz based on the USB clock so that you can verify it is correct with a logic probe or oscilloscope. - -Setup your USB in a crystal-less mode when available. That makes the code easier to port across boards. - -``board_led_write()`` -~~~~~~~~~~~~~~~~~~~~~ - -Feel free to skip this until you want to verify your demo code is running. To implement, set the pin corresponding to the led to output a value that lights the LED when ``state`` is true. - -OS Abstraction Layer (OSAL) -^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The OS Abstraction Layer is responsible for providing basic data structures for TinyUSB that may allow for concurrency when used with an RTOS. Without an RTOS it simply handles concurrency issues between the main code and interrupts. The code is almost entirely agnostic of MCU and lives in ``src/osal``. - -In RTOS configurations, ``tud_task()``/``tuh_task()`` blocks behind a synchronization structure when the event queue is empty, so that the scheduler may give the CPU to a different task. To take advantage of the library's capability to yield the CPU when there are no actionable USB device events, ensure that the ``CFG_TUSB_OS`` symbol is defined, e.g ``OPT_OS_FREERTOS`` enables the FreeRTOS scheduler to schedule other threads than that which calls ``tud_task()``/``tuh_task()``. - -Device API -^^^^^^^^^^ - -After the USB device is setup, the USB device code works by processing events on the main thread (by calling ``tud_task()``). These events are queued by the USB interrupt handler. So, there are three parts to the device low-level API: device setup, endpoint setup and interrupt processing. - -All of the code for the low-level device API is in ``src/portable///dcd_.c``. - -Device Setup -~~~~~~~~~~~~ - -``dcd_init()`` -"""""""""""""" - -Initializes the USB peripheral for device mode and enables it. -This function should enable internal D+/D- pull-up for enumeration. - -``dcd_int_enable()`` / ``dcd_int_disable()`` -"""""""""""""""""""""""""""""""""""""""""""" - -Enables or disables the USB device interrupt(s). May be used to prevent concurrency issues when mutating data structures shared between main code and the interrupt handler. - -``dcd_int_handler()`` -""""""""""""""""""""" - -Processes all the hardware generated events e.g Bus reset, new data packet from host etc ... It will be called by application in the MCU USB interrupt handler. - -``dcd_set_address()`` -""""""""""""""""""""" - -Called when the device is given a new bus address. - -If your peripheral automatically changes address during enumeration (like the nrf52) you may leave this empty and also no queue an event for the corresponding SETUP packet. - -``dcd_remote_wakeup()`` -""""""""""""""""""""""" - -Called to remote wake up host when suspended (e.g hid keyboard) - -``dcd_connect()`` / ``dcd_disconnect()`` -"""""""""""""""""""""""""""""""""""""""" - -Connect or disconnect the data-line pull-up resistor. Define only if MCU has an internal pull-up. (BSP may define for MCU without internal pull-up.) - -Special events -~~~~~~~~~~~~~~ - -You must let TinyUSB know when certain events occur so that it can continue its work. There are a few methods you can call to queue events for TinyUSB to process. - -``dcd_event_bus_signal()`` -"""""""""""""""""""""""""" - -There are a number of events that your peripheral may communicate about the state of the bus. Here is an overview of what they are. Events in **BOLD** must be provided for TinyUSB to work. - - -* **DCD_EVENT_RESET** - Triggered when the host resets the bus causing the peripheral to reset. Do any other internal reset you need from the interrupt handler such as resetting the control endpoint. -* DCD_EVENT_SOF - Signals the start of a new USB frame. - -Calls to this look like: - -.. code-block:: c - - dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); - - -The first ``0`` is the USB peripheral number. Statically saying ``0`` is common for single USB device MCUs. - -The ``true`` indicates the call is from an interrupt handler and will always be the case when porting in this way. - -``dcd_setup_received()`` -"""""""""""""""""""""""" - -SETUP packets are a special type of transaction that can occur at any time on the control endpoint, numbered ``0``. Since they are unique, most peripherals have special handling for them. Their data is always 8 bytes in length as well. - -Calls to this look like: - -.. code-block:: c - - dcd_event_setup_received(0, setup, true); - - -As before with ``dcd_event_bus_signal()`` the first argument is the USB peripheral number and the third is true to signal its being called from an interrupt handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. - -Endpoints -~~~~~~~~~ - -Endpoints are the core of the USB data transfer process. They come in a few forms such as control, isochronous, bulk, and interrupt. We won't cover the details here except with some caveats in open below. In general, data is transferred by setting up a buffer of a given length to be transferred on a given endpoint address and then waiting for an interrupt to signal that the transfer is finished. Further details below. - -Endpoints within USB have an address which encodes both the number and direction of an endpoint. TinyUSB provides ``tu_edpt_number()`` and ``tu_edpt_dir()`` to unpack this data from the address. Here is a snippet that does it. - -.. code-block:: c - - uint8_t epnum = tu_edpt_number(ep_addr); - uint8_t dir = tu_edpt_dir(ep_addr); - - -``dcd_edpt_open()`` -""""""""""""""""""" - -Opening an endpoint is done for all non-control endpoints once the host picks a configuration that the device should use. At this point, the endpoint should be enabled in the peripheral and configured to match the endpoint descriptor. Pay special attention to the direction of the endpoint you can get from the helper methods above. It will likely change what registers you are setting. - -Also make sure to enable endpoint specific interrupts. - -``dcd_edpt_close()`` -"""""""""""""""""""" - -Close an endpoint. his function is used for implementing alternate settings. - -After calling this, the device should not respond to any packets directed towards this endpoint. When called, this function must abort any transfers in progress through this endpoint, before returning. - -Implementation is optional. Must be called from the USB task. Interrupts could be disabled or enabled during the call. - -``dcd_edpt_xfer()`` -""""""""""""""""""" - -``dcd_edpt_xfer()`` is responsible for configuring the peripheral to send or receive data from the host. "xfer" is short for "transfer". **This is one of the core methods you must implement for TinyUSB to work (one other is the interrupt handler).** Data from the host is the OUT direction and data to the host is IN. It is used for all endpoints including the control endpoint 0. Make sure to handle the zero-length packet STATUS packet on endpoint 0 correctly. It may be a special transaction to the peripheral. - -Besides that, all other transactions are relatively straight-forward. The endpoint address provides the endpoint -number and direction which usually determines where to write the buffer info. The buffer and its length are usually -written to a specific location in memory and the peripheral is told the data is valid. (Maybe by writing a 1 to a -register or setting a counter register to 0 for OUT or length for IN.) - -The transmit buffer alignment is determined by ``CFG_TUSB_MEM_ALIGN``. - -One potential pitfall is that the buffer may be longer than the maximum endpoint size of one USB -packet. Some peripherals can handle transmitting multiple USB packets for a provided buffer (like the SAMD21). -Others (like the nRF52) may need each USB packet queued individually. To make this work you'll need to track -some state for yourself and queue up an intermediate USB packet from the interrupt handler. - -Once the transaction is going, the interrupt handler will notify TinyUSB of transfer completion. -During transmission, the IN data buffer is guaranteed to remain unchanged in memory until the ``dcd_xfer_complete()`` function is called. - -The ``dcd_edpt_xfer()`` function must never add zero-length-packets (ZLP) on its own to a transfer. If a ZLP is required, -then it must be explicitly sent by the stack calling ``dcd_edpt_xfer()``, by calling ``dcd_edpt_xfer()`` a second time with len=0. -For control transfers, this is automatically done in ``usbd_control.c``. - -At the moment, only a single buffer can be transmitted at once. There is no provision for double-buffering. new ``dcd_edpt_xfer()`` will not -be called again on the same endpoint address until the driver calls ``dcd_xfer_complete()`` (except in cases of USB resets). - -``dcd_xfer_complete()`` -""""""""""""""""""""""" - -Once a transfer completes you must call ``dcd_xfer_complete()`` from the USB interrupt handler to let TinyUSB know that a transaction has completed. Here is a sample call: - -.. code-block:: c - - dcd_event_xfer_complete(0, ep_addr, xfer->actual_len, XFER_RESULT_SUCCESS, true); - - -The arguments are: - - -* the USB peripheral number -* the endpoint address -* the actual length of the transfer. (OUT transfers may be smaller than the buffer given in ``dcd_edpt_xfer()``) -* the result of the transfer. Failure isn't handled yet. -* ``true`` to note the call is from an interrupt handler. - -``dcd_edpt_stall()`` / ``dcd_edpt_clear_stall()`` -""""""""""""""""""""""""""""""""""""""""""""""""" - -Stalling is one way an endpoint can indicate failure such as when an unsupported command is transmitted. The pair of ``dcd_edpt_stall()``, ``dcd_edpt_clear_stall()`` help manage the stall state of all endpoints. - -Woohoo! -------- - -At this point you should have everything working! πŸ™‚ Of course, you may not write perfect code. Here are some tips and tricks for debugging. - -Use `WireShark `_ or `a Beagle `_ to sniff the USB traffic. When things aren't working its likely very early in the USB enumeration process. Figuring out where can help clue in where the issue is. For example: - - -* If the host sends a SETUP packet and its not ACKed then your USB peripheral probably isn't started correctly. -* If the peripheral is started correctly but it still didn't work, then verify your usb clock is correct. (You did output a PWM based on it right? πŸ™‚) -* If the SETUP packet is ACKed but nothing is sent back then you interrupt handler isn't queueing the setup packet correctly. (Also, if you are using your own code instead of an example ``tud_task()`` may not be called.) If that's OK, the ``dcd_xfer_complete()`` may not be setting up the next transaction correctly. diff --git a/docs/faq.rst b/docs/faq.rst index ade51a379..a5fe09495 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -7,7 +7,7 @@ General Questions **Q: What microcontrollers does TinyUSB support?** -TinyUSB supports 30+ MCU families including STM32, RP2040, NXP (iMXRT, Kinetis, LPC), Microchip SAM, Nordic nRF5x, ESP32, and many others. See :doc:`reference/boards` for the complete list. +TinyUSB supports 50+ MCU families including STM32, RP2040, NXP (iMXRT, Kinetis, LPC), Microchip SAM, Nordic nRF5x, ESP32, and many others. See :doc:`reference/boards` for the complete list. **Q: Can I use TinyUSB in commercial projects?** @@ -178,33 +178,3 @@ ESP32-S3 has specific USB implementation challenges: - Check power supply requirements for host mode - Some features may be limited compared to other MCUs - Use ESP32-S3 specific examples and documentation - -STM32CubeIDE Integration -======================== - -**Q: How do I integrate TinyUSB with STM32CubeIDE?** - -1. In STM32CubeMX, enable USB_OTG_FS/HS under Connectivity, set to "Device_Only" mode -2. Enable the USB global interrupt in NVIC Settings -3. Add ``tusb.h`` include and call ``tusb_init()`` in main.c -4. Call ``tud_task()`` in your main loop -5. In the generated ``stm32xxx_it.c``, modify the USB IRQ handler to call ``tud_int_handler(0)`` -6. Create ``tusb_config.h`` and ``usb_descriptors.c`` files - -**Q: STM32CubeIDE generated code conflicts with TinyUSB** - -Don't use STM32's built-in USB middleware (USB Device Library) when using TinyUSB. Disable USB code generation in STM32CubeMX and let TinyUSB handle all USB functionality. - -**Q: STM32 USB interrupt handler setup** - -Replace the generated USB interrupt handler with a call to TinyUSB: - -.. code-block:: c - - void OTG_FS_IRQHandler(void) { - tud_int_handler(0); - } - -**Q: Which STM32 families work best with TinyUSB?** - -STM32F4, F7, and H7 families have the most mature TinyUSB support. STM32F0, F1, F3, L4 families are also supported but may have more limitations. Check the supported boards list for your specific variant. \ No newline at end of file diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 32c80b91c..0c3fcec80 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -2,14 +2,39 @@ Getting Started *************** -This guide will get you up and running with TinyUSB quickly. We'll start with working examples, then show you how to integrate TinyUSB into your own projects. +This guide will get you up and running with TinyUSB quickly with working examples. + +Project Structure +==================== + +TinyUSB separates example applications from board-specific hardware configurations: + +* **Example applications**: Located in `examples/ `_ directories +* **Board Support Packages (BSP)**: Located in ``hw/bsp/FAMILY/boards/BOARD_NAME/`` with hardware abstraction including pin mappings, clock settings, and linker scripts +* **Build system**: Located in `examples/build_system/ `_ which supports both Make and CMake. Though some MCU families such as espressif or rp2040 only support cmake + +For example, stm32h743eval is located in `hw/bsp/stm32h7/boards/stm32h743eval `_ where ``FAMILY=stm32h7`` and ``BOARD=stm32h743eval``. When you build with ``BOARD=stm32h743eval``, the build system automatically finds the corresponding BSP using the FAMILY. + +For guidance on integrating TinyUSB into your own firmware (configuration, descriptors, initialization, and callback workflow), see :doc:`integration`. Quick Start Examples ==================== The fastest way to understand TinyUSB is to see it working. These examples demonstrate core functionality and can be built immediately. -We'll assume you are using the stm32f407disco board. For other boards, see ``Board Support Packages`` below. +We'll assume you are using the **STM32H743 Eval board** (BOARD=stm32h743eval) under the **stm32h7** family. For other boards, see ``Board Support Packages`` below. + +Get the Code +------------ + +.. code-block:: bash + + $ git clone https://github.com/hathach/tinyusb tinyusb + $ cd tinyusb + $ python tools/get_deps.py -b stm32h743eval # or python tools/get_deps.py stm32h7 + +.. note:: + For rp2040 `pico-sdk `_ or `esp-idf `_ for Espressif targets are required; install them per vendor instructions. Simple Device Example --------------------- @@ -17,20 +42,33 @@ Simple Device Example The `cdc_msc `_ example creates a USB device with both a virtual serial port (CDC) and mass storage (MSC). **What it does:** + * Appears as a serial port that echoes back any text you send * Appears as a small USB drive with a README.TXT file * Blinks an LED to show activity -**Build and run:** +**Build and run with CMake:** + +.. code-block:: bash + + $ cd examples/device/cdc_msc + $ cmake -DBOARD=stm32h743eval -B build # add "-G Ninja" to use Ninja build + $ cmake --build build + # cmake --build build --target cdc_msc-jlink + +.. tip:: + Flashed/Debugger can be selected with --target ``-jlink``, ``-stlink`` or ``-openocd`` depending on your board. Use ``--target help`` to list all supported targets. + +**Build and run with Make:** .. code-block:: bash - $ git clone https://github.com/hathach/tinyusb tinyusb - $ cd tinyusb - $ python tools/get_deps.py stm32f4 # download dependencies, note ESP and RP2 need their SDKs, too $ cd examples/device/cdc_msc - $ cmake -DBOARD=stm32f407disco -B build # add "-G Ninja ." on Windows - $ cmake --build build # add "--target cdc_msc-jlink" for flashing using J-Link, "--target help" to list targets + $ make BOARD=stm32h743eval all + $ make BOARD=stm32h743eval flash-jlink + +.. tip:: + Flashed/Debugger can be selected with target ``flash-jlink``, ``flash-stlink`` or ``flash-openocd`` depending on your board. Connect the device to your computer and you'll see both a new serial port and a small USB drive appear. @@ -40,113 +78,91 @@ Simple Host Example The `cdc_msc_hid `_ example creates a USB host that can connect to USB devices with CDC, MSC, or HID interfaces. **What it does:** + * Detects and enumerates connected USB devices * Communicates with CDC devices (like USB-to-serial adapters) * Reads from MSC devices (like USB drives) * Receives input from HID devices (like keyboards and mice) -**Build and run:** +**Build and run with CMake:** .. code-block:: bash - $ # initial setup see previous example $ cd examples/host/cdc_msc_hid - $ cmake -DBOARD=stm32f407disco -B build # add "-G Ninja ." on Windows - $ cmake --build build # add "--target cdc_msc_hid-jlink" for flashing using J-Link, "--target help" to list targets - -Connect USB devices to see enumeration messages and device-specific interactions in the serial output. - -Project Structure ------------------ - -TinyUSB separates example applications from board-specific hardware configurations: - -* **Example applications**: Located in `examples/device/ `_, `examples/host/ `_, and `examples/dual/ `_ directories -* **Board Support Packages (BSP)**: Located in ``hw/bsp/FAMILY/boards/BOARD_NAME/`` with hardware abstraction including pin mappings, clock settings, and linker scripts - -For example, raspberry_pi_pico is located in `hw/bsp/rp2040/boards/raspberry_pi_pico `_ where ``FAMILY=rp2040`` and ``BOARD=raspberry_pi_pico``. When you build with ``BOARD=raspberry_pi_pico``, the build system automatically finds the corresponding BSP using the FAMILY. - -Add TinyUSB to Your Project -============================ + $ cmake -DBOARD=stm32h743eval -B build + $ cmake --build build -Once you've seen TinyUSB working, here's how to integrate it into your own project: +**Build and run with Make:** -Integration Steps ------------------ +.. code-block:: bash -1. **Get TinyUSB**: Copy this repository or add it as a git submodule to your project at ``your_project/tinyusb`` + $ cd examples/host/cdc_msc_hid + $ make BOARD=stm32h743eval all + $ make BOARD=stm32h743eval flash-jlink -2. **Add source files**: Add all ``.c`` files from ``tinyusb/src/`` to your project +Connect USB devices to see enumeration messages and device-specific interactions in the serial output. -3. **Configure include paths**: Add ``your_project/tinyusb/src`` to your include path. Ensure your include path contains ``tusb_config.h`` +Additional Build Options +------------------------ -4. **Configure TinyUSB**: Create ``tusb_config.h`` with required macros like ``CFG_TUSB_MCU`` and ``CFG_TUSB_OS``. Copy from ``examples/device/*/tusb_config.h`` as a starting point +Debug and Logging +^^^^^^^^^^^^^^^^^ -5. **Implement USB descriptors**: For device stack, implement all ``tud_descriptor_*_cb()`` callbacks +TinyUSB built-in logging can be enabled by setting `CFG_TUSB_DEBUG` which is done by passing ``LOG=level``. The higher the level, the more verbose the logging. -6. **Initialize TinyUSB**: Add ``tusb_init()`` to your initialization code +In addition to traditional hw uart as default, logging with debugger such as `Segger RTT `_ (10x faster) is also supported with `LOGGER=rtt` option. -7. **Handle interrupts**: Call ``tusb_int_handler()`` from your USB IRQ handler +.. code-block:: bash -8. **Run USB tasks**: Call ``tud_task()`` (device) or ``tuh_task()`` (host) periodically in your main loop + $ cmake -B build -DBOARD=stm32h743eval -DLOG=2 # logging level 2 with uart + $ cmake -B build -DBOARD=stm32h743eval -DLOG=2 -DLOGGER=rtt # logging level 2 with RTT -9. **Implement class callbacks**: Implement callbacks for enabled USB classes +.. code-block:: bash -Simple Integration Example --------------------------- + $ make BOARD=stm32h743eval LOG=2 all # logging level 2 with uart + $ make BOARD=stm32h743eval LOG=2 LOGGER=rtt all # logging level 2 with RTT -.. code-block:: c +RootHub Port Selection +^^^^^^^^^^^^^^^^^^^^^^ - #include "tusb.h" +Some boards support multiple usb controllers (roothub ports), by default one rh port is used as device, another as host in ``board.mk/board.cmake``. This can be overridden with option ``RHPORT_DEVICE=n`` or ``RHPORT_HOST=n`` To choose another port. For example to select the HS port of a STM32F746Disco board, use: - int main(void) { - board_init(); // Your board initialization +.. code-block:: bash - tusb_rhport_init_t dev_init = { - .role = TUSB_ROLE_DEVICE, - .speed = TUSB_SPEED_AUTO - }; - // tud_descriptor_* callbacks omitted here - tusb_init(0, &dev_init); + $ cmake -B build -DBOARD=stm32h743eval -DRHPORT_DEVICE=1 # select roothub port 1 as device - while(1) { - tud_task(); // TinyUSB device task - your_application(); // Your application code - } - } +.. code-block:: bash - void USB_IRQHandler(void) { - tusb_int_handler(0, true); - } + $ make BOARD=stm32h743eval RHPORT_DEVICE=1 all # select roothub port 1 as device -.. note:: - Unlike many libraries, TinyUSB callbacks don't need to be explicitly registered. The stack automatically calls functions with specific names (e.g., ``tud_cdc_rx_cb()``) when events occur. Simply implement the callbacks you need. +RootHub Port Speed +^^^^^^^^^^^^^^^^^^ -.. note:: - TinyUSB uses consistent naming prefixes: ``tud_`` for device stack functions and ``tuh_`` for host stack functions. See the :doc:`reference/glossary` for more details. +A MCU can support multiple operational speed. By default, the example build system will use the fastest supported on the board. Use option ``RHPORT_DEVICE_SPEED=OPT_MODE_FULL/HIGH_SPEED/`` or ``RHPORT_HOST_SPEED=OPT_MODE_FULL/HIGH_SPEED/`` e.g To force operating speed -Development Tips -================ +.. code-block:: bash -**Debug builds and logging:** + $ cmake -B build -DBOARD=stm32h743eval -DRHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED .. code-block:: bash - $ cmake -DBOARD=stm32f407disco -DDEBUG=1 ... # Debug build - $ cmake -DBOARD=stm32f407disco -DLOG=2 ... # Enable detailed logging + $ make BOARD=stm32h743eval RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED all + -**IAR Embedded Workbench:** +IAR Embedded Workbench +---------------------- For IAR users, project connection files are available. Import `tools/iar_template.ipcf `_ or use native CMake support (IAR 9.50.1+). See `tools/iar_gen.py `_ for automated project generation. + Common Issues and Solutions -=========================== +--------------------------- **Build Errors** * **"arm-none-eabi-gcc: command not found"**: Install ARM GCC toolchain: ``sudo apt-get install gcc-arm-none-eabi`` * **"Board 'X' not found"**: Check the available boards in ``hw/bsp/FAMILY/boards/`` or run ``python tools/build.py -l`` -* **Missing dependencies**: Run ``python tools/get_deps.py FAMILY`` where FAMILY matches your board +* **Missing dependencies**: Run ``python tools/get_deps.py FAMILY`` where FAMILY matches your board or ``python tools/get_deps.py -b BOARD`` **Runtime Issues** @@ -166,6 +182,7 @@ Some examples require udev permissions to access USB devices: Next Steps ========== +* Check :doc:`integration` for integrating TinyUSB into your own firmware * Check :doc:`reference/boards` for board-specific information * Explore more examples in `examples/device/ `_ and `examples/host/ `_ directories * Read :doc:`reference/usb_concepts` to understand USB fundamentals diff --git a/docs/index.rst b/docs/index.rst index ac10dbfd7..39d30a038 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,45 +1,21 @@ -TinyUSB Documentation -===================== - -TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events deferred to non-ISR task functions. - -For Developers --------------- - -TinyUSB provides a complete USB stack implementation supporting both device and host modes across a wide range of microcontrollers. The stack is designed for resource-constrained embedded systems with emphasis on code size, memory efficiency, and real-time performance. - -**Key Features:** - -* **Thread-safe design**: All USB interrupts are deferred to task context -* **Memory-safe**: No dynamic allocation, all buffers are statically allocated -* **Portable**: Supports 30+ MCU families from major vendors -* **Comprehensive**: Device classes (CDC, HID, MSC, Audio, etc.) and Host stack -* **RTOS support**: Works with bare metal, FreeRTOS, RT-Thread, and Mynewt - -**Quick Navigation:** - -* New to TinyUSB? Start with :doc:`getting_started` and :doc:`reference/glossary` -* Want to understand the design? Read :doc:`reference/architecture` and :doc:`reference/usb_concepts` -* Having issues? Check :doc:`faq` and :doc:`troubleshooting` - -Documentation Structure ------------------------ +.. include:: ../README_processed.rst .. toctree:: :maxdepth: 2 :caption: Information getting_started + integration + porting + reference/index faq troubleshooting - reference/index .. toctree:: :maxdepth: 1 :caption: Project Info info/index - contributing/index .. toctree:: :caption: External Links @@ -48,8 +24,3 @@ Documentation Structure Source Code Issue Tracker Discussions - -GitHub Project Main README -========================== - -.. include:: ../README_processed.rst diff --git a/docs/info/changelog.rst b/docs/info/changelog.rst index b4423f81e..d6bf846ed 100644 --- a/docs/info/changelog.rst +++ b/docs/info/changelog.rst @@ -20,6 +20,7 @@ API Changes ----------- - Core APIs + - Add weak callbacks with new syntax for better compiler compatibility - Add ``tusb_deinit()`` to cleanup stack - Add time functions: ``tusb_time_millis_api()`` and ``tusb_time_delay_ms_api()`` @@ -27,6 +28,7 @@ API Changes - Introduce ``xfer_isr()`` callback for ISO transfer optimization in device classes - Device APIs + - CDC: Add notification support ``tud_cdc_configure()``, ``tud_cdc_n_notify_uart_state()``, ``tud_cdc_n_notify_conn_speed_change()``, ``tud_cdc_notify_complete_cb()`` - MSC: Add ``tud_msc_inquiry2_cb()`` with bufsize parameter, update ``tud_msc_async_io_done()`` @@ -36,6 +38,7 @@ API Changes ``tud_mtp_response_send()``, ``tud_mtp_event_send()`` - Host APIs + - Core: Add ``tuh_edpt_close()``, ``tuh_address_set()``, ``tuh_descriptor_get_device_local()``, ``tuh_descriptor_get_string_langid()``, ``tuh_connected()``, ``tuh_bus_info_get()`` - Add enumeration callbacks: ``tuh_enum_descriptor_device_cb()``, @@ -50,6 +53,7 @@ Controller Driver (DCD & HCD) ----------------------------- - DWC2 + - Support DWC2 v4.30a with improved reset procedure - Fix core reset: wait for AHB idle before reset - Add STM32 DWC2 data cache support with proper alignment @@ -64,6 +68,7 @@ Controller Driver (DCD & HCD) - Refactor bitfields for better code generation - FSDEV (STM32) + - Fix AT32 compile issues after single-buffered endpoint changes - Add configurable single-buffered isochronous endpoints - Fix STM32H7 recurrent suspend ISR @@ -72,35 +77,42 @@ Controller Driver (DCD & HCD) - Improve PMA size handling for STM32U0 - EHCI + - Fix removed QHD getting reused - Fix NXP USBPHY disconnection detection - Chipidea/NXP + - Fix race condition with spinlock - Improve iMXRT support: fix build, disable BOARD_ConfigMPU, fix attach debouncing on port1 highspeed - Fix iMXRT1064 and add to HIL test pool - MAX3421E + - Use spinlock for thread safety instead of atomic flag - Implement ``hcd_edpt_close()`` - RP2040 + - Fix audio ISO transfer: reset state before notifying stack - Fix CMake RTOS cache variable - Abort transfer if active in ``iso_activate()`` - SAMD + - Add host controller driver support Device Stack ------------ - USBD Core + - Introduce ``xfer_isr()`` callback for interrupt-time transfer handling - Add ``usbd_edpt_xfer_fifo()`` stub - Revert endpoint busy/claim status if ``xfer_isr()`` defers to ``xfer_cb()`` - Audio + - Major simplification of UAC driver and alt settings management - Move ISO transfers into ``xfer_isr()`` for better performance - Remove FIFO mutex (single producer/consumer optimization) @@ -109,25 +121,30 @@ Device Stack - Update buffer macros with cache line size alignment - CDC + - Add notification support: ``CFG_TUD_CDC_NOTIFY``, ``tud_cdc_n_notify_conn_speed_change()``, ``tud_cdc_notify_complete_cb()`` - Reduce default bInterval from 16ms to 1ms for better responsiveness - Rename ``tud_cdc_configure_fifo()`` to ``tud_cdc_configure()`` and add ``tx_overwritable_if_not_connected`` option - Fix web serial robustness with major overhaul and logic cleanup - HID + - Add Usage Page and Table for Power Devices (0x84 - 0x85) - Fix HID descriptor parser variable size and 4-byte item handling - Add consumer page configurations - MIDI + - Fix MIDI interface descriptor handling after audio streaming interface - Skip RX data with all zeroes - MSC + - Add async I/O support for MSC using ``tud_msc_async_io_done()`` - Add ``tud_msc_inquiry2_cb()`` with bufsize for full inquiry response - MTP + - Add new Media Transfer Protocol (MTP) device class driver - Support MTP operations: GetDeviceInfo, SendObjectInfo, SendObject - Add MTP event support with ``tud_mtp_event_send()`` @@ -135,13 +152,16 @@ Device Stack - Add hardware-in-the-loop testing support - NCM + - Add USB NCM link state control support - Fix DHCP offer/ACK destination - USBTMC + - Add vendor-specific message support - Vendor + - Fix vendor device reset and open issues - Fix descriptor parsing for ``CFG_TUD_VENDOR > 1`` - Fix vendor FIFO argument calculation @@ -150,6 +170,7 @@ Host Stack ---------- - USBH Core + - Major enumeration improvements: - Fix enumeration racing conditions - Add proper attach debouncing with hub/rootport handling (200ms delay) @@ -173,6 +194,7 @@ Host Stack - Force removed devices in same bus info before setting address - CDC Serial Host + - Major refactor to generalize CDC serial drivers (FTDI, CP210x, CH34x, PL2303, ACM) - Add explicit ``sync()`` API with ``TU_API_SYNC()`` returning ``tusb_xfer_result_t`` - Rename ``tuh_cdc_get_local_line_coding()`` to ``tuh_cdc_get_line_coding_local()`` @@ -180,6 +202,7 @@ Host Stack - Implement ``tuh_cdc_get/set_dtr/rts()`` as inline functions - MIDI Host + - Major API changes: - Rename ``tuh_midi_stream_flush()`` to ``tuh_midi_write_flush()`` - Add ``tuh_midi_packet_read_n()`` and ``tuh_midi_packet_write_n()`` @@ -189,9 +212,11 @@ Host Stack - Add ``tuh_midi_descriptor_cb()`` and ``tuh_midi_itf_get_info()`` - MSC Host + - Continue async I/O improvements - HID Host + - Fix version string to actually show version 0.18.0 @@ -226,6 +251,7 @@ Controller Driver (DCD & HCD) ----------------------------- - DWC2 + - Add DMA support for both device and host controller - Add host driver support including: full/high speed, control/bulk/interrupt (CBI) transfer, split CBI i.e FS/LS attached via highspeed hub, hub support @@ -695,6 +721,7 @@ Controller Driver (DCD & HCD) ----------------------------- - [DWC2] Generalize synopsys dwc2 with synopsys/dwc2 which support both FS and HS phy (UTMI and ULPI) for various MCUs. + - Broadcom 28/27xx on raspberrypi SBC - Silicon Labs EFM32 - Espressif ESP32 Sx @@ -916,6 +943,7 @@ HID - Add more hid keys constant from 0x6B to 0xA4 - [Breaking] rename API + - ``HID_PROTOCOL_NONE/KEYBOARD/MOUSE`` to ``HID_ITF_PROTOCOL_NONE/KEYBOARD/MOUSE`` - ``tud_hid_boot_mode()`` to ``tud_hid_get_protocol()`` - ``tud_hid_boot_mode_cb()`` to ``tud_hid_set_protocol_cb()`` @@ -925,6 +953,7 @@ MIDI - Fix MIDI buffer overflow issue - [Breaking] rename API + - Rename ``tud_midi_read()`` to ``tud_midi_stream_read()`` - Rename ``tud_midi_write()`` to ``tud_midi_stream_write()`` - Rename ``tud_midi_receive()`` to ``tud_midi_packet_read()`` @@ -1075,15 +1104,19 @@ Device Controller Driver - Use ``dcd_event_bus_reset()`` with link speed to replace bus_signal - ESP32-S2: + - Add bus suspend and wakeup support - SAMD21: + - Fix (walkaround) samd21 setup_packet overflow by USB DMA - STM32 Synopsys: + - Rework USB FIFO allocation scheme and allow RX FIFO size reduction - Sony CXD56 + - Update Update Spresense SDK to 2.0.2 - Fix dcd issues with setup packets - Correct EP number for cdc_msc example @@ -1100,19 +1133,24 @@ USB Device **Class Driver** - CDC + - Allow to transmit data, even if the host does not support control line states i.e set DTR - HID + - change default ``CFG_TUD_HID_EP_BUFSIZE`` from 16 to 64 - MIDI + - Fix midi sysex sending bug - MSC + - Invoke only scsi complete callback after status transaction is complete. - Fix ``scsi_mode_sense6_t`` padding, which cause IAR compiler internal error. - USBTMC + - Change interrupt endpoint example size to 8 instead of 2 for better compatibility with mcu **Example** @@ -1154,6 +1192,7 @@ Device Controller Driver - Enhance STM32 Synopsys - Support bus events disconnection/suspend/resume/wakeup + - Improve transfer performance with optimizing xfer and fifo size - Support Highspeed port (OTG_HS) with both internal and external PHY - Support multiple usb ports with rhport=1 is highspeed on selected MCUs e.g H743, F23. It is possible to have OTG_HS to run on Fullspeed PHY (e.g lacking external PHY) @@ -1163,6 +1202,7 @@ Device Controller Driver - Support F105, F107 - Enhance STM32 fsdev + - Improve dcd fifo allocation - Fix ISTR race condition - Support remap USB IRQ on supported MCUs @@ -1171,6 +1211,7 @@ Device Controller Driver - Enhance NUC 505: enhance set configure behavior - Enhance SAMD + - Fix race condition with setup packet - Add SAMD11 option ``OPT_MCU_SAMD11`` - Add SAME5x option ``OPT_MCU_SAME5X`` @@ -1178,6 +1219,7 @@ Device Controller Driver - Fix SAMG control data toggle and stall race condition - Enhance nRF + - Fix hanged when ``tud_task()`` is called within critical section (disabled interrupt) - Fix disconnect bus event not submitted - Implement ISO transfer and ``dcd_edpt_close()`` @@ -1203,6 +1245,7 @@ USB Device - Improve USB Highspeed support with actual link speed detection with ``dcd_event_bus_reset()`` - Enhance class driver management + - ``usbd_driver_open()`` add max length argument, and return length of interface (0 for not supported). Return value is used for finding appropriate driver - Add application implemented class driver via ``usbd_app_driver_get_cb()`` - IAD is handled to assign driver id @@ -1219,11 +1262,13 @@ USB Device - USBTMC: fix descriptors when INT EP is disabled - CDC: + - Send zero length packet for end of data when needed - Add ``tud_cdc_tx_complete_cb()`` callback - Change ``tud_cdc_n_write_flush()`` return number of bytes forced to transfer, and flush when writing enough data to fifo - MIDI: + - Add packet interface - Add multiple jack descriptors - Fix MIDI driver for sysex @@ -1231,12 +1276,14 @@ USB Device - DFU Runtime: fix response to SET_INTERFACE and DFU_GETSTATUS request - Rename some configure macro to make it clear that those are used directly for endpoint transfer + - ``CFG_TUD_HID_BUFSIZE`` to ``CFG_TUD_HID_EP_BUFSIZE`` - ``CFG_TUD_CDC_EPSIZE`` to ``CFG_TUD_CDC_EP_BUFSIZE`` - ``CFG_TUD_MSC_BUFSIZE`` to ``CFG_TUD_MSC_EP_BUFSIZE`` - ``CFG_TUD_MIDI_EPSIZE`` to ``CFG_TUD_MIDI_EP_BUFSIZE`` - HID: + - Fix gamepad template descriptor - Add multiple HID interface API - Add extra comma to HID_REPORT_ID @@ -1258,6 +1305,7 @@ Examples - Add new ``hid_multiple_interface`` - Enhance ``net_lwip_webserver`` example + - Add multiple configuration: RNDIS for Windows, CDC-ECM for macOS (Linux will work with both) - Update lwip to STABLE-2_1_2_RELEASE for ``net_lwip_webserver`` diff --git a/docs/info/code_of_conduct.rst b/docs/info/code_of_conduct.rst new file mode 100644 index 000000000..2d70708d4 --- /dev/null +++ b/docs/info/code_of_conduct.rst @@ -0,0 +1 @@ +.. include:: ../../CODE_OF_CONDUCT.rst diff --git a/docs/info/index.rst b/docs/info/index.rst index a636f37dc..b6d30b432 100644 --- a/docs/info/index.rst +++ b/docs/info/index.rst @@ -10,3 +10,4 @@ Index changelog contributors + code_of_conduct diff --git a/docs/integration.rst b/docs/integration.rst new file mode 100644 index 000000000..3480746d0 --- /dev/null +++ b/docs/integration.rst @@ -0,0 +1,93 @@ +******************* +Integrating TinyUSB +******************* + +Once you've seen TinyUSB working in the examples, use this guide to wire the stack into your own firmware. + +Integration Steps +================= + +1. **Get TinyUSB**: Copy this repository or add it as a git submodule to your project at ``your_project/tinyusb``. +2. **Add source files**: Add every ``.c`` file from ``tinyusb/src/`` to your project build system. + +.. note:: + Only supported dcd/hcd drivers for your CPU sources under ``tinyusb/src/portable/vendor/usbip/`` are needed. Add + +3. **Configure TinyUSB**: Create ``tusb_config.h`` with macros such as ``CFG_TUSB_MCU``, ``CFG_TUSB_OS``, and class enable flags. Start from any example's ``tusb_config.h`` and tweak. +4. **Configure include paths**: Add ``your_project/tinyusb/src`` (and the folder holding ``tusb_config.h``) to your include paths. +5. **Implement USB descriptors**: For device stack, implement the ``tud_descriptor_*_cb()`` callbacks (device) or host descriptor helpers that match your product. +6. **Initialize TinyUSB**: Call ``tusb_init()`` once the clocks/peripherals are ready. Pass ``tusb_rhport_init_t`` if you need per-port settings. +7. **Handle interrupts**: From the USB ISR call ``tusb_int_handler(rhport, true)`` so the stack can process events. +8. **Run USB tasks**: Call ``tud_task()`` (device) or ``tuh_task()`` (host) regularly from the main loop, RTOS task. +9. **Implement class callbacks**: Provide the callbacks for the classes you enabled (e.g., ``tud_cdc_rx_cb()``, ``tuh_msc_mount_cb()``). + +Minimal Example +=============== + +.. code-block:: c + + #include "tusb.h" + + int main(void) { + board_init(); // Your board initialization + + // Init device stack on roothub port 0 for highspeed device + tusb_rhport_init_t dev_init = { + .role = TUSB_ROLE_DEVICE, + .speed = TUSB_SPEED_HIGH + }; + tusb_init(0, &dev_init); + + // init host stack on roothub port 1 for fullspeed host + tusb_rhport_init_t host_init = { + .role = TUSB_ROLE_DEVICE, + .speed = TUSB_SPEED_FULL + }; + tusb_init(1, &host_init); + + while (1) { + tud_task(); // device task + tuh_task(); // host task + + app_task(); // Your application logic + } + } + + void USB0_IRQHandler(void) { + // forward interrupt port 0 to TinyUSB stack + tusb_int_handler(0, true); + } + + void USB1_IRQHandler(void) { + // forward interrupt port 0 to TinyUSB stack + tusb_int_handler(1, true); + } + +.. note:: + Unlike many libraries, TinyUSB callbacks don't need to be registered. Implement functions with the prescribed names (for example ``tud_cdc_rx_cb()``) and the stack will invoke them automatically. + +.. note:: + Naming follows ``tud_*`` for device APIs and ``tuh_*`` for host APIs. Refer to :doc:`reference/glossary` for a summary of the prefixes and callback naming rules. + + +STM32CubeIDE Integration +======================== + +To integrate TinyUSB device stack with STM32CubeIDE + +1. In STM32CubeMX, enable USB_OTG_FS/HS under Connectivity, set to "Device_Only" mode +2. Enable the USB global interrupt in NVIC Settings +3. Add ``tusb.h`` include and call ``tusb_init()`` in main.c +4. Call ``tud_task()`` in your main loop +5. In the generated ``stm32xxx_it.c``, modify the USB IRQ handler to call ``tud_int_handler(0)`` + +.. code-block:: c + + void OTG_FS_IRQHandler(void) { + tud_int_handler(0); + } + +6. Create ``tusb_config.h`` and ``usb_descriptors.c`` files + +.. tip:: + STM32CubeIDE generated code conflicts with TinyUSB. Don't use STM32's built-in USB middleware (USB Device Library) when using TinyUSB. Disable USB code generation in STM32CubeMX and let TinyUSB handle all USB functionality. diff --git a/docs/porting.rst b/docs/porting.rst new file mode 100644 index 000000000..c3076354c --- /dev/null +++ b/docs/porting.rst @@ -0,0 +1,243 @@ + +******* +Porting +******* + +TinyUSB is designed to be a universal USB protocol stack for microcontrollers. It +handles most of the high level USB protocol and relies on the microcontroller's USB peripheral for +data transactions on different endpoints. Porting is the process of adding low-level support for +the rest of the common stack. Once the low-level is implemented, it is very easy to add USB support +for the microcontroller to other projects, especially those already using TinyUSB such as CircuitPython. + +Below are instructions on how to get the cdc_msc device example running on a new microcontroller. Doing so includes adding the common code necessary for other uses while minimizing other extra code. Whenever you see a phrase or word in ``<>`` it should be replaced. + +Register defs +------------- + +The first step to adding support is including the register definitions and startup code for the +microcontroller in TinyUSB. We write the TinyUSB implementation against these structs instead of higher level functions to keep the code small and to prevent function name collisions in linking of larger projects. For ARM microcontrollers this is the CMSIS definitions. They should be +placed in the ``hw/mcu//`` directory. + +Once this is done, create a directory in ``hw/bsp/`` for the specific board you are using to test the code (duplicating an existing board's directory is the best way to get started). The board should be a readily available development board so that others can also test. + +Build +----- + +Now that those directories are in place, we can start our iteration process to get the example building successfully. To build, run from the root of TinyUSB: + +.. code-block:: bash + + make -C examples/device/cdc_msc BOARD= + +Unless you've read ahead, this will fail miserably. Now, lets get it to fail less by updating the files in the board directory. The code in the board's directory is responsible for setting up the microcontroller's clocks and pins so that USB works. TinyUSB itself only operates on the USB peripheral. The board directory also includes information what files are needed to build the example. + +One of the first things to change is the ``-DCFG_TUSB_MCU`` C flag in the ``board.mk`` file. This is used to tell TinyUSB what platform is being built. So, add an entry to ``src/tusb_option.h`` and update the ``CFLAGS`` to match. + +Update ``board.mk``'s VENDOR and CHIP_FAMILY values when creating the directory for the struct files. Duplicate one of the other sources from ``src/portable`` into ``src/portable//`` and delete all of the implementation internals. We'll cover what everything there does later. For now, get it compiling. + +Implementation +-------------- + +At this point you should get an error due to an implementation issue and hopefully the build is setup for the new MCU. You will still need to modify the ``board.mk`` to include specific ``CFLAGS``, the linker script, linker flags, source files, include directories. All file paths are relative to the top of the TinyUSB repo. + +Board Support (BSP) +^^^^^^^^^^^^^^^^^^^ + +The board support code is only used for self-contained examples and testing. It is not used when TinyUSB is part of a larger project. Its responsible for getting the MCU started and the USB peripheral clocked. It also optionally provides LED definitions that are used to blink an LED to show that the code is running. + +It is located in ``hw/bsp//board_.c``. + +``board_init()`` +~~~~~~~~~~~~~~~~ + +``board_init()`` is responsible for starting the MCU, setting up the USB clock and USB pins. It is also responsible for initializing LED pins. + +One useful clock debugging technique is to set up a PWM output at a known value such as 500hz based on the USB clock so that you can verify it is correct with a logic probe or oscilloscope. + +Setup your USB in a crystal-less mode when available. That makes the code easier to port across boards. + +``board_led_write()`` +~~~~~~~~~~~~~~~~~~~~~ + +Feel free to skip this until you want to verify your demo code is running. To implement, set the pin corresponding to the led to output a value that lights the LED when ``state`` is true. + +OS Abstraction Layer (OSAL) +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The OS Abstraction Layer is responsible for providing basic data structures for TinyUSB that may allow for concurrency when used with an RTOS. Without an RTOS it simply handles concurrency issues between the main code and interrupts. The code is almost entirely agnostic of MCU and lives in ``src/osal``. + +In RTOS configurations, ``tud_task()``/``tuh_task()`` blocks behind a synchronization structure when the event queue is empty, so that the scheduler may give the CPU to a different task. To take advantage of the library's capability to yield the CPU when there are no actionable USB device events, ensure that the ``CFG_TUSB_OS`` symbol is defined, e.g ``OPT_OS_FREERTOS`` enables the FreeRTOS scheduler to schedule other threads than that which calls ``tud_task()``/``tuh_task()``. + +Device API +^^^^^^^^^^ + +After the USB device is setup, the USB device code works by processing events on the main thread (by calling ``tud_task()``). These events are queued by the USB interrupt handler. So, there are three parts to the device low-level API: device setup, endpoint setup and interrupt processing. + +All of the code for the low-level device API is in ``src/portable///dcd_.c``. + +Device Setup +~~~~~~~~~~~~ + +``dcd_init()`` +"""""""""""""" + +Initializes the USB peripheral for device mode and enables it. +This function should enable internal D+/D- pull-up for enumeration. + +``dcd_int_enable()`` / ``dcd_int_disable()`` +"""""""""""""""""""""""""""""""""""""""""""" + +Enables or disables the USB device interrupt(s). May be used to prevent concurrency issues when mutating data structures shared between main code and the interrupt handler. + +``dcd_int_handler()`` +""""""""""""""""""""" + +Processes all the hardware generated events e.g Bus reset, new data packet from host etc ... It will be called by application in the MCU USB interrupt handler. + +``dcd_set_address()`` +""""""""""""""""""""" + +Called when the device is given a new bus address. + +If your peripheral automatically changes address during enumeration (like the nrf52) you may leave this empty and also no queue an event for the corresponding SETUP packet. + +``dcd_remote_wakeup()`` +""""""""""""""""""""""" + +Called to remote wake up host when suspended (e.g hid keyboard) + +``dcd_connect()`` / ``dcd_disconnect()`` +"""""""""""""""""""""""""""""""""""""""" + +Connect or disconnect the data-line pull-up resistor. Define only if MCU has an internal pull-up. (BSP may define for MCU without internal pull-up.) + +Special events +~~~~~~~~~~~~~~ + +You must let TinyUSB know when certain events occur so that it can continue its work. There are a few methods you can call to queue events for TinyUSB to process. + +``dcd_event_bus_signal()`` +"""""""""""""""""""""""""" + +There are a number of events that your peripheral may communicate about the state of the bus. Here is an overview of what they are. Events in **BOLD** must be provided for TinyUSB to work. + + +* **DCD_EVENT_RESET** - Triggered when the host resets the bus causing the peripheral to reset. Do any other internal reset you need from the interrupt handler such as resetting the control endpoint. +* DCD_EVENT_SOF - Signals the start of a new USB frame. + +Calls to this look like: + +.. code-block:: c + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + + +The first ``0`` is the USB peripheral number. Statically saying ``0`` is common for single USB device MCUs. + +The ``true`` indicates the call is from an interrupt handler and will always be the case when porting in this way. + +``dcd_setup_received()`` +"""""""""""""""""""""""" + +SETUP packets are a special type of transaction that can occur at any time on the control endpoint, numbered ``0``. Since they are unique, most peripherals have special handling for them. Their data is always 8 bytes in length as well. + +Calls to this look like: + +.. code-block:: c + + dcd_event_setup_received(0, setup, true); + + +As before with ``dcd_event_bus_signal()`` the first argument is the USB peripheral number and the third is true to signal its being called from an interrupt handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. + +Endpoints +~~~~~~~~~ + +Endpoints are the core of the USB data transfer process. They come in a few forms such as control, isochronous, bulk, and interrupt. We won't cover the details here except with some caveats in open below. In general, data is transferred by setting up a buffer of a given length to be transferred on a given endpoint address and then waiting for an interrupt to signal that the transfer is finished. Further details below. + +Endpoints within USB have an address which encodes both the number and direction of an endpoint. TinyUSB provides ``tu_edpt_number()`` and ``tu_edpt_dir()`` to unpack this data from the address. Here is a snippet that does it. + +.. code-block:: c + + uint8_t epnum = tu_edpt_number(ep_addr); + uint8_t dir = tu_edpt_dir(ep_addr); + + +``dcd_edpt_open()`` +""""""""""""""""""" + +Opening an endpoint is done for all non-control endpoints once the host picks a configuration that the device should use. At this point, the endpoint should be enabled in the peripheral and configured to match the endpoint descriptor. Pay special attention to the direction of the endpoint you can get from the helper methods above. It will likely change what registers you are setting. + +Also make sure to enable endpoint specific interrupts. + +``dcd_edpt_close()`` +"""""""""""""""""""" + +Close an endpoint. his function is used for implementing alternate settings. + +After calling this, the device should not respond to any packets directed towards this endpoint. When called, this function must abort any transfers in progress through this endpoint, before returning. + +Implementation is optional. Must be called from the USB task. Interrupts could be disabled or enabled during the call. + +``dcd_edpt_xfer()`` +""""""""""""""""""" + +``dcd_edpt_xfer()`` is responsible for configuring the peripheral to send or receive data from the host. "xfer" is short for "transfer". **This is one of the core methods you must implement for TinyUSB to work (one other is the interrupt handler).** Data from the host is the OUT direction and data to the host is IN. It is used for all endpoints including the control endpoint 0. Make sure to handle the zero-length packet STATUS packet on endpoint 0 correctly. It may be a special transaction to the peripheral. + +Besides that, all other transactions are relatively straight-forward. The endpoint address provides the endpoint +number and direction which usually determines where to write the buffer info. The buffer and its length are usually +written to a specific location in memory and the peripheral is told the data is valid. (Maybe by writing a 1 to a +register or setting a counter register to 0 for OUT or length for IN.) + +The transmit buffer alignment is determined by ``CFG_TUSB_MEM_ALIGN``. + +One potential pitfall is that the buffer may be longer than the maximum endpoint size of one USB +packet. Some peripherals can handle transmitting multiple USB packets for a provided buffer (like the SAMD21). +Others (like the nRF52) may need each USB packet queued individually. To make this work you'll need to track +some state for yourself and queue up an intermediate USB packet from the interrupt handler. + +Once the transaction is going, the interrupt handler will notify TinyUSB of transfer completion. +During transmission, the IN data buffer is guaranteed to remain unchanged in memory until the ``dcd_xfer_complete()`` function is called. + +The ``dcd_edpt_xfer()`` function must never add zero-length-packets (ZLP) on its own to a transfer. If a ZLP is required, +then it must be explicitly sent by the stack calling ``dcd_edpt_xfer()``, by calling ``dcd_edpt_xfer()`` a second time with len=0. +For control transfers, this is automatically done in ``usbd_control.c``. + +At the moment, only a single buffer can be transmitted at once. There is no provision for double-buffering. new ``dcd_edpt_xfer()`` will not +be called again on the same endpoint address until the driver calls ``dcd_xfer_complete()`` (except in cases of USB resets). + +``dcd_xfer_complete()`` +""""""""""""""""""""""" + +Once a transfer completes you must call ``dcd_xfer_complete()`` from the USB interrupt handler to let TinyUSB know that a transaction has completed. Here is a sample call: + +.. code-block:: c + + dcd_event_xfer_complete(0, ep_addr, xfer->actual_len, XFER_RESULT_SUCCESS, true); + + +The arguments are: + + +* the USB peripheral number +* the endpoint address +* the actual length of the transfer. (OUT transfers may be smaller than the buffer given in ``dcd_edpt_xfer()``) +* the result of the transfer. Failure isn't handled yet. +* ``true`` to note the call is from an interrupt handler. + +``dcd_edpt_stall()`` / ``dcd_edpt_clear_stall()`` +""""""""""""""""""""""""""""""""""""""""""""""""" + +Stalling is one way an endpoint can indicate failure such as when an unsupported command is transmitted. The pair of ``dcd_edpt_stall()``, ``dcd_edpt_clear_stall()`` help manage the stall state of all endpoints. + +Woohoo! +------- + +At this point you should have everything working! πŸ™‚ Of course, you may not write perfect code. Here are some tips and tricks for debugging. + +Use `WireShark `_ or `a Beagle `_ to sniff the USB traffic. When things aren't working its likely very early in the USB enumeration process. Figuring out where can help clue in where the issue is. For example: + + +* If the host sends a SETUP packet and its not ACKed then your USB peripheral probably isn't started correctly. +* If the peripheral is started correctly but it still didn't work, then verify your usb clock is correct. (You did output a PWM based on it right? πŸ™‚) +* If the SETUP packet is ACKed but nothing is sent back then you interrupt handler isn't queueing the setup packet correctly. (Also, if you are using your own code instead of an example ``tud_task()`` may not be called.) If that's OK, the ``dcd_xfer_complete()`` may not be setting up the next transaction correctly. diff --git a/docs/reference/architecture.rst b/docs/reference/architecture.rst index 8e4c6890e..70ea17ed4 100644 --- a/docs/reference/architecture.rst +++ b/docs/reference/architecture.rst @@ -42,36 +42,23 @@ Layer Structure TinyUSB follows a layered architecture from hardware to application: -.. code-block:: none +.. figure:: ../assets/stack.svg + :width: 500px + :align: left + :alt: stackup + +.. raw:: html - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ Application Layer β”‚ ← Your code - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ USB Class Drivers β”‚ ← CDC, HID, MSC, etc. - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ Device/Host Stack Core β”‚ ← USB protocol handling - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ Hardware Abstraction (DCD/HCD) β”‚ ← MCU-specific drivers - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ OS Abstraction (OSAL) β”‚ ← RTOS integration - β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ - β”‚ Common Utilities & FIFO β”‚ ← Shared components - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +
Component Overview ------------------ -**Application Layer**: Your main application code that uses TinyUSB APIs. - -**Class Drivers**: Implement specific USB device classes (CDC, HID, MSC, etc.) and handle class-specific requests. - -**Device/Host Core**: Implements USB protocol state machines, endpoint management, and core USB functionality. - -**Hardware Abstraction**: MCU-specific code that interfaces with USB peripheral hardware. - -**OS Abstraction**: Provides threading primitives and synchronization for different RTOS environments. - -**Common Utilities**: Shared code including FIFO implementations, binary helpers, and utility functions. +- **Application Layer**: Your main application code that uses TinyUSB APIs. +- **Class Drivers**: Implement specific USB device classes (CDC, HID, MSC, etc.) and handle class-specific requests. +- **Device/Host Core**: Implements USB protocol state machines, endpoint management, and core USB functionality. +- **OS Abstraction**: Provides threading primitives and synchronization for different RTOS environments. +- **Device/Host Controller Driver**: drivers that interface with MCU USB peripherals. Several MCUs may share a common driver. Device Stack Architecture ========================= @@ -85,7 +72,7 @@ Core Components - MCU-specific USB device peripheral driver - Handles endpoint configuration and data transfers - Abstracts hardware differences between MCU families -- Located in ``src/portable/VENDOR/FAMILY/`` +- Located in ``src/portable/VENDOR/USBIP/`` **USB Device Core (USBD)**: - Implements USB device state machine diff --git a/docs/reference/boards.rst b/docs/reference/boards.rst index e668e2693..12da5c90b 100644 --- a/docs/reference/boards.rst +++ b/docs/reference/boards.rst @@ -107,17 +107,20 @@ olimex_emz64 Olimex PIC32-EMZ64 pic32mz http olimex_hmz144 Olimex PIC32-HMZ144 pic32mz https://www.olimex.com/Products/PIC/Development/PIC32-HMZ144/open-source-hardware cynthion_d11 Great Scott Gadgets Cynthion samd11 https://greatscottgadgets.com/cynthion/ samd11_xplained SAMD11 Xplained Pro samd11 https://www.microchip.com/en-us/development-tool/ATSAMD11-XPRO -atsamd21_xpro SAMD21 Xplained Pro samd21 https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMD21-XPRO -circuitplayground_express Adafruit Circuit Playground Express samd21 https://www.adafruit.com/product/3333 -curiosity_nano SAMD21 Curiosty Nano samd21 https://www.microchip.com/en-us/development-tool/dm320119 -cynthion_d21 Great Scott Gadgets Cynthion samd21 https://greatscottgadgets.com/cynthion/ -feather_m0_express Adafruit Feather M0 Express samd21 https://www.adafruit.com/product/3403 -itsybitsy_m0 Adafruit ItsyBitsy M0 samd21 https://www.adafruit.com/product/3727 -metro_m0_express Adafruit Metro M0 Express samd21 https://www.adafruit.com/product/3505 -qtpy Adafruit QT Py samd21 https://www.adafruit.com/product/4600 -seeeduino_xiao Seeeduino XIAO samd21 https://wiki.seeedstudio.com/Seeeduino-XIAO/ -sparkfun_samd21_mini_usb SparkFun SAMD21 Mini samd21 https://www.sparkfun.com/products/13664 -trinket_m0 Adafruit Trinket M0 samd21 https://www.adafruit.com/product/3500 +atsamd21_xpro SAMD21 Xplained Pro samd2x_l2x https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMD21-XPRO +atsaml21_xpro SAML21 Xplained Pro samd2x_l2x https://www.microchip.com/en-us/development-tool/atsaml21-xpro-b +circuitplayground_express Adafruit Circuit Playground Express samd2x_l2x https://www.adafruit.com/product/3333 +curiosity_nano SAMD21 Curiosty Nano samd2x_l2x https://www.microchip.com/en-us/development-tool/dm320119 +cynthion_d21 Great Scott Gadgets Cynthion samd2x_l2x https://greatscottgadgets.com/cynthion/ +feather_m0_express Adafruit Feather M0 Express samd2x_l2x https://www.adafruit.com/product/3403 +itsybitsy_m0 Adafruit ItsyBitsy M0 samd2x_l2x https://www.adafruit.com/product/3727 +metro_m0_express Adafruit Metro M0 Express samd2x_l2x https://www.adafruit.com/product/3505 +qtpy Adafruit QT Py samd2x_l2x https://www.adafruit.com/product/4600 +saml22_feather SAML22 Feather samd2x_l2x https://github.com/joeycastillo/Feather-Projects/tree/main/SAML22%20Feather +seeeduino_xiao Seeeduino XIAO samd2x_l2x https://wiki.seeedstudio.com/Seeeduino-XIAO/ +sensorwatch_m0 SensorWatch samd2x_l2x https://github.com/joeycastillo/Sensor-Watch +sparkfun_samd21_mini_usb SparkFun SAMD21 Mini samd2x_l2x https://www.sparkfun.com/products/13664 +trinket_m0 Adafruit Trinket M0 samd2x_l2x https://www.adafruit.com/product/3500 d5035_01 D5035-01 samd5x_e5x https://github.com/RudolphRiedel/USB_CAN-FD feather_m4_express Adafruit Feather M4 Express samd5x_e5x https://www.adafruit.com/product/3857 itsybitsy_m4 Adafruit ItsyBitsy M4 samd5x_e5x https://www.adafruit.com/product/3800 @@ -125,10 +128,9 @@ metro_m4_express Adafruit Metro M4 Express samd5x_e5x http pybadge Adafruit PyBadge samd5x_e5x https://www.adafruit.com/product/4200 pyportal Adafruit PyPortal samd5x_e5x https://www.adafruit.com/product/4116 same54_xplained SAME54 Xplained Pro samd5x_e5x https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAME54-XPRO +same70_qmtech SAME70 QMTech same7x https://www.aliexpress.com/item/1005003173783268.html +same70_xplained SAME70 Xplained same7x https://www.microchip.com/en-us/development-tool/atsame70-xpld samg55_xplained SAMG55 Xplained Pro samg https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMG55-XPRO -atsaml21_xpro SAML21 Xplained Pro saml2x https://www.microchip.com/en-us/development-tool/atsaml21-xpro-b -saml22_feather SAML22 Feather saml2x https://github.com/joeycastillo/Feather-Projects/tree/main/SAML22%20Feather -sensorwatch_m0 SensorWatch saml2x https://github.com/joeycastillo/Sensor-Watch ========================= =================================== ========== ================================================================================= ====== MindMotion @@ -295,6 +297,7 @@ stm32l052dap52 STM32 L052 DAP stm32l0 n/a stm32l0538disco STM32 L0538 Discovery stm32l0 https://www.st.com/en/evaluation-tools/32l0538discovery.html stm32l412nucleo STM32 L412 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l412kb.html stm32l476disco STM32 L476 Disco stm32l4 https://www.st.com/en/evaluation-tools/32l476gdiscovery.html +stm32l496nucleo STM32 L496 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l496ZG-P.html stm32l4p5nucleo STM32 L4P5 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l4p5zg.html stm32l4r5nucleo STM32 L4R5 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l4r5zi.html stm32n6570dk STM32 N6570-DK stm32n6 https://www.st.com/en/evaluation-tools/stm32n6570-dk.html diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst index e04cc2c2f..de1603383 100644 --- a/docs/reference/dependencies.rst +++ b/docs/reference/dependencies.rst @@ -4,9 +4,9 @@ Dependencies MCU low-level peripheral drivers and external libraries for building TinyUSB examples -======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================================== +======================================== ================================================================ ======================================== ============================================================================================================================================================================================================================================================================================================================================================== Local Path Repo Commit Required by -======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================================== +======================================== ================================================================ ======================================== ============================================================================================================================================================================================================================================================================================================================================================== hw/mcu/allwinner https://github.com/hathach/allwinner_driver.git 8e5e89e8e132c0fd90e72d5422e5d3d68232b756 fc100s hw/mcu/analog/msdk https://github.com/analogdevicesinc/msdk.git b20b398d3e5e2007594e54a74ba3d2a2e50ddd75 maxim hw/mcu/artery/at32f402_405 https://github.com/ArteryTek/AT32F402_405_Firmware_Library.git 4424515c2663e82438654e0947695295df2abdfe at32f402_405 @@ -23,7 +23,7 @@ hw/mcu/infineon/mtb-xmclib-cat3 https://github.com/Infineon/mtb-xmclib hw/mcu/microchip https://github.com/hathach/microchip_driver.git 9e8b37e307d8404033bb881623a113931e1edf27 sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg hw/mcu/mindmotion/mm32sdk https://github.com/hathach/mm32sdk.git b93e856211060ae825216c6a1d6aa347ec758843 mm32 hw/mcu/nordic/nrfx https://github.com/NordicSemiconductor/nrfx.git 11f57e578c7feea13f21c79ea0efab2630ac68c7 nrf -hw/mcu/nuvoton https://github.com/majbthrd/nuc_driver.git 2204191ec76283371419fbcec207da02e1bc22fa nuc +hw/mcu/nuvoton https://github.com/majbthrd/nuc_driver.git 2204191ec76283371419fbcec207da02e1bc22fa nuc100_120 nuc121_125 nuc126 nuc505 hw/mcu/nxp/lpcopen https://github.com/hathach/nxp_lpcopen.git b41cf930e65c734d8ec6de04f1d57d46787c76ae lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 hw/mcu/nxp/mcux-sdk https://github.com/nxp-mcuxpresso/mcux-sdk a1bdae309a14ec95a4f64a96d3315a4f89c397c6 kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt hw/mcu/raspberry_pi/Pico-PIO-USB https://github.com/sekigon-gonnoc/Pico-PIO-USB.git 675543bcc9baa8170f868ab7ba316d418dbcf41f rp2040 @@ -80,10 +80,10 @@ hw/mcu/wch/ch32f20x https://github.com/openwch/ch32f20x.gi hw/mcu/wch/ch32v103 https://github.com/openwch/ch32v103.git 7578cae0b21f86dd053a1f781b2fc6ab99d0ec17 ch32v10x hw/mcu/wch/ch32v20x https://github.com/openwch/ch32v20x.git c4c38f507e258a4e69b059ccc2dc27dde33cea1b ch32v20x hw/mcu/wch/ch32v307 https://github.com/openwch/ch32v307.git 184f21b852cb95eed58e86e901837bc9fff68775 ch32v30x -lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 2b7495b8535bdcb306dac29b9ded4cfb679d7e5c imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf saml2x lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32n6 stm32u0 stm32u5 stm32wb stm32wbasam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg tm4c -lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git b0bbb0423b278ca632cfe1474eb227961d835fd2 ra +lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 2b7495b8535bdcb306dac29b9ded4cfb679d7e5c imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf saml2x lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32u0 stm32u5 stm32wb stm32wbasam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg tm4c +lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git 6f0a58d01aa9bd2feba212097f9afe7acd991d52 ra stm32n6 lib/FreeRTOS-Kernel https://github.com/FreeRTOS/FreeRTOS-Kernel.git cc0e0707c0c748713485b870bb980852b210877f all lib/lwip https://github.com/lwip-tcpip/lwip.git 159e31b689577dbf69cf0683bbaffbd71fa5ee10 all lib/sct_neopixel https://github.com/gsteiert/sct_neopixel.git e73e04ca63495672d955f9268e003cffe168fcd8 lpc55 tools/uf2 https://github.com/microsoft/uf2.git c594542b2faa01cc33a2b97c9fbebc38549df80a all -======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================================== +======================================== ================================================================ ======================================== ============================================================================================================================================================================================================================================================================================================================================================== diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst index 561780c53..537769c43 100644 --- a/docs/reference/glossary.rst +++ b/docs/reference/glossary.rst @@ -95,4 +95,4 @@ Glossary Product Identifier. 16-bit number assigned by vendor to identify specific products. USB-IF - USB Implementers Forum. Organization that maintains USB specifications and assigns VIDs. \ No newline at end of file + USB Implementers Forum. Organization that maintains USB specifications and assigns VIDs. diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst index e30210d01..bb9f15166 100644 --- a/docs/troubleshooting.rst +++ b/docs/troubleshooting.rst @@ -15,13 +15,14 @@ Toolchain Problems The ARM GCC toolchain is not installed or not in PATH. *Solution*: + .. code-block:: bash # Ubuntu/Debian - sudo apt-get update && sudo apt-get install gcc-arm-none-eabi + $ sudo apt-get update && sudo apt-get install gcc-arm-none-eabi # macOS with Homebrew - brew install --cask gcc-arm-embedded + $ brew install --cask gcc-arm-embedded # Windows: Download from ARM website and add to PATH @@ -30,14 +31,15 @@ The ARM GCC toolchain is not installed or not in PATH. Build tools are missing. *Solution*: + .. code-block:: bash # Ubuntu/Debian - sudo apt-get install build-essential cmake + $ sudo apt-get install build-essential cmake # macOS - xcode-select --install - brew install cmake + $ xcode-select --install + $ brew install cmake Dependency Issues ----------------- @@ -47,10 +49,12 @@ Dependency Issues Dependencies for your MCU family are not downloaded. *Solution*: + .. code-block:: bash - # Download dependencies for specific family - python tools/get_deps.py stm32f4 # Replace with your family + # Download dependencies for specific board or family + $ python tools/get_deps.py -b stm32h743eval # Replace with your board + $ python tools/get_deps.py stm32f4 # Replace with your family # Or from example directory cd examples/device/cdc_msc @@ -61,14 +65,12 @@ Dependencies for your MCU family are not downloaded. Invalid board name in build command. *Diagnosis*: + .. code-block:: bash # List available boards for a family ls hw/bsp/stm32f4/boards/ - # List all supported boards - python tools/build.py -l - *Solution*: Use exact board name from the listing. Runtime Issues @@ -82,6 +84,7 @@ Device Mode Problems The most common issue - host doesn't see your USB device. *Diagnosis steps*: + 1. Check USB cable (must support data, not just power) 2. Enable logging: build with ``LOG=2`` 3. Use different USB ports/hosts @@ -99,17 +102,20 @@ The most common issue - host doesn't see your USB device. Device is detected but configuration fails. *Diagnosis*: + .. code-block:: bash # Build with logging enabled make BOARD=your_board LOG=2 all *Look for*: + - Setup request handling errors - Endpoint configuration problems - String descriptor issues *Solutions*: + - Implement all required descriptors - Check endpoint sizes match descriptors - Ensure control endpoint (EP0) handling is correct @@ -119,11 +125,13 @@ Device is detected but configuration fails. Device enumerates but data doesn't transfer correctly. *Common causes*: + - Buffer overruns in class callbacks - Incorrect endpoint usage (IN vs OUT) - Flow control issues in CDC class *Solutions*: + - Check buffer sizes in callbacks - Verify endpoint directions in descriptors - Implement proper flow control @@ -136,11 +144,13 @@ Host Mode Problems Host application doesn't see connected devices. *Hardware checks*: + - Power supply adequate for host mode - USB-A connector for host (not micro-USB) - Board supports host mode on selected port *Software checks*: + - ``tuh_task()`` called regularly - Host stack enabled in ``tusb_config.h`` - Correct root hub port configuration @@ -150,12 +160,14 @@ Host application doesn't see connected devices. Devices connect but enumeration fails. *Diagnosis*: + .. code-block:: bash # Enable host logging make BOARD=your_board LOG=2 RHPORT_HOST=1 all *Common issues*: + - Power supply insufficient during enumeration - Timing issues with slow devices - USB hub compatibility problems @@ -165,6 +177,7 @@ Devices connect but enumeration fails. Device enumerates but class-specific communication fails. *Troubleshooting*: + - Check device descriptors match expected class - Verify interface/endpoint assignments - Some devices need device-specific handling @@ -185,6 +198,7 @@ High CPU Usage **Symptoms**: MCU spending too much time in USB handling *Solutions*: + - Use efficient logging (RTT/SWO instead of UART) - Reduce log level in production builds - Optimize descriptor parsing @@ -197,11 +211,13 @@ STM32 Issues ------------ **Clock configuration problems**: + - USB requires precise 48MHz clock - HSE crystal must be configured correctly - PLL settings affect USB timing **Pin configuration**: + - USB pins need specific alternate function settings - VBUS sensing configuration - ID pin for OTG applications @@ -210,6 +226,7 @@ RP2040 Issues ------------- **PIO-USB for host mode**: + - Requires specific pin assignments - CPU overclocking may be needed for reliable operation - Timing-sensitive - avoid long interrupt disable periods @@ -218,8 +235,8 @@ ESP32 Issues ------------ **USB peripheral differences**: -- ESP32-S2/S3 have different USB capabilities -- Some variants only support device mode + +- ESP32-S2/S3/P4 have different USB capabilities - DMA configuration varies between models Advanced Debugging @@ -249,6 +266,7 @@ However, especially for diagnosis of crashes, it can still be useful. arm-none-eabi-gdb build/your_app.elf *Useful breakpoints*: + - ``dcd_int_handler()`` - USB interrupt entry - ``tud_task()`` - Main device task - Class-specific callbacks @@ -280,6 +298,7 @@ When reporting issues: 5. **Host environment**: OS version, USB port type **Resources**: + - GitHub Discussions: https://github.com/hathach/tinyusb/discussions - Issue Tracker: https://github.com/hathach/tinyusb/issues - Documentation: https://docs.tinyusb.org diff --git a/hw/bsp/family_support.cmake b/hw/bsp/family_support.cmake index ad68957df..23dfb9d80 100644 --- a/hw/bsp/family_support.cmake +++ b/hw/bsp/family_support.cmake @@ -10,6 +10,40 @@ get_filename_component(TOP ${TOP} ABSOLUTE) set(UF2CONV_PY ${TOP}/tools/uf2/utils/uf2conv.py) +function(family_resolve_board BOARD_NAME BOARD_PATH_OUT) + if ("${BOARD_NAME}" STREQUAL "") + message(FATAL_ERROR "You must set BOARD (e.g. metro_m4_express, raspberry_pi_pico). Use -DBOARD=xxx on the cmake command line.") + endif() + + file(GLOB _board_paths + LIST_DIRECTORIES true + RELATIVE ${TOP}/hw/bsp + ${TOP}/hw/bsp/*/boards/* + ) + + set(_hint_names "") + foreach(_board_path ${_board_paths}) + get_filename_component(_board_name ${_board_path} NAME) + if (_board_name STREQUAL "${BOARD_NAME}") + set(${BOARD_PATH_OUT} ${_board_path} PARENT_SCOPE) + return() + endif() + string(FIND "${_board_name}" "${BOARD_NAME}" _pos) + if (_pos EQUAL 0) + list(APPEND _hint_names ${_board_name}) + endif() + endforeach() + + if (_hint_names) + list(REMOVE_DUPLICATES _hint_names) + list(SORT _hint_names) + list(JOIN _hint_names ", " _hint_str) + message(FATAL_ERROR "BOARD '${BOARD_NAME}' not found. Boards with the same prefix:\n${_hint_str}") + else() + message(FATAL_ERROR "BOARD '${BOARD_NAME}' not found under hw/bsp/*/boards") + endif() +endfunction() + #------------------------------------------------------------- # Toolchain # Can be changed via -DTOOLCHAIN=gcc|iar or -DCMAKE_C_COMPILER= or ENV{CC}= @@ -78,21 +112,8 @@ endif () # FAMILY and BOARD #------------------------------------------------------------- if (NOT DEFINED FAMILY) - if (NOT DEFINED BOARD) - message(FATAL_ERROR "You must set a BOARD variable for the build (e.g. metro_m4_express, raspberry_pi_pico). - You can do this via -DBOARD=xxx on the cmake command line") - endif () - - # Find path contains BOARD - file(GLOB BOARD_PATH LIST_DIRECTORIES true - RELATIVE ${TOP}/hw/bsp - ${TOP}/hw/bsp/*/boards/${BOARD} - ) - if (NOT BOARD_PATH) - message(FATAL_ERROR "Could not detect FAMILY from BOARD=${BOARD}") - endif () + family_resolve_board("${BOARD}" BOARD_PATH) - # replace / with ; so that we can get the first element as FAMILY string(REPLACE "/" ";" BOARD_PATH ${BOARD_PATH}) list(GET BOARD_PATH 0 FAMILY) set(FAMILY ${FAMILY} CACHE STRING "Board family") diff --git a/tools/gen_doc.py b/tools/gen_doc.py index ab07bc116..3920531d5 100755 --- a/tools/gen_doc.py +++ b/tools/gen_doc.py @@ -23,7 +23,7 @@ def gen_deps_doc(): Dependencies ************ -MCU low-level peripheral driver and external libraries for building TinyUSB examples +MCU low-level peripheral drivers and external libraries for building TinyUSB examples {tabulate(df, headers="keys", tablefmt='rst')} """ -- cgit v1.3.1 From b4e92f63c6b653101320cbb9e8ca3f76fbc81509 Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Sat, 14 Mar 2026 09:19:24 +0100 Subject: fix windows build Signed-off-by: HiFiPhile --- docs/conf.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/conf.py') diff --git a/docs/conf.py b/docs/conf.py index cd0338413..9e9784fb7 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -52,11 +52,11 @@ def preprocess_readme(): src = Path(__file__).parent.parent / "README.rst" tgt = Path(__file__).parent.parent / "README_processed.rst" if src.exists(): - content = src.read_text() + content = src.read_text(encoding='utf-8') content = re.sub(r"docs/", r"", content) content = re.sub(r"\.rst\b", r".html", content) if not content.endswith("\n"): content += "\n" - tgt.write_text(content) + tgt.write_text(content, encoding='utf-8') preprocess_readme() -- cgit v1.3.1 From 22c2ece872262c1331482f8e80881ab1f5f36c0b Mon Sep 17 00:00:00 2001 From: HiFiPhile Date: Tue, 2 Jun 2026 11:10:15 +0200 Subject: try to get render right Signed-off-by: HiFiPhile --- README.rst | 8 ++++---- docs/conf.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) (limited to 'docs/conf.py') diff --git a/README.rst b/README.rst index fac098c1c..ecfbeb7cc 100644 --- a/README.rst +++ b/README.rst @@ -251,7 +251,7 @@ Supported CPUs | | +-------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ | | | 51u | βœ” | βœ– | βœ– | lpc_ip3511 | | | | +-------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ -| | | 54 | ⚠ | ⚠ | βœ” | lpc_ip3511, lpc_ip3516 | `NRND, read errata `_ | +| | | 54 | ⚠ | ⚠ | βœ” | lpc_ip3511, lpc_ip3516 | `NRND, read errata `_ | | | +-------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ | | | 55 | βœ” | βœ” | βœ” | lpc_ip3511, lpc_ip3516 | | | +---------+-------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ @@ -305,11 +305,11 @@ Supported CPUs +--------------+-----------------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ | ValentyUSB | eptri | βœ” | βœ– | βœ– | eptri | | +--------------+-----------------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ -| WCH | CH32F20x | ⚠ | | βœ” | ch32_usbhs | `ISO data loss `_ | +| WCH | CH32F20x | ⚠ | | βœ” | ch32_usbhs | `ISO data loss `_ | | +-----------------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ -| | CH32V20x | ⚠ | | βœ– | stm32_fsdev/ch32_usbfs | `ISO data loss `_ | +| | CH32V20x | ⚠ | | βœ– | stm32_fsdev/ch32_usbfs | `ISO data loss `_ | | +-----------------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ -| | CH32V305, CH32V307 | ⚠ | | βœ” | ch32_usbfs/hs | `ISO data loss `_ | +| | CH32V305, CH32V307 | ⚠ | | βœ” | ch32_usbfs/hs | `ISO data loss `_ | +--------------+-----------------------------+--------+------+-----------+------------------------+-----------------------------------------------------------------------------------------+ Table Legend diff --git a/docs/conf.py b/docs/conf.py index 9e9784fb7..86ddcf672 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -53,6 +53,25 @@ def preprocess_readme(): tgt = Path(__file__).parent.parent / "README_processed.rst" if src.exists(): content = src.read_text(encoding='utf-8') + # if the matching is inside a table, keep the table cell width by adding the same number of spaces in the end of the line + # match pattern: | ... `... `_ ... | + # change into: | ... `... <...>`_ ... | + def _rewrite_table_line(line): + if not (line.startswith('|') and line.rstrip().endswith('|')): + return line + + rewritten = re.sub(r"]+)>", r"<\1>", line) + delta = len(line) - len(rewritten) - 1 # -1 for rst->html + + if delta > 0: + last_pipe = rewritten.rfind('|') + if last_pipe >= 0: + rewritten = rewritten[:last_pipe] + (' ' * delta) + rewritten[last_pipe:] + + return rewritten + + content = ''.join(_rewrite_table_line(line) for line in content.splitlines(keepends=True)) + content = re.sub(r"docs/", r"", content) content = re.sub(r"\.rst\b", r".html", content) if not content.endswith("\n"): -- cgit v1.3.1